Exemplo n.º 1
0
void
GNUNET_ATS_TEST_logging_write_to_file (struct LoggingHandle *l,
    char *experiment_name, int plots)
{
  struct GNUNET_DISK_FileHandle *f[l->num_slaves];
  struct GNUNET_DISK_FileHandle *f_m;
  char *tmp_exp_name;
  char *filename_master;
  char *filename_slaves[l->num_slaves];
  char *data;
  struct PeerLoggingTimestep *cur_lt;
  struct PartnerLoggingTimestep *plt;
  struct GNUNET_TIME_Absolute timestamp;
  int c_m;
  int c_s;


  timestamp = GNUNET_TIME_absolute_get();

  tmp_exp_name = experiment_name;
  for (c_m = 0; c_m < l->num_masters; c_m++)
  {
    GNUNET_asprintf (&filename_master, "%s_%llu_master%u_%s",
        experiment_name, timestamp.abs_value_us, c_m, l->name);
    fprintf (stderr, "Writing data for master %u to file `%s'\n",
        c_m,filename_master);

    f_m = GNUNET_DISK_file_open (filename_master,
        GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE,
        GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE);
    if (NULL == f_m)
    {
      GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Cannot open log file `%s'\n", filename_master);
      GNUNET_free (filename_master);
      return;
    }

    GNUNET_asprintf (&data, "# master %u; experiment : %s\n"
        "timestamp; timestamp delta; #messages sent; #bytes sent; #throughput sent; #messages received; #bytes received; #throughput received; \n" ,
        c_m,  experiment_name);
    if (GNUNET_SYSERR == GNUNET_DISK_file_write(f_m, data, strlen(data)))
      GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
          "Cannot write data to log file `%s'\n",filename_master);
    GNUNET_free (data);

    for (c_s = 0; c_s < l->lp[c_m].peer->num_partners; c_s++)
    {
      GNUNET_asprintf (&filename_slaves[c_s], "%s_%llu_master%u_slave_%u_%s",
          tmp_exp_name, timestamp.abs_value_us, c_m, c_s, l->name);

      fprintf (stderr, "Writing data for master %u slave %u to file `%s'\n",
          c_m, c_s, filename_slaves[c_s]);

      f[c_s] = GNUNET_DISK_file_open (filename_slaves[c_s],
          GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE,
          GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE);
      if (NULL == f[c_s])
      {
        GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Cannot open log file `%s'\n", filename_slaves[c_s]);
        GNUNET_free (filename_slaves[c_s]);
        GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close(f_m));
        GNUNET_free (filename_master);
        return;
      }

      /* Header */
      GNUNET_asprintf (&data, "# master %u; slave %u ; experiment : %s\n"
          "timestamp; timestamp delta; #messages sent; #bytes sent; #throughput sent; #messages received; #bytes received; #throughput received; " \
          "rtt; bw in; bw out; ats_cost_lan; ats_cost_wlan; ats_delay; ats_distance; ats_network_type; ats_utilization_up ;ats_utilization_down;" \
          "pref bandwidth; pref delay\n",
          c_m, c_s, experiment_name);
      if (GNUNET_SYSERR == GNUNET_DISK_file_write(f[c_s], data, strlen(data)))
        GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
            "Cannot write data to log file `%s'\n",filename_slaves[c_s]);
      GNUNET_free (data);
    }

    for (cur_lt = l->lp[c_m].head; NULL != cur_lt; cur_lt = cur_lt->next)
    {
      if (l->verbose)
        fprintf (stderr,
           "Master [%u]: timestamp %llu %llu ; %u %u %u ; %u %u %u\n",
           l->lp[c_m].peer->no,
           (long long unsigned int) cur_lt->timestamp.abs_value_us,
           (long long unsigned int) GNUNET_TIME_absolute_get_difference(l->lp[c_m].start,
               cur_lt->timestamp).rel_value_us / 1000,
           cur_lt->total_messages_sent,
           cur_lt->total_bytes_sent,
           cur_lt->total_throughput_send,
           cur_lt->total_messages_received,
           cur_lt->total_bytes_received,
           cur_lt->total_throughput_recv);

      /* Assembling master string */
      GNUNET_asprintf (&data, "%llu;%llu;%u;%u;%u;%u;%u;%u;\n",
          (long long unsigned int) cur_lt->timestamp.abs_value_us,
          (long long unsigned int) GNUNET_TIME_absolute_get_difference(l->lp[c_m].start,
              cur_lt->timestamp).rel_value_us / 1000,
          cur_lt->total_messages_sent,
          cur_lt->total_bytes_sent,
          cur_lt->total_throughput_send,
          cur_lt->total_messages_received,
          cur_lt->total_bytes_received,
          cur_lt->total_throughput_recv);

      if (GNUNET_SYSERR == GNUNET_DISK_file_write(f_m, data, strlen(data)))
        GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
            "Cannot write data to master file %u\n", c_m);
      GNUNET_free (data);


      for (c_s = 0; c_s < l->lp[c_m].peer->num_partners; c_s++)
      {
        plt = &cur_lt->slaves_log[c_s];
        /* Log partners */

        /* Assembling slave string */
        GNUNET_asprintf(&data,
            "%llu;%llu;%u;%u;%u;%u;%u;%u;%.3f;%u;%u;%u;%u;%u;%u;%u;%.3f;%.3f\n",
            (long long unsigned int) cur_lt->timestamp.abs_value_us,
            (long long unsigned int) GNUNET_TIME_absolute_get_difference(l->lp[c_m].start,
                cur_lt->timestamp).rel_value_us / 1000,
            plt->total_messages_sent,
            plt->total_bytes_sent,
            plt->throughput_sent,
            plt->total_messages_received,
            plt->total_bytes_received,
            plt->throughput_recv,
            (double) plt->app_rtt / 1000,
            plt->bandwidth_in,
            plt->bandwidth_out,
            plt->ats_delay,
            plt->ats_distance,
            plt->ats_network_type,
            plt->ats_utilization_out,
            plt->ats_utilization_in,
            plt->pref_bandwidth,
            plt->pref_delay);

        if (l->verbose)
          fprintf (stderr,
              "\t Slave [%u]: %u %u %u ; %u %u %u rtt %u delay %llu bw_in %u bw_out %u \n",
              plt->slave->no,
              plt->total_messages_sent,
              plt->total_bytes_sent,
              plt->throughput_sent,
              plt->total_messages_received,
              plt->total_bytes_received,
              plt->throughput_recv,
              plt->app_rtt,
              (long long unsigned int) plt->ats_delay.rel_value_us,
              plt->bandwidth_in,
              plt->bandwidth_out);

        if (GNUNET_SYSERR == GNUNET_DISK_file_write(f[c_s], data, strlen(data)))
          GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
              "Cannot write data to log file `%s'\n", filename_slaves[c_s]);
        GNUNET_free (data);

      }
    }

    for (c_s = 0; c_s < l->lp[c_m].peer->num_partners; c_s++)
    {
      if (GNUNET_SYSERR == GNUNET_DISK_file_close(f[c_s]))
      {
        GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
            "Cannot close log file for master[%u] slave[%u]\n", c_m, c_s);
        continue;
      }
      GNUNET_log (GNUNET_ERROR_TYPE_INFO,
          "Data file successfully written to log file for `%s'\n",
          filename_slaves[c_s]);
    }

    if (GNUNET_SYSERR == GNUNET_DISK_file_close(f_m))
    {
      GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
                                "close",
                                filename_master);
      GNUNET_free (filename_master);
      return;
    }
    GNUNET_log (GNUNET_ERROR_TYPE_INFO,
        "Data file successfully written to log file for master `%s'\n", filename_master);

    if (GNUNET_YES == plots)
    {
      write_throughput_gnuplot_script (filename_master, &l->lp[c_m], filename_slaves, l->num_slaves);
      write_rtt_gnuplot_script (filename_master, &l->lp[c_m], filename_slaves, l->num_slaves);
      write_bw_gnuplot_script (filename_master, &l->lp[c_m], filename_slaves, l->num_slaves);
    }
  }
  GNUNET_free (filename_master);
}
Exemplo n.º 2
0
/**
 * Generate between the source master and the partner and send traffic with a
 * maximum rate.
 *
 * @param src traffic source
 * @param dest traffic partner
 * @param type type of traffic to generate
 * @param base_rate traffic base rate to send data with
 * @param max_rate  traffic maximum rate to send data with
 * @param period duration of a period of traffic generation (~ 1/frequency)
 * @param duration how long to generate traffic
 * @return the traffic generator
 */
struct TrafficGenerator *
GNUNET_ATS_TEST_generate_traffic_start (struct BenchmarkPeer *src,
                                        struct BenchmarkPartner *dest,
                                        enum GeneratorType type,
                                        long int base_rate,
                                        long int max_rate,
                                        struct GNUNET_TIME_Relative period,
                                        struct GNUNET_TIME_Relative duration)
{
    struct TrafficGenerator *tg;

    if (NULL != dest->tg)
    {
        GNUNET_break (0);
        return NULL;
    }

    tg = GNUNET_new (struct TrafficGenerator);
    GNUNET_CONTAINER_DLL_insert (tg_head, tg_tail, tg);
    tg->type = type;
    tg->src = src;
    tg->dest = dest;
    tg->base_rate = base_rate;
    tg->max_rate = max_rate;
    tg->duration_period = period;
    tg->time_start = GNUNET_TIME_absolute_get();
    tg->next_ping_transmission = GNUNET_TIME_UNIT_FOREVER_ABS;

    switch (type) {
    case GNUNET_ATS_TEST_TG_CONSTANT:
        GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                    "Setting up constant traffic generator master[%u] `%s' and slave [%u] `%s' max %u Bips\n",
                    dest->me->no, GNUNET_i2s (&dest->me->id),
                    dest->dest->no, GNUNET_i2s (&dest->dest->id),
                    base_rate);
        break;
    case GNUNET_ATS_TEST_TG_LINEAR:
        GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                    "Setting up linear traffic generator master[%u] `%s' and slave [%u] `%s' min %u Bips max %u Bips\n",
                    dest->me->no, GNUNET_i2s (&dest->me->id),
                    dest->dest->no, GNUNET_i2s (&dest->dest->id),
                    base_rate, max_rate);
        break;
    case GNUNET_ATS_TEST_TG_SINUS:
        GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                    "Setting up sinus traffic generator master[%u] `%s' and slave [%u] `%s' baserate %u Bips, amplitude %u Bps\n",
                    dest->me->no, GNUNET_i2s (&dest->me->id),
                    dest->dest->no, GNUNET_i2s (&dest->dest->id),
                    base_rate, max_rate);
        break;
    case GNUNET_ATS_TEST_TG_RANDOM:
        GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                    "Setting up random traffic generator master[%u] `%s' and slave [%u] `%s' min %u Bips max %u Bps\n",
                    dest->me->no, GNUNET_i2s (&dest->me->id),
                    dest->dest->no, GNUNET_i2s (&dest->dest->id),
                    base_rate, max_rate);
        break;
    default:
        break;
    }

    if ( ((GNUNET_YES == top->test_core) && (NULL != dest->cth)) ||
            ((GNUNET_NO == top->test_core) && (NULL != dest->tth)) )
    {
        GNUNET_break (0);
        GNUNET_CONTAINER_DLL_remove (tg_head, tg_tail, tg);
        GNUNET_free (tg);
        return NULL;
    }

    dest->tg = tg;
    tg->send_task = GNUNET_SCHEDULER_add_now (&comm_schedule_send, dest);
    return tg;
}
Exemplo n.º 3
0
static int
testLocation ()
{
  struct GNUNET_FS_Uri *uri;
  char *uric;
  struct GNUNET_FS_Uri *uri2;
  struct GNUNET_FS_Uri *baseURI;
  char *emsg;
  struct GNUNET_CRYPTO_EddsaPrivateKey *pk;

  baseURI =
      GNUNET_FS_uri_parse
      ("gnunet://fs/chk/4QZP479A9SKGFNMQ2ZBCYE71YV2QMTVGWTVPB6A10ASVCKXDHB05DKPSC7ZF6E9P9W1VE47394EQY7NXA47Q6R35M7P1MJPGP59D1Z8.D54QD1K5XCG5878T6YZ19AM60MQ6FC0YNVK7QY08KK0KM0FJJ3KQWYG112FN5T07KN7J0X35DF6WVBT9B8ZMZ3X2BXJ22X3KFQ6MV2G.15999",
       &emsg);
  GNUNET_assert (baseURI != NULL);
  GNUNET_assert (emsg == NULL);
  pk = GNUNET_CRYPTO_eddsa_key_create ();
  uri = GNUNET_FS_uri_loc_create (baseURI,
                                  pk,
                                  GNUNET_TIME_absolute_get ());
  GNUNET_free (pk);
  if (NULL == uri)
  {
    GNUNET_break (0);
    GNUNET_FS_uri_destroy (baseURI);
    return 1;
  }
  if (! GNUNET_FS_uri_test_loc (uri))
  {
    GNUNET_break (0);
    GNUNET_FS_uri_destroy (uri);
    GNUNET_FS_uri_destroy (baseURI);
    return 1;
  }
  uri2 = GNUNET_FS_uri_loc_get_uri (uri);
  if (! GNUNET_FS_uri_test_equal (baseURI, uri2))
  {
    GNUNET_break (0);
    GNUNET_FS_uri_destroy (uri);
    GNUNET_FS_uri_destroy (uri2);
    GNUNET_FS_uri_destroy (baseURI);
    return 1;
  }
  GNUNET_FS_uri_destroy (uri2);
  GNUNET_FS_uri_destroy (baseURI);
  uric = GNUNET_FS_uri_to_string (uri);
#if 0
  /* not for the faint of heart: */
  printf ("URI: `%s'\n", uric);
#endif
  uri2 = GNUNET_FS_uri_parse (uric, &emsg);
  GNUNET_free (uric);
  if (uri2 == NULL)
  {
    fprintf (stderr, "URI parsing failed: %s\n", emsg);
    GNUNET_break (0);
    GNUNET_FS_uri_destroy (uri);
    GNUNET_free (emsg);
    return 1;
  }
  GNUNET_assert (NULL == emsg);
  if (GNUNET_YES != GNUNET_FS_uri_test_equal (uri, uri2))
  {
    GNUNET_break (0);
    GNUNET_FS_uri_destroy (uri);
    GNUNET_FS_uri_destroy (uri2);
    return 1;
  }
  GNUNET_FS_uri_destroy (uri2);
  GNUNET_FS_uri_destroy (uri);
  return 0;
}
Exemplo n.º 4
0
static int
check ()
{
  struct GNUNET_TIME_Absolute now;
  struct GNUNET_TIME_AbsoluteNBO nown;
  struct GNUNET_TIME_Absolute future;
  struct GNUNET_TIME_Absolute past;
  struct GNUNET_TIME_Absolute last;
  struct GNUNET_TIME_Absolute forever;
  struct GNUNET_TIME_Absolute zero;
  struct GNUNET_TIME_Relative rel;
  struct GNUNET_TIME_Relative relForever;
  struct GNUNET_TIME_Relative relUnit;
  struct GNUNET_TIME_RelativeNBO reln;
  unsigned int i;

  forever = GNUNET_TIME_UNIT_FOREVER_ABS;
  relForever = GNUNET_TIME_UNIT_FOREVER_REL;
  relUnit = GNUNET_TIME_UNIT_MILLISECONDS;
  zero.abs_value = 0;

  last = now = GNUNET_TIME_absolute_get ();
  while (now.abs_value == last.abs_value)
    now = GNUNET_TIME_absolute_get ();
  GNUNET_assert (now.abs_value > last.abs_value);

  /* test overflow checking in multiply */
  rel = GNUNET_TIME_UNIT_SECONDS;
  GNUNET_log_skip (1, GNUNET_NO);
  for (i = 0; i < 55; i++)
    rel = GNUNET_TIME_relative_multiply (rel, 2);
  GNUNET_log_skip (0, GNUNET_NO);
  GNUNET_assert (rel.rel_value == GNUNET_TIME_UNIT_FOREVER_REL.rel_value);
  /*check zero */
  rel.rel_value = (UINT64_MAX) - 1024;
  GNUNET_assert (GNUNET_TIME_UNIT_ZERO.rel_value ==
                 GNUNET_TIME_relative_multiply (rel, 0).rel_value);

  /* test infinity-check for relative to absolute */
  GNUNET_log_skip (1, GNUNET_NO);
  last = GNUNET_TIME_relative_to_absolute (rel);
  GNUNET_assert (last.abs_value == GNUNET_TIME_UNIT_FOREVER_ABS.abs_value);
  GNUNET_log_skip (0, GNUNET_YES);

  /*check relative to absolute */
  rel.rel_value = 0;
  GNUNET_assert (GNUNET_TIME_absolute_get ().abs_value ==
                 GNUNET_TIME_relative_to_absolute (rel).abs_value);
  /*check forever */
  rel.rel_value = UINT64_MAX;
  GNUNET_assert (GNUNET_TIME_UNIT_FOREVER_ABS.abs_value ==
                 GNUNET_TIME_relative_to_absolute (rel).abs_value);
  /* check overflow for r2a */
  rel.rel_value = (UINT64_MAX) - 1024;
  GNUNET_log_skip (1, GNUNET_NO);
  last = GNUNET_TIME_relative_to_absolute (rel);
  GNUNET_log_skip (0, GNUNET_NO);
  GNUNET_assert (last.abs_value == GNUNET_TIME_UNIT_FOREVER_ABS.abs_value);

  /* check overflow for relative add */
  GNUNET_log_skip (1, GNUNET_NO);
  rel = GNUNET_TIME_relative_add (rel, rel);
  GNUNET_log_skip (0, GNUNET_NO);
  GNUNET_assert (rel.rel_value == GNUNET_TIME_UNIT_FOREVER_REL.rel_value);

  GNUNET_log_skip (1, GNUNET_NO);
  rel = GNUNET_TIME_relative_add (relForever, relForever);
  GNUNET_log_skip (0, GNUNET_NO);
  GNUNET_assert (rel.rel_value == relForever.rel_value);

  GNUNET_log_skip (1, GNUNET_NO);
  rel = GNUNET_TIME_relative_add (relUnit, relUnit);
  GNUNET_assert (rel.rel_value == 2 * relUnit.rel_value);

  /* check relation check in get_duration */
  future.abs_value = now.abs_value + 1000000;
  GNUNET_assert (GNUNET_TIME_absolute_get_difference (now, future).rel_value ==
                 1000000);
  GNUNET_assert (GNUNET_TIME_absolute_get_difference (future, now).rel_value ==
                 0);

  GNUNET_assert (GNUNET_TIME_absolute_get_difference (zero, forever).rel_value
                 == forever.abs_value);

  past.abs_value = now.abs_value - 1000000;
  rel = GNUNET_TIME_absolute_get_duration (future);
  GNUNET_assert (rel.rel_value == 0);
  rel = GNUNET_TIME_absolute_get_duration (past);
  GNUNET_assert (rel.rel_value >= 1000000);

  /* check get remaining */
  rel = GNUNET_TIME_absolute_get_remaining (now);
  GNUNET_assert (rel.rel_value == 0);
  rel = GNUNET_TIME_absolute_get_remaining (past);
  GNUNET_assert (rel.rel_value == 0);
  rel = GNUNET_TIME_absolute_get_remaining (future);
  GNUNET_assert (rel.rel_value > 0);
  GNUNET_assert (rel.rel_value <= 1000000);
  forever = GNUNET_TIME_UNIT_FOREVER_ABS;
  GNUNET_assert (GNUNET_TIME_UNIT_FOREVER_REL.rel_value ==
                 GNUNET_TIME_absolute_get_remaining (forever).rel_value);

  /* check endianess */
  reln = GNUNET_TIME_relative_hton (rel);
  GNUNET_assert (rel.rel_value == GNUNET_TIME_relative_ntoh (reln).rel_value);
  nown = GNUNET_TIME_absolute_hton (now);
  GNUNET_assert (now.abs_value == GNUNET_TIME_absolute_ntoh (nown).abs_value);

  /* check absolute addition */
  future = GNUNET_TIME_absolute_add (now, GNUNET_TIME_UNIT_SECONDS);
  GNUNET_assert (future.abs_value == now.abs_value + 1000);

  future = GNUNET_TIME_absolute_add (forever, GNUNET_TIME_UNIT_ZERO);
  GNUNET_assert (future.abs_value == forever.abs_value);

  rel.rel_value = (UINT64_MAX) - 1024;
  now.abs_value = rel.rel_value;
  future = GNUNET_TIME_absolute_add (now, rel);
  GNUNET_assert (future.abs_value == forever.abs_value);

  /* check zero */
  future = GNUNET_TIME_absolute_add (now, GNUNET_TIME_UNIT_ZERO);
  GNUNET_assert (future.abs_value == now.abs_value);

  GNUNET_assert (forever.abs_value ==
                 GNUNET_TIME_absolute_subtract (forever,
                                                GNUNET_TIME_UNIT_MINUTES).abs_value);
  /*check absolute subtract */
  now.abs_value = 50000;
  rel.rel_value = 100000;
  GNUNET_assert (GNUNET_TIME_UNIT_ZERO_ABS.abs_value ==
                 (GNUNET_TIME_absolute_subtract (now, rel)).abs_value);
  rel.rel_value = 10000;
  GNUNET_assert (40000 == (GNUNET_TIME_absolute_subtract (now, rel)).abs_value);

  /*check relative divide */
  GNUNET_assert (GNUNET_TIME_UNIT_FOREVER_REL.rel_value ==
                 (GNUNET_TIME_relative_divide (rel, 0)).rel_value);

  rel = GNUNET_TIME_UNIT_FOREVER_REL;
  GNUNET_assert (GNUNET_TIME_UNIT_FOREVER_REL.rel_value ==
                 (GNUNET_TIME_relative_divide (rel, 2)).rel_value);

  rel = GNUNET_TIME_relative_divide (relUnit, 2);
  GNUNET_assert (rel.rel_value == relUnit.rel_value / 2);


  /* check Return absolute time of 0ms */
  zero = GNUNET_TIME_UNIT_ZERO_ABS;

  /* check GNUNET_TIME_calculate_eta */
  last.abs_value = GNUNET_TIME_absolute_get ().abs_value - 1024;
  forever = GNUNET_TIME_UNIT_FOREVER_ABS;
  forever.abs_value = forever.abs_value - 1024;
  GNUNET_assert (GNUNET_TIME_UNIT_ZERO_ABS.abs_value ==
                 GNUNET_TIME_calculate_eta (forever, 50000, 100000).rel_value);
  /* check zero */
  GNUNET_log_skip (1, GNUNET_NO);
  GNUNET_assert (GNUNET_TIME_UNIT_ZERO.rel_value ==
                 (GNUNET_TIME_calculate_eta (last, 60000, 50000)).rel_value);
  GNUNET_log_skip (0, GNUNET_YES);
  /*check forever */
  GNUNET_assert (GNUNET_TIME_UNIT_FOREVER_REL.rel_value ==
                 (GNUNET_TIME_calculate_eta (last, 0, 50000)).rel_value);

  /*check relative subtract */
  now = GNUNET_TIME_absolute_get ();
  rel.rel_value = now.abs_value;
  relForever.rel_value = rel.rel_value + 1024;
  GNUNET_assert (1024 ==
                 GNUNET_TIME_relative_subtract (relForever, rel).rel_value);
  /*check zero */
  GNUNET_assert (GNUNET_TIME_UNIT_ZERO.rel_value ==
                 GNUNET_TIME_relative_subtract (rel, relForever).rel_value);
  /*check forever */
  rel.rel_value = UINT64_MAX;
  GNUNET_assert (GNUNET_TIME_UNIT_FOREVER_REL.rel_value ==
                 GNUNET_TIME_relative_subtract (rel, relForever).rel_value);

  /*check GNUNET_TIME_relative_min */
  now = GNUNET_TIME_absolute_get ();
  rel.rel_value = now.abs_value;
  relForever.rel_value = rel.rel_value - 1024;
  GNUNET_assert (relForever.rel_value ==
                 GNUNET_TIME_relative_min (rel, relForever).rel_value);

  /*check GNUNET_TIME_relative_max */
  GNUNET_assert (rel.rel_value ==
                 GNUNET_TIME_relative_max (rel, relForever).rel_value);

  /*check GNUNET_TIME_absolute_min */
  now = GNUNET_TIME_absolute_get ();
  last.abs_value = now.abs_value - 1024;
  GNUNET_assert (last.abs_value ==
                 GNUNET_TIME_absolute_min (now, last).abs_value);

  /*check  GNUNET_TIME_absolute_max */
  GNUNET_assert (now.abs_value ==
                 GNUNET_TIME_absolute_max (now, last).abs_value);

  return 0;
}
Exemplo n.º 5
0
/**
 * Try to read the HELLOs in the given filename and discard expired
 * addresses.  Removes the file if one the HELLO is malformed.  If all
 * addresses are expired, the HELLO is also removed (but the HELLO
 * with the public key is still returned if it was found and valid).
 * The file can contain multiple HELLO messages.
 *
 * @param fn name of the file
 * @param unlink_garbage if #GNUNET_YES, try to remove useless files
 * @param r ReadHostFileContext to store the resutl
 */
static void
read_host_file (const char *fn,
                int unlink_garbage,
                struct ReadHostFileContext *r)
{
  char buffer[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1] GNUNET_ALIGN;
  unsigned int size_total;
  struct GNUNET_TIME_Absolute now;
  unsigned int left;
  const struct GNUNET_HELLO_Message *hello;
  struct GNUNET_HELLO_Message *hello_clean;
  unsigned read_pos;
  int size_hello;

  r->friend_only_hello = NULL;
  r->hello = NULL;

  if (GNUNET_YES != GNUNET_DISK_file_test (fn))
    return;
  size_total = GNUNET_DISK_fn_read (fn, buffer, sizeof (buffer));
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Read %u bytes from `%s'\n",
              size_total,
              fn);
  if (size_total < sizeof (struct GNUNET_MessageHeader))
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
		_("Failed to parse HELLO in file `%s': %s\n"),
		fn, "Fail has invalid size");
    if ( (GNUNET_YES == unlink_garbage) &&
	 (0 != UNLINK (fn)) &&
	 (ENOENT != errno) )
      GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
                                "unlink",
                                fn);
    return;
  }

  read_pos = 0;
  while (read_pos < size_total)
  {
    hello = (const struct GNUNET_HELLO_Message *) &buffer[read_pos];
    size_hello = GNUNET_HELLO_size (hello);
    if ( (0 == size_hello) ||
         (size_total - read_pos < size_hello) )
    {
      GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                  _("Failed to parse HELLO in file `%s'\n"),
                  fn);
      if (0 == read_pos)
      {
        if ((GNUNET_YES == unlink_garbage) &&
            (0 != UNLINK (fn)) &&
            (ENOENT != errno) )
          GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
                                    "unlink",
                                    fn);
      }
      else
      {
        if ((GNUNET_YES == unlink_garbage) &&
            (0 != TRUNCATE (fn, read_pos)) &&
            (ENOENT != errno) )
          GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
                                    "truncate",
                                    fn);
      }
      return;
    }

    now = GNUNET_TIME_absolute_get ();
    hello_clean = GNUNET_HELLO_iterate_addresses (hello, GNUNET_YES,
						  &discard_expired, &now);
    if (NULL == hello_clean)
    {
      GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                  _("Failed to parse HELLO in file `%s'\n"),
                  fn);
      if ((GNUNET_YES == unlink_garbage) &&
          (0 != UNLINK (fn)) &&
          (ENOENT != errno) )
        GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
                                  "unlink",
                                  fn);
      return;
    }
    left = 0;
    (void) GNUNET_HELLO_iterate_addresses (hello_clean, GNUNET_NO,
					   &count_addresses, &left);

    if (0 == left)
    {
      GNUNET_free (hello_clean);
      break;
    }

    if (GNUNET_NO == GNUNET_HELLO_is_friend_only (hello_clean))
    {
      if (NULL == r->hello)
	r->hello = hello_clean;
      else
      {
	GNUNET_break (0);
	GNUNET_free (r->hello);
	r->hello = hello_clean;
      }
    }
    else
    {
      if (NULL == r->friend_only_hello)
	r->friend_only_hello = hello_clean;
      else
      {
	GNUNET_break (0);
	GNUNET_free (r->friend_only_hello);
	r->friend_only_hello = hello_clean;
      }
    }
    read_pos += size_hello;
  }

  if (0 == left)
  {
    /* no addresses left, remove from disk */
    if ( (GNUNET_YES == unlink_garbage) &&
         (0 != UNLINK (fn)) )
      GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
                                "unlink",
                                fn);
  }
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
	      "Found `%s' and `%s' HELLO message in file\n",
	      (NULL != r->hello) ? "public" : "NON-public",
	      (NULL != r->friend_only_hello) ? "friend only" : "NO friend only");
}
Exemplo n.º 6
0
/**
 * Figure out when and how to transmit to the given peer.
 *
 * @param cls the `struct PeerPlan`
 */
static void
schedule_peer_transmission (void *cls)
{
  struct PeerPlan *pp = cls;
  struct GSF_RequestPlan *rp;
  struct GNUNET_TIME_Relative delay;

  if (NULL != pp->task)
  {
    pp->task = NULL;
  }
  else
  {
    GNUNET_assert (NULL != pp->env);
    pp->env = NULL;
  }
  /* move ready requests to priority queue */
  while ((NULL != (rp = GNUNET_CONTAINER_heap_peek (pp->delay_heap))) &&
         (0 == GNUNET_TIME_absolute_get_remaining
          (rp->earliest_transmission).rel_value_us))
  {
    GNUNET_assert (rp == GNUNET_CONTAINER_heap_remove_root (pp->delay_heap));
    rp->hn = GNUNET_CONTAINER_heap_insert (pp->priority_heap,
                                           rp,
                                           rp->priority);
  }
  if (0 == GNUNET_CONTAINER_heap_get_size (pp->priority_heap))
  {
    /* priority heap (still) empty, check for delay... */
    rp = GNUNET_CONTAINER_heap_peek (pp->delay_heap);
    if (NULL == rp)
    {
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                  "No active requests for plan %p.\n",
                  pp);
      return;                   /* both queues empty */
    }
    delay = GNUNET_TIME_absolute_get_remaining (rp->earliest_transmission);
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                "Sleeping for %s before retrying requests on plan %p.\n",
                GNUNET_STRINGS_relative_time_to_string (delay,
							GNUNET_YES),
		pp);
    GNUNET_STATISTICS_set (GSF_stats,
                           gettext_noop ("# delay heap timeout (ms)"),
                           delay.rel_value_us / 1000LL, GNUNET_NO);

    pp->task =
        GNUNET_SCHEDULER_add_delayed (delay,
                                      &schedule_peer_transmission,
                                      pp);
    return;
  }
#if INSANE_STATISTICS
  GNUNET_STATISTICS_update (GSF_stats,
			    gettext_noop ("# query plans executed"),
                            1,
			    GNUNET_NO);
#endif
  /* process from priority heap */
  rp = GNUNET_CONTAINER_heap_remove_root (pp->priority_heap);
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Executing query plan %p\n",
              rp);
  GNUNET_assert (NULL != rp);
  rp->hn = NULL;
  rp->last_transmission = GNUNET_TIME_absolute_get ();
  rp->transmission_counter++;
  total_delay++;
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Executing plan %p executed %u times, planning retransmission\n",
              rp,
	      rp->transmission_counter);
  GNUNET_assert (NULL == pp->env);
  pp->env = GSF_pending_request_get_message_ (get_latest (rp));
  GNUNET_MQ_notify_sent (pp->env,
			 &schedule_peer_transmission,
			 pp);
  GSF_peer_transmit_ (pp->cp,
		      GNUNET_YES,
		      rp->priority,
		      pp->env);
  GNUNET_STATISTICS_update (GSF_stats,
                            gettext_noop ("# query messages sent to other peers"),
                            1,
                            GNUNET_NO);
  plan (pp,
	rp);
}
Exemplo n.º 7
0
static void
run (void *cls,
     const struct GNUNET_CONFIGURATION_Handle *c,
     struct GNUNET_TESTING_Peer *peer)
{
  const char *keywords[] = {
    "down_foo",
    "down_bar",
  };
  char *buf;
  struct GNUNET_CONTAINER_MetaData *meta;
  struct GNUNET_FS_Uri *kuri;
  struct GNUNET_FS_FileInformation *fi1;
  struct GNUNET_FS_FileInformation *fi2;
  struct GNUNET_FS_FileInformation *fidir;
  size_t i;
  struct GNUNET_FS_BlockOptions bo;

  cfg = c;
  fs = GNUNET_FS_start (cfg, "test-fs-publish-persistence", &progress_cb, NULL,
                        GNUNET_FS_FLAGS_PERSISTENCE, GNUNET_FS_OPTIONS_END);
  GNUNET_assert (NULL != fs);
  fn1 = GNUNET_DISK_mktemp ("gnunet-publish-test-dst");
  buf = GNUNET_malloc (FILESIZE);
  for (i = 0; i < FILESIZE; i++)
    buf[i] = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 256);
  GNUNET_assert (FILESIZE ==
                 GNUNET_DISK_fn_write (fn1, buf, FILESIZE,
                                       GNUNET_DISK_PERM_USER_READ |
                                       GNUNET_DISK_PERM_USER_WRITE));
  GNUNET_free (buf);

  fn2 = GNUNET_DISK_mktemp ("gnunet-publish-test-dst");
  buf = GNUNET_malloc (FILESIZE);
  for (i = 0; i < FILESIZE; i++)
    buf[i] = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 256);
  GNUNET_assert (FILESIZE ==
                 GNUNET_DISK_fn_write (fn2, buf, FILESIZE,
                                       GNUNET_DISK_PERM_USER_READ |
                                       GNUNET_DISK_PERM_USER_WRITE));
  GNUNET_free (buf);

  meta = GNUNET_CONTAINER_meta_data_create ();
  kuri = GNUNET_FS_uri_ksk_create_from_args (2, keywords);
  bo.content_priority = 42;
  bo.anonymity_level = 1;
  bo.replication_level = 0;
  bo.expiration_time = GNUNET_TIME_relative_to_absolute (LIFETIME);
  fi1 =
      GNUNET_FS_file_information_create_from_file (fs, "publish-context1", fn1,
                                                   kuri, meta, GNUNET_YES, &bo);
  GNUNET_assert (NULL != fi1);
  bo.anonymity_level = 2;
  fi2 =
      GNUNET_FS_file_information_create_from_file (fs, "publish-context2", fn2,
                                                   kuri, meta, GNUNET_YES, &bo);
  GNUNET_assert (NULL != fi2);
  bo.anonymity_level = 3;
  fidir =
      GNUNET_FS_file_information_create_empty_directory (fs,
                                                         "publish-context-dir",
                                                         kuri, meta, &bo, NULL);
  GNUNET_assert (GNUNET_OK == GNUNET_FS_file_information_add (fidir, fi1));
  GNUNET_assert (GNUNET_OK == GNUNET_FS_file_information_add (fidir, fi2));
  GNUNET_FS_uri_destroy (kuri);
  GNUNET_CONTAINER_meta_data_destroy (meta);
  GNUNET_assert (NULL != fidir);
  start = GNUNET_TIME_absolute_get ();
  GNUNET_FS_publish_start (fs, fidir, NULL, NULL, NULL,
                           GNUNET_FS_PUBLISH_OPTION_NONE);
  GNUNET_assert (publish != NULL);
}
Exemplo n.º 8
0
/**
 * Notification of FS that a search probe has made progress.
 * This function is used INSTEAD of the client's event handler
 * for downloads where the #GNUNET_FS_DOWNLOAD_IS_PROBE flag is set.
 *
 * @param cls closure, always NULL (!), actual closure
 *        is in the client-context of the info struct
 * @param info details about the event, specifying the event type
 *        and various bits about the event
 * @return client-context (for the next progress call
 *         for this operation; should be set to NULL for
 *         SUSPEND and STOPPED events).  The value returned
 *         will be passed to future callbacks in the respective
 *         field in the `struct GNUNET_FS_ProgressInfo`.
 */
void *
GNUNET_FS_search_probe_progress_ (void *cls,
                                  const struct GNUNET_FS_ProgressInfo *info)
{
  struct GNUNET_FS_SearchResult *sr = info->value.download.cctx;
  struct GNUNET_TIME_Relative dur;

  switch (info->status)
  {
  case GNUNET_FS_STATUS_DOWNLOAD_START:
    /* ignore */
    break;
  case GNUNET_FS_STATUS_DOWNLOAD_RESUME:
    /* probes should never be resumed */
    GNUNET_assert (0);
    break;
  case GNUNET_FS_STATUS_DOWNLOAD_SUSPEND:
    /* probes should never be suspended */
    GNUNET_break (0);
    break;
  case GNUNET_FS_STATUS_DOWNLOAD_PROGRESS:
    /* ignore */
    break;
  case GNUNET_FS_STATUS_DOWNLOAD_ERROR:
    if (GNUNET_SCHEDULER_NO_TASK != sr->probe_cancel_task)
    {
      GNUNET_SCHEDULER_cancel (sr->probe_cancel_task);
      sr->probe_cancel_task = GNUNET_SCHEDULER_NO_TASK;
    }
    sr->probe_cancel_task =
        GNUNET_SCHEDULER_add_delayed (sr->remaining_probe_time,
                                      &probe_failure_handler, sr);
    break;
  case GNUNET_FS_STATUS_DOWNLOAD_COMPLETED:
    if (GNUNET_SCHEDULER_NO_TASK != sr->probe_cancel_task)
    {
      GNUNET_SCHEDULER_cancel (sr->probe_cancel_task);
      sr->probe_cancel_task = GNUNET_SCHEDULER_NO_TASK;
    }
    sr->probe_cancel_task =
        GNUNET_SCHEDULER_add_now (&probe_success_handler, sr);
    break;
  case GNUNET_FS_STATUS_DOWNLOAD_STOPPED:
    if (GNUNET_SCHEDULER_NO_TASK != sr->probe_cancel_task)
    {
      GNUNET_SCHEDULER_cancel (sr->probe_cancel_task);
      sr->probe_cancel_task = GNUNET_SCHEDULER_NO_TASK;
    }
    sr = NULL;
    break;
  case GNUNET_FS_STATUS_DOWNLOAD_ACTIVE:
    if (GNUNET_SCHEDULER_NO_TASK == sr->probe_cancel_task)
    {
      sr->probe_active_time = GNUNET_TIME_absolute_get ();
      sr->probe_cancel_task =
        GNUNET_SCHEDULER_add_delayed (sr->remaining_probe_time,
                                      &probe_failure_handler, sr);
    }
    break;
  case GNUNET_FS_STATUS_DOWNLOAD_INACTIVE:
    if (GNUNET_SCHEDULER_NO_TASK != sr->probe_cancel_task)
    {
      GNUNET_SCHEDULER_cancel (sr->probe_cancel_task);
      sr->probe_cancel_task = GNUNET_SCHEDULER_NO_TASK;
    }
    dur = GNUNET_TIME_absolute_get_duration (sr->probe_active_time);
    sr->remaining_probe_time =
        GNUNET_TIME_relative_subtract (sr->remaining_probe_time, dur);
    if (0 == sr->remaining_probe_time.rel_value_us)
      sr->probe_cancel_task =
        GNUNET_SCHEDULER_add_now (&probe_failure_handler, sr);
    GNUNET_FS_search_result_sync_ (sr);
    break;
  default:
    GNUNET_break (0);
    return NULL;
  }
  return sr;
}
Exemplo n.º 9
0
static void
run (void *cls, char *const *args, const char *cfgfile,
     const struct GNUNET_CONFIGURATION_Handle *cfg)
{
  struct GNUNET_DATACACHE_Handle *h;
  struct GNUNET_HashCode k;
  struct GNUNET_HashCode n;
  struct GNUNET_TIME_Absolute exp;
  struct GNUNET_TIME_Absolute start;
  unsigned int i;
  char gstr[128];

  ok = 0;
  h = GNUNET_DATACACHE_create (cfg, "perfcache");

  if (h == NULL)
  {
    FPRINTF (stderr, "%s", "Failed to initialize datacache.  Database likely not setup, skipping test.\n");
    ok = 77; /* mark test as skipped */
    return;
  }
  exp = GNUNET_TIME_relative_to_absolute (GNUNET_TIME_UNIT_HOURS);
  start = GNUNET_TIME_absolute_get ();
  memset (&k, 0, sizeof (struct GNUNET_HashCode));
  for (i = 0; i < ITERATIONS; i++)
  {
    if (0 == i % (ITERATIONS / 80))
      FPRINTF (stderr, "%s",  ".");
    GNUNET_CRYPTO_hash (&k, sizeof (struct GNUNET_HashCode), &n);
    ASSERT (GNUNET_OK ==
            GNUNET_DATACACHE_put (h, &k, sizeof (struct GNUNET_HashCode),
                                  (const char *) &n, 1 + i % 16, exp,
				  0, NULL));
    k = n;
  }
  FPRINTF (stderr, "%s",  "\n");
  FPRINTF (stdout, "Stored %u items in %s\n", ITERATIONS,
	   GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (start), GNUNET_YES));
  GNUNET_snprintf (gstr, sizeof (gstr), "DATACACHE-%s", plugin_name);
  GAUGER (gstr, "Time to PUT item in datacache",
          GNUNET_TIME_absolute_get_duration (start).rel_value_us / 1000LL / ITERATIONS,
          "ms/item");
  start = GNUNET_TIME_absolute_get ();
  memset (&k, 0, sizeof (struct GNUNET_HashCode));
  for (i = 0; i < ITERATIONS; i++)
  {
    if (0 == i % (ITERATIONS / 80))
      FPRINTF (stderr, "%s",  ".");
    GNUNET_CRYPTO_hash (&k, sizeof (struct GNUNET_HashCode), &n);
    GNUNET_DATACACHE_get (h, &k, 1 + i % 16, &checkIt, &n);
    k = n;
  }
  FPRINTF (stderr, "%s",  "\n");
  FPRINTF (stdout,
           "Found %u/%u items in %s (%u were deleted during storage processing)\n",
           found, ITERATIONS,
           GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (start), GNUNET_YES),
           ITERATIONS - found);
  if (found > 0)
    GAUGER (gstr, "Time to GET item from datacache",
            GNUNET_TIME_absolute_get_duration (start).rel_value_us / 1000LL / found,
            "ms/item");
  GNUNET_DATACACHE_destroy (h);
  ASSERT (ok == 0);
  return;
FAILURE:
  if (h != NULL)
    GNUNET_DATACACHE_destroy (h);
  ok = GNUNET_SYSERR;
}
/**
 * This function updates the old token with new attributes,
 * removes deleted attributes and expiration times.
 *
 * @param cls the ego entry
 * @param tc task context
 */
static void
handle_token_update (void *cls,
                     const struct GNUNET_SCHEDULER_TaskContext *tc)
{
  char *token_header;
  char *token_payload;
  char *token_payload_json;
  char *new_token;
  char *new_payload_str;
  char *new_payload_base64;
  char *sig_str;
  char *key;
  char *padding;
  const struct GNUNET_CRYPTO_EcdsaPrivateKey *priv_key;
  struct EgoEntry *ego_entry = cls;
  struct GNUNET_GNSRECORD_Data token_record;
  struct GNUNET_CRYPTO_EccSignaturePurpose *purpose;
  struct GNUNET_CRYPTO_EcdsaSignature sig;
  struct GNUNET_HashCode key_hash;
  struct GNUNET_TIME_Relative token_rel_exp;
  struct GNUNET_TIME_Relative token_ttl;
  struct GNUNET_TIME_Absolute token_exp;
  struct GNUNET_TIME_Absolute token_nbf;
  struct GNUNET_TIME_Absolute new_exp;
  struct GNUNET_TIME_Absolute new_iat;
  struct GNUNET_TIME_Absolute new_nbf;
  json_t *payload_json;
  json_t *value;
  json_t *cur_value;
  json_t *new_payload_json;
  json_t *token_nbf_json;
  json_t *token_exp_json;
  json_error_t json_err;

  priv_key = GNUNET_IDENTITY_ego_get_private_key (ego_entry->ego);

  //Note: We need the token expiration time here. Not the record expiration
  //time.
  //There are two types of tokens: Token that expire on GNS level with
  //an absolute expiration time. Those are basically tokens that will
  //be automatically revoked on (record)expiration.
  //Tokens stored with relative expiration times will expire on the token level (token expiration)
  //but this service will reissue new tokens that can be retrieved from GNS
  //automatically.

  token_header = strtok (token, ".");

  token_payload = strtok (NULL, ".");

  GNUNET_STRINGS_base64_decode (token_payload,
                                strlen (token_payload),
                                &token_payload_json);

  payload_json = json_loads (token_payload_json, JSON_DECODE_ANY, &json_err);
  GNUNET_free (token_payload_json);

  token_exp_json = json_object_get (payload_json, "exp");
  token_nbf_json = json_object_get (payload_json, "nbf");
  token_exp.abs_value_us = json_integer_value(token_exp_json);
  token_nbf.abs_value_us = json_integer_value(token_nbf_json);
  token_rel_exp = GNUNET_TIME_absolute_get_difference (token_nbf, token_exp);

  token_ttl = GNUNET_TIME_absolute_get_remaining (token_exp);
  if (0 != GNUNET_TIME_absolute_get_remaining (token_exp).rel_value_us)
  {
    //This token is not yet expired! Save and skip
    if (min_rel_exp.rel_value_us > token_ttl.rel_value_us)
    {
      min_rel_exp = token_ttl;
    }
    json_decref (payload_json);
    GNUNET_free (token);
    token = NULL;
    GNUNET_free (label);
    label = NULL;
    GNUNET_NAMESTORE_zone_iterator_next (ns_it);
    return;
  }
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Token is expired. Create a new one\n");
  new_exp = GNUNET_TIME_relative_to_absolute (token_rel_exp);
  new_nbf = GNUNET_TIME_absolute_get ();
  new_iat = new_nbf;
  new_payload_json = json_object();
  json_object_foreach(payload_json, key, value) {
    if (0 == strcmp (key, "exp"))
    {
      json_object_set_new (new_payload_json, key, json_integer (new_exp.abs_value_us));
    }
    else if (0 == strcmp (key, "nbf"))
    {
      json_object_set_new (new_payload_json, key, json_integer (new_nbf.abs_value_us));
    }
    else if (0 == strcmp (key, "iat"))
    {
      json_object_set_new (new_payload_json, key, json_integer (new_iat.abs_value_us));
    }
    else if ((0 == strcmp (key, "iss"))
             || (0 == strcmp (key, "aud"))
             || (0 == strcmp (key, "sub"))
             || (0 == strcmp (key, "rnl")))
    {
      json_object_set (new_payload_json, key, value);
    }
    else {
      GNUNET_CRYPTO_hash (key,
                          strlen (key),
                          &key_hash);
      //Check if attr still exists. omit of not
      if (GNUNET_NO != GNUNET_CONTAINER_multihashmap_contains (ego_entry->attr_map,
                                                               &key_hash))
      {
        cur_value = GNUNET_CONTAINER_multihashmap_get (ego_entry->attr_map,
                                                       &key_hash);
        json_object_set (new_payload_json, key, cur_value);
      }
    }
  }

  // reassemble and set
  new_payload_str = json_dumps (new_payload_json, JSON_COMPACT);
  json_decref (payload_json);
  json_decref (new_payload_json);
  GNUNET_STRINGS_base64_encode (new_payload_str,
                                strlen (new_payload_str),
                                &new_payload_base64);
  //Remove padding
  padding = strtok(new_payload_base64, "=");
  while (NULL != padding)
    padding = strtok(NULL, "=");

  GNUNET_asprintf (&new_token, "%s,%s", token_header, new_payload_base64);
  purpose =
    GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
                   strlen (new_token));
  purpose->size =
    htonl (strlen (new_token) + sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose));
  purpose->purpose = htonl(GNUNET_SIGNATURE_PURPOSE_GNUID_TOKEN);
  memcpy (&purpose[1], new_token, strlen (new_token));
  if (GNUNET_OK != GNUNET_CRYPTO_ecdsa_sign (priv_key,
                                             purpose,
                                             &sig))
    GNUNET_break(0);
  GNUNET_free (new_token);
  sig_str = GNUNET_STRINGS_data_to_string_alloc (&sig,
                                                 sizeof (struct GNUNET_CRYPTO_EcdsaSignature));
  GNUNET_asprintf (&new_token, "%s.%s.%s",
                   token_header, new_payload_base64, sig_str);
  GNUNET_free (sig_str);
  GNUNET_free (new_payload_str);
  GNUNET_free (new_payload_base64);
  GNUNET_free (purpose);

  token_record.data = new_token;
  token_record.data_size = strlen (new_token);
  token_record.expiration_time = new_exp.abs_value_us;
  token_record.record_type = GNUNET_GNSRECORD_TYPE_ID_TOKEN;
  token_record.flags = GNUNET_GNSRECORD_RF_NONE | GNUNET_GNSRECORD_RF_RELATIVE_EXPIRATION;
  ns_qe = GNUNET_NAMESTORE_records_store (ns_handle,
                                          priv_key,
                                          label,
                                          1,
                                          &token_record,
                                          &store_token_cont,
                                          ego_entry);
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, ">>> Updating Token w/ %s\n", new_token);
  GNUNET_free (new_token);
  GNUNET_free (token);
  token = NULL;
  GNUNET_free (label);
  label = NULL;
}
Exemplo n.º 11
0
/**
 * Information callback for the solver
 *
 * @param op the solver operation
 * @param stat status of the solver operation
 * @param add additional solver information
 */
static void
solver_info_cb (void *cls,
    enum GAS_Solver_Operation op,
    enum GAS_Solver_Status stat,
    enum GAS_Solver_Additional_Information add)
{
  char *add_info;
  switch (add) {
    case GAS_INFO_NONE:
      add_info = "GAS_INFO_NONE";
      break;
    case GAS_INFO_FULL:
      add_info = "GAS_INFO_MLP_FULL";
      break;
    case GAS_INFO_UPDATED:
      add_info = "GAS_INFO_MLP_UPDATED";
      break;
    case GAS_INFO_PROP_ALL:
      add_info = "GAS_INFO_PROP_ALL";
      break;
    case GAS_INFO_PROP_SINGLE:
      add_info = "GAS_INFO_PROP_SINGLE";
      break;
    default:
      add_info = "INVALID";
      break;
  }

  struct Result *tmp;
  switch (op)
  {
    case GAS_OP_SOLVE_START:
      GNUNET_log(GNUNET_ERROR_TYPE_INFO,
          "Solver notifies `%s' with result `%s' `%s'\n", "GAS_OP_SOLVE_START",
          (GAS_STAT_SUCCESS == stat) ? "SUCCESS" : "FAIL", add_info);
      if (GNUNET_NO == ph.expecting_solution)
      {
        /* We do not expect a solution at the moment */
        GNUNET_break (0);
        return;
      }

      if ((GAS_STAT_SUCCESS == stat) && (NULL == ph.current_result))
      {
        tmp = GNUNET_new (struct Result);
        /* Create new result */
        if ((add == GAS_INFO_UPDATED) || (GNUNET_YES == ph.performed_update))
        {
          ph.current_result = tmp;
          //fprintf (stderr,"UPDATE %u %u\n",ph.current_iteration-1, ph.current_p);
          ph.iterations_results[ph.current_iteration-1].update_results_array[ph.current_p] = tmp;
        }
        else
        {
          ph.current_result = tmp;
          //fprintf (stderr,"FULL %u %u\n",ph.current_iteration-1, ph.current_p);
          ph.iterations_results[ph.current_iteration-1].results_array[ph.current_p] = tmp;
        }

        ph.current_result->addresses = ph.current_a;
        ph.current_result->peers = ph.current_p;
        ph.current_result->s_total = GNUNET_TIME_absolute_get();
        ph.current_result->d_total_full = GNUNET_TIME_UNIT_FOREVER_REL;
        ph.current_result->d_setup_full = GNUNET_TIME_UNIT_FOREVER_REL;
        ph.current_result->d_lp_full = GNUNET_TIME_UNIT_FOREVER_REL;
        ph.current_result->d_mlp_full = GNUNET_TIME_UNIT_FOREVER_REL;
        ph.current_result->info = add;
        if ((add == GAS_INFO_UPDATED) || (GNUNET_YES == ph.performed_update))
        {
          ph.current_result->update = GNUNET_YES;
        }
        else
        {
          ph.current_result->update = GNUNET_NO;
        }

      }
      return;
    case GAS_OP_SOLVE_STOP:
      GNUNET_log(GNUNET_ERROR_TYPE_INFO,
          "Solver notifies `%s' with result `%s', `%s'\n", "GAS_OP_SOLVE_STOP",
          (GAS_STAT_SUCCESS == stat) ? "SUCCESS" : "FAIL", add_info);
      if ((GNUNET_NO == ph.expecting_solution) || (NULL == ph.current_result))
      {
        /* We do not expect a solution at the moment */
        GNUNET_break (0);
        return;
      }

      if (GAS_STAT_SUCCESS == stat)
        ph.current_result->valid = GNUNET_YES;
      else
        ph.current_result->valid = GNUNET_NO;

      if (NULL != ph.current_result)
      {
        /* Finalize result */
        ph.current_result->e_total = GNUNET_TIME_absolute_get ();
        ph.current_result->d_total_full = GNUNET_TIME_absolute_get_difference (
            ph.current_result->s_total, ph.current_result->e_total);
      }
      ph.current_result = NULL;
      return;

    case GAS_OP_SOLVE_SETUP_START:
      GNUNET_log(GNUNET_ERROR_TYPE_INFO,
          "Solver notifies `%s' with result `%s'\n", "GAS_OP_SOLVE_SETUP_START",
          (GAS_STAT_SUCCESS == stat) ? "SUCCESS" : "FAIL");
      if ((GNUNET_NO == ph.expecting_solution) || (NULL == ph.current_result))
      {
        GNUNET_break(0);
        return;
      }

      if (GAS_STAT_SUCCESS == stat)
        ph.current_result->valid = GNUNET_YES;
      else
        ph.current_result->valid = GNUNET_NO;

      ph.current_result->s_setup = GNUNET_TIME_absolute_get ();
      return;

    case GAS_OP_SOLVE_SETUP_STOP:
      GNUNET_log(GNUNET_ERROR_TYPE_INFO,
          "Solver notifies `%s' with result `%s'\n", "GAS_OP_SOLVE_SETUP_STOP",
          (GAS_STAT_SUCCESS == stat) ? "SUCCESS" : "FAIL");
      if ((GNUNET_NO == ph.expecting_solution) || (NULL == ph.current_result))
      {
        GNUNET_break(0);
        return;
      }

      if (GAS_STAT_SUCCESS == stat)
        ph.current_result->valid = GNUNET_YES;
      else
        ph.current_result->valid = GNUNET_NO;

      ph.current_result->e_setup = GNUNET_TIME_absolute_get ();
      ph.current_result->d_setup_full = GNUNET_TIME_absolute_get_difference (
          ph.current_result->s_setup, ph.current_result->e_setup);
      return;

    case GAS_OP_SOLVE_MLP_LP_START:
      GNUNET_log(GNUNET_ERROR_TYPE_INFO,
          "Solver notifies `%s' with result `%s'\n", "GAS_OP_SOLVE_LP_START",
          (GAS_STAT_SUCCESS == stat) ? "SUCCESS" : "FAIL");
      if ((GNUNET_NO == ph.expecting_solution) || (NULL == ph.current_result))
      {
        GNUNET_break(0);
        return;
      }

      if (GAS_STAT_SUCCESS == stat)
        ph.current_result->valid = GNUNET_YES;
      else
        ph.current_result->valid = GNUNET_NO;

      ph.current_result->s_lp = GNUNET_TIME_absolute_get ();
      return;
    case GAS_OP_SOLVE_MLP_LP_STOP:
      GNUNET_log(GNUNET_ERROR_TYPE_INFO,
          "Solver notifies `%s' with result `%s'\n", "GAS_OP_SOLVE_LP_STOP",
          (GAS_STAT_SUCCESS == stat) ? "SUCCESS" : "FAIL");
      if ((GNUNET_NO == ph.expecting_solution) || (NULL == ph.current_result))
      {
        GNUNET_break(0);
        return;
      }

      if (GAS_STAT_SUCCESS == stat)
        ph.current_result->valid = GNUNET_YES;
      else
        ph.current_result->valid = GNUNET_NO;

      ph.current_result->e_lp = GNUNET_TIME_absolute_get ();
      ph.current_result->d_lp_full = GNUNET_TIME_absolute_get_difference (
          ph.current_result->s_lp, ph.current_result->e_lp);
      return;

    case GAS_OP_SOLVE_MLP_MLP_START:
      GNUNET_log(GNUNET_ERROR_TYPE_INFO,
          "Solver notifies `%s' with result `%s'\n", "GAS_OP_SOLVE_MLP_START",
          (GAS_STAT_SUCCESS == stat) ? "SUCCESS" : "FAIL");
      if ((GNUNET_NO == ph.expecting_solution) || (NULL == ph.current_result))
      {
        GNUNET_break(0);
        return;
      }

      if (GAS_STAT_SUCCESS == stat)
        ph.current_result->valid = GNUNET_YES;
      else
        ph.current_result->valid = GNUNET_NO;

      ph.current_result->s_mlp = GNUNET_TIME_absolute_get ();
      return;
    case GAS_OP_SOLVE_MLP_MLP_STOP:
      GNUNET_log(GNUNET_ERROR_TYPE_INFO,
          "Solver notifies `%s' with result `%s'\n", "GAS_OP_SOLVE_MLP_STOP",
          (GAS_STAT_SUCCESS == stat) ? "SUCCESS" : "FAIL");
      if ((GNUNET_NO == ph.expecting_solution) || (NULL == ph.current_result))
      {
        GNUNET_break(0);
        return;
      }

      if (GAS_STAT_SUCCESS == stat)
        ph.current_result->valid = GNUNET_YES;
      else
        ph.current_result->valid = GNUNET_NO;

      ph.current_result->e_mlp = GNUNET_TIME_absolute_get ();
      ph.current_result->d_mlp_full = GNUNET_TIME_absolute_get_difference (
      ph.current_result->s_mlp, ph.current_result->e_mlp);
      return;
    case GAS_OP_SOLVE_UPDATE_NOTIFICATION_START:
      GNUNET_log(GNUNET_ERROR_TYPE_INFO,
          "Solver notifies `%s' with result `%s'\n", "GAS_OP_SOLVE_UPDATE_NOTIFICATION_START",
          (GAS_STAT_SUCCESS == stat) ? "SUCCESS" : "FAIL");
      return;
    case GAS_OP_SOLVE_UPDATE_NOTIFICATION_STOP:
      GNUNET_log(GNUNET_ERROR_TYPE_INFO,
          "Solver notifies `%s' with result `%s'\n", "GAS_OP_SOLVE_UPDATE_NOTIFICATION_STOP",
          (GAS_STAT_SUCCESS == stat) ? "SUCCESS" : "FAIL");
      if (GAS_STAT_SUCCESS != stat)
      {
        GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
            "Solver `%s' failed to update problem with %u peers and %u address!\n",
            ph.ats_string, ph.current_p, ph.current_a);
      }

      return;
    default:
      break;
    }
Exemplo n.º 12
0
/**
 * Sign name and records
 *
 * @param key the private key
 * @param expire block expiration
 * @param label the name for the records
 * @param rd record data
 * @param rd_count number of records
 * @return NULL on error (block too large)
 */
struct GNUNET_GNSRECORD_Block *
GNUNET_GNSRECORD_block_create (const struct GNUNET_CRYPTO_EcdsaPrivateKey *key,
			       struct GNUNET_TIME_Absolute expire,
			       const char *label,
			       const struct GNUNET_GNSRECORD_Data *rd,
			       unsigned int rd_count)
{
  size_t payload_len = GNUNET_GNSRECORD_records_get_size (rd_count, rd);
  char payload[sizeof (uint32_t) + payload_len];
  struct GNUNET_GNSRECORD_Block *block;
  struct GNUNET_CRYPTO_EcdsaPublicKey pkey;
  struct GNUNET_CRYPTO_EcdsaPrivateKey *dkey;
  struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
  struct GNUNET_CRYPTO_SymmetricSessionKey skey;
  struct GNUNET_GNSRECORD_Data rdc[rd_count];
  uint32_t rd_count_nbo;
  unsigned int i;
  struct GNUNET_TIME_Absolute now;

  if (payload_len > GNUNET_GNSRECORD_MAX_BLOCK_SIZE)
    return NULL;
  /* convert relative to absolute times */
  now = GNUNET_TIME_absolute_get ();
  for (i=0;i<rd_count;i++)
  {
    rdc[i] = rd[i];
    if (0 != (rd[i].flags & GNUNET_GNSRECORD_RF_RELATIVE_EXPIRATION))
    {
      struct GNUNET_TIME_Relative t;

      /* encrypted blocks must never have relative expiration times, convert! */
      rdc[i].flags &= ~GNUNET_GNSRECORD_RF_RELATIVE_EXPIRATION;
      t.rel_value_us = rdc[i].expiration_time;
      rdc[i].expiration_time = GNUNET_TIME_absolute_add (now, t).abs_value_us;
    }
  }
  /* serialize */
  rd_count_nbo = htonl (rd_count);
  memcpy (payload, &rd_count_nbo, sizeof (uint32_t));
  GNUNET_assert (payload_len ==
		 GNUNET_GNSRECORD_records_serialize (rd_count, rdc,
						     payload_len, &payload[sizeof (uint32_t)]));
  block = GNUNET_malloc (sizeof (struct GNUNET_GNSRECORD_Block) +
			 sizeof (uint32_t) + payload_len);
  block->purpose.size = htonl (sizeof (uint32_t) + payload_len +
			       sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
			       sizeof (struct GNUNET_TIME_AbsoluteNBO));
  block->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_GNS_RECORD_SIGN);
  block->expiration_time = GNUNET_TIME_absolute_hton (expire);
  /* encrypt and sign */
  dkey = GNUNET_CRYPTO_ecdsa_private_key_derive (key,
                                                 label,
                                                 "gns");
  GNUNET_CRYPTO_ecdsa_key_get_public (dkey,
				    &block->derived_key);
  GNUNET_CRYPTO_ecdsa_key_get_public (key,
				    &pkey);
  derive_block_aes_key (&iv, &skey, label, &pkey);
  GNUNET_break (payload_len + sizeof (uint32_t) ==
		GNUNET_CRYPTO_symmetric_encrypt (payload, payload_len + sizeof (uint32_t),
                                                 &skey, &iv,
                                                 &block[1]));
  if (GNUNET_OK !=
      GNUNET_CRYPTO_ecdsa_sign (dkey,
			      &block->purpose,
			      &block->signature))
  {
    GNUNET_break (0);
    GNUNET_free (dkey);
    GNUNET_free (block);
    return NULL;
  }
  GNUNET_free (dkey);
  return block;
}
Exemplo n.º 13
0
/**
 * Decrypt block.
 *
 * @param block block to decrypt
 * @param zone_key public key of the zone
 * @param label the name for the records
 * @param proc function to call with the result
 * @param proc_cls closure for proc
 * @return #GNUNET_OK on success, #GNUNET_SYSERR if the block was
 *        not well-formed
 */
int
GNUNET_GNSRECORD_block_decrypt (const struct GNUNET_GNSRECORD_Block *block,
				const struct GNUNET_CRYPTO_EcdsaPublicKey *zone_key,
				const char *label,
				GNUNET_GNSRECORD_RecordCallback proc,
				void *proc_cls)
{
  size_t payload_len = ntohl (block->purpose.size) -
    sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) -
    sizeof (struct GNUNET_TIME_AbsoluteNBO);
  struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
  struct GNUNET_CRYPTO_SymmetricSessionKey skey;

  if (ntohl (block->purpose.size) <
      sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
      sizeof (struct GNUNET_TIME_AbsoluteNBO))
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  derive_block_aes_key (&iv, &skey, label, zone_key);
  {
    char payload[payload_len];
    uint32_t rd_count;

    GNUNET_break (payload_len ==
		  GNUNET_CRYPTO_symmetric_decrypt (&block[1], payload_len,
					     &skey, &iv,
					     payload));
    memcpy (&rd_count,
	    payload,
	    sizeof (uint32_t));
    rd_count = ntohl (rd_count);
    if (rd_count > 2048)
    {
      /* limit to sane value */
      GNUNET_break_op (0);
      return GNUNET_SYSERR;
    }
    {
      struct GNUNET_GNSRECORD_Data rd[rd_count];
      unsigned int i;
      unsigned int j;
      unsigned int k;
      struct GNUNET_TIME_Absolute now;

      if (GNUNET_OK !=
	  GNUNET_GNSRECORD_records_deserialize (payload_len - sizeof (uint32_t),
						&payload[sizeof (uint32_t)],
						rd_count,
						rd))
      {
	GNUNET_break_op (0);
	return GNUNET_SYSERR;
      }
      /* hide expired records */
      now = GNUNET_TIME_absolute_get ();
      j = 0;
      for (i=0;i<rd_count;i++)
      {
        if (0 != (rd[i].flags & GNUNET_GNSRECORD_RF_RELATIVE_EXPIRATION))
        {
          /* encrypted blocks must never have relative expiration times, skip! */
          GNUNET_break_op (0);
          continue;
        }

        if (0 != (rd[i].flags & GNUNET_GNSRECORD_RF_SHADOW_RECORD))
        {
          int include_record = GNUNET_YES;
          /* Shadow record, figure out if we have a not expired active record */
          for (k=0;k<rd_count;k++)
          {
            if (k == i)
              continue;
            if (rd[i].expiration_time < now.abs_value_us)
              include_record = GNUNET_NO; /* Shadow record is expired */
            if ((rd[k].record_type == rd[i].record_type)
                && (rd[k].expiration_time >= now.abs_value_us)
                && (0 == (rd[k].flags & GNUNET_GNSRECORD_RF_SHADOW_RECORD)))
              include_record = GNUNET_NO; /* We have a non-expired, non-shadow record of the same type */
          }
          if (GNUNET_YES == include_record)
          {
            rd[i].flags ^= GNUNET_GNSRECORD_RF_SHADOW_RECORD; /* Remove Flag */
            if (j != i)
              rd[j] = rd[i];
            j++;
          }
        }
        else if (rd[i].expiration_time >= now.abs_value_us)
        {
          /* Include this record */
          if (j != i)
            rd[j] = rd[i];
          j++;
        }
      }
      rd_count = j;
      if (NULL != proc)
      	proc (proc_cls, rd_count, (0 != rd_count) ? rd : NULL);
    }
  }
  return GNUNET_OK;
}
Exemplo n.º 14
0
/**
 * Log all data now
 *
 * @param l logging handle to use
 */
void
GNUNET_ATS_TEST_logging_now (struct LoggingHandle *l)
{
  struct LoggingPeer *bp;
  struct PeerLoggingTimestep *mlt;
  struct PeerLoggingTimestep *prev_log_mlt;
  struct PartnerLoggingTimestep *slt;
  struct PartnerLoggingTimestep *prev_log_slt;
  struct BenchmarkPartner *p;
  struct GNUNET_TIME_Relative delta;
  int c_s;
  int c_m;
  unsigned int app_rtt;
  double mult;

  if (GNUNET_YES != l->running)
    return;

  for (c_m = 0; c_m < l->num_masters; c_m++)
  {
    bp = &l->lp[c_m];
    mlt = GNUNET_new (struct PeerLoggingTimestep);
    GNUNET_CONTAINER_DLL_insert_tail(l->lp[c_m].head, l->lp[c_m].tail, mlt);
    prev_log_mlt = mlt->prev;

    /* Collect data */
    /* Current master state */
    mlt->timestamp = GNUNET_TIME_absolute_get();
    mlt->total_bytes_sent = bp->peer->total_bytes_sent;
    mlt->total_messages_sent = bp->peer->total_messages_sent;
    mlt->total_bytes_received = bp->peer->total_bytes_received;
    mlt->total_messages_received = bp->peer->total_messages_received;

    /* Throughput */
    if (NULL == prev_log_mlt)
     {
       /* Get difference to start */
       delta = GNUNET_TIME_absolute_get_difference (l->lp[c_m].start, mlt->timestamp);
     }
     else
     {
       /* Get difference to last timestep */
       delta = GNUNET_TIME_absolute_get_difference (mlt->prev->timestamp, mlt->timestamp);
     }

     /* Multiplication factor for throughput calculation */
     mult = (double) GNUNET_TIME_UNIT_SECONDS.rel_value_us / (delta.rel_value_us);

     /* Total throughput */
     if (NULL != prev_log_mlt)
     {
       if (mlt->total_bytes_sent - mlt->prev->total_bytes_sent > 0)
       {
         mlt->total_throughput_send = mult * (mlt->total_bytes_sent - mlt->prev->total_bytes_sent);
       }
       else
       {
         mlt->total_throughput_send = 0;
        // mlt->total_throughput_send = prev_log_mlt->total_throughput_send; /* no msgs send */
       }

       if (mlt->total_bytes_received - mlt->prev->total_bytes_received > 0)
       {
         mlt->total_throughput_recv = mult * (mlt->total_bytes_received - mlt->prev->total_bytes_received);
       }
       else
       {
         mlt->total_throughput_send = 0;
         //mlt->total_throughput_recv = prev_log_mlt->total_throughput_recv; /* no msgs received */
       }
     }
     else
     {
       mlt->total_throughput_send = mult * mlt->total_bytes_sent;
       mlt->total_throughput_send = mult * mlt->total_bytes_received;
     }

    if (GNUNET_YES == l->verbose)
    {
      GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
          "Master[%u] delta: %llu us, bytes (sent/received): %u / %u; throughput send/recv: %u / %u\n", c_m,
          delta.rel_value_us,
          mlt->total_bytes_sent,
          mlt->total_bytes_received,
          mlt->total_throughput_send,
          mlt->total_throughput_recv);
    }

    mlt->slaves_log = GNUNET_malloc (bp->peer->num_partners *
        sizeof (struct PartnerLoggingTimestep));

    for (c_s = 0; c_s < bp->peer->num_partners; c_s++)
    {
      GNUNET_log (GNUNET_ERROR_TYPE_INFO,
          "Collect logging data master[%u] slave [%u]\n", c_m, c_s);

      p = &bp->peer->partners[c_s];
      slt = &mlt->slaves_log[c_s];

      slt->slave = p->dest;
      /* Bytes sent from master to this slave */
      slt->total_bytes_sent = p->bytes_sent;
      /* Messages sent from master to this slave */
      slt->total_messages_sent = p->messages_sent;
      /* Bytes master received from this slave */
      slt->total_bytes_received = p->bytes_received;
      /* Messages master received from this slave */
      slt->total_messages_received = p->messages_received;
      slt->total_app_rtt = p->total_app_rtt;
      /* ats performance information */
      slt->ats_delay = p->props.delay;
      slt->ats_distance = p->props.distance;
      slt->ats_network_type = p->props.scope;
      slt->ats_utilization_in = p->props.utilization_out;
      slt->ats_utilization_out = p->props.utilization_out;
      slt->bandwidth_in = p->bandwidth_in;
      slt->bandwidth_out = p->bandwidth_out;
      slt->pref_bandwidth = p->pref_bandwidth;
      slt->pref_delay = p->pref_delay;

      /* Total application level rtt  */
      if (NULL == prev_log_mlt)
      {
        if (0 != slt->total_messages_sent)
          app_rtt = slt->total_app_rtt / slt->total_messages_sent;
        else
          app_rtt = 0;
      }
      else
      {
        prev_log_slt =  &prev_log_mlt->slaves_log[c_s];
        if ((slt->total_messages_sent - prev_log_slt->total_messages_sent) > 0)
          app_rtt = (slt->total_app_rtt - prev_log_slt->total_app_rtt) /
                  (slt->total_messages_sent - prev_log_slt->total_messages_sent);
        else
        {
          app_rtt = prev_log_slt->app_rtt; /* No messages were */
        }
      }
      slt->app_rtt = app_rtt;

      /* Partner throughput */
      if (NULL != prev_log_mlt)
      {
        prev_log_slt =  &prev_log_mlt->slaves_log[c_s];
        if (slt->total_bytes_sent > prev_log_slt->total_bytes_sent)
          slt->throughput_sent = mult * (slt->total_bytes_sent - prev_log_slt->total_bytes_sent);
        else
          slt->throughput_sent = 0;

        if (slt->total_bytes_received > prev_log_slt->total_bytes_received)
          slt->throughput_recv = mult *
              (slt->total_bytes_received - prev_log_slt->total_bytes_received);
        else
          slt->throughput_recv = 0;
      }
      else
      {
        slt->throughput_sent = mult * slt->total_bytes_sent;
        slt->throughput_recv = mult * slt->total_bytes_received;
      }

      if (GNUNET_YES == l->verbose)
      {
        GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
            "Master [%u] -> Slave [%u]: delta: %llu us, bytes (sent/received): %u / %u; throughput send/recv: %u / %u\n",
            c_m, c_s,
            delta.rel_value_us,
            mlt->total_bytes_sent,
            mlt->total_bytes_received,
            slt->throughput_sent,
            slt->throughput_recv);
      }
      else
        GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
          "Master [%u]: slave [%u]\n",
          bp->peer->no, p->dest->no);
    }
  }
}
Exemplo n.º 15
0
static void *
progress_cb (void *cls, const struct GNUNET_FS_ProgressInfo *event)
{
  switch (event->status)
  {
  case GNUNET_FS_STATUS_PUBLISH_PROGRESS:
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
		"Publish is progressing (%llu/%llu at level %u off %llu)...\n",
		(unsigned long long) event->value.publish.completed,
		(unsigned long long) event->value.publish.size,
		event->value.publish.specifics.progress.depth,
		(unsigned long long) event->value.publish.specifics.
		progress.offset);
    break;
  case GNUNET_FS_STATUS_PUBLISH_PROGRESS_DIRECTORY:
    break;
  case GNUNET_FS_STATUS_PUBLISH_COMPLETED:
    printf ("Publishing complete, %llu kbps.\n",
            (unsigned long long) (FILESIZE * 1000000LL /
                                  (1 +
                                   GNUNET_TIME_absolute_get_duration
                                   (start).rel_value_us) / 1024));
    start = GNUNET_TIME_absolute_get ();
    unindex = GNUNET_FS_unindex_start (fs, fn, "unindex");
    GNUNET_assert (unindex != NULL);
    break;
  case GNUNET_FS_STATUS_UNINDEX_COMPLETED:
    printf ("Unindex complete,  %llu kbps.\n",
            (unsigned long long) (FILESIZE * 1000000LL /
                                  (1 +
                                   GNUNET_TIME_absolute_get_duration
                                   (start).rel_value_us) / 1024));
    GNUNET_SCHEDULER_add_now (&abort_unindex_task, NULL);
    break;
  case GNUNET_FS_STATUS_UNINDEX_PROGRESS:
    consider_restart (event->status);
    GNUNET_assert (unindex == event->value.unindex.uc);
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
		"Unindex is progressing (%llu/%llu at level %u off %llu)...\n",
		(unsigned long long) event->value.unindex.completed,
		(unsigned long long) event->value.unindex.size,
		event->value.unindex.specifics.progress.depth,
		(unsigned long long) event->value.unindex.specifics.
		progress.offset);
    break;
  case GNUNET_FS_STATUS_PUBLISH_SUSPEND:
    if (event->value.publish.pc == publish)
      publish = NULL;
    break;
  case GNUNET_FS_STATUS_PUBLISH_RESUME:
    if (NULL == publish)
    {
      publish = event->value.publish.pc;
      return "publish-context";
    }
    break;
  case GNUNET_FS_STATUS_UNINDEX_SUSPEND:
    GNUNET_assert (event->value.unindex.uc == unindex);
    unindex = NULL;
    break;
  case GNUNET_FS_STATUS_UNINDEX_RESUME:
    GNUNET_assert (NULL == unindex);
    unindex = event->value.unindex.uc;
    return "unindex";
  case GNUNET_FS_STATUS_PUBLISH_ERROR:
    FPRINTF (stderr, "Error publishing file: %s\n",
             event->value.publish.specifics.error.message);
    GNUNET_break (0);
    GNUNET_SCHEDULER_add_now (&abort_publish_task, NULL);
    break;
  case GNUNET_FS_STATUS_UNINDEX_ERROR:
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
		"Error unindexing file: %s\n",
		event->value.unindex.specifics.error.message);
    GNUNET_SCHEDULER_add_now (&abort_unindex_task, NULL);
    break;
  case GNUNET_FS_STATUS_PUBLISH_START:
    GNUNET_assert (0 == strcmp ("publish-context", event->value.publish.cctx));
    GNUNET_assert (NULL == event->value.publish.pctx);
    GNUNET_assert (FILESIZE == event->value.publish.size);
    GNUNET_assert (0 == event->value.publish.completed);
    GNUNET_assert (1 == event->value.publish.anonymity);
    break;
  case GNUNET_FS_STATUS_PUBLISH_STOPPED:
    GNUNET_assert (publish == event->value.publish.pc);
    GNUNET_assert (FILESIZE == event->value.publish.size);
    GNUNET_assert (1 == event->value.publish.anonymity);
    GNUNET_FS_stop (fs);
    fs = NULL;
    break;
  case GNUNET_FS_STATUS_UNINDEX_START:
    consider_restart (event->status);
    GNUNET_assert (unindex == NULL);
    GNUNET_assert (0 == strcmp ("unindex", event->value.unindex.cctx));
    GNUNET_assert (0 == strcmp (fn, event->value.unindex.filename));
    GNUNET_assert (FILESIZE == event->value.unindex.size);
    GNUNET_assert (0 == event->value.unindex.completed);
    break;
  case GNUNET_FS_STATUS_UNINDEX_STOPPED:
    GNUNET_assert (unindex == event->value.unindex.uc);
    GNUNET_SCHEDULER_add_now (&abort_publish_task, NULL);
    break;
  default:
    printf ("Unexpected event: %d\n", event->status);
    break;
  }
  return NULL;
}
Exemplo n.º 16
0
/**
 * Signature of the event handler function called by the
 * respective event controller.
 *
 * @param cls closure
 * @param event information about the event
 */
static void
event_cb (void *cls, const struct GNUNET_TESTBED_EventInformation *event)
{
  struct GNUNET_TESTBED_RunHandle *rc = cls;
  struct RunContextOperation *rcop;

  if (RC_INIT == rc->state)
  {
    switch (event->type)
    {
    case GNUNET_TESTBED_ET_OPERATION_FINISHED:
      rcop = event->op_cls;
      if (NULL != event->details.operation_finished.emsg)
      {
        LOG (GNUNET_ERROR_TYPE_ERROR, _("Linking controllers failed. Exiting"));
        GNUNET_SCHEDULER_shutdown ();
      }
      else
        rc->reg_hosts++;
      GNUNET_assert (event->op == rcop->op);
      remove_rcop (rc, rcop);
      GNUNET_TESTBED_operation_done (rcop->op);
      GNUNET_free (rcop);
      if (rc->reg_hosts == rc->num_hosts)
      {
        rc->state = RC_LINKED;
        create_peers (rc);
      }
      return;
    default:
      GNUNET_break (0);
      GNUNET_SCHEDULER_shutdown ();
      return;
    }
  }
  if (GNUNET_TESTBED_ET_OPERATION_FINISHED != event->type)
    goto call_cc;
  if (NULL == (rcop = search_rcop (rc, event->op)))
    goto call_cc;
  remove_rcop (rc, rcop);
  GNUNET_TESTBED_operation_done (rcop->op);
  GNUNET_free (rcop);
  if ( (GNUNET_NO == rc->shutdown)
       && (NULL != event->details.operation_finished.emsg) )
  {
    LOG (GNUNET_ERROR_TYPE_ERROR, "A operation has failed with error: %s\n",
         event->details.operation_finished.emsg);
    GNUNET_SCHEDULER_shutdown ();
    return;
  }
  GNUNET_assert (GNUNET_YES == rc->shutdown);
  switch (rc->state)
  {
  case RC_LINKED:
  case RC_PEERS_CREATED:
  case RC_READY:
    rc->state = RC_PEERS_SHUTDOWN;
    GNUNET_free_non_null (rc->peers);
    rc->peers = NULL;
    DEBUG ("Peers shut down in %s\n", prof_time (rc));
    GNUNET_SCHEDULER_shutdown ();
    break;
  default:
    GNUNET_assert (0);
  }
  return;

call_cc:
  if ((0 != (rc->event_mask & (1LL << event->type))) && (NULL != rc->cc))
    rc->cc (rc->cc_cls, event);
  if (GNUNET_TESTBED_ET_PEER_START != event->type)
    return;
  if (NULL == (rcop = search_rcop (rc, event->op))) /* Not our operation */
    return;
  remove_rcop (rc, rcop);
  GNUNET_TESTBED_operation_done (rcop->op);
  GNUNET_free (rcop);
  rc->peer_count++;
  if (rc->peer_count < rc->num_peers)
    return;
  DEBUG ("%u peers started in %s\n", rc->num_peers, prof_time (rc));
  if (GNUNET_TESTBED_TOPOLOGY_NONE != rc->topology)
  {
    switch (rc->topology)
    {
    case GNUNET_TESTBED_TOPOLOGY_NONE:
      GNUNET_assert (0);
    case GNUNET_TESTBED_TOPOLOGY_ERDOS_RENYI:
    case GNUNET_TESTBED_TOPOLOGY_SMALL_WORLD_RING:
    case GNUNET_TESTBED_TOPOLOGY_SMALL_WORLD:
      rc->topology_operation =
          GNUNET_TESTBED_overlay_configure_topology (NULL, rc->num_peers,
                                                     rc->peers, &rc->num_oc,
                                                     &topology_completion_callback,
                                                     rc,
                                                     rc->topology,
                                                     rc->random_links,
                                                     GNUNET_TESTBED_TOPOLOGY_OPTION_END);
      break;
    case GNUNET_TESTBED_TOPOLOGY_FROM_FILE:
      GNUNET_assert (NULL != rc->topo_file);
      rc->topology_operation =
          GNUNET_TESTBED_overlay_configure_topology (NULL, rc->num_peers,
                                                     rc->peers, &rc->num_oc,
                                                     &topology_completion_callback,
                                                     rc,
                                                     rc->topology,
                                                     rc->topo_file,
                                                     GNUNET_TESTBED_TOPOLOGY_OPTION_END);
      break;
    case GNUNET_TESTBED_TOPOLOGY_SCALE_FREE:
      {
        unsigned long long number;
        unsigned int cap;
        GNUNET_assert (GNUNET_OK ==
                       GNUNET_CONFIGURATION_get_value_number (rc->cfg, TESTBED_CONFIG_SECTION,
                                                              SCALE_FREE_CAP,
                                                              &number));
        cap = (unsigned int) number;
        GNUNET_assert (GNUNET_OK ==
                       GNUNET_CONFIGURATION_get_value_number (rc->cfg, TESTBED_CONFIG_SECTION,
                                                              SCALE_FREE_M,
                                                              &number));
        rc->topology_operation =
            GNUNET_TESTBED_overlay_configure_topology (NULL, rc->num_peers,
                                                       rc->peers, &rc->num_oc,
                                                       &topology_completion_callback,
                                                       rc,
                                                       rc->topology,
                                                       cap,    /* uint16_t */
                                                       (unsigned int) number, /* uint8_t */
                                                       GNUNET_TESTBED_TOPOLOGY_OPTION_END);
      }
      break;
    default:
      rc->topology_operation =
          GNUNET_TESTBED_overlay_configure_topology (NULL, rc->num_peers,
                                                     rc->peers, &rc->num_oc,
                                                     &topology_completion_callback,
                                                     rc,
                                                     rc->topology,
                                                     GNUNET_TESTBED_TOPOLOGY_OPTION_END);
    }
    if (NULL == rc->topology_operation)
      LOG (GNUNET_ERROR_TYPE_WARNING,
           "Not generating a topology. Check number of peers\n");
    else
    {
      DEBUG ("Creating overlay topology\n");
      rc->pstart_time = GNUNET_TIME_absolute_get ();
      return;
    }
  }
  rc->state = RC_READY;
  call_master (rc);
}
Exemplo n.º 17
0
static void *
progress_cb (void *cls, const struct GNUNET_FS_ProgressInfo *event)
{
  const char *keywords[] = {
    "down_foo"
  };
  struct GNUNET_FS_Uri *kuri;

  switch (event->status)
  {
  case GNUNET_FS_STATUS_PUBLISH_PROGRESS:
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
		"Publish is progressing (%llu/%llu at level %u off %llu)...\n",
		(unsigned long long) event->value.publish.completed,
		(unsigned long long) event->value.publish.size,
		event->value.publish.specifics.progress.depth,
		(unsigned long long) event->value.publish.specifics.
		progress.offset);
    break;
  case GNUNET_FS_STATUS_PUBLISH_PROGRESS_DIRECTORY:
    break;
  case GNUNET_FS_STATUS_PUBLISH_COMPLETED:
    kuri = GNUNET_FS_uri_ksk_create_from_args (1, keywords);
    start = GNUNET_TIME_absolute_get ();
    search =
        GNUNET_FS_search_start (fs, kuri, 1, GNUNET_FS_SEARCH_OPTION_NONE,
                                "search");
    GNUNET_FS_uri_destroy (kuri);
    GNUNET_assert (search != NULL);
    break;
  case GNUNET_FS_STATUS_SEARCH_RESULT:
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Search complete.\n");
    break;
  case GNUNET_FS_STATUS_PUBLISH_ERROR:
    FPRINTF (stderr, "Error publishing file: %s\n",
             event->value.publish.specifics.error.message);
    GNUNET_break (0);
    GNUNET_SCHEDULER_add_now (&abort_publish_task, NULL);
    break;
  case GNUNET_FS_STATUS_SEARCH_ERROR:
    FPRINTF (stderr, "Error searching file: %s\n",
             event->value.search.specifics.error.message);
    GNUNET_SCHEDULER_add_now (&abort_search_task, NULL);
    break;
  case GNUNET_FS_STATUS_PUBLISH_START:
    GNUNET_assert (0 == strcmp ("publish-context", event->value.publish.cctx));
    GNUNET_assert (NULL == event->value.publish.pctx);
    GNUNET_assert (FILESIZE == event->value.publish.size);
    GNUNET_assert (0 == event->value.publish.completed);
    GNUNET_assert (1 == event->value.publish.anonymity);
    break;
  case GNUNET_FS_STATUS_PUBLISH_STOPPED:
    GNUNET_assert (publish == event->value.publish.pc);
    GNUNET_assert (FILESIZE == event->value.publish.size);
    GNUNET_assert (1 == event->value.publish.anonymity);
    GNUNET_FS_stop (fs);
    fs = NULL;
    break;
  case GNUNET_FS_STATUS_SEARCH_UPDATE:
    if ( (0 < event->value.search.specifics.update.availability_rank) &&
	 (0 < event->value.search.specifics.update.availability_certainty) )
      GNUNET_SCHEDULER_add_now (&abort_search_task, NULL);
    break;
  case GNUNET_FS_STATUS_SEARCH_START:
    GNUNET_assert (search == NULL);
    GNUNET_assert (0 == strcmp ("search", event->value.search.cctx));
    GNUNET_assert (1 == event->value.search.anonymity);
    break;
  case GNUNET_FS_STATUS_SEARCH_RESULT_STOPPED:
    break;
  case GNUNET_FS_STATUS_SEARCH_STOPPED:
    GNUNET_assert (search == event->value.search.sc);
    GNUNET_SCHEDULER_add_now (&abort_publish_task, NULL);
    break;
  default:
    FPRINTF (stderr,
             "Unexpected event: %d\n",
             event->status);
    break;
  }
  return NULL;
}
Exemplo n.º 18
0
static void *
progress_cb (void *cls, const struct GNUNET_FS_ProgressInfo *event)
{

  switch (event->status)
  {
  case GNUNET_FS_STATUS_PUBLISH_PROGRESS:
#if VERBOSE
    printf ("Publish is progressing (%llu/%llu at level %u off %llu)...\n",
            (unsigned long long) event->value.publish.completed,
            (unsigned long long) event->value.publish.size,
            event->value.publish.specifics.progress.depth,
            (unsigned long long) event->value.publish.specifics.
            progress.offset);
#endif
    break;
  case GNUNET_FS_STATUS_PUBLISH_COMPLETED:
    printf ("Publishing complete, %llu kbps.\n",
            (unsigned long long) (FILESIZE * 1000 /
                                  (1 +
                                   GNUNET_TIME_absolute_get_duration
                                   (start).rel_value) / 1024));
    start = GNUNET_TIME_absolute_get ();
    unindex = GNUNET_FS_unindex_start (fs, fn, "unindex");
    GNUNET_assert (unindex != NULL);
    break;
  case GNUNET_FS_STATUS_UNINDEX_COMPLETED:
    printf ("Unindex complete,  %llu kbps.\n",
            (unsigned long long) (FILESIZE * 1000 /
                                  (1 +
                                   GNUNET_TIME_absolute_get_duration
                                   (start).rel_value) / 1024));
    GNUNET_SCHEDULER_add_continuation (&abort_unindex_task, NULL,
                                       GNUNET_SCHEDULER_REASON_PREREQ_DONE);
    break;
  case GNUNET_FS_STATUS_UNINDEX_PROGRESS:
    GNUNET_assert (unindex == event->value.unindex.uc);
#if VERBOSE
    printf ("Unindex is progressing (%llu/%llu at level %u off %llu)...\n",
            (unsigned long long) event->value.unindex.completed,
            (unsigned long long) event->value.unindex.size,
            event->value.unindex.specifics.progress.depth,
            (unsigned long long) event->value.unindex.specifics.
            progress.offset);
#endif
    break;
  case GNUNET_FS_STATUS_PUBLISH_ERROR:
    FPRINTF (stderr, "Error publishing file: %s\n",
             event->value.publish.specifics.error.message);
    GNUNET_break (0);
    GNUNET_SCHEDULER_add_continuation (&abort_publish_task, NULL,
                                       GNUNET_SCHEDULER_REASON_PREREQ_DONE);
    break;
  case GNUNET_FS_STATUS_UNINDEX_ERROR:
    FPRINTF (stderr, "Error unindexing file: %s\n",
             event->value.unindex.specifics.error.message);
    GNUNET_SCHEDULER_add_continuation (&abort_unindex_task, NULL,
                                       GNUNET_SCHEDULER_REASON_PREREQ_DONE);
    break;
  case GNUNET_FS_STATUS_PUBLISH_START:
    GNUNET_assert (0 == strcmp ("publish-context", event->value.publish.cctx));
    GNUNET_assert (NULL == event->value.publish.pctx);
    GNUNET_assert (FILESIZE == event->value.publish.size);
    GNUNET_assert (0 == event->value.publish.completed);
    GNUNET_assert (1 == event->value.publish.anonymity);
    break;
  case GNUNET_FS_STATUS_PUBLISH_STOPPED:
    GNUNET_assert (publish == event->value.publish.pc);
    GNUNET_assert (FILESIZE == event->value.publish.size);
    GNUNET_assert (1 == event->value.publish.anonymity);
    GNUNET_FS_stop (fs);
    fs = NULL;
    break;
  case GNUNET_FS_STATUS_UNINDEX_START:
    GNUNET_assert (unindex == NULL);
    GNUNET_assert (0 == strcmp ("unindex", event->value.unindex.cctx));
    GNUNET_assert (0 == strcmp (fn, event->value.unindex.filename));
    GNUNET_assert (FILESIZE == event->value.unindex.size);
    GNUNET_assert (0 == event->value.unindex.completed);
    break;
  case GNUNET_FS_STATUS_UNINDEX_STOPPED:
    GNUNET_assert (unindex == event->value.unindex.uc);
    GNUNET_SCHEDULER_add_continuation (&abort_publish_task, NULL,
                                       GNUNET_SCHEDULER_REASON_PREREQ_DONE);
    break;
  default:
    printf ("Unexpected event: %d\n", event->status);
    break;
  }
  return NULL;
}
/**
 * Find a "good" address to use for a peer.  If we already have an existing
 * address, we stick to it.  Otherwise, we pick by lowest distance and then
 * by lowest latency.
 *
 * @param cls the 'struct ATS_Address**' where we store the result
 * @param key unused
 * @param value another 'struct ATS_Address*' to consider using
 * @return GNUNET_OK (continue to iterate)
 */
static int
find_address_it (void *cls, const GNUNET_HashCode * key, void *value)
{
  struct ATS_Address **ap = cls;
  struct ATS_Address *aa = (struct ATS_Address *) value;
  struct ATS_Address *ab = *ap;
  struct GNUNET_TIME_Absolute now;

  now = GNUNET_TIME_absolute_get();

  if (aa->blocked_until.abs_value == GNUNET_TIME_absolute_max (now, aa->blocked_until).abs_value)
  {
    /* This address is blocked for suggestion */
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                "Address %p blocked for suggestion for %llu ms \n",
                aa,
                GNUNET_TIME_absolute_get_difference(now, aa->blocked_until).rel_value);
    return GNUNET_OK;
  }

  aa->block_interval = GNUNET_TIME_relative_add (aa->block_interval, ATS_BLOCKING_DELTA);
  aa->blocked_until = GNUNET_TIME_absolute_add (now, aa->block_interval);

  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Address %p ready for suggestion, block interval now %llu \n", aa, aa->block_interval);

  /* FIXME this is a hack */


  if (NULL != ab)
  {
    if ((0 == strcmp (ab->plugin, "tcp")) &&
        (0 == strcmp (aa->plugin, "tcp")))
    {
      if ((0 != ab->addr_len) &&
          (0 == aa->addr_len))
      {
        /* saved address was an outbound address, but we have an inbound address */
        *ap = aa;
        return GNUNET_OK;
      }
      if (0 == ab->addr_len)
      {
        /* saved address was an inbound address, so do not overwrite */
        return GNUNET_OK;
      }
    }
  }
  /* FIXME end of hack */

  if (NULL == ab)
  {
    *ap = aa;
    return GNUNET_OK;
  }
  if ((ntohl (ab->assigned_bw_in.value__) == 0) &&
      (ntohl (aa->assigned_bw_in.value__) > 0))
  {
    /* stick to existing connection */
    *ap = aa;
    return GNUNET_OK;
  }
  if (ab->atsp_distance > aa->atsp_distance)
  {
    /* user shorter distance */
    *ap = aa;
    return GNUNET_OK;
  }
  if (ab->atsp_latency.rel_value > aa->atsp_latency.rel_value)
  {
    /* user lower latency */
    *ap = aa;
    return GNUNET_OK;
  }
  /* don't care */
  return GNUNET_OK;
}
Exemplo n.º 20
0
/**
 * Evaluate RSA performance.
 *
 * @param len keylength to evaluate with
 */
static void
eval (unsigned int len)
{
  struct GNUNET_TIME_Absolute start;
  struct GNUNET_CRYPTO_RsaSignature *sig;
  struct GNUNET_CRYPTO_RsaSignature *rsig;
  struct GNUNET_CRYPTO_RsaPublicKey *public_key;
  struct GNUNET_CRYPTO_RsaPrivateKey *private_key;
  struct GNUNET_CRYPTO_RsaBlindingKeySecret bsec[10];
  unsigned int i;
  char sbuf[128];
  char *bbuf;
  size_t bbuf_len;
  struct GNUNET_HashCode hc;

  start = GNUNET_TIME_absolute_get ();
  for (i=0;i<10;i++)
  {
    private_key = GNUNET_CRYPTO_rsa_private_key_create (len);
    GNUNET_CRYPTO_rsa_private_key_free (private_key);
  }
  printf ("10x %u-key generation took %s\n",
          len,
          GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (start),
                                                  GNUNET_YES));
  GNUNET_snprintf (sbuf,
                   sizeof (sbuf),
                   "RSA %u-key generation",
                   len);
  GAUGER ("UTIL", sbuf,
          64 * 1024 / (1 +
                       GNUNET_TIME_absolute_get_duration
                       (start).rel_value_us / 1000LL), "keys/ms");
  private_key = GNUNET_CRYPTO_rsa_private_key_create (len);
  public_key = GNUNET_CRYPTO_rsa_private_key_get_public (private_key);
  for (i=0;i<10;i++)
    GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_WEAK,
			        &bsec[i], sizeof (bsec[0]));
  /*
  start = GNUNET_TIME_absolute_get ();
  for (i=0;i<10;i++)
    rsa_blinding_key_derive(public_key, &bsec[i]);
  printf ("10x %u-blinding key generation took %s\n",
          len,
          GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (start),
                                                  GNUNET_YES));
  GNUNET_snprintf (sbuf,
                   sizeof (sbuf),
                   "RSA %u-blinding key generation",
                   len);
  GAUGER ("UTIL", sbuf,
          64 * 1024 / (1 +
                       GNUNET_TIME_absolute_get_duration
                       (start).rel_value_us / 1000LL), "keys/ms");
  */
  start = GNUNET_TIME_absolute_get ();
  GNUNET_CRYPTO_hash ("test", 4, &hc);
  for (i=0;i<10;i++)
  {
    GNUNET_CRYPTO_rsa_blind (&hc,
                             &bsec[i],
                             public_key,
                             &bbuf, &bbuf_len);
    GNUNET_free (bbuf);
  }
  printf ("10x %u-blinding took %s\n",
          len,
          GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (start),
						  GNUNET_YES));
  GNUNET_snprintf (sbuf,
                   sizeof (sbuf),
                   "RSA %u-blinding",
                   len);
  GAUGER ("UTIL",
          sbuf,
          64 * 1024 / (1 +
		       GNUNET_TIME_absolute_get_duration
		       (start).rel_value_us / 1000LL), "ops/ms");
  GNUNET_CRYPTO_rsa_blind (&hc,
                           &bsec[0],
                           public_key,
                           &bbuf, &bbuf_len);
  start = GNUNET_TIME_absolute_get ();
  for (i=0;i<10;i++)
  {
    sig = GNUNET_CRYPTO_rsa_sign_blinded (private_key,
                                          bbuf, bbuf_len);
    GNUNET_CRYPTO_rsa_signature_free (sig);
  }
  printf ("10x %u-signing took %s\n",
          len,
          GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (start),
						  GNUNET_YES));
  GNUNET_snprintf (sbuf,
                   sizeof (sbuf),
                   "RSA %u-signing",
                   len);
  GAUGER ("UTIL",
          sbuf,
          64 * 1024 / (1 +
		       GNUNET_TIME_absolute_get_duration
		       (start).rel_value_us / 1000LL), "ops/ms");
  sig = GNUNET_CRYPTO_rsa_sign_blinded (private_key,
                                        bbuf,
                                        bbuf_len);
  start = GNUNET_TIME_absolute_get ();
  for (i=0;i<10;i++)
  {
    rsig = GNUNET_CRYPTO_rsa_unblind (sig,
                                      &bsec[0],
                                      public_key);
    GNUNET_CRYPTO_rsa_signature_free (rsig);
  }
  printf ("10x %u-unblinding took %s\n",
          len,
          GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (start),
						  GNUNET_YES));
  GNUNET_snprintf (sbuf,
                   sizeof (sbuf),
                   "RSA %u-unblinding",
                   len);
  GAUGER ("UTIL",
          sbuf,
          64 * 1024 / (1 +
		       GNUNET_TIME_absolute_get_duration
		       (start).rel_value_us / 1000LL), "ops/ms");
  rsig = GNUNET_CRYPTO_rsa_unblind (sig,
                                    &bsec[0],
                                    public_key);
  start = GNUNET_TIME_absolute_get ();
  for (i=0;i<10;i++)
  {
    GNUNET_assert (GNUNET_OK ==
                   GNUNET_CRYPTO_rsa_verify (&hc,
                                             rsig,
                                             public_key));
  }
  printf ("10x %u-verifying took %s\n",
          len,
          GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (start),
						  GNUNET_YES));
  GNUNET_snprintf (sbuf,
                   sizeof (sbuf),
                   "RSA %u-verification",
                   len);
  GAUGER ("UTIL",
          sbuf,
          64 * 1024 / (1 +
		       GNUNET_TIME_absolute_get_duration
		       (start).rel_value_us / 1000LL), "ops/ms");
  GNUNET_CRYPTO_rsa_signature_free (sig);
  GNUNET_CRYPTO_rsa_public_key_free (public_key);
  GNUNET_CRYPTO_rsa_private_key_free (private_key);
  GNUNET_free (bbuf);
}
Exemplo n.º 21
0
/**
 * Update active address for a peer.  Check if active address exists
 * and what the best address is, if addresses are different switch.
 * Then reallocate bandwidth within the affected network scopes.
 *
 * @param s solver handle
 * @param current_address the address currently active for the peer,
 *        NULL for none
 * @param peer the peer to check
 */
static void
update_active_address (struct GAS_PROPORTIONAL_Handle *s,
                       struct ATS_Address *current_address,
                       const struct GNUNET_PeerIdentity *peer)
{
  struct ATS_Address *best_address;
  struct AddressWrapper *asi_cur;
  struct AddressWrapper *asi_best;
  struct AddressWrapper *aw;
  struct AddressWrapper *aw_min;
  unsigned int a_con;
  unsigned int con_min;

  best_address = get_best_address (s,
                                   s->env->addresses,
                                   peer);
  if (NULL != best_address)
    asi_best = best_address->solver_information;
  else
    asi_best = NULL;
  if (current_address == best_address)
    return; /* no changes */
  if (NULL != current_address)
  {
    /* We switch to a new address (or to none);
       mark old address as inactive. */
    asi_cur = current_address->solver_information;
    GNUNET_assert (GNUNET_YES == current_address->active);
    LOG (GNUNET_ERROR_TYPE_INFO,
         "Disabling previous active address for peer `%s'\n",
         GNUNET_i2s (peer));
    asi_cur->activated = GNUNET_TIME_UNIT_ZERO_ABS;
    current_address->active = GNUNET_NO;
    current_address->assigned_bw_in = 0;
    current_address->assigned_bw_out = 0;
    address_decrement_active (s,
                              asi_cur->network);
    if ( (NULL == best_address) ||
         (asi_best->network != asi_cur->network) )
      distribute_bandwidth_in_network (s,
                                       asi_cur->network);
    if (NULL == best_address)
    {
      /* We previously had an active address, but now we cannot
       * suggest one.  Therefore we have to disconnect the peer.
       * The above call to "distribute_bandwidth_in_network()
       * does not see 'current_address' so we need to trigger
       * the update here. */
      LOG (GNUNET_ERROR_TYPE_DEBUG,
           "Disconnecting peer `%s'.\n",
           GNUNET_i2s (peer));
      s->env->bandwidth_changed_cb (s->env->cls,
                                    current_address);
      return;
    }
  }
  if (NULL == best_address)
  {
    /* We do not have a new address, so we are done. */
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "Cannot suggest address for peer `%s'\n",
         GNUNET_i2s (peer));
    return;
  }
  /* We do have a new address, activate it */
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Selecting new address %p for peer `%s'\n",
       best_address,
       GNUNET_i2s (peer));
  /* Mark address as active */
  best_address->active = GNUNET_YES;
  asi_best->activated = GNUNET_TIME_absolute_get ();
  asi_best->network->active_addresses++;
  s->active_addresses++;
  GNUNET_STATISTICS_update (s->env->stats,
                            "# ATS active addresses total",
                            1,
                            GNUNET_NO);
  GNUNET_STATISTICS_update (s->env->stats,
                            asi_best->network->stat_active,
                            1,
                            GNUNET_NO);
  LOG (GNUNET_ERROR_TYPE_INFO,
       "Address %p for peer `%s' is now active\n",
       best_address,
       GNUNET_i2s (peer));

  if (GNUNET_NO ==
      is_bandwidth_available_in_network (asi_best->network,
                                         0))
  {
    /* we went over the maximum number of addresses for
       this scope; remove the address with the smallest
       connectivity requirement */
    con_min = UINT32_MAX;
    aw_min = NULL;
    for (aw = asi_best->network->head; NULL != aw; aw = aw->next)
    {
      if ( (con_min >
            (a_con = s->env->get_connectivity (s->env->cls,
                                               &aw->addr->peer))) &&
           (GNUNET_YES == aw->addr->active) )
      {
        aw_min = aw;
        con_min = a_con;
        if (0 == con_min)
          break;
      }
    }
    update_active_address (s,
                           aw_min->addr,
                           &aw_min->addr->peer);
  }
  distribute_bandwidth_in_network (s,
                                   asi_best->network);
}
Exemplo n.º 22
0
static int
testDirectory (unsigned int i)
{
  struct GNUNET_FS_DirectoryBuilder *db;
  char *data;
  size_t dlen;
  struct GNUNET_FS_Uri **uris;
  struct GNUNET_CONTAINER_MetaData **mds;
  struct GNUNET_CONTAINER_MetaData *meta;
  struct PCLS cls;
  char *emsg;
  int p;
  int q;
  char uri[512];
  char txt[128];
  int ret = 0;
  struct GNUNET_TIME_Absolute start;
  const char *s;

  cls.max = i;
  uris = GNUNET_malloc (sizeof (struct GNUNET_FS_Uri *) * i);
  mds = GNUNET_malloc (sizeof (struct GNUNET_CONTAINER_MetaData *) * i);
  meta = GNUNET_CONTAINER_meta_data_create ();
  GNUNET_CONTAINER_meta_data_insert (meta, "<test>", EXTRACTOR_METATYPE_TITLE,
                                     EXTRACTOR_METAFORMAT_UTF8, "text/plain",
                                     "A title", strlen ("A title") + 1);
  GNUNET_CONTAINER_meta_data_insert (meta, "<test>",
                                     EXTRACTOR_METATYPE_AUTHOR_NAME,
                                     EXTRACTOR_METAFORMAT_UTF8, "text/plain",
                                     "An author", strlen ("An author") + 1);
  for (p = 0; p < i; p++)
  {
    mds[p] = GNUNET_CONTAINER_meta_data_create ();
    for (q = 0; q <= p; q++)
    {
      GNUNET_snprintf (txt, sizeof (txt), "%u -- %u\n", p, q);
      GNUNET_CONTAINER_meta_data_insert (mds[p], "<test>",
#if HAVE_EXTRACTOR_H
                                         q % EXTRACTOR_metatype_get_max (),
#else
                                         q % 128,
#endif
                                         EXTRACTOR_METAFORMAT_UTF8,
                                         "text/plain", txt, strlen (txt) + 1);
    }
    GNUNET_snprintf (uri, sizeof (uri),
                     "gnunet://fs/chk/C282GG70GKK41O4551011DO413KFBVTVMQG1OG30I0K4045N0G41HAPB82G680A02JRVVFO8URVRU2F159011DO41000000022RG820.RNVVVVOOLCLK065B5D04HTNVNSIB2AI022RG8200HSLK1CO1000ATQ98824DMA2032LIMG50CG0K057NVUVG200000H000004400000.%u",
                     p);
    emsg = NULL;
    uris[p] = GNUNET_FS_uri_parse (uri, &emsg);
    if (uris[p] == NULL)
    {
      GNUNET_CONTAINER_meta_data_destroy (mds[p]);
      while (--p > 0)
      {
        GNUNET_CONTAINER_meta_data_destroy (mds[p]);
        GNUNET_FS_uri_destroy (uris[p]);
      }
      GNUNET_free (mds);
      GNUNET_free (uris);
      GNUNET_free (emsg);
      GNUNET_CONTAINER_meta_data_destroy (meta);
      ABORT ();                 /* error in testcase */
    }
    GNUNET_assert (emsg == NULL);
  }
  start = GNUNET_TIME_absolute_get ();
  db = GNUNET_FS_directory_builder_create (meta);
  for (p = 0; p < i; p++)
    GNUNET_FS_directory_builder_add (db, uris[p], mds[p], NULL);
  GNUNET_FS_directory_builder_finish (db, &dlen, (void **) &data);
  s = GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration
                                              (start),
					      GNUNET_YES);
  FPRINTF (stdout,
           "Creating directory with %u entires and total size %llu took %s\n",
           i, (unsigned long long) dlen, s);
  if (i < 100)
  {
    cls.pos = 0;
    cls.uri = uris;
    cls.md = mds;
    GNUNET_FS_directory_list_contents (dlen, data, 0, &processor, &cls);
    GNUNET_assert (cls.pos == i);
  }
  GNUNET_free (data);
  GNUNET_CONTAINER_meta_data_destroy (meta);
  for (p = 0; p < i; p++)
  {
    GNUNET_CONTAINER_meta_data_destroy (mds[p]);
    GNUNET_FS_uri_destroy (uris[p]);
  }
  GNUNET_free (uris);
  GNUNET_free (mds);
  return ret;
}
Exemplo n.º 23
0
int
main (int argc, char *argv[])
{
    int i;
    struct GNUNET_CRYPTO_EcdhePrivateKey *ecdhe[l];
    struct GNUNET_CRYPTO_EcdhePublicKey dhpub[l];
    struct GNUNET_CRYPTO_EddsaPrivateKey *eddsa[l];
    struct GNUNET_CRYPTO_EddsaPublicKey dspub[l];
    struct TestSig sig[l];

    start = GNUNET_TIME_absolute_get();
    for (i = 0; i < l; i++)
    {
        sig[i].purp.purpose = 0;
        sig[i].purp.size = htonl (sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose)
                                  + sizeof (struct GNUNET_HashCode));
        GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_WEAK,
                                    &sig[i].h,
                                    sizeof (sig[i].h));
    }
    log_duration ("", "Init");

    start = GNUNET_TIME_absolute_get();
    for (i = 0; i < l; i++)
        eddsa[i] = GNUNET_CRYPTO_eddsa_key_create();
    log_duration ("EdDSA", "create key");

    start = GNUNET_TIME_absolute_get();
    for (i = 0; i < l; i++)
        GNUNET_CRYPTO_eddsa_key_get_public (eddsa[i], &dspub[i]);
    log_duration ("EdDSA", "get pubilc");

    start = GNUNET_TIME_absolute_get();
    for (i = 0; i < l; i++)
        GNUNET_assert (GNUNET_OK ==
                       GNUNET_CRYPTO_eddsa_sign (eddsa[i],
                               &sig[i].purp,
                               &sig[i].sig));
    log_duration ("EdDSA", "sign HashCode");

    start = GNUNET_TIME_absolute_get();
    for (i = 0; i < l; i++)
        GNUNET_assert (GNUNET_OK ==
                       GNUNET_CRYPTO_eddsa_verify (0,
                               &sig[i].purp,
                               &sig[i].sig,
                               &dspub[i]));
    log_duration ("EdDSA", "verify HashCode");

    start = GNUNET_TIME_absolute_get();
    for (i = 0; i < l; i++)
        ecdhe[i] = GNUNET_CRYPTO_ecdhe_key_create();
    log_duration ("ECDH", "create key");

    start = GNUNET_TIME_absolute_get();
    for (i = 0; i < l; i++)
        GNUNET_CRYPTO_ecdhe_key_get_public (ecdhe[i], &dhpub[i]);
    log_duration ("ECDH", "get public");

    start = GNUNET_TIME_absolute_get();
    for (i = 0; i < l - 1; i+=2)
    {
        GNUNET_CRYPTO_ecc_ecdh (ecdhe[i], &dhpub[i+1], &sig[i].h);
        GNUNET_CRYPTO_ecc_ecdh (ecdhe[i+1], &dhpub[i], &sig[i+1].h);
    }
    log_duration ("ECDH", "do DH");

    return 0;
}
Exemplo n.º 24
0
/**
 * Periodically announce self id in the DHT
 *
 * @param cls closure
 */
static void
announce_id (void *cls)
{
  struct GNUNET_HashCode phash;
  const struct GNUNET_HELLO_Message *hello;
  size_t size;
  struct GNUNET_TIME_Absolute expiration;
  struct GNUNET_TIME_Relative next_put;

  hello = GCH_get_mine ();
  size = (NULL != hello) ? GNUNET_HELLO_size (hello) : 0;
  if (0 == size)
  {
    expiration = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get (),
                                           announce_delay);
    announce_delay = GNUNET_TIME_STD_BACKOFF (announce_delay);
  }
  else
  {
    expiration = GNUNET_HELLO_get_last_expiration (hello);
    announce_delay = GNUNET_TIME_UNIT_SECONDS;
  }

  /* Call again in id_announce_time, unless HELLO expires first,
   * but wait at least 1s. */
  next_put
    = GNUNET_TIME_absolute_get_remaining (expiration);
  next_put
    = GNUNET_TIME_relative_min (next_put,
                                id_announce_time);
  next_put
    = GNUNET_TIME_relative_max (next_put,
                                GNUNET_TIME_UNIT_SECONDS);
  announce_id_task
    = GNUNET_SCHEDULER_add_delayed (next_put,
                                    &announce_id,
                                    cls);
  GNUNET_STATISTICS_update (stats,
                            "# DHT announce",
                            1,
                            GNUNET_NO);
  memset (&phash,
          0,
          sizeof (phash));
  GNUNET_memcpy (&phash,
                 &my_full_id,
                 sizeof (my_full_id));
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Announcing my HELLO (%u bytes) in the DHT\n",
       size);
  GNUNET_DHT_put (dht_handle,   /* DHT handle */
                  &phash,       /* Key to use */
                  dht_replication_level,     /* Replication level */
                  GNUNET_DHT_RO_RECORD_ROUTE
                  | GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,    /* DHT options */
                  GNUNET_BLOCK_TYPE_DHT_HELLO,       /* Block type */
                  size,  /* Size of the data */
                  (const char *) hello, /* Data itself */
                  expiration,  /* Data expiration */
                  NULL,         /* Continuation */
                  NULL);        /* Continuation closure */
}
Exemplo n.º 25
0
static size_t
send_ping_ready_cb (void *cls, size_t size, void *buf)
{
    struct BenchmarkPartner *p = cls;
    static char msgbuf[TEST_MESSAGE_SIZE];
    struct GNUNET_MessageHeader *msg;
    struct GNUNET_TIME_Relative delay;

    if (NULL == buf)
    {
        GNUNET_break (0);
        return 0;
    }
    if (size < TEST_MESSAGE_SIZE)
    {
        GNUNET_break (0);
        return 0;
    }

    GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
               "Master [%u]: Sending PING to [%u]\n",
               p->me->no, p->dest->no);
    if (top->test_core)
    {
        if (NULL == p->cth)
        {
            GNUNET_break (0);
        }
        p->cth = NULL;
    }
    else
    {
        if (NULL == p->tth)
        {
            GNUNET_break (0);
        }
        p->tth = NULL;
    }

    msg = (struct GNUNET_MessageHeader *) &msgbuf;
    memset (&msgbuf, 'a', TEST_MESSAGE_SIZE);
    msg->type = htons (TEST_MESSAGE_TYPE_PING);
    msg->size = htons (TEST_MESSAGE_SIZE);
    memcpy (buf, msg, TEST_MESSAGE_SIZE);

    p->messages_sent++;
    p->bytes_sent += TEST_MESSAGE_SIZE;
    p->me->total_messages_sent++;
    p->me->total_bytes_sent += TEST_MESSAGE_SIZE;

    if (NULL == p->tg)
    {
        GNUNET_break (0);
        return TEST_MESSAGE_SIZE;
    }
    delay = get_delay (p->tg);

    GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Delay for next transmission %llu ms\n",
               (long long unsigned int) delay.rel_value_us / 1000);
    p->tg->next_ping_transmission = GNUNET_TIME_absolute_add(GNUNET_TIME_absolute_get(),
                                    delay);

    return TEST_MESSAGE_SIZE;
}
Exemplo n.º 26
0
/**
 * Core handler for size estimate flooding messages.
 *
 * @param cls peer this message is from
 * @param incoming_flood received message
 */
static void
handle_p2p_estimate (void *cls,
		     const struct GNUNET_NSE_FloodMessage *incoming_flood)
{
  struct NSEPeerEntry *peer_entry = cls;
  struct GNUNET_TIME_Absolute ts;
  uint32_t matching_bits;
  unsigned int idx;

#if ENABLE_NSE_HISTOGRAM
  {
    uint64_t t;

    t = GNUNET_TIME_absolute_get().abs_value_us;
    if (NULL != lh)
      GNUNET_TESTBED_LOGGER_write (lh, &t, sizeof (uint64_t));
    if (NULL != histogram)
      GNUNET_BIO_write_int64 (histogram, t);
  }
#endif
  GNUNET_STATISTICS_update (stats,
			    "# flood messages received",
			    1,
			    GNUNET_NO);
  matching_bits = ntohl (incoming_flood->matching_bits);
#if DEBUG_NSE
  {
    char origin[5];
    char pred[5];
    struct GNUNET_PeerIdentity os;

    GNUNET_snprintf (origin,
		     sizeof (origin),
		     "%s",
		     GNUNET_i2s (&incoming_flood->origin));
    GNUNET_snprintf (pred,
		     sizeof (pred),
		     "%s",
		     GNUNET_i2s (peer_entry->id));
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                "Flood at %s from `%s' via `%s' at `%s' with bits %u\n",
                GNUNET_STRINGS_absolute_time_to_string (GNUNET_TIME_absolute_ntoh (incoming_flood->timestamp)),
                origin,
		pred,
		GNUNET_i2s (&my_identity),
                (unsigned int) matching_bits);
  }
#endif

#if ENABLE_NSE_HISTOGRAM
  peer_entry->received_messages++;
  if (peer_entry->transmitted_messages > 0 &&
      peer_entry->last_transmitted_size >= matching_bits)
    GNUNET_STATISTICS_update(stats,
			     "# cross messages",
			     1,
			     GNUNET_NO);
#endif

  ts = GNUNET_TIME_absolute_ntoh (incoming_flood->timestamp);
  if (ts.abs_value_us == current_timestamp.abs_value_us)
    idx = estimate_index;
  else if (ts.abs_value_us ==
           current_timestamp.abs_value_us - gnunet_nse_interval.rel_value_us)
    idx = (estimate_index + HISTORY_SIZE - 1) % HISTORY_SIZE;
  else if (ts.abs_value_us == next_timestamp.abs_value_us)
  {
    if (matching_bits <= ntohl (next_message.matching_bits))
      return;         /* ignore, simply too early/late */
    if (GNUNET_YES !=
	verify_message_crypto (incoming_flood))
    {
      GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                  "Peer %s is likely ill-configured!\n",
                  GNUNET_i2s (peer_entry->id));
      GNUNET_break_op (0);
      return;
    }
    next_message = *incoming_flood;
    return;
  }
  else
  {
    GNUNET_STATISTICS_update (stats,
                              "# flood messages discarded (clock skew too large)",
                              1, GNUNET_NO);
    return;
  }
  if (0 == (memcmp (peer_entry->id,
		    &my_identity,
		    sizeof (struct GNUNET_PeerIdentity))))
  {
    /* send to self, update our own estimate IF this also comes from us! */
    if (0 ==
        memcmp (&incoming_flood->origin,
		&my_identity, sizeof (my_identity)))
      update_network_size_estimate ();
    return;
  }
  if (matching_bits ==
      ntohl (size_estimate_messages[idx].matching_bits))
  {
    /* Cancel transmission in the other direction, as this peer clearly has
       up-to-date information already. Even if we didn't talk to this peer in
       the previous round, we should no longer send it stale information as it
       told us about the current round! */
    peer_entry->previous_round = GNUNET_YES;
    if (idx != estimate_index)
    {
      /* do not transmit information for the previous round to this peer
         anymore (but allow current round) */
      return;
    }
    /* got up-to-date information for current round, cancel transmission to
     * this peer altogether */
    if (NULL != peer_entry->transmit_task)
    {
      GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
      peer_entry->transmit_task = NULL;
    }
    return;
  }
  if (matching_bits < ntohl (size_estimate_messages[idx].matching_bits))
  {
    if ( (idx < estimate_index) &&
	 (peer_entry->previous_round == GNUNET_YES))
    {
      peer_entry->previous_round = GNUNET_NO;
    }
    /* push back our result now, that peer is spreading bad information... */
    if (NULL != peer_entry->transmit_task)
      GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
    peer_entry->transmit_task
      = GNUNET_SCHEDULER_add_now (&transmit_task_cb,
				  peer_entry);
    /* Not closer than our most recent message, no need to do work here */
    GNUNET_STATISTICS_update (stats,
                              "# flood messages ignored (had closer already)",
                              1,
			      GNUNET_NO);
    return;
  }
  if (GNUNET_YES !=
      verify_message_crypto (incoming_flood))
  {
    GNUNET_break_op (0);
    return;
  }
  GNUNET_assert (matching_bits >
                 ntohl (size_estimate_messages[idx].matching_bits));
  /* Cancel transmission in the other direction, as this peer clearly has
   * up-to-date information already.
   */
  peer_entry->previous_round = GNUNET_YES;
  if (idx == estimate_index)
  {
    /* cancel any activity for current round */
    if (NULL != peer_entry->transmit_task)
    {
      GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
      peer_entry->transmit_task = NULL;
    }
  }
  size_estimate_messages[idx] = *incoming_flood;
  size_estimate_messages[idx].hop_count =
      htonl (ntohl (incoming_flood->hop_count) + 1);
  hop_count_max =
      GNUNET_MAX (ntohl (incoming_flood->hop_count) + 1,
		  hop_count_max);
  GNUNET_STATISTICS_set (stats,
			 "# estimated network diameter",
			 hop_count_max, GNUNET_NO);

  /* have a new, better size estimate, inform clients */
  update_network_size_estimate ();

  /* flood to rest */
  GNUNET_CONTAINER_multipeermap_iterate (peers,
					 &update_flood_times,
                                         peer_entry);
}
static void
secret_ready_cb (void *cls,
                 struct GNUNET_SECRETSHARING_Share *my_share,
                 struct GNUNET_SECRETSHARING_PublicKey *public_key,
                 unsigned int num_ready_peers,
                 struct GNUNET_PeerIdentity *ready_peers)
{
  struct GNUNET_SECRETSHARING_Session **sp = cls;
  unsigned int n = sp - session_handles;
  char pubkey_str[1024];
  char *ret;

  num_generated++;
  *sp = NULL;
  shares[n] = my_share;
  if (NULL == my_share)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_INFO, "key generation failed for peer #%u\n", n);
  }
  else
  {
    ret = GNUNET_STRINGS_data_to_string (public_key, sizeof *public_key, pubkey_str, 1024);
    GNUNET_assert (NULL != ret);
    *ret = '\0';
    GNUNET_log (GNUNET_ERROR_TYPE_INFO, "key generation successful for peer #%u, pubkey %s\n", n,
                pubkey_str);

    /* we're the first to get the key -> store it */
    if (num_generated == 1)
    {
      common_pubkey = *public_key;
    }
    else if (0 != memcmp (public_key, &common_pubkey, sizeof (struct GNUNET_SECRETSHARING_PublicKey)))
    {
      GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "generated public keys do not match\n");
      GNUNET_SCHEDULER_shutdown ();
      return;
    }
  }

  // FIXME: destroy testbed operation

  if (num_generated == num_peers)
  {
    int i;
    if (GNUNET_NO == decrypt)
    {
      GNUNET_SCHEDULER_shutdown ();
      return;
    }

    decrypt_start = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get (), delay);
    decrypt_deadline = GNUNET_TIME_absolute_add (decrypt_start, timeout);


    // compute g^42
    GNUNET_SECRETSHARING_plaintext_generate_i (&reference_plaintext, 42);
    GNUNET_SECRETSHARING_encrypt (&common_pubkey, &reference_plaintext, &ciphertext);

    // FIXME: store the ops somewhere!
    for (i = 0; i < num_peers; i++)
      GNUNET_TESTBED_service_connect (NULL, peers[i], "secretsharing", &decrypt_connect_complete, NULL,
                                      &decrypt_connect_adapter, &decrypt_disconnect_adapter, &decrypt_handles[i]);
  }
}
Exemplo n.º 28
0
/**
 * Initialize a message to clients with the current network
 * size estimate.
 *
 * @param em message to fill in
 */
static void
setup_estimate_message (struct GNUNET_NSE_ClientMessage *em)
{
  double mean;
  double sum;
  double std_dev;
  double variance;
  double val;
  double nsize;

#define WEST 1
  /* Weighted incremental algorithm for stddev according to West (1979) */
#if WEST
  double sumweight;
  double weight;
  double q;
  double r;
  double temp;

  mean = 0.0;
  sum = 0.0;
  sumweight = 0.0;
  variance = 0.0;
  for (unsigned int i = 0; i < estimate_count; i++)
  {
    unsigned int j = (estimate_index - i + HISTORY_SIZE) % HISTORY_SIZE;

    val = htonl (size_estimate_messages[j].matching_bits);
    weight = estimate_count + 1 - i;

    temp = weight + sumweight;
    q = val - mean;
    r = q * weight / temp;
    mean += r;
    sum += sumweight * q * r;
    sumweight = temp;
  }
  if (estimate_count > 0)
    variance = (sum / sumweight) * estimate_count / (estimate_count - 1.0);
#else
  /* trivial version for debugging */
  double vsq;

  /* non-weighted trivial version */
  sum = 0.0;
  vsq = 0.0;
  variance = 0.0;
  mean = 0.0;

  for (unsigned int i = 0; i < estimate_count; i++)
  {
    unsigned int j = (estimate_index - i + HISTORY_SIZE) % HISTORY_SIZE;

    val = htonl (size_estimate_messages[j].matching_bits);
    sum += val;
    vsq += val * val;
  }
  if (0 != estimate_count)
  {
    mean = sum / estimate_count;
    variance = (vsq - mean * sum) / (estimate_count - 1.0);     // terrible for numerical stability...
  }
#endif
  if (variance >= 0)
    std_dev = sqrt (variance);
  else
    std_dev = variance;         /* must be infinity due to estimate_count == 0 */
  current_std_dev = std_dev;
  current_size_estimate = mean;

  em->header.size = htons (sizeof (struct GNUNET_NSE_ClientMessage));
  em->header.type = htons (GNUNET_MESSAGE_TYPE_NSE_ESTIMATE);
  em->reserved = htonl (0);
  em->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
  {
    double se = mean - 0.332747;
    unsigned int j = GNUNET_CONTAINER_multipeermap_size (peers);
    if (0 == j)
      j = 1; /* Avoid log2(0); can only happen if CORE didn't report
		connection to self yet */
    nsize = log2 (j);
    em->size_estimate = GNUNET_hton_double (GNUNET_MAX (se,
							nsize));
    em->std_deviation = GNUNET_hton_double (std_dev);
    GNUNET_STATISTICS_set (stats,
			   "# nodes in the network (estimate)",
			   (uint64_t) pow (2, GNUNET_MAX (se,
							  nsize)),
			   GNUNET_NO);
  }
}
static void *
progress_cb (void *cls, const struct GNUNET_FS_ProgressInfo *event)
{
  const char *keywords[] = {
    "down_foo"
  };
  struct GNUNET_FS_Uri *kuri;

  switch (event->status)
  {
  case GNUNET_FS_STATUS_PUBLISH_PROGRESS:
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
		"Publish is progressing (%llu/%llu at level %u off %llu)...\n",
		(unsigned long long) event->value.publish.completed,
		(unsigned long long) event->value.publish.size,
		event->value.publish.specifics.progress.depth,
		(unsigned long long) event->value.publish.specifics.
		progress.offset);
    break;
  case GNUNET_FS_STATUS_PUBLISH_COMPLETED:
    kuri = GNUNET_FS_uri_ksk_create_from_args (1, keywords);
    start = GNUNET_TIME_absolute_get ();
    GNUNET_FS_search_start (fs, kuri, 1, GNUNET_FS_SEARCH_OPTION_NONE,
                            "search");
    GNUNET_FS_uri_destroy (kuri);
    GNUNET_assert (search != NULL);
    break;
  case GNUNET_FS_STATUS_PUBLISH_SUSPEND:
    if (event->value.publish.pc == publish)
      publish = NULL;
    break;
  case GNUNET_FS_STATUS_PUBLISH_RESUME:
    if (NULL == publish)
      publish = event->value.publish.pc;
    break;
  case GNUNET_FS_STATUS_SEARCH_RESULT:
    /* FIXME: consider_restart (event->status); cannot be tested with
     * search result since we exit here after the first one... */
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
		"Search complete.\n");
    GNUNET_SCHEDULER_add_continuation (&abort_search_task, NULL,
                                       GNUNET_SCHEDULER_REASON_PREREQ_DONE);
    break;
  case GNUNET_FS_STATUS_PUBLISH_ERROR:
    FPRINTF (stderr, "Error publishing file: %s\n",
             event->value.publish.specifics.error.message);
    GNUNET_break (0);
    GNUNET_SCHEDULER_add_continuation (&abort_publish_task, NULL,
                                       GNUNET_SCHEDULER_REASON_PREREQ_DONE);
    break;
  case GNUNET_FS_STATUS_SEARCH_ERROR:
    FPRINTF (stderr, "Error searching file: %s\n",
             event->value.search.specifics.error.message);
    GNUNET_SCHEDULER_add_continuation (&abort_search_task, NULL,
                                       GNUNET_SCHEDULER_REASON_PREREQ_DONE);
    break;
  case GNUNET_FS_STATUS_SEARCH_SUSPEND:
    if (event->value.search.sc == search)
      search = NULL;
    break;
  case GNUNET_FS_STATUS_SEARCH_RESUME:
    if (NULL == search)
    {
      search = event->value.search.sc;
      return "search";
    }
    break;
  case GNUNET_FS_STATUS_PUBLISH_START:
    GNUNET_assert (0 == strcmp ("publish-context", event->value.publish.cctx));
    GNUNET_assert (NULL == event->value.publish.pctx);
    GNUNET_assert (FILESIZE == event->value.publish.size);
    GNUNET_assert (0 == event->value.publish.completed);
    GNUNET_assert (1 == event->value.publish.anonymity);
    break;
  case GNUNET_FS_STATUS_PUBLISH_STOPPED:
    GNUNET_assert (publish == event->value.publish.pc);
    GNUNET_assert (FILESIZE == event->value.publish.size);
    GNUNET_assert (1 == event->value.publish.anonymity);
    GNUNET_FS_stop (fs);
    fs = NULL;
    break;
  case GNUNET_FS_STATUS_SEARCH_START:
    consider_restart (event->status);
    GNUNET_assert (search == NULL);
    search = event->value.search.sc;
    GNUNET_assert (0 == strcmp ("search", event->value.search.cctx));
    GNUNET_assert (1 == event->value.search.anonymity);
    break;
  case GNUNET_FS_STATUS_SEARCH_RESULT_STOPPED:
    break;
  case GNUNET_FS_STATUS_SEARCH_STOPPED:
    GNUNET_assert (search == event->value.search.sc);
    GNUNET_SCHEDULER_add_continuation (&abort_publish_task, NULL,
                                       GNUNET_SCHEDULER_REASON_PREREQ_DONE);
    search = NULL;
    break;
  default:
    FPRINTF (stderr, "Unexpected event: %d\n", event->status);
    break;
  }
  return NULL;
}
Exemplo n.º 30
0
/**
 * Function is called whenever a message is received.
 *
 * @param cls closure (set from GNUNET_CADET_connect, peer number)
 * @param channel connection to the other end
 * @param channel_ctx place to store local state associated with the channel
 * @param message the actual message
 * @return GNUNET_OK to keep the connection open,
 *         GNUNET_SYSERR to close it (signal serious error)
 */
int
data_callback (void *cls, struct GNUNET_CADET_Channel *channel,
               void **channel_ctx,
               const struct GNUNET_MessageHeader *message)
{
  struct GNUNET_CADET_TransmitHandle **pth;
  long client = (long) cls;
  long expected_target_client;
  uint32_t *data;
  uint32_t payload;
  unsigned int counter;

  ok++;
  counter = get_expected_target () == client ? data_received : ack_received;

  GNUNET_CADET_receive_done (channel);

  if ((ok % 10) == 0)
  {
    if (NULL != disconnect_task)
    {
      GNUNET_log (GNUNET_ERROR_TYPE_INFO, " reschedule timeout\n");
      GNUNET_SCHEDULER_cancel (disconnect_task);
      disconnect_task = GNUNET_SCHEDULER_add_delayed (SHORT_TIME,
                                                      &gather_stats_and_exit,
                                                      (void *) __LINE__);
    }
  }

  switch (client)
  {
  case 0L:
    GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Root client got a message!\n");
    GNUNET_assert (channel == ch);
    pth = &th;
    break;
  case 1L:
  case 4L:
    GNUNET_assert (client == peers_requested - 1);
    GNUNET_assert (channel == incoming_ch);
    pth = &incoming_th;
    GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Leaf client %ld got a message.\n",
                client);
    break;
  default:
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Client %ld not valid.\n", client);
    GNUNET_assert (0);
  }
  GNUNET_log (GNUNET_ERROR_TYPE_INFO, " ok: (%d/%d)\n", ok, ok_goal);
  data = (uint32_t *) &message[1];
  payload = ntohl (*data);
  if (payload == counter)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_INFO, " payload as expected: %u\n", payload);
  }
  else
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR, " payload %u, expected: %u\n",
                payload, counter);
  }
  expected_target_client = get_expected_target ();

  if (GNUNET_NO == initialized)
  {
    initialized = GNUNET_YES;
    start_time = GNUNET_TIME_absolute_get ();
    if (SPEED == test)
    {
      GNUNET_assert (peers_requested - 1 == client);
      data_job = GNUNET_SCHEDULER_add_now (&data_task, NULL);
      return GNUNET_OK;
    }
  }

  counter++;
  if (client == expected_target_client) /* Normally 4 */
  {
    data_received++;
    GNUNET_log (GNUNET_ERROR_TYPE_INFO, " received data %u\n", data_received);
    if (SPEED != test || (ok_goal - 2) == ok)
    {
      /* Send ACK */
      GNUNET_assert (NULL == *pth);
      *pth = GNUNET_CADET_notify_transmit_ready (channel, GNUNET_NO,
                                                 GNUNET_TIME_UNIT_FOREVER_REL,
                                                 size_payload + ack_sent,
                                                 &tmt_rdy, (void *) client);
      return GNUNET_OK;
    }
    else
    {
      if (data_received < TOTAL_PACKETS)
        return GNUNET_OK;
    }
  }
  else /* Normally 0 */
  {
    if (SPEED_ACK == test || SPEED == test)
    {
      ack_received++;
      GNUNET_log (GNUNET_ERROR_TYPE_INFO, " received ack %u\n", ack_received);
      /* send more data */
      GNUNET_assert (NULL == *pth);
      *pth = GNUNET_CADET_notify_transmit_ready (channel, GNUNET_NO,
                                                 GNUNET_TIME_UNIT_FOREVER_REL,
                                                 size_payload + data_sent,
                                                 &tmt_rdy, (void *) client);
      if (ack_received < TOTAL_PACKETS && SPEED != test)
        return GNUNET_OK;
      if (ok == 2 && SPEED == test)
        return GNUNET_OK;
      show_end_data();
    }
    if (test == P2P_SIGNAL)
    {
      if (NULL != incoming_th)
      {
        GNUNET_CADET_notify_transmit_ready_cancel (incoming_th);
        incoming_th = NULL;
      }
      GNUNET_CADET_channel_destroy (incoming_ch);
      incoming_ch = NULL;
    }
    else
    {
      if (NULL != th)
      {
        GNUNET_CADET_notify_transmit_ready_cancel (th);
        th = NULL;
      }
      GNUNET_CADET_channel_destroy (ch);
      ch = NULL;
    }
  }

  return GNUNET_OK;
}