Ejemplo n.º 1
0
static gboolean
sim_parser_connect_test3 (void)
{
  bson_t *bson_connect = bson_new ();
  bson_t child;
  SimParser *parser = NULL;
  SimCommand *cmd = NULL;
  gboolean result = FALSE;
  uint8_t uuid[]={0x07,0x92,0xd6,0x72,0xf4,0xce,0x11,0xe4,0x9d,0xe2,0x00,0x0c,0x29,0xd9,0x46,0xde};
  bson_append_document_begin (bson_connect,"connect", -1, &child);
  BSON_APPEND_INT32 (&child, "id", 10);
  BSON_APPEND_INT32 (&child, "type", SIM_SESSION_TYPE_WEB);
  BSON_APPEND_UTF8 (&child, "version", "x.x.x");
  if (bson_append_binary (&child, "sensor_id", -1, BSON_SUBTYPE_UUID, uuid, 16) == FALSE)
    return FALSE;
  bson_append_document_end (bson_connect, &child);
  do{
    if ((parser = sim_parser_new()) == NULL)
    { 
      result = FALSE;
      break;
    }
    if ((cmd = sim_parser_bson (parser, bson_get_data (bson_connect), bson_connect->len)) != NULL)
    {
      result = FALSE;
      break;
    }
    result = TRUE;
  } while (0);

  return result;
}
Ejemplo n.º 2
0
/* Check a correct CONNECT message */
static gboolean
sim_parser_connect_test1 (void)
{
  bson_t *bson_connect = bson_new ();
  bson_t child;
  uint8_t uuid[]={0x07,0x92,0xd6,0x72,0xf4,0xce,0x11,0xe4,0x9d,0xe2,0x00,0x0c,0x29,0xd9,0x46,0xde};
  SimParser *parser = NULL;
  SimCommand *cmd = NULL;
  gboolean result = FALSE;
  bson_append_document_begin (bson_connect,"connect", -1, &child);
  BSON_APPEND_INT32 (&child, "id", 10);
  BSON_APPEND_INT32 (&child, "type", SIM_SESSION_TYPE_WEB);
  BSON_APPEND_UTF8 (&child, "version", "5.0.1");
  if (bson_append_binary (&child, "sensor_id", -1, BSON_SUBTYPE_UUID, uuid, 16) == FALSE)
    return FALSE;
  bson_append_document_end (bson_connect, &child);
  /* Check */
  bson_iter_t iter;
  bson_iter_init (&iter, bson_connect);
  do{
    if ((parser = sim_parser_new()) == NULL)
    { 
      result = FALSE;
      break;
    }
    if ((cmd = sim_parser_bson (parser, bson_get_data (bson_connect), bson_connect->len)) == NULL)
    {
      result = FALSE;
      break;
    }
    if (cmd->type !=  SIM_COMMAND_TYPE_CONNECT)
    {
      result = FALSE;
      break;
    }
    if (cmd->data.connect.sensor_ver->major != 5 || cmd->data.connect.sensor_ver->minor != 0 || cmd->data.connect.sensor_ver->micro != 1)
    {
      result = FALSE;
      break;
    }
    if (cmd->data.connect.sensor_id == NULL)
    {
      result = FALSE;
      break;
    }
    /* Check uuid */
    SimUuid * uuidbin =  sim_uuid_new_from_bin (uuid);
    gboolean test =  sim_uuid_equal (uuidbin, cmd->data.connect.sensor_id);
    g_object_unref (uuidbin);
    if (!test)
    {
      result = FALSE;
      break;
    }
    result = TRUE;
  } while (0);
  bson_destroy (bson_connect);
  g_object_unref (parser);
  return result;
}
Ejemplo n.º 3
0
/* check a  missing mandatory fix */
static gboolean
sim_parser_connect_test2 (void)
{
  bson_t *bson_connect = bson_new ();
  bson_t child;
  SimParser *parser = NULL;
  SimCommand *cmd = NULL;
  gboolean result = FALSE;
  bson_append_document_begin (bson_connect,"connect", -1, &child);
  BSON_APPEND_INT32 (&child, "id", 10);
  BSON_APPEND_INT32 (&child, "type", SIM_SESSION_TYPE_WEB);
  BSON_APPEND_UTF8 (&child, "version", "5.0.1");
  bson_append_document_end (bson_connect, &child);
  do{
    if ((parser = sim_parser_new()) == NULL)
    { 
      result = FALSE;
      break;
    }
    if ((cmd = sim_parser_bson (parser, bson_get_data (bson_connect), bson_connect->len)) != NULL)
    {
      result = FALSE;
      break;
    }
    result = TRUE;
  } while (0);

  return result;
}
Ejemplo n.º 4
0
static int mongo_get_oauth_key(const u08bits *kid, oauth_key_data_raw *key) {

	mongoc_collection_t * collection = mongo_get_collection("oauth_key");

	if (!collection)
		return -1;

	bson_t query;
	bson_init(&query);
	BSON_APPEND_UTF8(&query, "kid", (const char *)kid);

	bson_t fields;
	bson_init(&fields);
	BSON_APPEND_INT32(&fields, "lifetime", 1);
	BSON_APPEND_INT32(&fields, "timestamp", 1);
	BSON_APPEND_INT32(&fields, "as_rs_alg", 1);
	BSON_APPEND_INT32(&fields, "ikm_key", 1);

	mongoc_cursor_t * cursor;
	cursor = mongoc_collection_find(collection, MONGOC_QUERY_NONE, 0, 1, 0,
			&query, &fields, NULL);

	int ret = -1;

	ns_bzero(key,sizeof(oauth_key_data_raw));
	STRCPY(key->kid,kid);

	if (!cursor) {
		TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR,
				"Error querying MongoDB collection 'oauth_key'\n");
	} else {
		const bson_t * item;
		uint32_t length;
		bson_iter_t iter;
		if (mongoc_cursor_next(cursor, &item)) {
			if (bson_iter_init(&iter, item) && bson_iter_find(&iter, "as_rs_alg") && BSON_ITER_HOLDS_UTF8(&iter)) {
				STRCPY(key->as_rs_alg,bson_iter_utf8(&iter, &length));
			}
			if (bson_iter_init(&iter, item) && bson_iter_find(&iter, "ikm_key") && BSON_ITER_HOLDS_UTF8(&iter)) {
				STRCPY(key->ikm_key,bson_iter_utf8(&iter, &length));
			}
			if (bson_iter_init(&iter, item) && bson_iter_find(&iter, "timestamp") && BSON_ITER_HOLDS_INT64(&iter)) {
				key->timestamp = (u64bits)bson_iter_int64(&iter);
			}
			if (bson_iter_init(&iter, item) && bson_iter_find(&iter, "lifetime") && BSON_ITER_HOLDS_INT32(&iter)) {
				key->lifetime = (u32bits)bson_iter_int32(&iter);
			}
			ret = 0;
		}
		mongoc_cursor_destroy(cursor);
	}
	mongoc_collection_destroy(collection);
	bson_destroy(&query);
	bson_destroy(&fields);
	return ret;
}
static void
test_find_and_modify_write_concern_wire_32_failure (void *context)
{
   mongoc_collection_t *collection;
   mongoc_client_t *client;
   bson_error_t error;
   mongoc_find_and_modify_opts_t *opts;
   bson_t reply;
   bson_t query = BSON_INITIALIZER;
   bson_t *update;
   bool success;
   mongoc_write_concern_t *wc;

   client = test_framework_client_new ();
   collection = get_test_collection (client, "writeFailure");
   wc = mongoc_write_concern_new ();

   mongoc_write_concern_set_w (wc, 42);
   mongoc_collection_set_write_concern (collection, wc);

   /* Find Zlatan Ibrahimovic, the striker */
   BSON_APPEND_UTF8 (&query, "firstname", "Zlatan");
   BSON_APPEND_UTF8 (&query, "lastname", "Ibrahimovic");
   BSON_APPEND_UTF8 (&query, "profession", "Football player");
   BSON_APPEND_INT32 (&query, "age", 34);
   BSON_APPEND_INT32 (
      &query, "goals", (16 + 35 + 23 + 57 + 16 + 14 + 28 + 84) + (1 + 6 + 62));

   /* Add his football position */
   update = BCON_NEW ("$set", "{", "position", BCON_UTF8 ("striker"), "}");

   opts = mongoc_find_and_modify_opts_new ();

   mongoc_find_and_modify_opts_set_update (opts, update);

   /* Create the document if it didn't exist, and return the updated document */
   mongoc_find_and_modify_opts_set_flags (
      opts, MONGOC_FIND_AND_MODIFY_UPSERT | MONGOC_FIND_AND_MODIFY_RETURN_NEW);

   success = mongoc_collection_find_and_modify_with_opts (
      collection, &query, opts, &reply, &error);

   ASSERT (!success);
   ASSERT_ERROR_CONTAINS (
      error, MONGOC_ERROR_WRITE_CONCERN, 100, "Write Concern error:");

   bson_destroy (&reply);
   bson_destroy (update);
   bson_destroy (&query);
   mongoc_find_and_modify_opts_destroy (opts);
   mongoc_collection_drop (collection, NULL);
   mongoc_collection_destroy (collection);
   mongoc_client_destroy (client);
}
Ejemplo n.º 6
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;
}
static void
test_create_collection (void)
{
   mongoc_database_t *database;
   mongoc_collection_t *collection;
   mongoc_client_t *client;
   bson_error_t error = { 0 };
   bson_t options;
   bson_t storage_opts;
   bson_t wt_opts;

   char *dbname;
   char *name;
   bool r;

   client = mongoc_client_new (gTestUri);
   assert (client);

   dbname = gen_collection_name ("dbtest");
   database = mongoc_client_get_database (client, dbname);
   assert (database);
   bson_free (dbname);

   bson_init (&options);
   BSON_APPEND_INT32 (&options, "size", 1234);
   BSON_APPEND_INT32 (&options, "max", 4567);
   BSON_APPEND_BOOL (&options, "capped", true);
   BSON_APPEND_BOOL (&options, "autoIndexId", true);

   BSON_APPEND_DOCUMENT_BEGIN(&options, "storage", &storage_opts);
   BSON_APPEND_DOCUMENT_BEGIN(&storage_opts, "wiredtiger", &wt_opts);
   BSON_APPEND_UTF8(&wt_opts, "configString", "block_compressor=zlib");
   bson_append_document_end(&storage_opts, &wt_opts);
   bson_append_document_end(&options, &storage_opts);


   name = gen_collection_name ("create_collection");
   collection = mongoc_database_create_collection (database, name, &options, &error);
   assert (collection);
   bson_destroy (&options);
   bson_free (name);

   r = mongoc_collection_drop (collection, &error);
   assert (r);

   r = mongoc_database_drop (database, &error);
   assert (r);

   mongoc_collection_destroy (collection);
   mongoc_database_destroy (database);
   mongoc_client_destroy (client);
}
Ejemplo n.º 8
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_command_secondary (void)
{
    mongoc_client_t *client;
    mongoc_cursor_t *cursor;
    mongoc_read_prefs_t *read_prefs;
    bson_t cmd = BSON_INITIALIZER;

    client = mongoc_client_new (gTestUri);
    assert (client);

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

    read_prefs = mongoc_read_prefs_new (MONGOC_READ_PRIMARY_PREFERRED);

    suppress_one_message ();
    cursor = mongoc_client_command (client, "admin", MONGOC_QUERY_NONE, 0, 1, 0, &cmd, NULL, read_prefs);

    mongoc_read_prefs_destroy (read_prefs);

    /* ensure we detected this must go to primary */
    assert (cursor->redir_primary);

    mongoc_cursor_destroy (cursor);
    mongoc_client_destroy (client);
    bson_destroy (&cmd);
}
Ejemplo n.º 10
0
bool
mongoc_database_remove_all_users (mongoc_database_t *database,
                                  bson_error_t      *error)
{
   mongoc_collection_t *col;
   bson_error_t lerror;
   bson_t cmd;
   bool ret;

   ENTRY;

   bson_return_val_if_fail (database, false);

   bson_init (&cmd);
   BSON_APPEND_INT32 (&cmd, "dropAllUsersFromDatabase", 1);
   ret = mongoc_database_command_simple (database, &cmd, NULL, NULL, &lerror);
   bson_destroy (&cmd);

   if (!ret && (lerror.code == MONGOC_ERROR_QUERY_COMMAND_NOT_FOUND)) {
      bson_init (&cmd);

      col = mongoc_client_get_collection (database->client, database->name,
                                          "system.users");
      BSON_ASSERT (col);

      ret = mongoc_collection_delete (col, MONGOC_DELETE_NONE, &cmd, NULL,
                                      error);

      bson_destroy (&cmd);
      mongoc_collection_destroy (col);
   }

   RETURN (ret);
}
void
_mongoc_write_command_delete_append (mongoc_write_command_t *command,
                                     const bson_t           *selector)
{
   const char *key;
   char keydata [16];
   bson_t doc;

   ENTRY;

   BSON_ASSERT (command);
   BSON_ASSERT (command->type == MONGOC_WRITE_COMMAND_DELETE);
   BSON_ASSERT (selector);

   BSON_ASSERT (selector->len >= 5);

   bson_init (&doc);
   BSON_APPEND_DOCUMENT (&doc, "q", selector);
   BSON_APPEND_INT32 (&doc, "limit", command->u.delete_.multi ? 0 : 1);

   key = NULL;
   bson_uint32_to_string (command->n_documents, &key, keydata, sizeof keydata);
   BSON_ASSERT (key);
   BSON_APPEND_DOCUMENT (command->documents, key, &doc);
   command->n_documents++;

   bson_destroy (&doc);

   EXIT;
}
Ejemplo n.º 12
0
static void saveAlarmLog(mongoc_collection_t *coll,char* se_id,int code,char * tel,char * msg,char* userId,char * device_name,char* name,char * de_id){
     bson_t *sdoc = bson_new ();
     bson_oid_t a_oid;
     bson_oid_init (&a_oid, NULL);
     BSON_APPEND_OID (sdoc, "_id", &a_oid);
     //BSON_APPEND_OID (sdoc, "device_id", de_oid);
     //BSON_APPEND_UTF8 (sdoc, "name", name);
     //BSON_APPEND_INT32 (sdoc, "sensorType", sensorType);
     BSON_APPEND_INT32 (sdoc, "code", code);
     BSON_APPEND_UTF8 (sdoc, "mobile", tel);
     BSON_APPEND_UTF8 (sdoc, "sendmsg", msg);
     BSON_APPEND_UTF8 (sdoc, "user_id", userId);
     BSON_APPEND_UTF8 (sdoc, "se_id", se_id);
     BSON_APPEND_UTF8 (sdoc, "de_id", de_id);
     BSON_APPEND_UTF8 (sdoc, "device_name", device_name);
     BSON_APPEND_UTF8 (sdoc, "sensor_name", name);
     time_t timep;
     time(&timep);
     BSON_APPEND_DOUBLE (sdoc, "time", timep);
     bson_error_t serror;
     if (!mongoc_collection_insert (coll, MONGOC_INSERT_NONE, sdoc, NULL, &serror)) {
        fprintf (stderr, "%s\n", serror.message);
     }
     bson_destroy (sdoc);
}
Ejemplo n.º 13
0
static int mongo_set_oauth_key(oauth_key_data_raw *key) {

  mongoc_collection_t * collection = mongo_get_collection("oauth_key");

  if(!collection)
    return -1;

  bson_t query;
  bson_init(&query);
  BSON_APPEND_UTF8(&query, "kid", (const char *)key->kid);

  bson_t doc;
  bson_init(&doc);
  BSON_APPEND_UTF8(&doc, "kid", (const char *)key->kid);
  BSON_APPEND_UTF8(&doc, "as_rs_alg", (const char *)key->as_rs_alg);
  BSON_APPEND_UTF8(&doc, "ikm_key", (const char *)key->ikm_key);
  BSON_APPEND_INT64(&doc, "timestamp", (int64_t)key->timestamp);
  BSON_APPEND_INT32(&doc, "lifetime", (int32_t)key->lifetime);

  int ret = -1;

  if (!mongoc_collection_update(collection, MONGOC_UPDATE_UPSERT, &query, &doc, NULL, NULL)) {
    TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error inserting/updating oauth key information\n");
  } else {
    ret = 0;
  }
  mongoc_collection_destroy(collection);
  bson_destroy(&doc);
  bson_destroy(&query);
  return ret;
}
Ejemplo n.º 14
0
static int mongo_get_admin_user(const u08bits *usname, u08bits *realm, password_t pwd)
{
	mongoc_collection_t * collection = mongo_get_collection("admin_user");

	if(!collection)
    return -1;

	realm[0]=0;
	pwd[0]=0;

	bson_t query;
	bson_init(&query);
	BSON_APPEND_UTF8(&query, "name", (const char *)usname);

	bson_t fields;
	bson_init(&fields);
	BSON_APPEND_INT32(&fields, "realm", 1);
	BSON_APPEND_INT32(&fields, "password", 1);

	mongoc_cursor_t * cursor;
	cursor = mongoc_collection_find(collection, MONGOC_QUERY_NONE, 0, 1, 0, &query, &fields, NULL);

	int ret = -1;

	if (!cursor) {
		TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error querying MongoDB collection 'admin_user'\n");
	} else {
		const bson_t * item;
		uint32_t length;
		bson_iter_t iter;
		if (mongoc_cursor_next(cursor, &item)) {
			if (bson_iter_init(&iter, item) && bson_iter_find(&iter, "realm") && BSON_ITER_HOLDS_UTF8(&iter)) {
				strncpy((char*)realm,bson_iter_utf8(&iter, &length),STUN_MAX_REALM_SIZE);
				ret = 0;
			}
			if (bson_iter_init(&iter, item) && bson_iter_find(&iter, "password") && BSON_ITER_HOLDS_UTF8(&iter)) {
				strncpy((char*)pwd,bson_iter_utf8(&iter, &length),STUN_MAX_PWD_SIZE);
				ret = 0;
			}
		}
		mongoc_cursor_destroy(cursor);
	}
	mongoc_collection_destroy(collection);
	bson_destroy(&query);
	bson_destroy(&fields);
	return ret;
}
static void
test_insert (void)
{
   mongoc_database_t *database;
   mongoc_collection_t *collection;
   mongoc_client_t *client;
   bson_context_t *context;
   bson_error_t error;
   bool r;
   bson_oid_t oid;
   unsigned i;
   bson_t b;


   client = mongoc_client_new(gTestUri);
   ASSERT (client);

   database = get_test_database (client);
   ASSERT (database);

   collection = get_test_collection (client, "test_insert");
   ASSERT (collection);

   mongoc_collection_drop(collection, &error);

   context = bson_context_new(BSON_CONTEXT_NONE);
   ASSERT (context);

   for (i = 0; i < 10; i++) {
      bson_init(&b);
      bson_oid_init(&oid, context);
      bson_append_oid(&b, "_id", 3, &oid);
      bson_append_utf8(&b, "hello", 5, "/world", 5);
      r = mongoc_collection_insert(collection, MONGOC_INSERT_NONE, &b, NULL,
                                   &error);
      if (!r) {
         MONGOC_WARNING("%s\n", error.message);
      }
      ASSERT (r);
      bson_destroy(&b);
   }

   bson_init (&b);
   BSON_APPEND_INT32 (&b, "$hello", 1);
   r = mongoc_collection_insert (collection, MONGOC_INSERT_NONE, &b, NULL,
                                 &error);
   ASSERT (!r);
   ASSERT (error.domain == MONGOC_ERROR_BSON);
   ASSERT (error.code == MONGOC_ERROR_BSON_INVALID);
   bson_destroy (&b);

   r = mongoc_collection_drop (collection, &error);
   ASSERT (r);

   mongoc_collection_destroy(collection);
   mongoc_database_destroy(database);
   bson_context_destroy(context);
   mongoc_client_destroy(client);
}
bool
_mongoc_write_result_complete (mongoc_write_result_t *result,
                               bson_t                *bson,
                               bson_error_t          *error)
{
   ENTRY;

   BSON_ASSERT (result);

   if (bson) {
      BSON_APPEND_INT32 (bson, "nInserted", result->nInserted);
      BSON_APPEND_INT32 (bson, "nMatched", result->nMatched);
      if (!result->omit_nModified) {
         BSON_APPEND_INT32 (bson, "nModified", result->nModified);
      }
      BSON_APPEND_INT32 (bson, "nRemoved", result->nRemoved);
      BSON_APPEND_INT32 (bson, "nUpserted", result->nUpserted);
      if (!bson_empty0 (&result->upserted)) {
         BSON_APPEND_ARRAY (bson, "upserted", &result->upserted);
      }
      BSON_APPEND_ARRAY (bson, "writeErrors", &result->writeErrors);
      if (result->n_writeConcernErrors) {
         BSON_APPEND_ARRAY (bson, "writeConcernErrors",
                            &result->writeConcernErrors);
      }
   }

   /* set bson_error_t from first write error or write concern error */
   _set_error_from_response (&result->writeErrors,
                             MONGOC_ERROR_COMMAND,
                             "write",
                             &result->error);

   if (!result->error.code) {
      _set_error_from_response (&result->writeConcernErrors,
                                MONGOC_ERROR_WRITE_CONCERN,
                                "write concern",
                                &result->error);
   }

   if (error) {
      memcpy (error, &result->error, sizeof *error);
   }

   RETURN (!result->failed && result->error.code == 0);
}
Ejemplo n.º 17
0
void fam_flags(mongoc_collection_t *collection)
{
   mongoc_find_and_modify_opts_t *opts;
   bson_t reply;
   bson_error_t error;
   bson_t query = BSON_INITIALIZER;
   bson_t *update;
   bool success;


   /* Find Zlatan Ibrahimovic, the striker */
   BSON_APPEND_UTF8 (&query, "firstname", "Zlatan");
   BSON_APPEND_UTF8 (&query, "lastname", "Ibrahimovic");
   BSON_APPEND_UTF8 (&query, "profession", "Football player");
   BSON_APPEND_INT32 (&query, "age", 34);
   BSON_APPEND_INT32 (&query, "goals", (16+35+23+57+16+14+28+84)+(1+6+62));

   /* Add his football position */
   update = BCON_NEW ("$set", "{",
      "position", BCON_UTF8 ("striker"),
   "}");

   opts = mongoc_find_and_modify_opts_new ();

   mongoc_find_and_modify_opts_set_update (opts, update);

   /* Create the document if it didn't exist, and return the updated document */
   mongoc_find_and_modify_opts_set_flags (opts, MONGOC_FIND_AND_MODIFY_UPSERT|MONGOC_FIND_AND_MODIFY_RETURN_NEW);

   success = mongoc_collection_find_and_modify_with_opts (collection, &query, opts, &reply, &error);

   if (success) {
      char *str;

      str = bson_as_json (&reply, NULL);
      printf ("%s\n", str);
      bson_free (str);
   } else {
      fprintf(stderr, "Got error: \"%s\" on line %d\n", error.message, __LINE__);
   }

   bson_destroy (&reply);
   bson_destroy (update);
   bson_destroy (&query);
   mongoc_find_and_modify_opts_destroy (opts);
}
Ejemplo n.º 18
0
int main(int argc, char *argv[]) {
	mongoc_client_t *client;
	mongoc_collection_t *collection;
	mongoc_cursor_t *cursor;
	const bson_t *doc;
	bson_t *query;
	char *str;

	mongoc_init();

	client = mongoc_client_new("mongodb://localhost:27017/");
	collection = mongoc_client_get_collection(client, "stockopedia",
			"instruments");

	query = bson_new();
	bson_t *fields = bson_new();
	BSON_APPEND_INT32(fields, "RIC", 1);

	cursor = mongoc_collection_find(collection, MONGOC_QUERY_NONE, 0, 0, 0,
			query, fields, NULL);

	bson_iter_t iter;
	const bson_value_t *value;

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

		if (bson_iter_init(&iter, doc)) {
			while (bson_iter_next(&iter)) {
				printf("Found a field named: %s\n", bson_iter_key(&iter));

				value = bson_iter_value(&iter);
				if (value->value_type == BSON_TYPE_UTF8) {
					printf("It's a UTF8 : '%s'\n", value->value.v_utf8.str);
				}
			}
		}

		//printf("Found element key : '%s'\n", bson_iter_key(&iter));

//		if (bson_iter_init(&iter, doc)) {
//
//		}

		bson_free(str);
	}

	//Now fetch quotes for each RIC

	bson_destroy(query);
	mongoc_cursor_destroy(cursor);
	mongoc_collection_destroy(collection);
	mongoc_client_destroy(client);

	return 0;
}
Ejemplo n.º 19
0
static bool
txn_abort (mongoc_client_session_t *session, bson_t *reply, bson_error_t *error)
{
   bson_t cmd = BSON_INITIALIZER;
   bson_t opts = BSON_INITIALIZER;
   bson_error_t err_local;
   bson_error_t *err_ptr = error ? error : &err_local;
   bson_t reply_local = BSON_INITIALIZER;
   mongoc_write_err_type_t error_type;
   bool r = false;

   _mongoc_bson_init_if_set (reply);

   if (!mongoc_client_session_append (session, &opts, err_ptr)) {
      GOTO (done);
   }

   if (session->txn.opts.write_concern) {
      if (!mongoc_write_concern_append (session->txn.opts.write_concern,
                                        &opts)) {
         bson_set_error (err_ptr,
                         MONGOC_ERROR_TRANSACTION,
                         MONGOC_ERROR_TRANSACTION_INVALID_STATE,
                         "Invalid transaction write concern");
         GOTO (done);
      }
   }

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

   /* will be reinitialized by mongoc_client_write_command_with_opts */
   bson_destroy (&reply_local);
   r = mongoc_client_write_command_with_opts (
      session->client, "admin", &cmd, &opts, &reply_local, err_ptr);

   /* Transactions Spec: "Drivers MUST retry the commitTransaction command once
    * after it fails with a retryable error", same for abort */
   error_type = _mongoc_write_error_get_type (r, err_ptr, &reply_local);
   if (error_type == MONGOC_WRITE_ERR_RETRY) {
      bson_destroy (&reply_local);
      r = mongoc_client_write_command_with_opts (
         session->client, "admin", &cmd, &opts, &reply_local, err_ptr);
   }

   if (!r) {
      /* we won't return an error from abortTransaction, so warn */
      MONGOC_WARNING ("Error in abortTransaction: %s", err_ptr->message);
   }

done:
   bson_destroy (&reply_local);
   bson_destroy (&cmd);
   bson_destroy (&opts);

   return r;
}
int
main (int   argc,
      char *argv[])
{
   mongoc_client_t *client;
   mongoc_apm_callbacks_t *callbacks;
   stats_t stats = { 0 }; 
   mongoc_collection_t *collection;
   const char *uristr = "mongodb://127.0.0.1/?appname=cmd-monitoring-example";
   const char *collection_name = "test";
   bson_t doc;

   mongoc_init ();

   if (argc > 1) {
      uristr = argv [1];
   }

   client = mongoc_client_new (uristr);

   if (!client) {
      fprintf (stderr, "Failed to parse URI.\n");
      return EXIT_FAILURE;
   }

   mongoc_client_set_error_api (client, 2);
   callbacks = mongoc_apm_callbacks_new ();
   mongoc_apm_set_command_started_cb (callbacks, command_started);
   mongoc_apm_set_command_succeeded_cb (callbacks, command_succeeded );
   mongoc_apm_set_command_failed_cb (callbacks, command_failed);
   mongoc_client_set_apm_callbacks (client,
                                    callbacks,
                                    (void *) &stats /* context pointer */);

   bson_init (&doc);
   BSON_APPEND_INT32 (&doc, "_id", 1);

   collection = mongoc_client_get_collection (client, "test", collection_name);
   mongoc_collection_drop (collection, NULL);
   mongoc_collection_insert (collection, MONGOC_INSERT_NONE, &doc, NULL, NULL);
   /* duplicate key error on the second insert */
   mongoc_collection_insert (collection, MONGOC_INSERT_NONE, &doc, NULL, NULL);

   printf ("started: %d\nsucceeded: %d\nfailed: %d\n",
           stats.started, stats.succeeded, stats.failed);

   bson_destroy (&doc);
   mongoc_collection_destroy (collection);
   mongoc_apm_callbacks_destroy (callbacks);
   mongoc_client_destroy (client);

   mongoc_cleanup ();

   return EXIT_SUCCESS;
}
Ejemplo n.º 21
0
static bool
mongoc_uri_parse_option (mongoc_uri_t *uri,
                         const char   *str)
{
   int32_t v_int;
   const char *end_key;
   char *key;
   char *value;

   if (!(key = scan_to_unichar(str, '=', &end_key))) {
      return false;
   }

   value = bson_strdup(end_key + 1);
   mongoc_uri_do_unescape(&value);

   if (!strcasecmp(key, "connecttimeoutms") ||
       !strcasecmp(key, "sockettimeoutms") ||
       !strcasecmp(key, "maxpoolsize") ||
       !strcasecmp(key, "minpoolsize") ||
       !strcasecmp(key, "maxidletimems") ||
       !strcasecmp(key, "waitqueuemultiple") ||
       !strcasecmp(key, "waitqueuetimeoutms") ||
       !strcasecmp(key, "wtimeoutms")) {
      v_int = strtol(value, NULL, 10);
      bson_append_int32(&uri->options, key, -1, v_int);
   } else if (!strcasecmp(key, "w")) {
      if (*value == '-' || isdigit(*value)) {
         v_int = strtol (value, NULL, 10);
         BSON_APPEND_INT32 (&uri->options, "w", v_int);
      } else if (0 == strcasecmp (value, "majority")) {
         BSON_APPEND_UTF8 (&uri->options, "w", "majority");
      } else if (*value) {
         BSON_APPEND_UTF8 (&uri->options, "W", value);
      }
   } else if (!strcasecmp(key, "canonicalizeHostname") ||
              !strcasecmp(key, "journal") ||
              !strcasecmp(key, "safe") ||
              !strcasecmp(key, "slaveok") ||
              !strcasecmp(key, "ssl")) {
      bson_append_bool (&uri->options, key, -1,
                        (0 == strcasecmp (value, "true")) ||
                        (0 == strcasecmp (value, "t")) ||
                        (0 == strcmp (value, "1")));
   } else if (!strcasecmp(key, "readpreferencetags")) {
      mongoc_uri_parse_tags(uri, value, &uri->read_prefs);
   } else {
      bson_append_utf8(&uri->options, key, -1, value, -1);
   }

   bson_free(key);
   bson_free(value);

   return true;
}
Ejemplo n.º 22
0
/**
 * mongoc_write_concern_freeze:
 * @write_concern: A mongoc_write_concern_t.
 *
 * This is an internal function.
 *
 * Freeze the write concern if necessary and encode it into a bson_ts which
 * represent the raw bson form and the get last error command form.
 *
 * You may not modify the write concern further after calling this function.
 */
static void
_mongoc_write_concern_freeze (mongoc_write_concern_t *write_concern)
{
   bson_t *compiled;
   bson_t *compiled_gle;

   BSON_ASSERT (write_concern);

   compiled = &write_concern->compiled;
   compiled_gle = &write_concern->compiled_gle;

   write_concern->frozen = true;

   bson_init (compiled);
   bson_init (compiled_gle);

   if (write_concern->w == MONGOC_WRITE_CONCERN_W_TAG) {
      BSON_ASSERT (write_concern->wtag);
      BSON_APPEND_UTF8 (compiled, "w", write_concern->wtag);
   } else if (write_concern->w == MONGOC_WRITE_CONCERN_W_MAJORITY) {
      BSON_APPEND_UTF8 (compiled, "w", "majority");
   } else if (write_concern->w == MONGOC_WRITE_CONCERN_W_DEFAULT) {
      /* Do Nothing */
   } else {
      BSON_APPEND_INT32 (compiled, "w", write_concern->w);
   }

   if (write_concern->fsync_ != MONGOC_WRITE_CONCERN_FSYNC_DEFAULT) {
      bson_append_bool(compiled, "fsync", 5, !!write_concern->fsync_);
   }

   if (write_concern->journal != MONGOC_WRITE_CONCERN_JOURNAL_DEFAULT) {
      bson_append_bool(compiled, "j", 1, !!write_concern->journal);
   }

   if (write_concern->wtimeout) {
      bson_append_int32(compiled, "wtimeout", 8, write_concern->wtimeout);
   }

   BSON_APPEND_INT32 (compiled_gle, "getlasterror", 1);
   bson_concat (compiled_gle, compiled);
}
Ejemplo n.º 23
0
int database_create_transaction_indexes(struct database* db)
{
    bson_t* keys;
    mongoc_index_opt_t opt;
    bson_error_t error;

    mongoc_collection_t* collection = mongoc_client_get_collection(db->client, database_name(db), "transactions");

    // transactions.hash
    {
        keys = bson_new();
        BSON_APPEND_INT32(keys, "hash", 1);

        mongoc_index_opt_init(&opt);
        opt.unique = 1;

        if(mongoc_collection_create_index(collection, keys, &opt, &error) == 0) {
            printf("index creation error (transaction.hash)\n");
        }

        bson_destroy(keys);
    }

    // (transaction.inputs.output_reference.hash, transaction.inputs.output_reference.index) [non-unique]
    {
        keys = bson_new();
        BSON_APPEND_INT32(keys, "inputs.output_reference.hash", 1);
        BSON_APPEND_INT32(keys, "inputs.output_reference.index", 1);

        mongoc_index_opt_init(&opt);
        opt.unique = 0;

        if(mongoc_collection_create_index(collection, keys, &opt, &error) == 0) {
            printf("index creation error (inputs.output_reference)\n");
        }

        bson_destroy(keys);
    }

    mongoc_collection_destroy(collection);
    return 0;
}
Ejemplo n.º 24
0
bool
bson_append_int32_from_s (bson_t     *bson,
                          const char *key,
                          const char *value)
{
    bool ret = true;

    if (value && strcmp ("\\N", value) != 0)
        ret = BSON_APPEND_INT32 (bson, key, atoi (value));
    return ret;
}
Ejemplo n.º 25
0
static void
test_create_collection (void)
{
   mongoc_database_t *database;
   mongoc_collection_t *collection;
   mongoc_client_t *client;
   bson_error_t error = { 0 };
   bson_t options;
   char *dbname;
   char *name;
   bool r;

   client = mongoc_client_new (gTestUri);
   assert (client);

   dbname = gen_collection_name ("dbtest");
   database = mongoc_client_get_database (client, dbname);
   assert (database);
   bson_free (dbname);

   bson_init (&options);
   BSON_APPEND_INT32 (&options, "size", 1234);
   BSON_APPEND_INT32 (&options, "max", 4567);
   BSON_APPEND_BOOL (&options, "capped", true);
   BSON_APPEND_BOOL (&options, "autoIndexId", true);

   name = gen_collection_name ("create_collection");
   collection = mongoc_database_create_collection (database, name, &options, &error);
   assert (collection);
   bson_free (name);

   r = mongoc_collection_drop (collection, &error);
   assert (r);

   r = mongoc_database_drop (database, &error);
   assert (r);

   mongoc_collection_destroy (collection);
   mongoc_database_destroy (database);
   mongoc_client_destroy (client);
}
Ejemplo n.º 26
0
static future_t *
client_read_cmd (func_ctx_t *ctx, bson_t *cmd)
{
   BSON_APPEND_INT32 (cmd, "foo", 1);
   return future_client_read_command_with_opts (ctx->client,
                                                "db",
                                                tmp_bson ("{'foo': 1}"),
                                                ctx->prefs,
                                                ctx->opts,
                                                NULL,
                                                &ctx->error);
}
static void
too_large_error (bson_error_t *error,
                 int32_t       idx,
                 int32_t       len,
                 int32_t       max_bson_size,
                 bson_t       *err_doc)
{
   /* MongoDB 2.6 uses code 2 for "too large". TODO: see CDRIVER-644 */
   const int code = 2;

   bson_set_error (error, MONGOC_ERROR_BSON, code,
                   "Document %u is too large for the cluster. "
                   "Document is %u bytes, max is %d.",
                   idx, len, max_bson_size);

   if (err_doc) {
      BSON_APPEND_INT32 (err_doc, "index", idx);
      BSON_APPEND_UTF8 (err_doc, "err", error->message);
      BSON_APPEND_INT32 (err_doc, "code", code);
   }
}
Ejemplo n.º 28
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;
}
Ejemplo n.º 29
0
static int mongo_set_realm_option_one(u08bits *realm, unsigned long value, const char* opt) {
  mongoc_collection_t * collection = mongo_get_collection("realm"); 

	if(!collection)
    return -1;
    
  bson_t query, doc, child;
  bson_init(&query);
  BSON_APPEND_UTF8(&query, "realm", (const char *)realm);
  bson_init(&doc);
  
  size_t klen = 9 + strlen(opt);
  char * _k = (char *)turn_malloc(klen);
  strcpy(_k, "options.");
  strcat(_k, opt);
  
  if (value > 0) {
    bson_append_document_begin(&doc, "$set", -1, &child);
    BSON_APPEND_INT32(&child, _k, (int32_t)value);
    bson_append_document_end(&doc, &child);
  } else {
    bson_append_document_begin(&doc, "$unset", -1, &child);
    BSON_APPEND_INT32(&child, _k, 1);
    bson_append_document_end(&doc, &child);
  }
  turn_free(_k,klen);
  
  int ret = -1;
  
  if (!mongoc_collection_update(collection, MONGOC_UPDATE_MULTI_UPDATE, &query, &doc, NULL, NULL)) {
    TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error deleting origin information\n");
  } else {
    ret = 0;
  }
  mongoc_collection_destroy(collection);
  bson_destroy(&query);
  bson_destroy(&doc);
  return ret;
}
Ejemplo n.º 30
0
int32_t
_mongoc_write_result_merge_arrays (uint32_t offset,
                                   mongoc_write_result_t *result, /* IN */
                                   bson_t *dest,                  /* IN */
                                   bson_iter_t *iter)             /* IN */
{
   const bson_value_t *value;
   bson_iter_t ar;
   bson_iter_t citer;
   int32_t idx;
   int32_t count = 0;
   int32_t aridx;
   bson_t child;
   const char *keyptr = NULL;
   char key[12];
   int len;

   ENTRY;

   BSON_ASSERT (result);
   BSON_ASSERT (dest);
   BSON_ASSERT (iter);
   BSON_ASSERT (BSON_ITER_HOLDS_ARRAY (iter));

   aridx = bson_count_keys (dest);

   if (bson_iter_recurse (iter, &ar)) {
      while (bson_iter_next (&ar)) {
         if (BSON_ITER_HOLDS_DOCUMENT (&ar) &&
             bson_iter_recurse (&ar, &citer)) {
            len =
               (int) bson_uint32_to_string (aridx++, &keyptr, key, sizeof key);
            bson_append_document_begin (dest, keyptr, len, &child);
            while (bson_iter_next (&citer)) {
               if (BSON_ITER_IS_KEY (&citer, "index")) {
                  idx = bson_iter_int32 (&citer) + offset;
                  BSON_APPEND_INT32 (&child, "index", idx);
               } else {
                  value = bson_iter_value (&citer);
                  BSON_APPEND_VALUE (&child, bson_iter_key (&citer), value);
               }
            }
            bson_append_document_end (dest, &child);
            count++;
         }
      }
   }

   RETURN (count);
}