예제 #1
0
char *be_mongo_getuser(void *handle, const char *username)
{
    struct mongo_backend *conf = (struct mongo_backend *)handle;
   mongoc_collection_t *collection;
   mongoc_cursor_t *cursor;
   bson_error_t error;
   const bson_t *doc;
   const char *collection_name = "passport";
   bson_t query;
   char *str = NULL;
   char *result = malloc(33);
   memset(result, 0, 33);

   bson_init (&query);

   bson_append_utf8 (&query, "username", -1, username, -1);

   collection = mongoc_client_get_collection (conf->client, "cas", collection_name);
   cursor = mongoc_collection_find (collection,
                                    MONGOC_QUERY_NONE,
                                    0,
                                    0,
                                    0,
                                    &query,
                                    NULL,  /* Fields, NULL for all. */
                                    NULL); /* Read Prefs, NULL for default */


   bson_iter_t iter;
   while (!mongoc_cursor_error (cursor, &error) &&
          mongoc_cursor_more (cursor)) {
      if (mongoc_cursor_next (cursor, &doc)) {

         bson_iter_init(&iter, doc);
         bson_iter_find(&iter, "pwd");
         //fprintf (stdout, "%s\n", bson_iter_utf8(&iter, NULL));
         str = bson_as_json (doc, NULL);
         //fprintf (stdout, "%s\n", str);
         bson_free (str);
         char *src = (char *)bson_iter_utf8(&iter, NULL);
         memcpy(result, src, strlen(src));
      }
   }

   if (mongoc_cursor_error (cursor, &error)) {
      fprintf (stderr, "Cursor Failure: %s\n", error.message);
      return result;
   }

   bson_destroy (&query);
   mongoc_cursor_destroy (cursor);
   mongoc_collection_destroy (collection);
   return result;
}
예제 #2
0
int be_mongo_superuser(void *conf, const char *username)
{
	struct mongo_backend *handle = (struct mongo_backend *) conf;
	mongoc_collection_t *collection;
	mongoc_cursor_t *cursor;
	bson_error_t error;
	const bson_t *doc;
	int result;
	
	bson_t query;
	bson_iter_t iter;
	bson_init (&query);
	bson_append_utf8(&query, "username", -1, username, -1);

	collection = mongoc_client_get_collection(handle->client, dbName, colName);

	cursor = mongoc_collection_find(collection,
									MONGOC_QUERY_NONE,
									0,
									0,
									0,
									&query,
									NULL,
									NULL);
									
	while (!mongoc_cursor_error (cursor, &error) &&
			mongoc_cursor_more (cursor)) {
		if (mongoc_cursor_next (cursor, &doc)) {
				bson_iter_init(&iter, doc);
				bson_iter_find(&iter, superUser);
				
				result = (int64_t) bson_iter_as_int64(&iter);

				//_log(LOG_NOTICE, "SUPERUSER: %d", result);
				
		}
	}

	if (mongoc_cursor_error (cursor, &error)) {
      	fprintf (stderr, "Cursor Failure: %s\n", error.message);
    	  return result;
   	}

	bson_destroy (&query);
	mongoc_cursor_destroy (cursor);
   	mongoc_collection_destroy (collection);



	return result;
}
예제 #3
0
char *be_mongo_getuser(void *handle, const char *username, const char *password, int *authenticated)
{
    struct mongo_backend *conf = (struct mongo_backend *)handle;
   mongoc_collection_t *collection;
   mongoc_cursor_t *cursor;
   bson_error_t error;
   const bson_t *doc;
   bson_iter_t iter;
   bson_t query;
   char *result;

   bson_init (&query);

   bson_append_utf8 (&query, "username", -1, username, -1);

   collection = mongoc_client_get_collection (conf->client, dbName, colName);
   cursor = mongoc_collection_find (collection,
                                    MONGOC_QUERY_NONE,
                                    0,
                                    0,
                                    0,
                                    &query,
                                    NULL,  /* Fields, NULL for all. */
                                    NULL); /* Read Prefs, NULL for default */


   while (!mongoc_cursor_error (cursor, &error) &&
          mongoc_cursor_more (cursor)) {
      if (mongoc_cursor_next (cursor, &doc)) {

         bson_iter_init(&iter, doc);
         bson_iter_find(&iter, passLoc);
		 
         char *src = (char *)bson_iter_utf8(&iter, NULL);
		 size_t tmp = strlen(src); 
		 result = (char *) malloc(tmp);
		 memset(result, 0, tmp);
         memcpy(result, src, tmp);
      }
   }

   if (mongoc_cursor_error (cursor, &error)) {
      fprintf (stderr, "Cursor Failure: %s\n", error.message);
      return result;
   }
   bson_destroy (&query);
   mongoc_cursor_destroy (cursor);
   mongoc_collection_destroy (collection);
   return result;
}
static void
test_mongoc_client_authenticate (void)
{
    mongoc_collection_t *collection;
    mongoc_database_t *database;
    mongoc_client_t *client;
    mongoc_cursor_t *cursor;
    const bson_t *doc;
    bson_error_t error;
    char *username;
    char *uri;
    bool r;
    bson_t q;

    username = gen_test_user ();
    uri = gen_good_uri (username);

    /*
     * Add a user to the test database.
     */
    client = mongoc_client_new(gTestUri);
    database = mongoc_client_get_database(client, "test");
    mongoc_database_remove_user (database, username, &error);
    r = mongoc_database_add_user(database, username, "testpass", NULL, NULL, &error);
    ASSERT_CMPINT(r, ==, 1);
    mongoc_database_destroy(database);
    mongoc_client_destroy(client);

    /*
     * Try authenticating with that user.
     */
    bson_init(&q);
    client = mongoc_client_new(uri);
    collection = mongoc_client_get_collection(client, "test", "test");
    cursor = mongoc_collection_find(collection, MONGOC_QUERY_NONE, 0, 1, 0,
                                    &q, NULL, NULL);
    r = mongoc_cursor_next(cursor, &doc);
    if (!r) {
        r = mongoc_cursor_error(cursor, &error);
        if (r) {
            MONGOC_ERROR("Authentication failure: \"%s\"", error.message);
        }
        assert(!r);
    }
    mongoc_cursor_destroy(cursor);

    /*
     * Remove all test users.
     */
    database = mongoc_client_get_database (client, "test");
    r = mongoc_database_remove_all_users (database, &error);
    assert (r);
    mongoc_database_destroy (database);

    mongoc_collection_destroy(collection);
    mongoc_client_destroy(client);

    bson_free (username);
    bson_free (uri);
}
bool TMongoDriver::find(const QString &collection, const QVariantMap &criteria, const QVariantMap &orderBy,
                        const QStringList &fields, int limit, int skip, int )
{
    if (!isOpen()) {
        return false;
    }

    errorCode = 0;
    errorString.clear();

    mongoc_collection_t *col = mongoc_client_get_collection(mongoClient, qPrintable(dbName), qPrintable(collection));
    mongoc_cursor_t *cursor = mongoc_collection_find(col, MONGOC_QUERY_NONE, skip, limit, 0,
                                                     (bson_t *)TBson::toBson(criteria, orderBy).data(),
                                                     (bson_t *)TBson::toBson(fields).data(),
                                                     nullptr); /* Read Prefs, nullptr for default */

    setLastCommandStatus(mongoc_collection_get_last_error(col));
    mongoc_collection_destroy(col);
    mongoCursor->setCursor(cursor);

    if (cursor) {
        bson_error_t error;
        if (mongoc_cursor_error(cursor, &error)) {
            errorCode = error.code;
            errorString = QLatin1String(error.message);
        }
    } else {
        tSystemError("MongoDB Cursor Error");
    }
    return (bool)cursor;
}
예제 #6
0
파일: cursor.c 프로젝트: ibiris/mongolite
SEXP R_mongo_cursor_next_json (SEXP ptr, SEXP n){
  mongoc_cursor_t *c = r2cursor(ptr);
  int len = asInteger(n);
  SEXP out = PROTECT(allocVector(STRSXP, len));
  const bson_t *b = NULL;
  int total = 0;
  bson_error_t err;
  while(total < len){
    if(!mongoc_cursor_next(c, &b)){
      if(mongoc_cursor_error (c, &err))
        stop(err.message);
      else
        //cursor exchausted: done
        break;
    } else {
      size_t jsonlength;
      const char *str = bson_as_json ((bson_t*) b, &jsonlength);
      SET_STRING_ELT(out, total, mkCharLenCE(str, jsonlength, CE_UTF8));
      if(str) bson_free(str);
      total++;
    }
  }
  if(total < len){
    SEXP out2 = PROTECT(allocVector(STRSXP, total));
    for(int i = 0; i < total; i++){
      SET_STRING_ELT(out2, i, STRING_ELT(out, i));
    }
    UNPROTECT(2);
    return out2;
  }
  UNPROTECT(1);
  return out;
}
예제 #7
0
파일: cursor.c 프로젝트: ibiris/mongolite
SEXP R_mongo_cursor_next_bsonlist (SEXP ptr, SEXP n){
  mongoc_cursor_t *c = r2cursor(ptr);
  int len = asInteger(n);
  SEXP out = PROTECT(allocVector(VECSXP, len));
  const bson_t *b = NULL;
  int total = 0;
  bson_error_t err;
  while(total < len){
    if(!mongoc_cursor_next(c, &b)){
      if(mongoc_cursor_error (c, &err))
        stop(err.message);
      else
        break; //cursor exchausted: done
    } else {
      SEXP bin = PROTECT(allocVector(RAWSXP, b->len));
      memcpy(RAW(bin), bson_get_data(b), b->len);
      SET_VECTOR_ELT(out, total, bin);
      UNPROTECT(1);
      total++;
    }
  }
  if(total < len){
    SEXP out2 = PROTECT(allocVector(VECSXP, total));
    for(int i = 0; i < total; i++){
      SET_VECTOR_ELT(out2, i, VECTOR_ELT(out, i));
    }
    UNPROTECT(2);
    return out2;
  }
  UNPROTECT(1);
  return out;
}
예제 #8
0
static void
print_pipeline (mongoc_collection_t *collection)
{
   mongoc_cursor_t *cursor;
   bson_error_t error;
   const bson_t *doc;
   bson_t *pipeline;
   char *str;

   pipeline = BCON_NEW ("pipeline", "[",
      "{", "$group", "{", "_id", "$state", "total_pop", "{", "$sum", "$pop", "}", "}", "}",
      "{", "$match", "{", "total_pop", "{", "$gte", BCON_INT32 (10000000), "}", "}", "}",
   "]");

   cursor = mongoc_collection_aggregate (collection, MONGOC_QUERY_NONE, pipeline, NULL, NULL);

   while (mongoc_cursor_next (cursor, &doc)) {
      str = bson_as_json (doc, NULL);
      printf ("%s\n", str);
      bson_free (str);
   }

   if (mongoc_cursor_error (cursor, &error)) {
      fprintf (stderr, "Cursor Failure: %s\n", error.message);
   }

   mongoc_cursor_destroy (cursor);
   bson_destroy (pipeline);
}
예제 #9
0
static void
test_mongoc_client_authenticate_failure (void)
{
   mongoc_collection_t *collection;
   mongoc_cursor_t *cursor;
   mongoc_client_t *client;
   const bson_t *doc;
   bson_error_t error;
   bool r;
   bson_t q;

   /*
    * Try authenticating with that user.
    */
   bson_init(&q);
   client = mongoc_client_new(gTestUriWithBadPassword);
   collection = mongoc_client_get_collection(client, "test", "test");
   cursor = mongoc_collection_find(collection, MONGOC_QUERY_NONE, 0, 1, 0,
                                   &q, NULL, NULL);
   r = mongoc_cursor_next(cursor, &doc);
   assert(!r);
   r = mongoc_cursor_error(cursor, &error);
   assert(r);
   assert(error.domain == MONGOC_ERROR_CLIENT);
   assert(error.code == MONGOC_ERROR_CLIENT_AUTHENTICATE);
   mongoc_cursor_destroy(cursor);
   mongoc_collection_destroy(collection);
   mongoc_client_destroy(client);
}
예제 #10
0
static void
test_clone (void)
{
   mongoc_cursor_t *clone;
   mongoc_cursor_t *cursor;
   mongoc_client_t *client;
   const bson_t *doc;
   bson_error_t error;
   mongoc_uri_t *uri;
   bson_bool_t r;
   bson_t q = BSON_INITIALIZER;
   char *uristr;

   uristr = bson_strdup_printf("mongodb://%s/", HOST);
   uri = mongoc_uri_new(uristr);
   bson_free(uristr);

   client = mongoc_client_new_from_uri(uri);
   BSON_ASSERT(client);

   cursor = _mongoc_cursor_new(client, "test.test", MONGOC_QUERY_NONE, 0, 1, 1,
                               FALSE, &q, NULL, NULL);
   BSON_ASSERT(cursor);

   r = mongoc_cursor_next(cursor, &doc);
   if (!r && mongoc_cursor_error(cursor, &error)) {
      MONGOC_ERROR("%s", error.message);
      abort();
   }

   clone = mongoc_cursor_clone(cursor);
   BSON_ASSERT(cursor);

   r = mongoc_cursor_next(clone, &doc);
   if (!r && mongoc_cursor_error(clone, &error)) {
      MONGOC_ERROR("%s", error.message);
      abort();
   }

   mongoc_cursor_destroy(cursor);
   mongoc_cursor_destroy(clone);
   mongoc_client_destroy(client);
   mongoc_uri_destroy(uri);
}
예제 #11
0
int be_mongo_getuser(void *handle, const char *username, const char *password, char **phash, const char *clientid)
{
	struct mongo_backend *conf = (struct mongo_backend *)handle;
	mongoc_collection_t *collection;
	mongoc_cursor_t *cursor;
	bson_error_t error;
	const bson_t *doc;
	bson_iter_t iter;
	bson_t query;
	char *result = NULL;

	bson_init (&query);

	bson_append_utf8 (&query, conf->user_username_prop, -1, username, -1);

	collection = mongoc_client_get_collection (conf->client, conf->database, conf->user_coll);
	cursor = mongoc_collection_find_with_opts(collection, &query, NULL, NULL);

	if (!mongoc_cursor_error (cursor, &error) &&
		mongoc_cursor_next (cursor, &doc)) {

		bson_iter_init(&iter, doc);
		if (bson_iter_find(&iter, conf->user_password_prop)) {
			const char *password_src = bson_iter_utf8(&iter, NULL);
			size_t password_len = strlen(password_src) + 1;
			result = (char *) malloc(password_len);
			memcpy(result, password_src, password_len);
		} else {
			_log(LOG_NOTICE, "[mongo] (%s) missing for user (%s)", conf->user_password_prop, username);
		}
	}

	if (mongoc_cursor_error (cursor, &error)) {
		fprintf (stderr, "Cursor Failure: %s\n", error.message);
	}

	bson_destroy (&query);
	mongoc_cursor_destroy (cursor);
	mongoc_collection_destroy (collection);

	*phash = result;
	return BACKEND_DEFER;
}
예제 #12
0
 bool Cursor::hasNext() {
     const bson_t *doc;
     if (mongoc_cursor_error(cursor_, &last_error_) ||
         !mongoc_cursor_more(cursor_))
         return false;
     if (!mongoc_cursor_next(cursor_, &doc))
         return false;
     last_result_ = Document(*doc);
     return true;
 }
예제 #13
0
파일: collection.c 프로젝트: cran/mongolite
SEXP R_mongo_collection_find_indexes(SEXP ptr_col) {
  mongoc_collection_t *col = r2col(ptr_col);
  bson_error_t err;

  mongoc_cursor_t *c = mongoc_collection_find_indexes_with_opts (col, NULL);
  if(mongoc_cursor_error(c, &err))
    stop(err.message);

  return cursor2r(c, ptr_col);
}
예제 #14
0
/**
 * mongoc_database_has_collection:
 * @database: (in): A #mongoc_database_t.
 * @name: (in): The name of the collection to check for.
 * @error: (out) (allow-none): A location for a #bson_error_t, or %NULL.
 *
 * Checks to see if a collection exists within the database on the MongoDB
 * server.
 *
 * This will return %false if their was an error communicating with the
 * server, or if the collection does not exist.
 *
 * If @error is provided, it will first be zeroed. Upon error, error.domain
 * will be set.
 *
 * Returns: %true if @name exists, otherwise %false. @error may be set.
 */
bool
mongoc_database_has_collection (mongoc_database_t *database,
                                const char        *name,
                                bson_error_t      *error)
{
    mongoc_collection_t *collection;
    mongoc_read_prefs_t *read_prefs;
    mongoc_cursor_t *cursor;
    const bson_t *doc;
    bson_iter_t iter;
    bool ret = false;
    const char *cur_name;
    bson_t q = BSON_INITIALIZER;
    char ns[140];

    ENTRY;

    BSON_ASSERT (database);
    BSON_ASSERT (name);

    if (error) {
        memset (error, 0, sizeof *error);
    }

    bson_snprintf (ns, sizeof ns, "%s.%s", database->name, name);
    ns[sizeof ns - 1] = '\0';

    read_prefs = mongoc_read_prefs_new (MONGOC_READ_PRIMARY);
    collection = mongoc_client_get_collection (database->client,
                 database->name,
                 "system.namespaces");
    cursor = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, 0, &q,
                                     NULL, read_prefs);

    while (!mongoc_cursor_error (cursor, error) &&
            mongoc_cursor_more (cursor)) {
        while (mongoc_cursor_next (cursor, &doc) &&
                bson_iter_init_find (&iter, doc, "name") &&
                BSON_ITER_HOLDS_UTF8 (&iter)) {
            cur_name = bson_iter_utf8(&iter, NULL);
            if (!strcmp(cur_name, ns)) {
                ret = true;
                GOTO(cleanup);
            }
        }
    }

cleanup:
    mongoc_cursor_destroy (cursor);
    mongoc_collection_destroy (collection);
    mongoc_read_prefs_destroy (read_prefs);

    RETURN(ret);
}
예제 #15
0
bool Collection::Cursor::CursorImpl::Next() const
{
	const bson_t* doc = NULL;

	bool result = mongoc_cursor_next( m_cursor.get(), &doc );

	bson_error_t error;
	if( mongoc_cursor_error( m_cursor.get(), &error ) )
		throw MongoError( std::string(error.message).append(" in Cursor::Next") );

	return result;
}
예제 #16
0
파일: cursor.c 프로젝트: ibiris/mongolite
SEXP R_mongo_cursor_next_bson (SEXP ptr){
  mongoc_cursor_t *c = r2cursor(ptr);
  const bson_t *b = NULL;
  if(!mongoc_cursor_next(c, &b)){
    bson_error_t err;
    if(mongoc_cursor_error (c, &err))
      stop(err.message);
    else
      return R_NilValue;
  }
  return bson2r((bson_t*) b);
}
예제 #17
0
int database_find_blockchain_transaction(struct database* db, unsigned char* hash, size_t max_height, struct transaction** tx, size_t* height)
{
    mongoc_collection_t* collection = mongoc_client_get_collection(db->client, database_name(db), "transactions");

    // Build a query doc
    bson_t* query = bson_new();

    // Set the hash
    BSON_APPEND_BINARY(query, "hash", BSON_SUBTYPE_BINARY, (uint8_t*)hash, 32);

    // Force the height to be valid (on the main chain)
    bson_t* height_doc = bson_new();
    BSON_APPEND_DOCUMENT_BEGIN(query, "height", height_doc);
    BSON_APPEND_INT32(height_doc, "$lte", (int)max_height);
    BSON_APPEND_INT32(height_doc, "$gte", 0);
    bson_append_document_end(query, height_doc);

    // Perform find
    mongoc_cursor_t* cursor = mongoc_collection_find(collection, MONGOC_QUERY_NONE, 0, 0, 0, query, NULL, NULL);

    bson_error_t error;
    if(cursor == NULL || mongoc_cursor_error(cursor, &error)) {
        printf("MongoDB error: %s\n", (cursor == NULL) ? "NULL cursor" : error.message);
        return -1;
    }

    bson_t const* doc;
    int found = 0;
    while(mongoc_cursor_next(cursor, &doc) != 0) {
        if(height != NULL) {
            bson_iter_t iter;
            if(!bson_iter_init_find(&iter, doc, "height") || !BSON_ITER_HOLDS_INT32(&iter)) {
                printf("MongoDB error: tx doesn't have height!\n");
                return -1;
            }
            *height = (size_t)bson_iter_int32(&iter);
        }

        if(tx != NULL) {
            *tx = transaction_from_bson(doc);
        }

        found = 1;
        break;
    }

    mongoc_cursor_destroy(cursor);
    bson_destroy(height_doc);
    bson_destroy(query);
    mongoc_collection_destroy(collection);
    return found;
}
예제 #18
0
mongoc_cursor_t *
mongoc_database_find_collections (mongoc_database_t *database,
                                  const bson_t      *filter,
                                  bson_error_t      *error)
{
   mongoc_cursor_t *cursor;
   mongoc_read_prefs_t *read_prefs;
   bson_t cmd = BSON_INITIALIZER;
   bson_t child;
   bson_error_t lerror;

   BSON_ASSERT (database);

   BSON_APPEND_INT32 (&cmd, "listCollections", 1);

   if (filter) {
      BSON_APPEND_DOCUMENT (&cmd, "filter", filter);
      BSON_APPEND_DOCUMENT_BEGIN (&cmd, "cursor", &child);
      bson_append_document_end (&cmd, &child);
   }

   read_prefs = mongoc_read_prefs_new (MONGOC_READ_PRIMARY);

   cursor = _mongoc_cursor_new (database->client, database->name,
                                MONGOC_QUERY_SLAVE_OK, 0, 0, 0, true,
                                NULL, NULL, NULL, NULL);

   _mongoc_cursor_cursorid_init (cursor, &cmd);

   if (_mongoc_cursor_cursorid_prime (cursor)) {
       /* intentionally empty */
   } else {
      if (mongoc_cursor_error (cursor, &lerror)) {
         if (lerror.code == MONGOC_ERROR_QUERY_COMMAND_NOT_FOUND) {
            /* We are talking to a server that doesn' support listCollections. */
            /* clear out the error. */
            memset (&lerror, 0, sizeof lerror);
            /* try again with using system.namespaces */
            mongoc_cursor_destroy (cursor);
            cursor = _mongoc_database_find_collections_legacy (
               database, filter, error);
         } else if (error) {
            memcpy (error, &lerror, sizeof *error);
         }
      }
   }

   bson_destroy (&cmd);
   mongoc_read_prefs_destroy (read_prefs);

   return cursor;
}
예제 #19
0
/**
 * Grabs the results obtained from the MongoDB cursor and loads them into
 * in-memory arrays.
 *
 * @param cursor A pointer to a Monary cursor, which contains both a MongoDB
 * cursor and Monary column data that stores the retrieved information.
 *
 * @return The number of rows loaded into memory.
 */
int monary_load_query(monary_cursor* cursor)
{
    bson_error_t error;             // A location for errors
    const bson_t* bson;             // Pointer to an immutable BSON buffer
    int num_masked;
    int row;
    int total_values;
    monary_column_data* coldata;
    mongoc_cursor_t* mcursor;

    mcursor = cursor->mcursor;  // The underlying MongoDB cursor
    coldata = cursor->coldata;  // A pointer to the NumPy array data
    row = 0;                    // Iterator var over the lengths of the arrays
    num_masked = 0;             // The number of failed loads
    
    // read result values
    while(row < coldata->num_rows
            && !mongoc_cursor_error(mcursor, &error)
            && mongoc_cursor_next(mcursor, &bson)) {

#ifndef NDEBUG
        if(row % 500000 == 0) {
            DEBUG("...%i rows loaded", row);
        }
#endif

        num_masked += monary_bson_to_arrays(coldata, row, bson);
        ++row;
    }

    if (mongoc_cursor_error(mcursor, &error)) {
        DEBUG("error: %d.%d %s", error.domain, error.code, error.message);
    }

    total_values = row * coldata->num_columns;
    DEBUG("%i rows loaded; %i / %i values were masked", row, num_masked, total_values);

    return row;
}
static void
test_wire_version (void)
{
    mongoc_collection_t *collection;
    mongoc_cursor_t *cursor;
    mongoc_client_t *client;
    mock_server_t *server;
    uint16_t port;
    const bson_t *doc;
    bson_error_t error;
    bool r;
    bson_t q = BSON_INITIALIZER;
    char *uristr;

    port = 20000 + (rand () % 1000);

    server = mock_server_new ("127.0.0.1", port, NULL, NULL);
    mock_server_set_wire_version (server, 10, 11);
    mock_server_run_in_thread (server);

    usleep (5000);

    uristr = bson_strdup_printf ("mongodb://127.0.0.1:%hu/", port);
    client = mongoc_client_new (uristr);

    collection = mongoc_client_get_collection (client, "test", "test");

    cursor = mongoc_collection_find (collection,
                                     MONGOC_QUERY_NONE,
                                     0,
                                     1,
                                     0,
                                     &q,
                                     NULL,
                                     NULL);

    r = mongoc_cursor_next (cursor, &doc);
    assert (!r);

    r = mongoc_cursor_error (cursor, &error);
    assert (r);

    assert (error.domain == MONGOC_ERROR_PROTOCOL);
    assert (error.code == MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION);

    mongoc_cursor_destroy (cursor);
    mongoc_collection_destroy (collection);
    mock_server_quit (server, 0);
    mongoc_client_destroy (client);
    bson_free (uristr);
}
예제 #21
0
// Find the spend of a specified output_reference within a given blockheight range (main chain only)
// if found, load tx and the input that spends it
int database_find_blockchain_spend(struct database* db, struct transaction_output_reference* output_reference, size_t start_height, size_t max_height, struct transaction** tx)
{
    mongoc_collection_t* collection = mongoc_client_get_collection(db->client, database_name(db), "transactions");

    // Build a query doc
    bson_t* query = bson_new();

    // Build a query that tries to find where this output_reference is spent
    unsigned char hash[32];
    transaction_output_reference_hash(output_reference, hash);

    bson_t* output_reference_doc = bson_new();
    BSON_APPEND_DOCUMENT_BEGIN(query, "inputs.output_reference", output_reference_doc);
    BSON_APPEND_BINARY(output_reference_doc, "hash", BSON_SUBTYPE_BINARY, (uint8_t*)hash, 32);
    BSON_APPEND_INT32(output_reference_doc, "index", transaction_output_reference_index(output_reference));
    bson_append_document_end(query, output_reference_doc);

    // Force the height to be valid
    bson_t* height_doc = bson_new();
    BSON_APPEND_DOCUMENT_BEGIN(query, "height", height_doc);
    BSON_APPEND_INT32(height_doc, "$lte", (int)max_height);
    BSON_APPEND_INT32(height_doc, "$gte", start_height);
    bson_append_document_end(query, height_doc);

    // Perform find
    mongoc_cursor_t* cursor = mongoc_collection_find(collection, MONGOC_QUERY_NONE, 0, 0, 0, query, NULL, NULL);

    bson_error_t error;
    if(cursor == NULL || mongoc_cursor_error(cursor, &error)) {
        printf("MongoDB error: %s\n", (cursor == NULL) ? "NULL cursor" : error.message);
        return -1;
    }

    bson_t const* doc;
    int found = 0;
    while(mongoc_cursor_next(cursor, &doc) != 0) {
        if(tx != NULL) {
            *tx = transaction_from_bson(doc);
        }

        found = 1;
        break;
    }

    mongoc_cursor_destroy(cursor);
    bson_destroy(height_doc);
    bson_destroy(output_reference_doc);
    bson_destroy(query);
    mongoc_collection_destroy(collection);
    return found;
}
static void
test_mongoc_client_authenticate_failure (void)
{
    mongoc_collection_t *collection;
    mongoc_cursor_t *cursor;
    mongoc_client_t *client;
    const bson_t *doc;
    bson_error_t error;
    bool r;
    bson_t q;
    bson_t empty = BSON_INITIALIZER;

    /*
     * Try authenticating with that user.
     */
    bson_init(&q);
    client = mongoc_client_new(gTestUriWithBadPassword);
    collection = mongoc_client_get_collection(client, "test", "test");
    cursor = mongoc_collection_find(collection, MONGOC_QUERY_NONE, 0, 1, 0,
                                    &q, NULL, NULL);
    r = mongoc_cursor_next(cursor, &doc);
    assert(!r);
    r = mongoc_cursor_error(cursor, &error);
    assert(r);
    assert(error.domain == MONGOC_ERROR_CLIENT);
    assert(error.code == MONGOC_ERROR_CLIENT_AUTHENTICATE);
    mongoc_cursor_destroy(cursor);

    /*
     * Try various commands while in the failed state to ensure we get the
     * same sort of errors.
     */
    r = mongoc_collection_insert (collection, 0, &empty, NULL, &error);
    assert (!r);
    assert (error.domain == MONGOC_ERROR_CLIENT);
    assert (error.code == MONGOC_ERROR_CLIENT_AUTHENTICATE);

    /*
     * Try various commands while in the failed state to ensure we get the
     * same sort of errors.
     */
    r = mongoc_collection_update (collection, 0, &q, &empty, NULL, &error);
    assert (!r);
    assert (error.domain == MONGOC_ERROR_CLIENT);
    assert (error.code == MONGOC_ERROR_CLIENT_AUTHENTICATE);

    mongoc_collection_destroy(collection);
    mongoc_client_destroy(client);
}
예제 #23
0
int be_mongo_superuser(void *conf, const char *username)
{
	struct mongo_backend *handle = (struct mongo_backend *) conf;
	mongoc_collection_t *collection;
	mongoc_cursor_t *cursor;
	bson_error_t error;
	const bson_t *doc;
	int result = 0;

	bson_t query;
	bson_iter_t iter;
	bson_init (&query);
	bson_append_utf8(&query, handle->user_username_prop, -1, username, -1);

	collection = mongoc_client_get_collection(handle->client, handle->database, handle->user_coll);

	cursor = mongoc_collection_find_with_opts(collection, &query, NULL, NULL);

	if (!mongoc_cursor_error (cursor, &error) &&
		mongoc_cursor_next (cursor, &doc)) {
		bson_iter_init(&iter, doc);
		if (bson_iter_find(&iter, handle->user_superuser_prop)) {
			result = bson_iter_as_bool(&iter) ? 1 : 0;
		}
	}

	if (mongoc_cursor_error (cursor, &error)) {
		fprintf(stderr, "Cursor Failure: %s\n", error.message);
	}

	bson_destroy (&query);
	mongoc_cursor_destroy (cursor);
	mongoc_collection_destroy (collection);

	return (result) ? BACKEND_ALLOW : BACKEND_DEFER;
}
예제 #24
0
static void
tail_collection (mongoc_collection_t *collection)
{
   mongoc_cursor_t *cursor;
   uint32_t last_time;
   const bson_t *doc;
   bson_error_t error;
   bson_iter_t iter;

   BSON_ASSERT (collection);

   last_time = (uint32_t) time (NULL);

   while (true) {
      cursor = query_collection (collection, last_time);
      while (!mongoc_cursor_error (cursor, &error) &&
             mongoc_cursor_more (cursor)) {
         if (mongoc_cursor_next (cursor, &doc)) {
            if (bson_iter_init_find (&iter, doc, "ts") &&
                BSON_ITER_HOLDS_TIMESTAMP (&iter)) {
               bson_iter_timestamp (&iter, &last_time, NULL);
            }
            print_bson (doc);
         }
      }
      if (mongoc_cursor_error (cursor, &error)) {
         if (error.domain == MONGOC_ERROR_SERVER) {
            fprintf (stderr, "%s\n", error.message);
            exit (1);
         }
      }

      mongoc_cursor_destroy (cursor);
      sleep (1);
   }
}
예제 #25
0
int
main (int   argc,
      char *argv[])
{
   mongoc_database_t *database;
   mongoc_cursor_t *cursor;
   mongoc_client_t *client;
   const bson_t *reply;
   bson_uint16_t port;
   bson_error_t error;
   bson_t ping;
   char *host_and_port;
   char *str;

   if (argc < 2 || argc > 3) {
      fprintf(stderr, "usage: %s HOSTNAME [PORT]\n", argv[0]);
      return 1;
   }

   port = (argc == 3) ? atoi(argv[2]) : 27017;
   host_and_port = bson_strdup_printf("mongodb://%s:%hu", argv[1], port);
   client = mongoc_client_new(host_and_port);
   if (!client) {
      fprintf(stderr, "Invalid hostname or port: %s\n", host_and_port);
      return 2;
   }

   bson_init(&ping);
   bson_append_int32(&ping, "ping", 4, 1);
   database = mongoc_client_get_database(client, "test");
   cursor = mongoc_database_command(database, 0, 0, 1, 0, &ping, NULL, NULL);
   if (mongoc_cursor_next(cursor, &reply)) {
      str = bson_as_json(reply, NULL);
      fprintf(stdout, "%s\n", str);
      bson_free(str);
   } else if (mongoc_cursor_error(cursor, &error)) {
      fprintf(stderr, "Ping failure: %s\n", error.message);
      return 3;
   }

   mongoc_cursor_destroy(cursor);
   bson_destroy(&ping);
   mongoc_client_destroy(client);
   bson_free(host_and_port);

   return 0;
}
예제 #26
0
/*
 * Performs a query against the configured MongoDB server and return
 * cursor which can be destroyed by calling mongoc_cursor_current.
 */
MONGO_CURSOR*
MongoCursorCreate(MONGO_CONN* conn, char* database, char *collection, BSON* q)
{
	mongoc_collection_t *c = NULL;
	MONGO_CURSOR *cur = NULL;
	bson_error_t error;

	c = mongoc_client_get_collection (conn, database, collection);
	cur = mongoc_collection_find(c, MONGOC_QUERY_SLAVE_OK, 0, 0, 0, q, NULL, NULL);
	mongoc_cursor_error(cur, &error);
	if (!cur)
		ereport(ERROR, (errmsg("failed to create cursor"),
						errhint("Mongo error: \"%s\"", error.message)));

	mongoc_collection_destroy(c);
	return cur;
}
예제 #27
0
static void
fetch (mongoc_collection_t *col,
       const bson_t        *spec)
{
   mongoc_cursor_t *cursor;
   const bson_t *b;
   bson_error_t error;

   cursor = mongoc_collection_find(col, MONGOC_QUERY_NONE, 0, 0, spec, NULL, NULL);
   while (mongoc_cursor_next(cursor, &b)) {
      BSON_ASSERT(b);
      print_doc(b);
   }
   if (mongoc_cursor_error(cursor, &error)) {
      MONGOC_WARNING("Cursor error: %s", error.message);
   }
   mongoc_cursor_destroy(cursor);
}
예제 #28
0
static void
ping (mongoc_database_t *db,
      const bson_t      *cmd)
{
   mongoc_cursor_t *cursor;
   const bson_t *b;
   bson_error_t error;

   cursor = mongoc_database_command(db, MONGOC_QUERY_NONE, 0, 1, cmd, NULL, NULL);
   while (mongoc_cursor_next(cursor, &b)) {
      BSON_ASSERT(b);
      print_doc(b);
   }
   if (mongoc_cursor_error(cursor, &error)) {
      MONGOC_WARNING("Cursor error: %s", error.message);
   }
   mongoc_cursor_destroy(cursor);
}
예제 #29
0
static void
query_collection (mongoc_collection_t *col)
{
   mongoc_cursor_t *cursor;
   const bson_t *doc;
   bson_error_t error;
   bson_t q;

   bson_init(&q);
   bson_append_utf8(&q, "hello", -1, "world", -1);

   cursor = mongoc_collection_find(col,
                                   MONGOC_QUERY_NONE,
                                   0,
                                   0,
                                   0,
                                   &q,
                                   NULL,
                                   NULL);

   while (mongoc_cursor_next(cursor, &doc)) {
      char *str;

      str = bson_as_json(doc, NULL);
      fprintf(stderr, "%s\n", str);
      bson_free(str);
   }

   if (mongoc_cursor_error(cursor, &error)) {
      if (gExpectingFailure) {
         if ((error.domain != MONGOC_ERROR_STREAM) ||
             (error.code != MONGOC_ERROR_STREAM_SOCKET)) {
            abort();
         }
         gExpectingFailure = FALSE;
      } else {
         MONGOC_WARNING("%s", error.message);
         abort();
      }
   }

   bson_destroy(&q);
}
예제 #30
0
    // iterate over all results and return the count.  returns -1 on error.
    int64_t Cursor::itcount() {
        int64_t count = 0;
        const bson_t *doc;

        // iterate over all results
        while (true) {
            if (mongoc_cursor_error(cursor_, &last_error_)) {
                DEBUG("cursor failure: %s\n", last_error_.message);
                return -1;
            }
            if (!mongoc_cursor_more(cursor_) ||
                !mongoc_cursor_next(cursor_, &doc)) {
                break;
            }
            ++count;
        }

        return count;
    }