コード例 #1
0
/**
 * The owning peer of this path is no longer interested in maintaining
 * it, so the path should be discarded or shortened (in case a
 * previous peer on the path finds the path desirable).
 *
 * @param path the path that is being released
 */
void
GCPP_release (struct CadetPeerPath *path)
{
  struct CadetPeerPathEntry *entry;

  path->hn = NULL;
  entry = &path->entries[path->entries_length - 1];
  while (1)
  {
    /* cut 'off' end of path, verifying it is not in use */
    GNUNET_assert (NULL ==
                   GNUNET_CONTAINER_multipeermap_get (path->connections,
                                                      GCP_get_id (entry->peer)));
    GCP_path_entry_remove (entry->peer,
                           entry,
                           path->entries_length - 1);
    path->entries_length--; /* We don't bother shrinking the 'entries' array,
                               as it's probably not worth it. */
    if (0 == path->entries_length)
      break; /* the end */

    /* see if new peer at the end likes this path any better */
    entry = &path->entries[path->entries_length - 1];
    path->hn = GCP_attach_path (entry->peer,
                                path,
                                path->entries_length);
    if (NULL != path->hn)
      return; /* yep, got attached, we are done. */
  }

  /* nobody wants us, discard the path */
  path_destroy (path);
}
コード例 #2
0
ファイル: qos.c プロジェクト: KTrel/c-bgp_updated
/**
 * Aggregate N routes. The announced delay is the best route's delay.
 * The aggregated route has all the attribute (Next-Hop,
 * Communities, ...) of the best routes except the AS-Path which is an
 * AS-SET containing the AS-Num of all the ASes traversed by one of
 * the aggregated routes.
 */
SRoute * qos_route_aggregate(SRoutes * pRoutes, SRoute * pBestRoute)
{
  SRoute * pAggrRoute;
  int iIndex;
  SRoute * pRoute;
  SPath ** ppPaths= (SPath **) MALLOC(sizeof(SPath *)*
				      ptr_array_length(pRoutes));
  qos_delay_t tDelay;
  
  assert(routes_list_get_num(pRoutes) >= 1);

  // Aggregate Delay
  tDelay.tMean= 0;
  tDelay.uWeight= 0;
  for (iIndex= 0; iIndex < routes_list_get_num(pRoutes); iIndex++) {
    pRoute= (SRoute *) pRoutes->data[iIndex];
    tDelay.tMean+= pRoute->tDelay.uWeight*pRoute->tDelay.tMean;
    tDelay.uWeight+= pRoute->tDelay.uWeight;
    ppPaths[iIndex]= pRoute->pASPath;
  }
  tDelay.tMean= (int) (tDelay.tMean/tDelay.uWeight);

  // Aggregate Bandwidth: NOT YET IMPLEMENTED

  // Aggregate Paths
  pAggrRoute= route_copy(pBestRoute);
  pAggrRoute->tDelay= tDelay;
  pAggrRoute->tDelay.tDelay= pBestRoute->tDelay.tDelay;
  path_destroy(&pAggrRoute->pASPath);
  pAggrRoute->pASPath= path_aggregate(ppPaths, routes_list_get_num(pRoutes));
  FREE(ppPaths);

  return pAggrRoute;
}
コード例 #3
0
/**
 * Return a newly allocated individual path to reach a peer from the local peer,
 * according to the path tree of some tunnel.
 *
 * @param t Tunnel from which to read the path tree.
 * @param peer Short ID of the destination peer to whom we want a path.
 *
 * @return A newly allocated individual path to reach the destination peer.
 *         Path must be destroyed afterwards.
 */
struct MeshPeerPath *
tree_get_path_to_peer (struct MeshTunnelTree *t, GNUNET_PEER_Id peer)
{
  struct MeshTunnelTreeNode *n;
  struct MeshPeerPath *p;

  n = tree_find_peer (t, peer);
  if (NULL == n)
  {
    GNUNET_break (0);
    return NULL;
  }
  p = path_new (0);

  /* Building the path (inverted!) */
  while (n->peer != 1)
  {
    GNUNET_array_append (p->peers, p->length, n->peer);
    GNUNET_PEER_change_rc (n->peer, 1);
    n = n->parent;
    if (NULL == n)
    {
      GNUNET_break (0);
      path_destroy (p);
      return NULL;
    }
  }
  GNUNET_array_append (p->peers, p->length, 1);
  GNUNET_PEER_change_rc (1, 1);

  path_invert (p);

  return p;
}
コード例 #4
0
ファイル: cadet_path.c プロジェクト: muggenhor/GNUnet
/**
 * @brief Destroy a path after some time has past.
 *
 * If the path is returned from DHT again after a while, try again.
 *
 * Removes the path from the peer (except for direct paths).
 *
 * @param cls Closure (path to destroy).
 * @param tc Task context.
 */
static void
path_destroy_delayed (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
{
  struct CadetPeerPath *path = cls;
  struct CadetPeer *peer;

  LOG (GNUNET_ERROR_TYPE_INFO, "Destroy delayed %p (%u)\n", path, path->length);
  path->path_delete = NULL;

  /* During shutdown, the peers peermap might not exist anymore. */
  if ((GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason) == 0)
  {
    if (2 >= path->length)
    {
      /* This is not the place to destroy direct paths, only core_disconnect
       * should do it and never delay it.
       */
      GNUNET_break (0);
    }
    peer = GCP_get_short (path->peers[path->length - 1], GNUNET_NO);
    if (NULL != peer)
      GCP_remove_path (peer, path);
  }
  else
    path_destroy (path);
}
コード例 #5
0
ファイル: files.c プロジェクト: jgraef/meinOS
/**
 * Gets absolute path by relative path
 *  @param relative Relative or absolute path
 *  @return Absolute path (Can be passed to free())
 */
static char *getabsolutepath(const char *relative) {
  path_t *path = path_parse(relative);
  if (!path->root) {
    path_t *newpath = path_cat(workdir.path,path);
    path_destroy(path);
    path = newpath;
  }
  path_reject_dots(path);
  return path_output(path,NULL);
}
コード例 #6
0
ファイル: perfect_path.c プロジェクト: aylingm/metacortex
void perfect_path_print_paths(char *filename, int max_length, int singleton_length,
							  boolean with_coverages, dBGraph * db_graph)
{
	FILE * fout = NULL;
	FILE * fout_cov = NULL;
	int i;
	fout = fopen(filename, "w");
	
	if (with_coverages) {
		char filename_cov[strlen(filename) + 10];
		sprintf(filename_cov, "%s_cov", filename);
		fout_cov = fopen(filename_cov, "w");
	}
	limit = max_length;
	
	//Path *path = path_new(max_length, db_graph->kmer_size);
	//path->id=-1;
    
    perfect_path_print_supernodes_args ** args = calloc(db_graph->number_of_threads, sizeof(perfect_path_print_supernodes_args * ));
    
    for (i = 0; i < db_graph->number_of_threads; i++) {
        args[i] = calloc(1, sizeof(perfect_path_print_supernodes_args)) ;
        args[i]->db_graph = db_graph;
        args[i]->path = path_new(max_length, db_graph->kmer_size);
        args[i]->fout = fout;
        args[i]->fout_cov = fout_cov;//TODO: Make the printing function "thread safe"
    }
  
	//buffers = path_array_new(2);
	
	
	double graph_cov = db_graph_get_average_coverage(db_graph);
    log_and_screen_printf("Average coverage: %5.2f \n", graph_cov);
    
    
	
	hash_table_traverse_with_args(&print_supernode, (void ** ) args ,db_graph);
	
	
	log_and_screen_printf("%'d nodes visited [%'qd singletons, %'qd repetitive]\n", args[0]->count_nodes, args[0]->count_sing, args[0]->count_rep);//TODO: At some point we can make this multithreading
	path_counts_print_and_log(&args[0]->counts);
    
    
	for (i = 0; i < db_graph->number_of_threads; i++) {
        free(args[i]);
        path_destroy(args[i]->path);
    }
    free(args);
	
	
	fclose(fout);
	if (with_coverages) {
		fclose(fout_cov);
	}
}
コード例 #7
0
ファイル: mu-container.c プロジェクト: DamienCassou/mu
static void
mu_container_path_foreach (MuContainer *c, MuContainerPathForeachFunc func,
			gpointer user_data)
{
	Path *path;

	path = path_new (100);

	mu_container_path_foreach_real (c, 0, path, func, user_data);

	path_destroy (path);
}
コード例 #8
0
/**
* destroy_client(void)
*
* @brief Destroys client
* @param void
* @return void
*/
void destroy_client(void)
{
	printf("Clearing Data.\n");
	unload_shops();
	unload_spells();
	unload_items();
	unload_npcs();
	unload_players();
	unload_maps();
	endsocket();
	path_destroy();
}
コード例 #9
0
ファイル: api_path.c プロジェクト: emcmanus/FlashMesa3D
void vgDestroyPath(VGPath p)
{
   struct path *path = 0;
   struct vg_context *ctx = vg_current_context();

   if (p == VG_INVALID_HANDLE) {
      vg_set_error(ctx, VG_BAD_HANDLE_ERROR);
      return;
   }

   path = (struct path *)p;
   path_destroy(path);
}
コード例 #10
0
ファイル: cadet_path.c プロジェクト: muggenhor/GNUnet
/**
 * Builds a path from a PeerIdentity array.
 *
 * @param peers PeerIdentity array.
 * @param size Size of the @c peers array.
 * @param myid ID of local peer, to find @c own_pos.
 * @param own_pos Output parameter: own position in the path.
 *
 * @return Fixed and shortened path.
 */
struct CadetPeerPath *
path_build_from_peer_ids (struct GNUNET_PeerIdentity *peers,
                          unsigned int size,
                          GNUNET_PEER_Id myid,
                          unsigned int *own_pos)
{
  struct CadetPeerPath *path;
  GNUNET_PEER_Id shortid;
  unsigned int i;
  unsigned int j;
  unsigned int offset;

  /* Create path */
  LOG (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
  path = path_new (size);
  *own_pos = 0;
  offset = 0;
  for (i = 0; i < size; i++)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG, "  - %u: taking %s\n",
         i, GNUNET_i2s (&peers[i]));
    shortid = GNUNET_PEER_intern (&peers[i]);

    /* Check for loops / duplicates */
    for (j = 0; j < i - offset; j++)
    {
      if (path->peers[j] == shortid)
      {
        LOG (GNUNET_ERROR_TYPE_DEBUG, "    already exists at pos %u\n", j);
        offset = i - j;
        LOG (GNUNET_ERROR_TYPE_DEBUG, "    offset now %u\n", offset);
        GNUNET_PEER_change_rc (shortid, -1);
      }
    }
    LOG (GNUNET_ERROR_TYPE_DEBUG, "    storing at %u\n", i - offset);
    path->peers[i - offset] = shortid;
    if (path->peers[i - offset] == myid)
      *own_pos = i - offset;
  }
  path->length -= offset;

  if (path->peers[*own_pos] != myid)
  {
    /* create path: self not found in path through self */
    GNUNET_break_op (0);
    path_destroy (path);
    return NULL;
  }

  return path;
}
コード例 #11
0
ファイル: encodedecodetest.c プロジェクト: GabrielLiz/ccnx
int
encode_sample_test(const struct ccn_pkey *signing_key, const struct ccn_pkey *verification_key, 
			const char *algorithm, char *paths[], char *contents[], 
			struct ccn_charbuf *signed_info, char *outname)
{
    int result = 0;
    int fd;
    struct path * cur_path = NULL;
    struct ccn_charbuf *buffer = ccn_charbuf_create();
    struct ccn_skeleton_decoder dd = {0};
    ssize_t res;

    printf("Encoding sample message data length %d\n", (int)strlen(contents[0]));
    cur_path = path_create(paths[0]);
    if (encode_message(buffer, cur_path, contents[0], strlen(contents[0]), signed_info, signing_key, 
			algorithm)) {
        printf("Failed to encode message!\n");
	result = 1;
    } else {
        printf("Encoded sample message length is %d\n", (int)buffer->length);

        res = ccn_skeleton_decode(&dd, buffer->buf, buffer->length);
        if (!(res == buffer->length && dd.state == 0)) {
            printf("Failed to decode!  Result %d State %d\n", (int)res, dd.state);
            result = 1;
        }
        if (outname != NULL) {
            fd = open(outname, O_WRONLY|O_CREAT|O_TRUNC, S_IRWXU);
            if (fd == -1)
                perror(outname);
            res = write(fd, buffer->buf, buffer->length);
            close(fd);
        }
        if (decode_message(buffer, cur_path, contents[0], strlen(contents[0]), verification_key) != 0) {
            result = 1;
        }
        printf("Expect signature verification failure: ");
        if (buffer->length >= 20)
            buffer->buf[buffer->length - 20] += 1;
        if (decode_message(buffer, cur_path, contents[0], strlen(contents[0]), verification_key) == 0) {
            result = 1;
        }
    }
    path_destroy(&cur_path);
    ccn_charbuf_destroy(&buffer);
    printf("Done with sample message\n");
    return result;
}
コード例 #12
0
ファイル: krad_adapter.c プロジェクト: kripton/krad_radio-1
int kr_adapter_unlink(kr_adapter_path *path) {
  int i;
  kr_adapter *adapter;
  if (path == NULL) return -1;
  adapter = path->adapter;
  for (i = 0; i < KR_ADAPTER_PATHS_MAX; i++) {
    if (adapter->path[i] == NULL) continue;
    if (adapter->path[i] == path) {
      path_destroy(path);
      free(path);
      adapter->path[i] = NULL;
      return 0;
    }
  }
  return -1;
}
コード例 #13
0
ファイル: ex.c プロジェクト: Rocket-Buddha/GameCode4
/* pathname -- true/nil error */
static int ex_remove(lua_State *L)
{
  const char *pathname = luaL_checkstring(L, 1);
  struct stat attr;
  if (stat(pathname, &attr) == -1)
    return push_error(L);
  if (attr.st_mode & S_IFDIR) {
    if (!path_destroy(pathname))
      return push_error(L);
  } else {
    if (remove(pathname) == -1)
      return push_error(L);
  }
  lua_pushboolean(L, 1);
  return 1;
}
コード例 #14
0
ファイル: ex.c プロジェクト: ClowReed32/Cthugha-Engine-Demos
/* pathname -- true/nil error */
static int ex_remove(lua_State *L)
{
  const char *pathname = luaL_checkstring(L, 1);
  DWORD attr = GetFileAttributes(pathname);
  if (attr == (DWORD)-1)
    return push_error(L);
  if (attr & FILE_ATTRIBUTE_DIRECTORY) {
    if (!path_destroy(pathname))
		return push_error(L);
  } else {
    SetFileAttributes(pathname, FILE_ATTRIBUTE_ARCHIVE);
    if (!DeleteFile(pathname))
      return push_error(L);
  }
  lua_pushboolean(L, 1);
  return 1;
}
コード例 #15
0
ファイル: test-path.c プロジェクト: imaami/kivijalka
int
main (int    argc,
      char **argv)
{
	if (argv[1]) {
		path_head_t path;
		char *str;

		path_create (&path, argv[1]);

		if ((str = path_strdup (&path))) {
			printf ("%s (%zu)\n", str, path_strlen (&path));
			free (str);
		}

		path_destroy (&path);
	}
	return 0;
}
コード例 #16
0
void destroy_server(void)
{
	uint32 i = 0;

	printf("Saving online players.\n");

	for(i = 0; i < total_players_online(); i++)
		left_game(player_online(i));

	printf("Clearing Data.\n");
	unload_shops();
	unload_spells();
	unload_items();
	unload_npcs();
	unload_players();
	unload_maps();
	unload_socket();
	path_destroy();
	strings_destroy();
}
コード例 #17
0
/**
 * Function to process paths received for a new peer addition. The recorded
 * paths form the initial tunnel, which can be optimized later.
 * Called on each result obtained for the DHT search.
 *
 * @param cls closure
 * @param exp when will this value expire
 * @param key key of the result
 * @param get_path path of the get request
 * @param get_path_length lenght of @a get_path
 * @param put_path path of the put request
 * @param put_path_length length of the @a put_path
 * @param type type of the result
 * @param size number of bytes in data
 * @param data pointer to the result data
 */
static void
dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
                    const struct GNUNET_HashCode * key,
                    const struct GNUNET_PeerIdentity *get_path,
                    unsigned int get_path_length,
                    const struct GNUNET_PeerIdentity *put_path,
                    unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
                    size_t size, const void *data)
{
  struct GCD_search_handle *h = cls;
  struct GNUNET_HELLO_Message *hello;
  struct CadetPeerPath *p;
  struct CadetPeer *peer;
  char *s;

  p = path_build_from_dht (get_path, get_path_length,
                           put_path, put_path_length);
  if (NULL == p)
  {
    GNUNET_break_op (0);
    return;
  }

  s = path_2s (p);
  LOG (GNUNET_ERROR_TYPE_INFO,
       "Got path from DHT: %s\n",
       s);
  GNUNET_free_non_null (s);

  peer = GCP_get_short (p->peers[p->length - 1], GNUNET_YES);
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Got HELLO for %s\n",
       GCP_2s (peer));
  h->callback (h->cls, p);
  path_destroy (p);
  hello = (struct GNUNET_HELLO_Message *) data;
  GCP_set_hello (peer, hello);
  GCP_try_connect (peer);
}
コード例 #18
0
ファイル: path.c プロジェクト: Abyss116/luaplus51-all
/*
 * "os.path" API implementation
 */
int path_create(const char* inPath)
{
#if defined(WIN32)
  char path[MAX_PATH];
#else
  char path[FILENAME_MAX];
#endif
  char* pathPtr = path;
  char ch;

  if (*inPath == '/'  ||  *inPath == '\\') {
    *pathPtr++ = *inPath;
    inPath++;			// Skip the initial /
#if defined(WIN32)
    if (*inPath == '/'  ||  *inPath == '\\') {
      // UNC share
      *pathPtr++ = *inPath;
      inPath++;			// Skip the initial /
      // Copy the machine name.
      while ( (ch = *inPath++) ) {
        *pathPtr++ = ch;
        if (ch == '/'  ||  ch == '\\')
          break;
      }
      // Copy the share name.
      while ( (ch = *inPath++) ) {
        *pathPtr++ = ch;
        if (ch == '/'  ||  ch == '\\')
          break;
      }
    }
#endif
  }

  /* Copy the rest of the path into a buffer we can modify. */
  while ((ch = *inPath++)) {
    if (ch == '/'  ||  ch == '\\') {
#if defined(WIN32)
      *pathPtr++ = '\\';
#else
      *pathPtr++ = '/';
#endif /* WIN32 */
    } else
      *pathPtr++ = ch;
  }
  *pathPtr = 0;

  /* Determine which directories already exist. */
  --pathPtr;
  while (pathPtr > path) {
	struct stat fileInfo;
	char ch;
    while (pathPtr > path  &&  *pathPtr != '/'  &&  *pathPtr != '\\')
	  --pathPtr;
    ch = *pathPtr;
    if (ch == '/'  ||  ch == '\\') {
      *pathPtr = 0;
#if defined(WIN32)
      if (pathPtr > path + 1) {
        if (pathPtr[-1] == ':') {
            *pathPtr = ch;
			break;
        }
	  }
#endif /* WIN32 */
	  if (stat(path, &fileInfo) == 0) {
#if defined(WIN32)
        if (fileInfo.st_mode & _S_IFDIR) {
#else
        if (S_ISDIR(fileInfo.st_mode)) {
#endif // defined(WIN32)
          *pathPtr = ch;
          break;
	    } else {
          return 0;
        }
	  }
      *pathPtr = ch;
	}
	--pathPtr;
  }

  ++pathPtr;

  /* Create any remaining directories. */
  while ((ch = *pathPtr)) {
    if (ch == '/'  ||  ch == '\\') {
      *pathPtr = 0;
#if defined(WIN32)
      if (!CreateDirectory(path, NULL)  &&  GetLastError() != ERROR_ALREADY_EXISTS)
        return 0;
      *pathPtr++ = '\\';
#else
      if (mkdir(path, 0777)  &&  errno != EEXIST)
        return 0;
      *pathPtr++ = '/';
#endif
    } else {
      ++pathPtr;
	}
  }

  return 1;
}


int path_destroy(const char* inDirName)
{
  int ret = 1;
#if defined(WIN32)
  char dirName[MAX_PATH];
  char* dirNamePtr = dirName;
  char ch;
  WIN32_FIND_DATA fd;
  HANDLE handle;

  if (*inDirName == 0)
    return ret;

  while (ch = *inDirName++) {
    if (ch == '/'  ||  ch == '\\')
      *dirNamePtr++ = '\\';
    else
      *dirNamePtr++ = ch;
  }
  if (dirNamePtr[-1] != '\\')
    *dirNamePtr++ = '\\';
  *dirNamePtr = 0;

  strcpy(dirNamePtr, "*.*");

  handle = FindFirstFile(dirName, &fd);
  *dirNamePtr = 0;

  if (handle != INVALID_HANDLE_VALUE) {
    do {
      if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
        int skipDir = fd.cFileName[0] == '.'  &&
          (fd.cFileName[1] == 0  ||  (fd.cFileName[1] == '.'  &&  fd.cFileName[2] == 0));
        if (!skipDir) {
          strcpy(dirNamePtr, fd.cFileName);
          strcat(dirNamePtr, "\\");
		  if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
			  if (!path_destroy(dirName)) {
				ret = 0;
			  }
		  } else {
			  if (!RemoveDirectory(dirNamePtr))
				  ret = 0;
		  }
        }
      } else {
        strcpy(dirNamePtr, fd.cFileName);
        SetFileAttributes(dirName, FILE_ATTRIBUTE_ARCHIVE);
        if (!DeleteFile(dirName)) {
          ret = 0;
        }
      }
    } while (FindNextFile(handle, &fd));

    FindClose(handle);
  }

  *--dirNamePtr = 0;
  if (!RemoveDirectory(dirName))
    ret = 0;
#else
  char dirName[FILENAME_MAX];
  char* dirNamePtr;
  char ch;

  if (*inDirName == 0)
    return ret;

  dirNamePtr = dirName;

  while ((ch = *inDirName++)) {
    if (ch == '/'  ||  ch == '\\')
      *dirNamePtr++ = '/';
    else
      *dirNamePtr++ = ch;
  }
  if (dirNamePtr[-1] != '/')
    *dirNamePtr++ = '/';
  *dirNamePtr = 0;

  DIR* dirp = opendir(dirName);
  if (dirp)
  {
    struct dirent* dp;
    while ((dp = readdir(dirp)) != NULL) {
      strcpy(dirNamePtr, dp->d_name);
      if (dp->d_type & DT_DIR) {
        int skipDir = dp->d_name[0] == '.'  &&  (dp->d_name[1] == 0  ||  (dp->d_name[1] == '.'  &&  dp->d_name[2] == 0));
        if (!skipDir) {
          strcat(dirNamePtr, "/");
          if (!path_destroy(dirName)) {
            ret = 0;
          }
        }
      } else {
        if (unlink(dirName) == -1) {
          ret = 0;
        }
      }
    }
  }

  closedir(dirp);

  *--dirNamePtr = 0;
  if (rmdir(dirName) == -1)
    ret = 0;
#endif

  return ret;
}
コード例 #19
0
int main(int argc, char **argv)
{
    graph_t graph;
    path_t best, candidate, best_candidate;
    int rot_size, rot_start;
    int verbose = 0;

    if ((argc == 2) && (strncmp(argv[1], "-v", sizeof("-v")) == 0)) {
        verbose = 1;
    }
    else if (argc > 1) {
        fprintf(stderr, "\n");
        fprintf(stderr, "  Parâmetros inválidos!\n");
        fprintf(stderr, "\n");
        fprintf(stderr, "Uso: %s [-v]\n", argv[0]);
        fprintf(stderr, " -v     Ativa modo verbose (exibe detalhes da "
                        "execução do algoritmo)\n");
        return EXIT_FAILURE;
    }

    process_input(&graph);
    graph_calculate_distances(&graph);

    path_init(&best, &graph);
    path_find_greedy(&best, 1);

    if (verbose) {
        printf("1o. caminho: ");
        print_path(&best);
    }

    for (rot_size = 2; rot_size < graph.node_count; ++rot_size) {
        if (verbose) {
            printf("\n\n===== Trocando caminhos com tamanho %2d =====\n", rot_size);
        }

        path_copy(&best_candidate, &best);

        for (rot_start = 1; rot_start <= graph.node_count - rot_size; ++rot_start) {
            path_copy(&candidate, &best);
            path_rotate(&candidate, rot_size, rot_start);
            if (verbose) {
                printf("Troca # %3d: ", rot_start);
                print_path(&candidate);
            }

            if (candidate.distance < best_candidate.distance) {
                path_copy(&best_candidate, &candidate);
            }

            path_destroy(&candidate);
        }

        if (best_candidate.distance < best.distance) {
            path_copy(&best, &best_candidate);
        }

        if (verbose) {
            printf("\n   MELHOR  : ");
            print_path(&best);
        }
    }

    if (verbose) {
        printf("\n============================================\n");
    }

    printf("Melhor caminho encontrado:\n");
    print_path(&best);

    path_destroy(&best);
    path_destroy(&best_candidate);
    graph_destroy(&graph);

    return EXIT_SUCCESS;
}
コード例 #20
0
ファイル: api_path.c プロジェクト: emcmanus/FlashMesa3D
void vgPathTransformedBounds(VGPath path,
                             VGfloat * minX,
                             VGfloat * minY,
                             VGfloat * width,
                             VGfloat * height)
{
   struct vg_context *ctx = vg_current_context();
   struct path *p = 0;
   VGbitfield caps;

   if (path == VG_INVALID_HANDLE) {
      vg_set_error(ctx, VG_BAD_HANDLE_ERROR);
      return;
   }

   if (!minX || !minY || !width || !height) {
      vg_set_error(ctx, VG_ILLEGAL_ARGUMENT_ERROR);
      return;
   }

   if (!is_aligned(minX) || !is_aligned(minY) ||
       !is_aligned(width) || !is_aligned(height)) {
      vg_set_error(ctx, VG_ILLEGAL_ARGUMENT_ERROR);
      return;
   }

   p = (struct path*)path;

   caps = path_capabilities(p);
   if (!(caps & VG_PATH_CAPABILITY_PATH_TRANSFORMED_BOUNDS)) {
      vg_set_error(ctx, VG_PATH_CAPABILITY_ERROR);
      return;
   }

#if 0
   /* faster, but seems to have precision problems... */
   path_bounding_rect(p, minX, minY, width, height);
   if (*width > 0 && *height > 0) {
      VGfloat pts[] = {*minX,          *minY,
                       *minX + *width, *minY,
                       *minX + *width, *minY + *height,
                       *minX,          *minY + *height};
      struct matrix *matrix = &ctx->state.vg.path_user_to_surface_matrix;
      VGfloat maxX, maxY;
      matrix_map_point(matrix, pts[0], pts[1], pts + 0, pts + 1);
      matrix_map_point(matrix, pts[2], pts[3], pts + 2, pts + 3);
      matrix_map_point(matrix, pts[4], pts[5], pts + 4, pts + 5);
      matrix_map_point(matrix, pts[6], pts[7], pts + 6, pts + 7);
      *minX = MIN2(pts[0], MIN2(pts[2], MIN2(pts[4], pts[6])));
      *minY = MIN2(pts[1], MIN2(pts[3], MIN2(pts[5], pts[7])));
      maxX = MAX2(pts[0], MAX2(pts[2], MAX2(pts[4], pts[6])));
      maxY = MAX2(pts[1], MAX2(pts[3], MAX2(pts[5], pts[7])));
      *width  = maxX - *minX;
      *height = maxY - *minY;
   }
#else
   {
      struct path *dst = path_create(VG_PATH_DATATYPE_F, 1.0, 0,
                                     0, 0, VG_PATH_CAPABILITY_ALL);
      path_transform(dst, p);
      path_bounding_rect(dst, minX, minY, width, height);
      path_destroy(dst);
   }
#endif
}
コード例 #21
0
ファイル: encodedecodetest.c プロジェクト: Emat12/ccnx
int
main (int argc, char *argv[]) {
    struct ccn_charbuf *buffer = ccn_charbuf_create();
    struct ccn_charbuf *signed_info = ccn_charbuf_create();
    struct ccn_skeleton_decoder dd = {0};
    ssize_t res;
    char *outname = NULL;
    int fd;
    int result = 0;
    char * contents[] = {"INVITE sip:[email protected] SIP/2.0\nVia: SIP/2.0/UDP 127.0.0.1:5060;rport;branch=z9hG4bK519044721\nFrom: <sip:[email protected]>;tag=2105643453\nTo: Test User <sip:[email protected]>\nCall-ID: [email protected]\nCSeq: 20 INVITE\nContact: <sip:[email protected]:5060>\nMax-Forwards: 70\nUser-Agent: Linphone-1.7.1/eXosip\nSubject: Phone call\nExpires: 120\nAllow: INVITE, ACK, CANCEL, BYE, OPTIONS, REFER, SUBSCRIBE, NOTIFY, MESSAGE\nContent-Type: application/sdp\nContent-Length:   448\n\nv=0\no=jthornto 123456 654321 IN IP4 127.0.0.1\ns=A conversation\nc=IN IP4 127.0.0.1\nt=0 0\nm=audio 7078 RTP/AVP 111 110 0 3 8 101\na=rtpmap:111 speex/16000/1\na=rtpmap:110 speex/8000/1\na=rtpmap:0 PCMU/8000/1\na=rtpmap:3 GSM/8000/1\na=rtpmap:8 PCMA/8000/1\na=rtpmap:101 telephone-event/8000\na=fmtp:101 0-11\nm=video 9078 RTP/AVP 97 98 99\na=rtpmap:97 theora/90000\na=rtpmap:98 H263-1998/90000\na=fmtp:98 CIF=1;QCIF=1\na=rtpmap:99 MP4V-ES/90000\n", 
 
			 "Quaer #%2d zjduer  badone",
                         "",
                         NULL};
    char * paths[] = { "/sip/protocol/parc.com/domain/foo/principal/invite/verb/[email protected]/id", 
		       "/d/e/f",
                       "/zero/length/content",
                       NULL};
    struct path * cur_path = NULL;
    struct ccn_keystore *keystore = ccn_keystore_create();
    char *home = getenv("HOME");
    char *keystore_suffix = "/.ccnx/.ccnx_keystore";
    char *keystore_name = NULL;

    int i;

    if (argc == 3 && strcmp(argv[1], "-o") == 0) {
	outname = argv[2];
    } else {
	printf("Usage: %s -o <outfilename>\n", argv[0]);
	exit(1);
    }

    if (home == NULL) {
        printf("Unable to determine home directory for keystore\n");
        exit(1);
    }
    keystore_name = calloc(1, strlen(home) + strlen(keystore_suffix) + 1);
    
    strcat(keystore_name, home);
    strcat(keystore_name, keystore_suffix);

    if (0 != ccn_keystore_init(keystore, keystore_name, "Th1s1sn0t8g00dp8ssw0rd.")) {
        printf("Failed to initialize keystore\n");
        exit(1);
    }

    printf("Creating signed_info\n");
    res = ccn_signed_info_create(signed_info,
                                 /*pubkeyid*/ccn_keystore_public_key_digest(keystore),
                                 /*publisher_key_id_size*/ccn_keystore_public_key_digest_length(keystore),
                                 /*datetime*/NULL,
                                 /*type*/CCN_CONTENT_GONE,
                                 /*freshness*/ 42,
                                 /*finalblockid*/NULL,
                                 /*keylocator*/NULL);
    if (res < 0) {
        printf("Failed to create signed_info!\n");
    }
    
    res = ccn_skeleton_decode(&dd, signed_info->buf, signed_info->length);
    if (!(res == signed_info->length && dd.state == 0)) {
        printf("Failed to decode signed_info!  Result %d State %d\n", (int)res, dd.state);
        result = 1;
    }
    memset(&dd, 0, sizeof(dd));
    printf("Done with signed_info\n");

    printf("Encoding sample message data length %d\n", (int)strlen(contents[0]));
    cur_path = path_create(paths[0]);
    if (encode_message(buffer, cur_path, contents[0], strlen(contents[0]), signed_info, ccn_keystore_private_key(keystore))) {
	printf("Failed to encode message!\n");
    } else {
	printf("Encoded sample message length is %d\n", (int)buffer->length);

	res = ccn_skeleton_decode(&dd, buffer->buf, buffer->length);
	if (!(res == buffer->length && dd.state == 0)) {
	    printf("Failed to decode!  Result %d State %d\n", (int)res, dd.state);
	    result = 1;
	}
        if (outname != NULL) {
            fd = open(outname, O_WRONLY|O_CREAT|O_TRUNC, S_IRWXU);
            if (fd == -1)
                perror(outname);
            res = write(fd, buffer->buf, buffer->length);
            close(fd);
	}
        if (decode_message(buffer, cur_path, contents[0], strlen(contents[0]), ccn_keystore_public_key(keystore)) != 0) {
	    result = 1;
	}
        printf("Expect signature verification failure: ");
        if (buffer->length >= 20)
            buffer->buf[buffer->length - 20] += 1;
	if (decode_message(buffer, cur_path, contents[0], strlen(contents[0]), ccn_keystore_public_key(keystore)) == 0) {
	    result = 1;
	}
    }
    path_destroy(&cur_path);
    ccn_charbuf_destroy(&buffer);
    printf("Done with sample message\n");
    
    /* Now exercise as unit tests */
    
    for (i = 0; paths[i] != NULL && contents[i] != NULL; i++) {
	printf("Unit test case %d\n", i);
	cur_path = path_create(paths[i]);
	buffer = ccn_charbuf_create();
	if (encode_message(buffer, cur_path, contents[i], strlen(contents[i]), signed_info, ccn_keystore_private_key(keystore))) {
	    printf("Failed encode\n");
            result = 1;
	} else if (decode_message(buffer, cur_path, contents[i], strlen(contents[i]), ccn_keystore_public_key(keystore))) {
	    printf("Failed decode\n");
            result = 1;
	}
	path_destroy(&cur_path);
	ccn_charbuf_destroy(&buffer);
    }
    
    /* Test the uri encode / decode routines */
        
    init_all_chars_percent_encoded();
    const char *uri_tests[] = {
        "_+4", "ccnx:/this/is/a/test",       "",     "ccnx:/this/is/a/test",
        ".+4", "../test2?x=2",              "?x=2", "ccnx:/this/is/a/test2",
        "_-X", "../should/error",           "",     "",
        "_+2", "/missing/scheme",           "",     "ccnx:/missing/scheme",
        ".+0", "../../../../../././#/",     "#/",   "ccnx:/",
        ".+1", all_chars_percent_encoded,   "",     all_chars_percent_encoded_canon,
        "_+1", all_chars_percent_encoded_canon, "", all_chars_percent_encoded_canon,
        ".+4", "ccnx:/.../.%2e./...././.....///?...", "?...", "ccnx:/.../.../..../.....",
        "_-X", "/%3G?bad-pecent-encode",    "",     "",
        "_-X", "/%3?bad-percent-encode",    "",     "",
        "_-X", "/%#bad-percent-encode",    "",     "",
        "_+3", "ccnx://[email protected]:42/ignore/host/part of uri", "", "ccnx:/ignore/host/part%20of%20uri",
        NULL, NULL, NULL, NULL
    };
    const char **u;
    struct ccn_charbuf *uri_out = ccn_charbuf_create();
    buffer = ccn_charbuf_create();
    for (u = uri_tests; *u != NULL; u += 4, i++) {
        printf("Unit test case %d\n", i);
        if (u[0][0] != '.')
            buffer->length = 0;
        res = ccn_name_from_uri(buffer, u[1]);
        if (!expected_res(res, u[0][1])) {
            printf("Failed: ccn_name_from_uri wrong res %d\n", (int)res);
            result = 1;
        }
        if (res >= 0) {
            if (res > strlen(u[1])) {
                printf("Failed: ccn_name_from_uri long res %d\n", (int)res);
                result = 1;
            }
            else if (0 != strcmp(u[1] + res, u[2])) {
                printf("Failed: ccn_name_from_uri expecting leftover '%s', got '%s'\n", u[2], u[1] + res);
                result = 1;
            }
            uri_out->length = 0;
            res = ccn_uri_append(uri_out, buffer->buf, buffer->length, 1);
            if (!expected_res(res, u[0][2])) {
                printf("Failed: ccn_uri_append wrong res %d\n", (int)res);
                result = 1;
            }
            if (res >= 0) {
                if (uri_out->length != strlen(u[3])) {
                    printf("Failed: ccn_uri_append produced wrong number of characters\n");
                    result = 1;
                }
                ccn_charbuf_reserve(uri_out, 1)[0] = 0;
                if (0 != strcmp((const char *)uri_out->buf, u[3])) {
                    printf("Failed: ccn_uri_append produced wrong output\n");
                    printf("Expected: %s\n", u[3]);
                    printf("  Actual: %s\n", (const char *)uri_out->buf);
                    result = 1;
                }
            }
        }
    }
    ccn_charbuf_destroy(&buffer);
    ccn_charbuf_destroy(&uri_out);
    printf("Name marker tests\n");
    do {
        const char *expected_uri = "ccnx:/example.com/.../%01/%FE/%01%02%03%04%05%06%07%08/%FD%10%10%10%10%1F%FF/%00%81";
        const char *expected_chopped_uri = "ccnx:/example.com/.../%01/%FE";
        const char *expected_bumped_uri = "ccnx:/example.com/.../%01/%FF";
        const char *expected_bumped2_uri = "ccnx:/example.com/.../%01/%00%00";

        printf("Unit test case %d\n", i++);
        buffer = ccn_charbuf_create();
        uri_out = ccn_charbuf_create();
        res = ccn_name_init(buffer);
        res |= ccn_name_append_str(buffer, "example.com");
        res |= ccn_name_append_numeric(buffer, CCN_MARKER_NONE, 0);
        res |= ccn_name_append_numeric(buffer, CCN_MARKER_NONE, 1);
        res |= ccn_name_append_numeric(buffer, 0xFE, 0);
        res |= ccn_name_append_numeric(buffer, CCN_MARKER_NONE, 0x0102030405060708ULL);
        res |= ccn_name_append_numeric(buffer, CCN_MARKER_VERSION, 0x101010101FFFULL);
        res |= ccn_name_append_numeric(buffer, CCN_MARKER_SEQNUM, 129);
        res |= ccn_uri_append(uri_out, buffer->buf, buffer->length, 1);
        if (res < 0) {
            printf("Failed: name marker tests had negative res\n");
            result = 1;
        }
        if (0 != strcmp(ccn_charbuf_as_string(uri_out), expected_uri)) {
            printf("Failed: name marker tests produced wrong output\n");
            printf("Expected: %s\n", expected_uri);
            printf("  Actual: %s\n", (const char *)uri_out->buf);
            result = 1;
        }
        res = ccn_name_chop(buffer, NULL, 100);
        if (res != -1) {
            printf("Failed: ccn_name_chop did not produce error \n");
            result = 1;
        }
        res = ccn_name_chop(buffer, NULL, 4);
        if (res != 4) {
            printf("Failed: ccn_name_chop got wrong length\n");
            result = 1;
        }
        uri_out->length = 0;
        ccn_uri_append(uri_out, buffer->buf, buffer->length, 1);
        if (0 != strcmp(ccn_charbuf_as_string(uri_out), expected_chopped_uri)) {
            printf("Failed: ccn_name_chop botch\n");
            printf("Expected: %s\n", expected_chopped_uri);
            printf("  Actual: %s\n", (const char *)uri_out->buf);
            result = 1;
        }
        res = ccn_name_next_sibling(buffer);
        if (res != 4) {
            printf("Failed: ccn_name_next_sibling got wrong length\n");
            result = 1;
        }
        uri_out->length = 0;
        ccn_uri_append(uri_out, buffer->buf, buffer->length, 1);
        if (0 != strcmp(ccn_charbuf_as_string(uri_out), expected_bumped_uri)) {
            printf("Failed: ccn_name_next_sibling botch\n");
            printf("Expected: %s\n", expected_bumped_uri);
            printf("  Actual: %s\n", (const char *)uri_out->buf);
            result = 1;
        }
        ccn_name_next_sibling(buffer);
        uri_out->length = 0;
        ccn_uri_append(uri_out, buffer->buf, buffer->length, 1);
        if (0 != strcmp(ccn_charbuf_as_string(uri_out), expected_bumped2_uri)) {
            printf("Failed: ccn_name_next_sibling botch\n");
            printf("Expected: %s\n", expected_bumped2_uri);
            printf("  Actual: %s\n", (const char *)uri_out->buf);
            result = 1;
        }
        ccn_charbuf_destroy(&buffer);
        ccn_charbuf_destroy(&uri_out);
    } while (0);
    printf("Message digest tests\n");
    do {
        printf("Unit test case %d\n", i++);
        struct ccn_digest *dg = ccn_digest_create(CCN_DIGEST_SHA256);
        if (dg == NULL) {
            printf("Failed: ccn_digest_create returned NULL\n");
            result = 1;
            break;
        }
        printf("Unit test case %d\n", i++);
        const unsigned char expected_digest[] = {
            0xb3, 0x82, 0xcd, 0xb0, 0xe9, 0x5d, 0xf7, 0x3b, 0xe7, 0xdc, 0x19, 0x81, 0x3a, 0xfd, 0xdf, 0x89, 0xfb, 0xd4, 0xd4, 0xa0, 0xdb, 0x11, 0xa6, 0xba, 0x24, 0x16, 0x5b, 0xad, 0x9d, 0x90, 0x72, 0xb0
        };
        unsigned char actual_digest[sizeof(expected_digest)] = {0};
        const char *data = "Content-centric";
        if (ccn_digest_size(dg) != sizeof(expected_digest)) {
            printf("Failed: wrong digest size\n");
            result = 1;
            break;
        }
        printf("Unit test case %d\n", i++);
        ccn_digest_init(dg);
        res = ccn_digest_update(dg, data, strlen(data));
        if (res != 0)
            printf("Warning: check res %d\n", (int)res);
        printf("Unit test case %d\n", i++);
        res = ccn_digest_final(dg, actual_digest, sizeof(expected_digest));
        if (res != 0)
            printf("Warning: check res %d\n", (int)res);
        if (0 != memcmp(actual_digest, expected_digest, sizeof(expected_digest))) {
            printf("Failed: wrong digest\n");
            result = 1;
            break;
        }
    } while (0);
    printf("Really basic PRNG test\n");
    do {
        unsigned char r1[42];
        unsigned char r2[42];
        printf("Unit test case %d\n", i++);
        ccn_add_entropy(&i, sizeof(i), 0); /* Not much entropy, really. */
        ccn_random_bytes(r1, sizeof(r1));
        memcpy(r2, r1, sizeof(r2));
        ccn_random_bytes(r2, sizeof(r2));
        if (0 == memcmp(r1, r2, sizeof(r2))) {
            printf("Failed: badly broken PRNG\n");
            result = 1;
            break;
        }
    } while (0);
    printf("Bloom filter tests\n");
    do {
        unsigned char seed1[4] = "1492";
        const char *a[13] = {
            "one", "two", "three", "four",
            "five", "six", "seven", "eight",
            "nine", "ten", "eleven", "twelve",
            "thirteen"
        };
        struct ccn_bloom *b1 = NULL;
        struct ccn_bloom *b2 = NULL;
        int j, k, t1, t2;
        unsigned short us;
        
        printf("Unit test case %d\n", i++);
        b1 = ccn_bloom_create(13, seed1);
        
        for (j = 0; j < 13; j++)
            if (ccn_bloom_match(b1, a[j], strlen(a[j]))) break;
        if (j < 13) {
            printf("Failed: \"%s\" matched empty Bloom filter\n", a[j]);
            result = 1;
            break;
        }
        printf("Unit test case %d\n", i++);
        for (j = 0; j < 13; j++)
            ccn_bloom_insert(b1, a[j], strlen(a[j]));
        for (j = 0; j < 13; j++)
            if (!ccn_bloom_match(b1, a[j], strlen(a[j]))) break;
        if (j < 13) {
            printf("Failed: \"%s\" not found when it should have been\n", a[j]);
            result = 1;
            break;
        }
        printf("Unit test case %d\n", i++);
        for (j = 0, k = 0; j < 13; j++)
            if (ccn_bloom_match(b1, a[j]+1, strlen(a[j]+1)))
                k++;
        if (k > 0) {
            printf("Mmm, found %d false positives\n", k);
            if (k > 2) {
                result = 1;
                break;
            }
        }
        unsigned char seed2[5] = "aqfb\0";
        for (; seed2[3] <= 'f'; seed2[3]++) {
            printf("Unit test case %d (%4s)    ", i++, seed2);
            b2 = ccn_bloom_create(13, seed2);
            for (j = 0; j < 13; j++)
                ccn_bloom_insert(b2, a[j], strlen(a[j]));
            for (j = 0, k = 0, us = ~0; us > 0; us--) {
                t1 = ccn_bloom_match(b1, &us, sizeof(us));
                t2 = ccn_bloom_match(b2, &us, sizeof(us));
                j += (t1 | t2);
                k += (t1 & t2);
            }
            printf("either=%d both=%d wiresize=%d\n", j, k, ccn_bloom_wiresize(b1));
            if (k > 12) {
                printf("Failed: Bloom seeding may not be effective\n");
                result = 1;
            }
            ccn_bloom_destroy(&b2);
        }
        ccn_bloom_destroy(&b1);
    } while (0);
    printf("ccn_sign_content() tests\n");
    do {
        struct ccn *h = ccn_create();
        struct ccn_charbuf *co = ccn_charbuf_create();
        struct ccn_signing_params sparm = CCN_SIGNING_PARAMS_INIT;
        struct ccn_parsed_ContentObject pco = {0};
        struct ccn_charbuf *name = ccn_charbuf_create();
        
        printf("Unit test case %d\n", i++);
        ccn_name_from_uri(name, "ccnx:/test/data/%00%42");
        res = ccn_sign_content(h, co, name, NULL, "DATA", 4);
        if (res != 0) {
            printf("Failed: res == %d\n", (int)res);
            result = 1;
        }
        sparm.template_ccnb = ccn_charbuf_create();
        res = ccn_parse_ContentObject(co->buf, co->length, &pco, NULL);
        if (res != 0) {
            printf("Failed: ccn_parse_ContentObject res == %d\n", (int)res);
            result = 1;
            break;
        }
        ccn_charbuf_append(sparm.template_ccnb,
            co->buf + pco.offset[CCN_PCO_B_SignedInfo],
            pco.offset[CCN_PCO_E_SignedInfo] - pco.offset[CCN_PCO_B_SignedInfo]);
        sparm.sp_flags = CCN_SP_TEMPL_TIMESTAMP;
        printf("Unit test case %d\n", i++);
        res = ccn_sign_content(h, co, name, &sparm, "DATA", 4);
        if (res != 0) {
            printf("Failed: res == %d\n", (int)res);
            result = 1;
        }
        printf("Unit test case %d\n", i++);
        sparm.sp_flags = -1;
        res = ccn_sign_content(h, co, name, &sparm, "DATA", 4);
        if (res != -1) {
            printf("Failed: res == %d\n", (int)res);
            result = 1;
        }
        ccn_charbuf_destroy(&name);
        ccn_charbuf_destroy(&sparm.template_ccnb);
        ccn_charbuf_destroy(&co);
        ccn_destroy(&h);
    } while (0);
    printf("link tests\n");
    do {
        struct ccn_charbuf *l = ccn_charbuf_create();
        struct ccn_charbuf *name = ccn_charbuf_create();
        struct ccn_parsed_Link pl = {0};
        struct ccn_buf_decoder decoder;
        struct ccn_buf_decoder *d;
        struct ccn_indexbuf *comps = ccn_indexbuf_create();
        printf("Unit test case %d\n", i++);
        ccn_name_from_uri(name, "ccnx:/test/link/name");
        ccnb_append_Link(l, name, "label", NULL);
        d = ccn_buf_decoder_start(&decoder, l->buf, l->length);
        res = ccn_parse_Link(d, &pl, comps);
        if (res != 3 /* components in name */) {
            printf("Failed: ccn_parse_Link res == %d\n", (int)res);
            result = 1;
        }        
    } while (0);
    
    exit(result);
}
コード例 #22
0
ファイル: metacortex.c プロジェクト: TGAC/kontaminant
/*----------------------------------------------------------------------*
 * Function:                                                            *
 * Purpose:                                                             *
 * Params:                                                              *
 * Returns:                                                             *
 *----------------------------------------------------------------------*/
int grow_graph_from_node(dBNode* start_node, dBNode** best_node, dBGraph* graph)
{                         
    Queue* nodes_to_walk;
    dBNode* node;
    int orientation;
    int depth;
    int current_graph_size = 0;
    int best_coverage = 0;
    int best_edges = 0;
    
    *best_node = 0;
    
    // Nucleotide iterator, used to walk all possible paths from a node
    void walk_if_exists(Nucleotide n) {
        //if (debug) printf("Trying nucleotide %i\n", n);
        
        // If there is an edge in any colour for this nucleotide...
        if (db_node_edge_exist_any_colour(node, n, orientation)) {
            
            //if (debug) printf("  Edge exists\n");
            
            // Get first node along this edge and check we've not already visited it...
            Orientation next_orientation;
            Nucleotide reverse_nucleotide;
            dBNode * next_node;
            next_node = db_graph_get_next_node(node, orientation, &next_orientation, n, &reverse_nucleotide, graph);
            if (!next_node) {
                log_and_screen_printf("Error: Something went wrong with db_graph_get_next_node\n");
                exit(-1);
            }
            
            // If not already visited the first node, walk it...
            if (!db_node_check_flag_visited(next_node)) {
                pathStep first_step;
                Path * new_path;
                dBNode* end_node; 
                int i = 0;
                                
                // Get path				
                first_step.node = node;
                first_step.orientation = orientation;
                first_step.label = n;
                new_path = path_new(MAX_EXPLORE_NODES, graph->kmer_size);
                if (!new_path) {
                    log_and_screen_printf("ERROR: Not enough memory to allocate new path.\n");
                    exit(-1);
                }
                
                db_graph_get_perfect_path_with_first_edge_all_colours(&first_step, &db_node_action_do_nothing, new_path, graph);
                
                // Add end node to list of nodes to visit
                end_node = new_path->nodes[new_path->length-1];
                if (!db_node_check_flag_visited(end_node)) {
                    if (!db_node_is_blunt_end_all_colours(end_node, new_path->orientations[new_path->length-1])) {
                        if (queue_push_node(nodes_to_walk, end_node, depth+1) == NULL) {
                            log_and_screen_printf("Queue too large. Ending.\n");
                            exit(1);
                        }                        
                    }
                }
                
                // Now go through all nodes, look for best and mark all as visited
                for (i=0; i<new_path->length; i++) {
                    if (!db_node_check_flag_visited(new_path->nodes[i])) {
                        int this_coverage = element_get_coverage_all_colours(new_path->nodes[i]);
                        int this_edges = db_node_edges_count_all_colours(new_path->nodes[i], forward) + db_node_edges_count_all_colours(new_path->nodes[i], reverse);
                        
                        if ((best_node == 0) ||
                            (this_coverage > best_coverage) ||
                            ((this_coverage == best_coverage) && (this_edges < best_edges)))
                        {
                            best_coverage = this_coverage;
                            best_edges = this_edges;
                            *best_node = new_path->nodes[i];                            
                        }
                        
                        db_node_action_set_flag_visited(new_path->nodes[i]);
                        current_graph_size++;                        
                    }
                }
                
                // Clean up
                path_destroy(new_path);
            }
        }
    }
    
    // Start a queue of nodes to walk
    //log_and_screen_printf("Allocating %d Mb to store queue information (max %d nodes, when full each node could be %d)...\n", ((METACORTEX_QUEUE_SIZE * sizeof(QueueItem*)) / 1024) / 1024, METACORTEX_QUEUE_SIZE, sizeof(QueueItem));
    nodes_to_walk = queue_new(METACORTEX_QUEUE_SIZE);
    if (!nodes_to_walk) {
        log_and_screen_printf("Couldn't get memory for node queue.\n");
        exit(-1);
    }
    
    // Add start node to list of nodes to visit
    if (queue_push_node(nodes_to_walk, start_node, 0) == NULL) {
        log_and_screen_printf("Queue too large. Ending.\n");
        exit(-1);        
    }
    
    if (!db_node_check_flag_visited(start_node)) {
        db_node_action_set_flag_visited(start_node);
        current_graph_size++;
    }
    
    // Now keep visiting nodes and walking paths
    while (nodes_to_walk->number_of_items > 0) {
        // Take top node from list
        node = queue_pop_node(nodes_to_walk, &depth);
        
        // Look at all paths out from here
        orientation = forward;
        nucleotide_iterator(&walk_if_exists);
        orientation = reverse;
        nucleotide_iterator(&walk_if_exists);				
    }
    
    queue_free(nodes_to_walk);
    
    // If we didn't find a start node, presumably this is a singleton?
    if (*best_node == 0) {
        printf("Note: didn't find a best node, setting to start node\n");
        *best_node = start_node;
    }
    
    return current_graph_size;
}
コード例 #23
0
ファイル: path.c プロジェクト: manbug/luaplus51-all
int path_destroy(const char* inDirName)
{
#if defined(WIN32)
  char dirName[MAX_PATH];
  char* dirNamePtr = dirName;
  char ch;
  WIN32_FIND_DATA fd;
  HANDLE handle;

  if (*inDirName == 0)
    return 1;

  while (ch = *inDirName++) {
    if (ch == '/'  ||  ch == '\\')
      *dirNamePtr++ = '\\';
    else
      *dirNamePtr++ = ch;
  }
  if (dirNamePtr[-1] != '\\')
    *dirNamePtr++ = '\\';
  *dirNamePtr = 0;

  strcpy(dirNamePtr, "*.*");

  handle = FindFirstFile(dirName, &fd);
  *dirNamePtr = 0;

  if (handle != INVALID_HANDLE_VALUE)
  {
    do {
      if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
        int skipDir = fd.cFileName[0] == '.'  &&
          (fd.cFileName[1] == 0  ||  (fd.cFileName[1] == '.'  &&  fd.cFileName[2] == 0));
        if (!skipDir) {
          strcpy(dirNamePtr, fd.cFileName);
          strcat(dirNamePtr, "\\");
          if (!path_destroy(dirName)) {
            FindClose(handle);
            return 0;
          }
        }
      } else {
        strcpy(dirNamePtr, fd.cFileName);
        SetFileAttributes(dirName, FILE_ATTRIBUTE_ARCHIVE);
        if (!DeleteFile(dirName)) {
          FindClose(handle);
          return 0;
        }
      }
	} while (FindNextFile(handle, &fd));

    FindClose(handle);
  }

  *--dirNamePtr = 0;
  if (!RemoveDirectory(dirName))
    return 0;
#else
  char dirName[FILENAME_MAX];
  char* dirNamePtr;
  char ch;

  if (*inDirName == 0)
    return 1;

  dirNamePtr = dirName;

  while (ch = *inDirName++) {
    if (ch == '/'  ||  ch == '\\')
      *dirNamePtr++ = '/';
    else
      *dirNamePtr++ = ch;
  }
  if (dirNamePtr[-1] != '/')
    *dirNamePtr++ = '/';
  *dirNamePtr = 0;

  DIR* dirp = opendir(dirName);
  if (dirp)
  {
    struct dirent* dp;
    while ((dp = readdir(dirp)) != NULL) {
      strcpy(dirNamePtr, dp->d_name);
	  if (dp->d_type & DT_DIR) {
        int skipDir = dp->d_name[0] == '.'  &&  (dp->d_name[1] == 0  ||  (dp->d_name[1] == '.'  &&  dp->d_name[2] == 0));
        if (!skipDir) {
          strcat(dirNamePtr, "/");
          if (!path_destroy(dirName)) {
            closedir(dirp);
            return 0;
		  }
        }
      } else {
        if (unlink(dirName) == -1) {
          closedir(dirp);
          return 0;
        }
      }
    }
  }

  closedir(dirp);

  *--dirNamePtr = 0;
  if (rmdir(dirName) == -1)
    return 0;
#endif

  return 1;
}
コード例 #24
0
ファイル: encodedecodetest.c プロジェクト: GabrielLiz/ccnx
int
main(int argc, char *argv[])
{
    struct ccn_charbuf *buffer;
    struct ccn_charbuf *signed_info = ccn_charbuf_create();
    struct ccn_skeleton_decoder dd = {0};
    ssize_t res;
    char *outname = NULL;
    int result = 0;
    char * contents[] = {"INVITE sip:[email protected] SIP/2.0\nVia: SIP/2.0/UDP 127.0.0.1:5060;rport;branch=z9hG4bK519044721\nFrom: <sip:[email protected]>;tag=2105643453\nTo: Test User <sip:[email protected]>\nCall-ID: [email protected]\nCSeq: 20 INVITE\nContact: <sip:[email protected]:5060>\nMax-Forwards: 70\nUser-Agent: Linphone-1.7.1/eXosip\nSubject: Phone call\nExpires: 120\nAllow: INVITE, ACK, CANCEL, BYE, OPTIONS, REFER, SUBSCRIBE, NOTIFY, MESSAGE\nContent-Type: application/sdp\nContent-Length:   448\n\nv=0\no=jthornto 123456 654321 IN IP4 127.0.0.1\ns=A conversation\nc=IN IP4 127.0.0.1\nt=0 0\nm=audio 7078 RTP/AVP 111 110 0 3 8 101\na=rtpmap:111 speex/16000/1\na=rtpmap:110 speex/8000/1\na=rtpmap:0 PCMU/8000/1\na=rtpmap:3 GSM/8000/1\na=rtpmap:8 PCMA/8000/1\na=rtpmap:101 telephone-event/8000\na=fmtp:101 0-11\nm=video 9078 RTP/AVP 97 98 99\na=rtpmap:97 theora/90000\na=rtpmap:98 H263-1998/90000\na=fmtp:98 CIF=1;QCIF=1\na=rtpmap:99 MP4V-ES/90000\n",
 
			 "Quaer #%2d zjduer  badone",
                         "",
                         NULL};
    char * paths[] = { "/sip/protocol/parc.com/domain/foo/principal/invite/verb/[email protected]/id", 
		       "/d/e/f",
                       "/zero/length/content",
                       NULL};
    struct path * cur_path = NULL;
    struct ccn_keystore *keystore = ccn_keystore_create();
    struct ccn_keystore *aes_keystore = ccn_aes_keystore_create();
    char *keystore_name = NULL;
    char *keystore_password = NULL;
    char *aes_keystore_name = NULL;
    unsigned char keybuf[32];

    int i;

    while ((i = getopt(argc, argv, "a:k:p:o:")) != -1) {
        switch (i) {
	    case 'a':
                aes_keystore_name = optarg;
                break;
            case 'k':
                keystore_name = optarg;
                break;
            case 'p':
                keystore_password = optarg;
                break;
            case 'o':
                outname = optarg;
                break;
            default:
                printf("Usage: %s [-k <keystore>] [-o <outfilename>]\n", argv[0]);
                exit(1);
        }
    }

    if (keystore_name == NULL)
        keystore_name = "test.keystore";

    if (aes_keystore_name == NULL)
        aes_keystore_name = "test.aeskeystore";

    if (keystore_password == NULL)
        keystore_password = "******";

    res = ccn_keystore_init(keystore, keystore_name, keystore_password);
    if (res != 0) {
        printf ("Initializing keystore in %s\n", keystore_name);
        res = ccn_keystore_file_init(keystore_name, keystore_password,
                                     "ccnxuser", 0, 3650);
        if (res != 0) {
            fprintf (stderr, "Cannot create keystore [%s]", keystore_name);
            return res;
        }
        res = ccn_keystore_init(keystore, keystore_name, keystore_password);
        if (res != 0) {
            printf("Failed to initialize keystore\n");
            exit(1);
        }
    }

    res = ccn_aes_keystore_init(aes_keystore, aes_keystore_name, keystore_password);
    if (res != 0) {
        printf ("Initializing AES keystore in %s\n", aes_keystore_name);
        ccn_generate_symmetric_key(keybuf, 256);
        res = ccn_aes_keystore_file_init(aes_keystore_name, keystore_password, keybuf, 256);
        if (res != 0) {
            fprintf (stderr, "Cannot create keystore [%s]", keystore_name);
            return res;
        }
        res = ccn_aes_keystore_init(aes_keystore, aes_keystore_name, keystore_password);
        if (res != 0) {
            printf("Failed to initialize keystore\n");
            exit(1);
        }
    }

    printf("Creating signed_info\n");
    res = ccn_signed_info_create(signed_info,
                                 /*pubkeyid*/ccn_keystore_key_digest(keystore),
                                 /*publisher_key_id_size*/ccn_keystore_key_digest_length(keystore),
                                 /*timestamp*/NULL,
                                 /*type*/CCN_CONTENT_GONE,
                                 /*freshness*/ 42,
                                 /*finalblockid*/NULL,
                                 /*keylocator*/NULL);
    if (res < 0) {
        printf("Failed to create signed_info!\n");
    }

    res = ccn_skeleton_decode(&dd, signed_info->buf, signed_info->length);
    if (!(res == signed_info->length && dd.state == 0)) {
        printf("Failed to decode signed_info!  Result %d State %d\n", (int)res, dd.state);
        result = 1;
    }
    memset(&dd, 0, sizeof(dd));
    printf("Done with signed_info\n");

    result = encode_sample_test(ccn_keystore_key(keystore), ccn_keystore_public_key(keystore), 
		ccn_keystore_digest_algorithm(keystore), paths, contents, signed_info, outname);

    if (! result) {
    	result = encode_sample_test(ccn_keystore_key(aes_keystore), ccn_keystore_key(aes_keystore), 
                        ccn_keystore_digest_algorithm(aes_keystore),
			paths, contents, signed_info, outname);
    }

    /* Now exercise as unit tests */

    for (i = 0; paths[i] != NULL && contents[i] != NULL; i++) {
        printf("Unit test case %d\n", i);
        cur_path = path_create(paths[i]);
        buffer = ccn_charbuf_create();
        if (encode_message(buffer, cur_path, contents[i], strlen(contents[i]), signed_info,
                       ccn_keystore_key(keystore), ccn_keystore_digest_algorithm(keystore))) {
            printf("Failed encode\n");
            result = 1;
        } else if (decode_message(buffer, cur_path, contents[i], strlen(contents[i]), 
                       ccn_keystore_public_key(keystore))) {
            printf("Failed decode\n");
            result = 1;
        }
        ccn_charbuf_destroy(&buffer);
        buffer = ccn_charbuf_create();
        if (encode_message(buffer, cur_path, contents[i], strlen(contents[i]), signed_info,
                       ccn_keystore_key(aes_keystore), ccn_keystore_digest_algorithm(aes_keystore))) {
            printf("Failed encode\n");
            result = 1;
        } else if (decode_message(buffer, cur_path, contents[i], strlen(contents[i]), ccn_keystore_key(aes_keystore))) {
            printf("Failed decode\n");
            result = 1;
        }
        path_destroy(&cur_path);
        ccn_charbuf_destroy(&buffer);
    }

    /* Test the uri encode / decode routines */

    init_all_chars_percent_encoded();
    init_all_chars_mixed_encoded();
    const char *uri_tests[] = {
        "_+4", "ccnx:/this/is/a/test",       "",     "ccnx:/this/is/a/test",
        ".+4", "../test2?x=2",              "?x=2", "ccnx:/this/is/a/test2",
        "_-X", "../should/error",           "",     "",
        "_+2", "/missing/scheme",           "",     "ccnx:/missing/scheme",
        ".+0", "../../../../../././#/",     "#/",   "ccnx:/",
        ".+1", all_chars_percent_encoded,   "",     all_chars_percent_encoded_canon,
        "_+1", all_chars_percent_encoded_canon, "", all_chars_percent_encoded_canon,
        ".+4", "ccnx:/.../.%2e./...././.....///?...", "?...", "ccnx:/.../.../..../.....",
        "_-X", "/%3G?bad-pecent-encode",    "",     "",
        "_-X", "/%3?bad-percent-encode",    "",     "",
        "_-X", "/%#bad-percent-encode",    "",     "",
        "_+3", "ccnx://[email protected]:42/ignore/host/part of uri", "", "ccnx:/ignore/host/part%20of%20uri",
        NULL, NULL, NULL, NULL
    };
    const char **u;
    struct ccn_charbuf *uri_out = ccn_charbuf_create();
    buffer = ccn_charbuf_create();
    for (u = uri_tests; *u != NULL; u += 4, i++) {
        printf("Unit test case %d\n", i);
        if (u[0][0] != '.')
            buffer->length = 0;
        res = ccn_name_from_uri(buffer, u[1]);
        if (!expected_res(res, u[0][1])) {
            printf("Failed: ccn_name_from_uri wrong res %d\n", (int)res);
            result = 1;
        }
        if (res >= 0) {
            if (res > strlen(u[1])) {
                printf("Failed: ccn_name_from_uri long res %d\n", (int)res);
                result = 1;
            }
            else if (0 != strcmp(u[1] + res, u[2])) {
                printf("Failed: ccn_name_from_uri expecting leftover '%s', got '%s'\n", u[2], u[1] + res);
                result = 1;
            }
            uri_out->length = 0;
            res = ccn_uri_append(uri_out, buffer->buf, buffer->length,
                                 CCN_URI_PERCENTESCAPE | CCN_URI_INCLUDESCHEME);
            if (!expected_res(res, u[0][2])) {
                printf("Failed: ccn_uri_append wrong res %d\n", (int)res);
                result = 1;
            }
            if (res >= 0) {
                if (uri_out->length != strlen(u[3])) {
                    printf("Failed: ccn_uri_append produced wrong number of characters\n");
                    result = 1;
                }
                ccn_charbuf_reserve(uri_out, 1)[0] = 0;
                if (0 != strcmp((const char *)uri_out->buf, u[3])) {
                    printf("Failed: ccn_uri_append produced wrong output\n");
                    printf("Expected: %s\n", u[3]);
                    printf("  Actual: %s\n", (const char *)uri_out->buf);
                    result = 1;
                }
            }
        }
    }
    ccn_charbuf_destroy(&buffer);
    ccn_charbuf_destroy(&uri_out);
    printf("Name marker tests\n");
    do {
        const char *expected_uri = "ccnx:/example.com/.../%01/%FE/%01%02%03%04%05%06%07%08/%FD%10%10%10%10%1F%FF/%00%81";
        const char *expected_chopped_uri = "ccnx:/example.com/.../%01/%FE";
        const char *expected_bumped_uri = "ccnx:/example.com/.../%01/%FF";
        const char *expected_bumped2_uri = "ccnx:/example.com/.../%01/%00%00";

        printf("Unit test case %d\n", i++);
        buffer = ccn_charbuf_create();
        uri_out = ccn_charbuf_create();
        res = ccn_name_init(buffer);
        res |= ccn_name_append_str(buffer, "example.com");
        res |= ccn_name_append_numeric(buffer, CCN_MARKER_NONE, 0);
        res |= ccn_name_append_numeric(buffer, CCN_MARKER_NONE, 1);
        res |= ccn_name_append_numeric(buffer, 0xFE, 0);
        res |= ccn_name_append_numeric(buffer, CCN_MARKER_NONE, 0x0102030405060708ULL);
        res |= ccn_name_append_numeric(buffer, CCN_MARKER_VERSION, 0x101010101FFFULL);
        res |= ccn_name_append_numeric(buffer, CCN_MARKER_SEQNUM, 129);
        res |= ccn_uri_append(uri_out, buffer->buf, buffer->length,
                              CCN_URI_PERCENTESCAPE | CCN_URI_INCLUDESCHEME);
        if (res < 0) {
            printf("Failed: name marker tests had negative res\n");
            result = 1;
        }
        if (0 != strcmp(ccn_charbuf_as_string(uri_out), expected_uri)) {
            printf("Failed: name marker tests produced wrong output\n");
            printf("Expected: %s\n", expected_uri);
            printf("  Actual: %s\n", (const char *)uri_out->buf);
            result = 1;
        }
        res = ccn_name_chop(buffer, NULL, 100);
        if (res != -1) {
            printf("Failed: ccn_name_chop did not produce error \n");
            result = 1;
        }
        res = ccn_name_chop(buffer, NULL, 4);
        if (res != 4) {
            printf("Failed: ccn_name_chop got wrong length\n");
            result = 1;
        }
        uri_out->length = 0;
        ccn_uri_append(uri_out, buffer->buf, buffer->length, CCN_URI_INCLUDESCHEME);
        if (0 != strcmp(ccn_charbuf_as_string(uri_out), expected_chopped_uri)) {
            printf("Failed: ccn_name_chop botch\n");
            printf("Expected: %s\n", expected_chopped_uri);
            printf("  Actual: %s\n", (const char *)uri_out->buf);
            result = 1;
        }
        res = ccn_name_next_sibling(buffer);
        if (res != 4) {
            printf("Failed: ccn_name_next_sibling got wrong length\n");
            result = 1;
        }
        uri_out->length = 0;
        ccn_uri_append(uri_out, buffer->buf, buffer->length, CCN_URI_INCLUDESCHEME);
        if (0 != strcmp(ccn_charbuf_as_string(uri_out), expected_bumped_uri)) {
            printf("Failed: ccn_name_next_sibling botch\n");
            printf("Expected: %s\n", expected_bumped_uri);
            printf("  Actual: %s\n", (const char *)uri_out->buf);
            result = 1;
        }
        ccn_name_next_sibling(buffer);
        uri_out->length = 0;
        ccn_uri_append(uri_out, buffer->buf, buffer->length, 
                       CCN_URI_PERCENTESCAPE | CCN_URI_INCLUDESCHEME);
        if (0 != strcmp(ccn_charbuf_as_string(uri_out), expected_bumped2_uri)) {
            printf("Failed: ccn_name_next_sibling botch\n");
            printf("Expected: %s\n", expected_bumped2_uri);
            printf("  Actual: %s\n", (const char *)uri_out->buf);
            result = 1;
        }
        ccn_charbuf_destroy(&buffer);
        ccn_charbuf_destroy(&uri_out);
    } while (0);

    do {
        const char *expected_uri_mixed = "ccnx:/example.com/.../%01/%FE/=0102030405060708/=FD101010101FFF/=0081";
        
        printf("Unit test case %d\n", i++);
        buffer = ccn_charbuf_create();
        uri_out = ccn_charbuf_create();
        res = ccn_name_init(buffer);
        res |= ccn_name_append_str(buffer, "example.com");
        res |= ccn_name_append_numeric(buffer, CCN_MARKER_NONE, 0);
        res |= ccn_name_append_numeric(buffer, CCN_MARKER_NONE, 1);
        res |= ccn_name_append_numeric(buffer, 0xFE, 0);
        res |= ccn_name_append_numeric(buffer, CCN_MARKER_NONE, 0x0102030405060708ULL);
        res |= ccn_name_append_numeric(buffer, CCN_MARKER_VERSION, 0x101010101FFFULL);
        res |= ccn_name_append_numeric(buffer, CCN_MARKER_SEQNUM, 129);
        res |= ccn_uri_append(uri_out, buffer->buf, buffer->length,
                              CCN_URI_MIXEDESCAPE | CCN_URI_INCLUDESCHEME);
        if (res < 0) {
            printf("Failed: name marker tests had negative res\n");
            result = 1;
        }
        if (0 != strcmp(ccn_charbuf_as_string(uri_out), expected_uri_mixed)) {
            printf("Failed: name marker tests produced wrong output\n");
            printf("Expected: %s\n", expected_uri_mixed);
            printf("  Actual: %s\n", (const char *)uri_out->buf);
            result = 1;
        }
        ccn_charbuf_destroy(&buffer);
        ccn_charbuf_destroy(&uri_out);
    } while (0);
    printf("Empty component encoding test\n");
    do {
        struct ccn_charbuf *name = ccn_charbuf_create();
        struct ccn_charbuf *expected_encoding = ccn_charbuf_create();
        /* manually create an encoding of <Name><Component/></Name> to ensure
         * that the regular encoders do not create a 0-length blob as part of
         * the empty component.
         */
        ccnb_element_begin(expected_encoding, CCN_DTAG_Name);
        ccnb_element_begin(expected_encoding, CCN_DTAG_Component);
        ccnb_element_end(expected_encoding);
        ccnb_element_end(expected_encoding);
        ccn_name_from_uri(name, "ccnx:/...");
        if (expected_encoding->length != name->length) {
            printf("Failed: encoding length %u but expected %u\n", (unsigned) name->length,
                   (unsigned)expected_encoding->length);
            result = 1;
        }
        for (i = 0; i < expected_encoding->length; i++) {
            if (expected_encoding->buf[i] != name->buf[i]) {
                printf("Failed: encoding mismatch at %d, got %d but expected %d\n",
                       i, name->buf[i], expected_encoding->buf[i]);
                result = 1;
            }
        }
        
    } while (0);
    
    printf("Timestamp tests\n");
    do {
        intmax_t sec;
        int nsec;
        int r;
        int f;
        struct ccn_charbuf *a[2];
        int t0 = 1363899678;
        
        printf("Unit test case %d\n", i++);
        /* Run many increasing inputs and make sure the output is in order. */
        a[0] = ccn_charbuf_create();
        a[1] = ccn_charbuf_create();
        ccnb_append_timestamp_blob(a[1], CCN_MARKER_NONE, t0 - 1, 0);
        for (f = 0, nsec = 0, sec = t0; sec < t0 + 20; nsec += 122099) {
            while (nsec >= 1000000000) {
                sec++;
                nsec -= 1000000000;
            }
            ccn_charbuf_reset(a[f]);
            r = ccnb_append_timestamp_blob(a[f], CCN_MARKER_NONE, sec, nsec);
            if (r != 0 || a[f]->length != 7 || memcmp(a[1-f]->buf, a[f]->buf, 6) > 0) {
                printf("Failed ccnb_append_timestamp_blob(...,%jd,%d)\n", sec, nsec);
                result = 1;
            }
            f = 1 - f;
        }
        ccn_charbuf_destroy(&a[0]);
        ccn_charbuf_destroy(&a[1]);
    } while (0);
    printf("Message digest tests\n");
    do {
        printf("Unit test case %d\n", i++);
        struct ccn_digest *dg = ccn_digest_create(CCN_DIGEST_SHA256);
        if (dg == NULL) {
            printf("Failed: ccn_digest_create returned NULL\n");
            result = 1;
            break;
        }
        printf("Unit test case %d\n", i++);
        const unsigned char expected_digest[] = {
            0xb3, 0x82, 0xcd, 0xb0, 0xe9, 0x5d, 0xf7, 0x3b, 0xe7, 0xdc, 0x19, 0x81, 0x3a, 0xfd, 0xdf, 0x89, 0xfb, 0xd4, 0xd4, 0xa0, 0xdb, 0x11, 0xa6, 0xba, 0x24, 0x16, 0x5b, 0xad, 0x9d, 0x90, 0x72, 0xb0
        };
        unsigned char actual_digest[sizeof(expected_digest)] = {0};
        const char *data = "Content-centric";
        if (ccn_digest_size(dg) != sizeof(expected_digest)) {
            printf("Failed: wrong digest size\n");
            result = 1;
            break;
        }
        printf("Unit test case %d\n", i++);
        ccn_digest_init(dg);
        res = ccn_digest_update(dg, data, strlen(data));
        if (res != 0)
            printf("Warning: check res %d\n", (int)res);
        printf("Unit test case %d\n", i++);
        res = ccn_digest_final(dg, actual_digest, sizeof(expected_digest));
        if (res != 0)
            printf("Warning: check res %d\n", (int)res);
        if (0 != memcmp(actual_digest, expected_digest, sizeof(expected_digest))) {
            printf("Failed: wrong digest\n");
            result = 1;
            break;
        }
    } while (0);
    printf("Really basic PRNG test\n");
    do {
        unsigned char r1[42];
        unsigned char r2[42];
        printf("Unit test case %d\n", i++);
        ccn_add_entropy(&i, sizeof(i), 0); /* Not much entropy, really. */
        ccn_random_bytes(r1, sizeof(r1));
        memcpy(r2, r1, sizeof(r2));
        ccn_random_bytes(r2, sizeof(r2));
        if (0 == memcmp(r1, r2, sizeof(r2))) {
            printf("Failed: badly broken PRNG\n");
            result = 1;
            break;
        }
    } while (0);
    printf("Bloom filter tests\n");
    do {
        unsigned char seed1[4] = "1492";
        const char *a[13] = {
            "one", "two", "three", "four",
            "five", "six", "seven", "eight",
            "nine", "ten", "eleven", "twelve",
            "thirteen"
        };
        struct ccn_bloom *b1 = NULL;
        struct ccn_bloom *b2 = NULL;
        int j, k, t1, t2;
        unsigned short us;

        printf("Unit test case %d\n", i++);
        b1 = ccn_bloom_create(13, seed1);

        for (j = 0; j < 13; j++)
            if (ccn_bloom_match(b1, a[j], strlen(a[j]))) break;
        if (j < 13) {
            printf("Failed: \"%s\" matched empty Bloom filter\n", a[j]);
            result = 1;
            break;
        }
        printf("Unit test case %d\n", i++);
        for (j = 0; j < 13; j++)
            ccn_bloom_insert(b1, a[j], strlen(a[j]));
        for (j = 0; j < 13; j++)
            if (!ccn_bloom_match(b1, a[j], strlen(a[j]))) break;
        if (j < 13) {
            printf("Failed: \"%s\" not found when it should have been\n", a[j]);
            result = 1;
            break;
        }
        printf("Unit test case %d\n", i++);
        for (j = 0, k = 0; j < 13; j++)
            if (ccn_bloom_match(b1, a[j]+1, strlen(a[j]+1)))
                k++;
        if (k > 0) {
            printf("Mmm, found %d false positives\n", k);
            if (k > 2) {
                result = 1;
                break;
            }
        }
        unsigned char seed2[5] = "aqfb\0";
        for (; seed2[3] <= 'f'; seed2[3]++) {
            printf("Unit test case %d (%4s)    ", i++, seed2);
            b2 = ccn_bloom_create(13, seed2);
            for (j = 0; j < 13; j++)
                ccn_bloom_insert(b2, a[j], strlen(a[j]));
            for (j = 0, k = 0, us = ~0; us > 0; us--) {
                t1 = ccn_bloom_match(b1, &us, sizeof(us));
                t2 = ccn_bloom_match(b2, &us, sizeof(us));
                j += (t1 | t2);
                k += (t1 & t2);
            }
            printf("either=%d both=%d wiresize=%d\n", j, k, ccn_bloom_wiresize(b1));
            if (k > 12) {
                printf("Failed: Bloom seeding may not be effective\n");
                result = 1;
            }
            ccn_bloom_destroy(&b2);
        }
        ccn_bloom_destroy(&b1);
    } while (0);
    printf("ccn_sign_content() tests\n");
    do {
        struct ccn *h = ccn_create();
	int res;
	res = unit_tests_for_signing(h, &i, 0);
	if (res == 1)
            result = 1;
        printf("Unit test case %d\n", i++);
        ccn_destroy(&h);
    } while (0);
    do {
        struct ccn *h = ccn_create();
	int res;
	res = ccn_load_default_key(h, aes_keystore_name, keystore_password);
	if (res < 0) {
            result = 1;
            printf("Failed: res == %d\n", (int)res);
        } else 
            res = unit_tests_for_signing(h, &i, 1);
	if (res == 1)
            result = 1;
        printf("Unit test case %d\n", i++);
        ccn_destroy(&h);
    } while (0);
    printf("link tests\n");
    printf("link tests\n");
    do {
        struct ccn_charbuf *l = ccn_charbuf_create();
        struct ccn_charbuf *name = ccn_charbuf_create();
        struct ccn_parsed_Link pl = {0};
        struct ccn_buf_decoder decoder;
        struct ccn_buf_decoder *d;
        struct ccn_indexbuf *comps = ccn_indexbuf_create();
        printf("Unit test case %d\n", i++);
        ccn_name_from_uri(name, "ccnx:/test/link/name");
        ccnb_append_Link(l, name, "label", NULL);
        d = ccn_buf_decoder_start(&decoder, l->buf, l->length);
        res = ccn_parse_Link(d, &pl, comps);
        if (res != 3 /* components in name */) {
            printf("Failed: ccn_parse_Link res == %d\n", (int)res);
            result = 1;
        }
    } while (0);

    exit(result);
}