static void do_alarm(mongoc_collection_t *sensorcoll,char * se_id,char * alarmType,char * upperBoundC,char *lowerBoundC, char *duration,char *target,char * contactId,char* addr,mongoc_collection_t *alarmlogcoll,char* userId,char *device_name,char * de_id){ mongoc_cursor_t *cursor; bson_t *doc; bson_t *query; char *str; query = bson_new (); bson_oid_t se_oid; bson_oid_init_from_string(&se_oid, se_id); BSON_APPEND_OID (query, "_id",&se_oid); cursor = mongoc_collection_find (sensorcoll, MONGOC_QUERY_NONE, 0, 0, 0, query, NULL, NULL); double ivalue=0; double dalarmtime=0; int interval=0; int balarm=0; int buse=0; char name[1024]; memset(name,0,1024); while (mongoc_cursor_next (cursor, &doc)) { str = bson_as_json (doc, NULL); printf ("%s\n", str); bson_free (str); bson_iter_t iter; bson_iter_t sub_iter; if (bson_iter_init (&iter, doc)) { while (bson_iter_next (&iter)) { //printf ("Found a field named: %s\n", bson_iter_key (&iter)); bson_value_t *value; value = bson_iter_value (&iter); //printf("type %d\n",value->value_type); if (value->value_type == BSON_TYPE_INT32) { if(strcmp(bson_iter_key (&iter),"value")==0){ printf("value %d\n", value->value.v_int32); ivalue=value->value.v_double; buse =1; }else if(strcmp(bson_iter_key (&iter),"interval")==0){ interval=value->value.v_int32; }else if(strcmp(bson_iter_key (&iter),"balarm")==0){ balarm=value->value.v_int32; } } if(strcmp(bson_iter_key (&iter),"value")==0){ printf("value type %d,%d\n",value->value_type,BSON_TYPE_INT32); } if (value->value_type == BSON_TYPE_DOUBLE) { if(strcmp(bson_iter_key (&iter),"value")==0){ //printf("value %d\n", (int)value->value.v_double); buse =1; ivalue=value->value.v_double; } if(strcmp(bson_iter_key (&iter),"alarmtime")==0){ dalarmtime=value->value.v_double; } } if (value->value_type == BSON_TYPE_UTF8) { if(strcmp(bson_iter_key (&iter),"name")==0){ //printf("value %d\n", (int)value->value.v_double); strcpy(name,value->value.v_utf8.str); } if(strcmp(bson_iter_key (&iter),"value")==0){ //printf("value %d\n", (int)value->value.v_double); ivalue=atof(value->value.v_utf8.str); buse =1; } } } } } bson_destroy (query); printf("se_id:%s,buse:%d\n",se_id,buse); printf("alarmType:%s,%f : %s,%s",alarmType,ivalue,upperBoundC,lowerBoundC); time_t t; t = time(NULL); struct tm *lt; int ii = time(&t); int bdoalarm=1; if(balarm==1){ bdoalarm=1; if(dalarmtime>0 &&interval>0){ if((ii-dalarmtime)<3600){ bdoalarm=0; } } } if(buse ==1){ if(strcmp(alarmType,"val_above")==0){ int iupper=atoi(upperBoundC); if(iupper<ivalue){ printf("val_above %d value\n",iupper,ivalue); char msg[2048]; memset(msg,0,2048); snprintf(msg, sizeof(msg) - 1, "故障报警:%s的%s数值高于%d,位置是%s,请及时处理!", device_name, name, iupper, addr); char buf[1024]; URLEncodeGBK(msg, strlen(msg), buf,sizeof(buf)); printf("%s\n",buf); printf("alarm info: %s\n",msg); if(bdoalarm>0){ int code=sendsms_c(buf,contactId); saveAlarmLog(alarmlogcoll,se_id,code,contactId,msg,userId,device_name,name,de_id); updateAlarm(sensorcoll,se_id,interval+1,1); printf("send sms \n"); } }else { updateAlarm(sensorcoll,se_id,0,0); } }else if(strcmp(alarmType,"val_below")==0){ int iupper=atoi(lowerBoundC); if(iupper>ivalue){ printf("val_below %d value %d\n",iupper,ivalue); char msg[2048]; memset(msg,0,2048); snprintf(msg, sizeof(msg) - 1, "故障报警:%s的%s数值低于%d,位置是%s,请及时处理!", device_name, name, iupper, addr); char buf[1024]; URLEncodeGBK(msg, strlen(msg), buf,sizeof(buf)); printf("%s\n",buf); printf("alarm info: %s\n",msg); if(bdoalarm>0){ int code=sendsms_c(buf,contactId); saveAlarmLog(alarmlogcoll,se_id,code,contactId,msg,userId,device_name,name,de_id); updateAlarm(sensorcoll,se_id,interval+1,1); printf("send sms \n"); } }else { updateAlarm(sensorcoll,se_id,0,0); } }else if(strcmp(alarmType,"switch_on")==0){ if(ivalue==1){ char msg[2048]; memset(msg,0,2048); snprintf(msg, sizeof(msg) - 1, "故障报警:%s,%s,位置是%s,请及时处理!", device_name, name, addr); char buf[1024]; URLEncodeGBK(msg, strlen(msg), buf,sizeof(buf)); printf("%s\n",buf); printf("alarm info: %s\n",msg); if(bdoalarm>0){ int code=sendsms_c(buf,contactId); saveAlarmLog(alarmlogcoll,se_id,code,contactId,msg,userId,device_name,name,de_id); updateAlarm(sensorcoll,se_id,interval+1,1); printf("send sms \n"); } }else { updateAlarm(sensorcoll,se_id,0,0); } }else if(strcmp(alarmType,"offline")==0){ if(ivalue==1){ char msg[2048]; memset(msg,0,2048); snprintf(msg, sizeof(msg) - 1, "故障报警:%s,%s,位置是%s,请及时处理!", device_name, name, addr); char buf[1024]; URLEncodeGBK(msg, strlen(msg), buf,sizeof(buf)); printf("%s\n",buf); printf("alarm info: %s\n",msg); if(bdoalarm>0){ int code=sendsms_c(buf,contactId); saveAlarmLog(alarmlogcoll,se_id,code,contactId,msg,userId,device_name,name,de_id); updateAlarm(sensorcoll,se_id,interval+1,1); printf("send sms \n"); } }else { updateAlarm(sensorcoll,se_id,0,0); } } } }
static void chunk_free( bson *oChunk ) { bson_destroy( oChunk ); bson_free( oChunk ); }
void gridfile_destroy( gridfile *gfile ) { bson_destroy( gfile->meta ); bson_free( gfile->meta ); }
static void test_get_collection_info (void) { mongoc_database_t *database; mongoc_collection_t *collection; mongoc_client_t *client; bson_error_t error = { 0 }; bson_iter_t iter; bson_iter_t col_array; bson_iter_t col_iter; bson_t capped_options = BSON_INITIALIZER; bson_t autoindexid_options = BSON_INITIALIZER; bson_t noopts_options = BSON_INITIALIZER; bson_t name_filter = BSON_INITIALIZER; int r; int num_infos = 0; bson_t *infos = NULL; const char *name; char *dbname; char *capped_name; char *autoindexid_name; char *noopts_name; client = mongoc_client_new (gTestUri); assert (client); dbname = gen_collection_name ("dbtest"); database = mongoc_client_get_database (client, dbname); assert (database); bson_free (dbname); capped_name = gen_collection_name ("capped"); BSON_APPEND_BOOL (&capped_options, "capped", true); BSON_APPEND_INT32 (&capped_options, "size", 10000000); BSON_APPEND_INT32 (&capped_options, "max", 1024); autoindexid_name = gen_collection_name ("autoindexid"); BSON_APPEND_BOOL (&autoindexid_options, "autoIndexId", false); noopts_name = gen_collection_name ("noopts"); collection = mongoc_database_create_collection (database, capped_name, &capped_options, &error); assert (collection); mongoc_collection_destroy (collection); collection = mongoc_database_create_collection (database, autoindexid_name, &autoindexid_options, &error); assert (collection); mongoc_collection_destroy (collection); collection = mongoc_database_create_collection (database, noopts_name, &noopts_options, &error); assert (collection); mongoc_collection_destroy (collection); /* first we filter on collection name. */ BSON_APPEND_UTF8 (&name_filter, "name", noopts_name); /* We only test with filters since get_collection_names will * test w/o filters for us. */ /* Filter on an exact match of name */ infos = mongoc_database_get_collection_info (database, &name_filter, &error); assert (infos); assert (!error.domain); assert (!error.code); if (bson_iter_init_find (&iter, infos, "collections") && BSON_ITER_HOLDS_ARRAY (&iter) && bson_iter_recurse (&iter, &col_array)) { while (bson_iter_next (&col_array)) { if (BSON_ITER_HOLDS_DOCUMENT (&col_array) && bson_iter_recurse (&col_array, &col_iter) && bson_iter_find (&col_iter, "name") && BSON_ITER_HOLDS_UTF8 (&col_iter) && (name = bson_iter_utf8 (&col_iter, NULL))) { ++num_infos; assert (0 == strcmp (name, noopts_name)); } else { assert (false); } } } assert (1 == num_infos); num_infos = 0; bson_destroy (infos); infos = NULL; r = mongoc_database_drop (database, &error); assert (r); assert (!error.domain); assert (!error.code); bson_free (capped_name); bson_free (noopts_name); bson_free (autoindexid_name); mongoc_database_destroy (database); mongoc_client_destroy (client); }
static void cleanup_globals (void) { bson_free (gTestUri); }
/* TODO: factor */ static void * worker_thread (void *data) { worker_closure_t *closure = (worker_closure_t *) data; mock_server_t *server = closure->server; mongoc_stream_t *client_stream = closure->client_stream; mongoc_buffer_t buffer; mongoc_rpc_t *rpc = NULL; bool handled; bson_error_t error; int32_t msg_len; bool stopped; sync_queue_t *q; request_t *request; mongoc_array_t autoresponders; ssize_t i; autoresponder_handle_t handle; #ifdef MONGOC_ENABLE_SSL bool ssl; #endif ENTRY; BSON_ASSERT(closure); #ifdef MONGOC_ENABLE_SSL mongoc_mutex_lock (&server->mutex); ssl = server->ssl; mongoc_mutex_unlock (&server->mutex); if (ssl) { if (!mongoc_stream_tls_handshake_block (client_stream, "localhost", TIMEOUT, &error)) { MONGOC_ERROR("Blocking TLS handshake failed"); mongoc_stream_close (client_stream); mongoc_stream_destroy (client_stream); RETURN (NULL); } } #endif _mongoc_buffer_init (&buffer, NULL, 0, NULL, NULL); _mongoc_array_init (&autoresponders, sizeof (autoresponder_handle_t)); again: bson_free (rpc); rpc = NULL; handled = false; mongoc_mutex_lock (&server->mutex); stopped = server->stopped; mongoc_mutex_unlock (&server->mutex); if (stopped) { GOTO(failure); } if (_mongoc_buffer_fill (&buffer, client_stream, 4, TIMEOUT, &error) == -1) { GOTO (again); } assert (buffer.len >= 4); memcpy (&msg_len, buffer.data + buffer.off, 4); msg_len = BSON_UINT32_FROM_LE (msg_len); if (msg_len < 16) { MONGOC_WARNING ("No data"); GOTO (failure); } if (_mongoc_buffer_fill (&buffer, client_stream, (size_t) msg_len, -1, &error) == -1) { MONGOC_WARNING ("%s():%d: %s", BSON_FUNC, __LINE__, error.message); GOTO (failure); } assert (buffer.len >= (unsigned) msg_len); /* copies message from buffer */ request = request_new (&buffer, msg_len, server, client_stream, closure->port); mongoc_mutex_lock (&server->mutex); _mongoc_array_copy (&autoresponders, &server->autoresponders); mongoc_mutex_unlock (&server->mutex); if (mock_server_get_verbose (server)) { printf ("%5.2f %hu -> %hu %s\n", mock_server_get_uptime_sec (server), closure->port, server->port, request->as_str); fflush (stdout); } /* run responders most-recently-added-first */ for (i = server->autoresponders.len - 1; i >= 0; i--) { handle = _mongoc_array_index (&server->autoresponders, autoresponder_handle_t, i); if (handle.responder (request, handle.data)) { handled = true; /* responder should destroy the request */ request = NULL; break; } } if (!handled) { q = mock_server_get_queue (server); q_put (q, (void *) request); request = NULL; } memmove (buffer.data, buffer.data + buffer.off + msg_len, buffer.len - msg_len); buffer.off = 0; buffer.len -= msg_len; GOTO (again); failure: _mongoc_array_destroy (&autoresponders); _mongoc_buffer_destroy (&buffer); mongoc_stream_close (client_stream); mongoc_stream_destroy (client_stream); bson_free (rpc); bson_free (closure); _mongoc_buffer_destroy (&buffer); RETURN (NULL); }
void test_mongo_wire_cmd_insert_n (void) { bson *ins, *tmp; const bson *docs[10]; mongo_packet *p; mongo_packet_header hdr; const guint8 *data; gint32 data_size; bson_cursor *c; gint32 pos; ins = test_bson_generate_full (); tmp = bson_new (); docs[0] = ins; docs[1] = tmp; docs[2] = ins; docs[3] = ins; docs[4] = NULL; docs[5] = ins; ok (mongo_wire_cmd_insert_n (1, NULL, 1, docs) == NULL, "mongo_wire_cmd_insert_n() fails with a NULL namespace"); ok (mongo_wire_cmd_insert_n (1, "test.ns", 1, NULL) == NULL, "mongo_wire_cmd_insert_n() fails with no documents"); ok (mongo_wire_cmd_insert_n (1, "test.ns", 0, docs) == NULL, "mongo_wire_cmd_insert_n() fails with no documents"); ok (mongo_wire_cmd_insert_n (1, "test.ns", 2, docs) == NULL, "mongo_wire_cmd_insert_n() fails with an unfinished document"); bson_finish (tmp); ok (mongo_wire_cmd_insert_n (1, "test.ns", 5, docs) == NULL, "mongo_wire_cmd_insert_n() fails with a NULL document in the array"); ok ((p = mongo_wire_cmd_insert_n (1, "test.ns", 3, docs)) != NULL, "mongo_wire_cmd_insert() works"); bson_free (ins); bson_free (tmp); /* Test basic header data */ mongo_wire_packet_get_header (p, &hdr); cmp_ok ((data_size = mongo_wire_packet_get_data (p, &data)), "!=", -1, "Packet data size appears fine"); cmp_ok (hdr.length, "==", sizeof (mongo_packet_header) + data_size, "Packet header length is correct"); cmp_ok (hdr.id, "==", 1, "Header ID is ok"); cmp_ok (hdr.resp_to, "==", 0, "Response ID is ok"); /* * Test the first document */ /* pos = zero + collection_name + NULL */ pos = sizeof (gint32) + strlen ("test.ns") + 1; ok ((ins = bson_new_from_data (data + pos, _DOC_SIZE (data, pos) - 1)) != NULL, "First document is included"); bson_finish (ins); ok ((c = bson_find (ins, "int32")) != NULL, "BSON contains 'int32'"); cmp_ok (bson_cursor_type (c), "==", BSON_TYPE_INT32, "int32 has correct type"); bson_cursor_next (c); cmp_ok (bson_cursor_type (c), "==", BSON_TYPE_INT64, "next element has correct type too"); ok (bson_cursor_next (c) == FALSE, "No more data after the update BSON object"); bson_cursor_free (c); /* * Test the second document */ pos += bson_size (ins); ok ((tmp = bson_new_from_data (data + pos, _DOC_SIZE (data, pos) - 1)) != NULL, "Second document is included"); bson_finish (tmp); cmp_ok (bson_size (tmp), "==", 5, "Second document is empty"); bson_free (ins); bson_free (tmp); mongo_wire_packet_free (p); }
/* Parse server-first-message of the form: * r=client-nonce|server-nonce,s=user-salt,i=iteration-count * * Generate client-final-message of the form: * c=channel-binding(base64),r=client-nonce|server-nonce,p=client-proof */ static bool _mongoc_scram_step2 (mongoc_scram_t *scram, const uint8_t *inbuf, uint32_t inbuflen, uint8_t *outbuf, uint32_t outbufmax, uint32_t *outbuflen, bson_error_t *error) { uint8_t *val_r = NULL; uint32_t val_r_len; uint8_t *val_s = NULL; uint32_t val_s_len; uint8_t *val_i = NULL; uint32_t val_i_len; uint8_t **current_val; uint32_t *current_val_len; const uint8_t *ptr; const uint8_t *next_comma; char *tmp; char *hashed_password; uint8_t decoded_salt[MONGOC_SCRAM_B64_HASH_SIZE] = {0}; int32_t decoded_salt_len; bool rval = true; int iterations; BSON_ASSERT (scram); BSON_ASSERT (outbuf); BSON_ASSERT (outbufmax); BSON_ASSERT (outbuflen); /* all our passwords go through md5 thanks to MONGODB-CR */ tmp = bson_strdup_printf ("%s:mongo:%s", scram->user, scram->pass); hashed_password = _mongoc_hex_md5 (tmp); bson_zero_free (tmp, strlen (tmp)); /* we need all of the incoming message for the final client proof */ if (!_mongoc_scram_buf_write ((char *) inbuf, inbuflen, scram->auth_message, scram->auth_messagemax, &scram->auth_messagelen)) { goto BUFFER_AUTH; } if (!_mongoc_scram_buf_write (",", -1, scram->auth_message, scram->auth_messagemax, &scram->auth_messagelen)) { goto BUFFER_AUTH; } for (ptr = inbuf; ptr < inbuf + inbuflen;) { switch (*ptr) { case 'r': current_val = &val_r; current_val_len = &val_r_len; break; case 's': current_val = &val_s; current_val_len = &val_s_len; break; case 'i': current_val = &val_i; current_val_len = &val_i_len; break; default: bson_set_error (error, MONGOC_ERROR_SCRAM, MONGOC_ERROR_SCRAM_PROTOCOL_ERROR, "SCRAM Failure: unknown key (%c) in sasl step 2", *ptr); goto FAIL; break; } ptr++; if (*ptr != '=') { bson_set_error (error, MONGOC_ERROR_SCRAM, MONGOC_ERROR_SCRAM_PROTOCOL_ERROR, "SCRAM Failure: invalid parse state in sasl step 2"); goto FAIL; } ptr++; next_comma = (const uint8_t *) memchr (ptr, ',', (inbuf + inbuflen) - ptr); if (next_comma) { *current_val_len = (uint32_t) (next_comma - ptr); } else { *current_val_len = (uint32_t) ((inbuf + inbuflen) - ptr); } *current_val = (uint8_t *) bson_malloc (*current_val_len + 1); memcpy (*current_val, ptr, *current_val_len); (*current_val)[*current_val_len] = '\0'; if (next_comma) { ptr = next_comma + 1; } else { break; } } if (!val_r) { bson_set_error (error, MONGOC_ERROR_SCRAM, MONGOC_ERROR_SCRAM_PROTOCOL_ERROR, "SCRAM Failure: no r param in sasl step 2"); goto FAIL; } if (!val_s) { bson_set_error (error, MONGOC_ERROR_SCRAM, MONGOC_ERROR_SCRAM_PROTOCOL_ERROR, "SCRAM Failure: no s param in sasl step 2"); goto FAIL; } if (!val_i) { bson_set_error (error, MONGOC_ERROR_SCRAM, MONGOC_ERROR_SCRAM_PROTOCOL_ERROR, "SCRAM Failure: no i param in sasl step 2"); goto FAIL; } /* verify our nonce */ if (val_r_len < scram->encoded_nonce_len || mongoc_memcmp (val_r, scram->encoded_nonce, scram->encoded_nonce_len)) { bson_set_error ( error, MONGOC_ERROR_SCRAM, MONGOC_ERROR_SCRAM_PROTOCOL_ERROR, "SCRAM Failure: client nonce not repeated in sasl step 2"); } *outbuflen = 0; if (!_mongoc_scram_buf_write ( "c=biws,r=", -1, outbuf, outbufmax, outbuflen)) { goto BUFFER; } if (!_mongoc_scram_buf_write ( (char *) val_r, val_r_len, outbuf, outbufmax, outbuflen)) { goto BUFFER; } if (!_mongoc_scram_buf_write ((char *) outbuf, *outbuflen, scram->auth_message, scram->auth_messagemax, &scram->auth_messagelen)) { goto BUFFER_AUTH; } if (!_mongoc_scram_buf_write (",p=", -1, outbuf, outbufmax, outbuflen)) { goto BUFFER; } decoded_salt_len = bson_b64_pton ((char *) val_s, decoded_salt, sizeof (decoded_salt)); if (-1 == decoded_salt_len) { bson_set_error (error, MONGOC_ERROR_SCRAM, MONGOC_ERROR_SCRAM_PROTOCOL_ERROR, "SCRAM Failure: unable to decode salt in sasl step2"); goto FAIL; } if (16 != decoded_salt_len) { bson_set_error (error, MONGOC_ERROR_SCRAM, MONGOC_ERROR_SCRAM_PROTOCOL_ERROR, "SCRAM Failure: invalid salt length of %d in sasl step2", decoded_salt_len); goto FAIL; } iterations = (int) bson_ascii_strtoll ((char *) val_i, &tmp, 10); /* tmp holds the location of the failed to parse character. So if it's * null, we got to the end of the string and didn't have a parse error */ if (*tmp) { bson_set_error ( error, MONGOC_ERROR_SCRAM, MONGOC_ERROR_SCRAM_PROTOCOL_ERROR, "SCRAM Failure: unable to parse iterations in sasl step2"); goto FAIL; } if (iterations < 0) { bson_set_error (error, MONGOC_ERROR_SCRAM, MONGOC_ERROR_SCRAM_PROTOCOL_ERROR, "SCRAM Failure: iterations is negative in sasl step2"); goto FAIL; } /* Save the presecrets for caching */ scram->hashed_password = bson_strdup (hashed_password); scram->iterations = iterations; memcpy (scram->decoded_salt, decoded_salt, sizeof (scram->decoded_salt)); if (scram->cache && _mongoc_scram_cache_has_presecrets (scram->cache, scram)) { _mongoc_scram_cache_apply_secrets (scram->cache, scram); } if (!*scram->salted_password) { _mongoc_scram_salt_password (scram, hashed_password, (uint32_t) strlen (hashed_password), decoded_salt, decoded_salt_len, (uint32_t) iterations); } _mongoc_scram_generate_client_proof (scram, outbuf, outbufmax, outbuflen); goto CLEANUP; BUFFER_AUTH: bson_set_error ( error, MONGOC_ERROR_SCRAM, MONGOC_ERROR_SCRAM_PROTOCOL_ERROR, "SCRAM Failure: could not buffer auth message in sasl step2"); goto FAIL; BUFFER: bson_set_error (error, MONGOC_ERROR_SCRAM, MONGOC_ERROR_SCRAM_PROTOCOL_ERROR, "SCRAM Failure: could not buffer sasl step2"); goto FAIL; FAIL: rval = false; CLEANUP: bson_free (val_r); bson_free (val_s); bson_free (val_i); if (hashed_password) { bson_zero_free (hashed_password, strlen (hashed_password)); } return rval; }
static bool _mongoc_scram_step3 (mongoc_scram_t *scram, const uint8_t *inbuf, uint32_t inbuflen, uint8_t *outbuf, uint32_t outbufmax, uint32_t *outbuflen, bson_error_t *error) { uint8_t *val_e = NULL; uint32_t val_e_len; uint8_t *val_v = NULL; uint32_t val_v_len; uint8_t **current_val; uint32_t *current_val_len; const uint8_t *ptr; const uint8_t *next_comma; bool rval = true; BSON_ASSERT (scram); BSON_ASSERT (outbuf); BSON_ASSERT (outbufmax); BSON_ASSERT (outbuflen); for (ptr = inbuf; ptr < inbuf + inbuflen;) { switch (*ptr) { case 'e': current_val = &val_e; current_val_len = &val_e_len; break; case 'v': current_val = &val_v; current_val_len = &val_v_len; break; default: bson_set_error (error, MONGOC_ERROR_SCRAM, MONGOC_ERROR_SCRAM_PROTOCOL_ERROR, "SCRAM Failure: unknown key (%c) in sasl step 3", *ptr); goto FAIL; break; } ptr++; if (*ptr != '=') { bson_set_error (error, MONGOC_ERROR_SCRAM, MONGOC_ERROR_SCRAM_PROTOCOL_ERROR, "SCRAM Failure: invalid parse state in sasl step 3"); goto FAIL; } ptr++; next_comma = (const uint8_t *) memchr (ptr, ',', (inbuf + inbuflen) - ptr); if (next_comma) { *current_val_len = (uint32_t) (next_comma - ptr); } else { *current_val_len = (uint32_t) ((inbuf + inbuflen) - ptr); } *current_val = (uint8_t *) bson_malloc (*current_val_len + 1); memcpy (*current_val, ptr, *current_val_len); (*current_val)[*current_val_len] = '\0'; if (next_comma) { ptr = next_comma + 1; } else { break; } } *outbuflen = 0; if (val_e) { bson_set_error ( error, MONGOC_ERROR_SCRAM, MONGOC_ERROR_SCRAM_PROTOCOL_ERROR, "SCRAM Failure: authentication failure in sasl step 3 : %s", val_e); goto FAIL; } if (!val_v) { bson_set_error (error, MONGOC_ERROR_SCRAM, MONGOC_ERROR_SCRAM_PROTOCOL_ERROR, "SCRAM Failure: no v param in sasl step 3"); goto FAIL; } if (!_mongoc_scram_verify_server_signature (scram, val_v, val_v_len)) { bson_set_error ( error, MONGOC_ERROR_SCRAM, MONGOC_ERROR_SCRAM_PROTOCOL_ERROR, "SCRAM Failure: could not verify server signature in sasl step 3"); goto FAIL; } /* Update the cache if authentication succeeds */ _mongoc_scram_update_cache (scram); goto CLEANUP; FAIL: rval = false; CLEANUP: bson_free (val_e); bson_free (val_v); return rval; }
int main (int argc, char *argv[]) { mongoc_database_t *database = NULL; mongoc_client_t *client = NULL; mongoc_collection_t *collection = NULL; char *host_and_port; int res = 0; char* other_host_and_port = NULL; if (argc < 2 || argc > 3) { fprintf (stderr, "usage: %s MONGOD-1-CONNECTION-STRING " "[MONGOD-2-HOST-NAME:MONGOD-2-PORT]\n", argv[0]); fprintf (stderr, "MONGOD-1-CONNECTION-STRING can be " "of the following forms:\n"); fprintf (stderr, "localhost\t\t\t\tlocal machine\n"); fprintf (stderr, "localhost:27018\t\t\t\tlocal machine on port 27018\n"); fprintf (stderr, "mongodb://*****:*****@localhost:27017\t" "local machine on port 27017, and authenticate with username " "user and password pass\n"); return 1; } mongoc_init (); if (strncmp (argv[1], "mongodb://", 10) == 0) { host_and_port = bson_strdup (argv [1]); } else { host_and_port = bson_strdup_printf ("mongodb://%s", argv[1]); } other_host_and_port = argc > 2 ? argv[2] : NULL; client = mongoc_client_new (host_and_port); if (!client) { fprintf(stderr, "Invalid hostname or port: %s\n", host_and_port); res = 2; goto cleanup; } database = mongoc_client_get_database (client, "test"); collection = mongoc_database_get_collection (database, COLLECTION_NAME); printf ("Inserting data\n"); if (!insert_data (collection)) { res = 3; goto cleanup; } printf ("explain\n"); if (!explain (collection)) { res = 4; goto cleanup; } if (other_host_and_port) { printf ("copydb\n"); if (!copydb (client, other_host_and_port)) { res = 5; goto cleanup; } printf ("clone collection\n"); if (!clone_collection (database, other_host_and_port)) { res = 6; goto cleanup; } } cleanup: if (collection) { mongoc_collection_destroy (collection); } if (database) { mongoc_database_destroy (database); } if (client) { mongoc_client_destroy (client); } bson_free (host_and_port); mongoc_cleanup (); return res; }
static void * mock_server_worker (void *data) { mongoc_buffer_t buffer; mongoc_stream_t *stream; mock_server_t *server; mongoc_rpc_t rpc; bson_error_t error; int32_t msg_len; void **closure = data; BSON_ASSERT(closure); server = closure[0]; stream = closure[1]; _mongoc_buffer_init(&buffer, NULL, 0, NULL); again: if (_mongoc_buffer_fill (&buffer, stream, 4, INT_MAX, &error) == -1) { MONGOC_WARNING ("%s", error.message); goto failure; } assert (buffer.len >= 4); memcpy(&msg_len, buffer.data + buffer.off, 4); msg_len = BSON_UINT32_FROM_LE(msg_len); if (msg_len < 16) { MONGOC_WARNING ("No data"); goto failure; } if (_mongoc_buffer_fill (&buffer, stream, msg_len, INT_MAX, &error) == -1) { MONGOC_WARNING ("%s", error.message); goto failure; } assert (buffer.len >= msg_len); DUMP_BYTES (buffer, buffer.data + buffer.off, buffer.len); if (!_mongoc_rpc_scatter(&rpc, buffer.data + buffer.off, msg_len)) { MONGOC_WARNING ("Failed to scatter"); goto failure; } _mongoc_rpc_swab_from_le(&rpc); if (!handle_command(server, stream, &rpc)) { server->handler(server, stream, &rpc, server->handler_data); } memmove (buffer.data, buffer.data + buffer.off + msg_len, buffer.len - msg_len); buffer.off = 0; buffer.len -= msg_len; goto again; failure: mongoc_stream_close(stream); mongoc_stream_destroy(stream); bson_free(closure); return NULL; }
void mongo_gridfs_get (config_t *config, gint argc, gchar *argv[]) { mongo_sync_gridfs *gfs; mongo_sync_gridfs_chunked_file *gfile; mongo_sync_cursor *cursor; gint64 n = 0; bson *query; int fd; gchar *gfn, *ofn; if (argc < 4) { fprintf (stderr, "Usage: %s get GRIDFS_FILENAME OUTPUT_FILENAME\n", argv[0]); exit (1); } gfn = argv[2]; ofn = argv[3]; gfs = mongo_gridfs_connect (config); VLOG ("Trying to find '%s'...\n", gfn); query = bson_build (BSON_TYPE_STRING, "filename", gfn, -1, BSON_TYPE_NONE); bson_finish (query); gfile = mongo_sync_gridfs_chunked_find (gfs, query); if (!gfile) mongo_gridfs_error (errno); bson_free (query); VLOG ("Opening output file '%s'...\n", ofn); fd = open (ofn, O_RDWR | O_CREAT | O_TRUNC, 0600); if (fd == -1) { fprintf (stderr, "Error opening output file '%s': %s\n", ofn, strerror (errno)); exit (1); } VLOG ("Writing '%s' -> '%s' (%" G_GINT64_FORMAT " bytes in %" G_GINT64_FORMAT " chunks)\n", gfn, ofn, mongo_sync_gridfs_file_get_length (gfile), mongo_sync_gridfs_file_get_chunks (gfile)); cursor = mongo_sync_gridfs_chunked_file_cursor_new (gfile, 0, 0); if (!cursor) mongo_gridfs_error (errno); while (mongo_sync_cursor_next (cursor)) { gint32 size; guint8 *data; VLOG ("\rWriting chunk %" G_GINT64_FORMAT "...", n++); data = mongo_sync_gridfs_chunked_file_cursor_get_chunk (cursor, &size); if (!data) mongo_gridfs_error (errno); if (write (fd, data, size) != size) { perror ("write()"); exit (1); } g_free (data); } mongo_sync_cursor_free (cursor); mongo_sync_gridfs_chunked_file_free (gfile); close (fd); mongo_sync_gridfs_free (gfs, TRUE); VLOG("\n"); }
void mongo_gridfs_put (config_t *config, gint argc, gchar *argv[]) { mongo_sync_gridfs *gfs; mongo_sync_gridfs_chunked_file *gfile; bson *meta; int fd; guint8 *data; struct stat st; gchar *gfn, *ifn, *oid_s; if (argc < 4) { fprintf (stderr, "Usage: %s put INPUT_FILENAME GRIDFS_FILENAME\n", argv[0]); exit (1); } ifn = argv[2]; gfn = argv[3]; mongo_util_oid_init (0); gfs = mongo_gridfs_connect (config); VLOG ("Opening input file: '%s'...\n", ifn); fd = open (ifn, O_RDONLY); if (!fd) { fprintf (stderr, "Error opening input file: %s\n", strerror (errno)); exit (1); } if (fstat (fd, &st) != 0) { fprintf (stderr, "Error stat'ing the input file: %s\n", strerror (errno)); exit (1); } data = mmap (NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0); if (data == MAP_FAILED) { fprintf (stderr, "Error mmapping the input file: %s\n", strerror (errno)); } meta = bson_build (BSON_TYPE_STRING, "filename", gfn, -1, BSON_TYPE_NONE); bson_finish (meta); VLOG ("Uploading '%s' -> '%s'...\n", ifn, gfn); gfile = mongo_sync_gridfs_chunked_file_new_from_buffer (gfs, meta, data, st.st_size); if (!gfile) mongo_gridfs_error (errno); bson_free (meta); munmap (data, st.st_size); oid_s = mongo_util_oid_as_string (mongo_sync_gridfs_file_get_id (gfile)); printf ("Uploaded file: %s (_id: %s; md5 = %s)\n", gfn, oid_s, mongo_sync_gridfs_file_get_md5 (gfile)); g_free (oid_s); mongo_sync_gridfs_chunked_file_free (gfile); mongo_sync_gridfs_free (gfs, TRUE); }
static void getaddressbyID(char *msg,mongoc_collection_t *coll,char * deviceId,char * device_name){ mongoc_cursor_t *cursor; bson_t *doc; bson_t *query; char *str; query = bson_new (); bson_oid_t de_oid; bson_oid_init_from_string(&de_oid, deviceId); BSON_APPEND_OID (query, "_id",&de_oid); cursor = mongoc_collection_find (coll, MONGOC_QUERY_NONE, 0, 0, 0, query, NULL, NULL); double ivalue=0; int buse=0; double lat; double lon; //char lat[256]; //char lon[256]; //memset(lat,'\0',256); //memset(lon,'\0',256); while (mongoc_cursor_next (cursor, &doc)) { str = bson_as_json (doc, NULL); //printf ("%s\n", str); bson_free (str); bson_iter_t iter; bson_iter_t sub_iter; if (bson_iter_init (&iter, doc)) { while (bson_iter_next (&iter)) { //printf ("Found a field named: %s\n", bson_iter_key (&iter)); bson_value_t *value; value = bson_iter_value (&iter); //printf("type %d\n",value->value_type); if (value->value_type == BSON_TYPE_DOUBLE) { if(strcmp(bson_iter_key (&iter),"lat")==0){ (lat=value->value.v_double); } if(strcmp(bson_iter_key (&iter),"lon")==0){ (lon=value->value.v_double); } } if (value->value_type == BSON_TYPE_UTF8) { if(strcmp(bson_iter_key (&iter),"device_name")==0){ strcpy(device_name,value->value.v_utf8.str); } } } } } bson_destroy (query); CURL *curl; CURLcode res; curl = curl_easy_init(); if (curl) { static char str[20480]; memset(str,'\0',20480); char url[1028]; memset(url,'\0',1028); sprintf(url,"http://api.map.baidu.com/geocoder/v2/?ak=IDvNBsejl9oqMbPF316iKsXR&output=json&location=%.8f,%.8f",lat,lon); printf("%s\n",url); curl_easy_setopt(curl, CURLOPT_URL, url); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data); curl_easy_setopt(curl, CURLOPT_WRITEDATA, str); res = curl_easy_perform(curl); printf("%s\n",str); char *s = strstr(str, "formatted_address"); if(NULL!=s){ s=strstr(s, "\""); s=strstr(s+1, "\""); printf("\n%s\n",s); char *p=strstr(s+1, "\""); int len=strlen(s)-strlen(p)-1; strncpy(msg,s+1,len); msg[len]='\0'; printf("msg:%s\n",msg); printf("\n\n"); } curl_easy_cleanup(curl); } }
static int mongo_cursor_op_query( mongo_cursor *cursor ) { int res; bson empty; char *data; mongo_message *mm; bson temp; bson_iterator it; /* Clear any errors. */ bson_free( cursor->conn->lasterrstr ); cursor->conn->lasterrstr = NULL; cursor->conn->lasterrcode = 0; cursor->conn->err = 0; cursor->err = 0; /* Set up default values for query and fields, if necessary. */ if( ! cursor->query ) cursor->query = bson_empty( &empty ); else if( mongo_cursor_bson_valid( cursor, cursor->query ) != MONGO_OK ) return MONGO_ERROR; if( ! cursor->fields ) cursor->fields = bson_empty( &empty ); else if( mongo_cursor_bson_valid( cursor, cursor->fields ) != MONGO_OK ) return MONGO_ERROR; mm = mongo_message_create( 16 + /* header */ 4 + /* options */ strlen( cursor->ns ) + 1 + /* ns */ 4 + 4 + /* skip,return */ bson_size( cursor->query ) + bson_size( cursor->fields ) , 0 , 0 , MONGO_OP_QUERY ); data = &mm->data; data = mongo_data_append32( data , &cursor->options ); data = mongo_data_append( data , cursor->ns , strlen( cursor->ns ) + 1 ); data = mongo_data_append32( data , &cursor->skip ); data = mongo_data_append32( data , &cursor->limit ); data = mongo_data_append( data , cursor->query->data , bson_size( cursor->query ) ); if ( cursor->fields ) data = mongo_data_append( data , cursor->fields->data , bson_size( cursor->fields ) ); bson_fatal_msg( ( data == ( ( char * )mm ) + mm->head.len ), "query building fail!" ); res = mongo_message_send( cursor->conn , mm ); if( res != MONGO_OK ) { return MONGO_ERROR; } res = mongo_read_response( cursor->conn, ( mongo_reply ** )&( cursor->reply ) ); if( res != MONGO_OK ) { return MONGO_ERROR; } if( cursor->reply->fields.num == 1 ) { bson_init_data( &temp, &cursor->reply->objs ); if( bson_find( &it, &temp, "$err" ) ) { cursor->conn->lasterrstr = (char *)bson_malloc( bson_iterator_string_len( &it ) ); strcpy( cursor->conn->lasterrstr, bson_iterator_string( &it ) ); bson_find( &it, &temp, "code" ); cursor->conn->lasterrcode = bson_iterator_int( &it ); cursor->err = MONGO_CURSOR_QUERY_FAIL; return MONGO_ERROR; } } cursor->seen += cursor->reply->fields.num; cursor->flags |= MONGO_CURSOR_QUERY_SENT; return MONGO_OK; }
char * _mongoc_sasl_prep_impl (const char *name, const char *in_utf8, int in_utf8_len, bson_error_t *err) { /* The flow is in_utf8 -> in_utf16 -> SASLPrep -> out_utf16 -> out_utf8. */ UChar *in_utf16, *out_utf16; char *out_utf8; int32_t in_utf16_len, out_utf16_len, out_utf8_len; UErrorCode error_code = U_ZERO_ERROR; UStringPrepProfile *prep; #define SASL_PREP_ERR_RETURN(msg) \ do { \ bson_set_error (err, \ MONGOC_ERROR_SCRAM, \ MONGOC_ERROR_SCRAM_PROTOCOL_ERROR, \ (msg), \ name); \ return NULL; \ } while (0) /* 1. convert str to UTF-16. */ /* preflight to get the destination length. */ (void) u_strFromUTF8 ( NULL, 0, &in_utf16_len, in_utf8, in_utf8_len, &error_code); if (error_code != U_BUFFER_OVERFLOW_ERROR) { SASL_PREP_ERR_RETURN ("could not calculate UTF-16 length of %s"); } /* convert to UTF-16. */ error_code = U_ZERO_ERROR; in_utf16 = bson_malloc (sizeof (UChar) * (in_utf16_len + 1)); /* add one for null byte. */ (void) u_strFromUTF8 ( in_utf16, in_utf16_len + 1, NULL, in_utf8, in_utf8_len, &error_code); if (error_code) { bson_free (in_utf16); SASL_PREP_ERR_RETURN ("could not convert %s to UTF-16"); } /* 2. perform SASLPrep. */ prep = usprep_openByType (USPREP_RFC4013_SASLPREP, &error_code); if (error_code) { bson_free (in_utf16); SASL_PREP_ERR_RETURN ("could not start SASLPrep for %s"); } /* preflight. */ out_utf16_len = usprep_prepare ( prep, in_utf16, in_utf16_len, NULL, 0, USPREP_DEFAULT, NULL, &error_code); if (error_code != U_BUFFER_OVERFLOW_ERROR) { bson_free (in_utf16); usprep_close (prep); SASL_PREP_ERR_RETURN ("could not calculate SASLPrep length of %s"); } /* convert. */ error_code = U_ZERO_ERROR; out_utf16 = bson_malloc (sizeof (UChar) * (out_utf16_len + 1)); (void) usprep_prepare (prep, in_utf16, in_utf16_len, out_utf16, out_utf16_len + 1, USPREP_DEFAULT, NULL, &error_code); if (error_code) { bson_free (in_utf16); bson_free (out_utf16); usprep_close (prep); SASL_PREP_ERR_RETURN ("could not execute SASLPrep for %s"); } bson_free (in_utf16); usprep_close (prep); /* 3. convert back to UTF-8. */ /* preflight. */ (void) u_strToUTF8 ( NULL, 0, &out_utf8_len, out_utf16, out_utf16_len, &error_code); if (error_code != U_BUFFER_OVERFLOW_ERROR) { bson_free (out_utf16); SASL_PREP_ERR_RETURN ("could not calculate UTF-8 length of %s"); } /* convert. */ error_code = U_ZERO_ERROR; out_utf8 = (char *) bson_malloc ( sizeof (char) * (out_utf8_len + 1)); /* add one for null byte. */ (void) u_strToUTF8 ( out_utf8, out_utf8_len + 1, NULL, out_utf16, out_utf16_len, &error_code); if (error_code) { bson_free (out_utf8); bson_free (out_utf16); SASL_PREP_ERR_RETURN ("could not convert %s back to UTF-8"); } bson_free (out_utf16); return out_utf8; #undef SASL_PREP_ERR_RETURN }
void mock_server_destroy (mock_server_t *server) { size_t i; autoresponder_handle_t *handle; int64_t deadline = bson_get_monotonic_time () + 10 * 1000 * 1000; request_t *request; mongoc_mutex_lock (&server->mutex); if (server->running) { server->stopped = true; } mongoc_mutex_unlock (&server->mutex); while (bson_get_monotonic_time () <= deadline) { /* wait 10 seconds */ mongoc_mutex_lock (&server->mutex); if (!server->running) { mongoc_mutex_unlock (&server->mutex); break; } mongoc_mutex_unlock (&server->mutex); _mongoc_usleep (1000); } mongoc_mutex_lock (&server->mutex); if (server->running) { fprintf (stderr, "server still running after timeout\n"); fflush (stderr); abort (); } mongoc_mutex_unlock (&server->mutex); mongoc_thread_join (server->main_thread); _mongoc_array_destroy (&server->worker_threads); for (i = 0; i < server->autoresponders.len; i++) { handle = &_mongoc_array_index (&server->autoresponders, autoresponder_handle_t, i); autoresponder_handle_destroy (handle); } _mongoc_array_destroy (&server->autoresponders); mongoc_cond_destroy (&server->cond); mongoc_mutex_unlock (&server->mutex); mongoc_mutex_destroy (&server->mutex); mongoc_socket_destroy (server->sock); bson_free (server->uri_str); mongoc_uri_destroy (server->uri); while ((request = (request_t *) q_get_nowait (server->q))) { request_destroy (request); } q_destroy (server->q); bson_free (server); }
int main () { bson_t empty = BSON_INITIALIZER; const bson_t *doc; bson_t *to_insert = BCON_NEW ("x", BCON_INT32 (1)); const bson_t *err_doc; bson_error_t error; const char *uri_string; mongoc_uri_t *uri; mongoc_client_t *client; mongoc_collection_t *coll; mongoc_change_stream_t *stream; mongoc_write_concern_t *wc = mongoc_write_concern_new (); bson_t opts = BSON_INITIALIZER; bool r; mongoc_init (); uri_string = "mongodb://" "localhost:27017,localhost:27018,localhost:" "27019/db?replicaSet=rs0"; uri = mongoc_uri_new_with_error (uri_string, &error); if (!uri) { fprintf (stderr, "failed to parse URI: %s\n" "error message: %s\n", uri_string, error.message); return EXIT_FAILURE; } client = mongoc_client_new_from_uri (uri); if (!client) { return EXIT_FAILURE; } coll = mongoc_client_get_collection (client, "db", "coll"); stream = mongoc_collection_watch (coll, &empty, NULL); mongoc_write_concern_set_wmajority (wc, 10000); mongoc_write_concern_append (wc, &opts); r = mongoc_collection_insert_one (coll, to_insert, &opts, NULL, &error); if (!r) { fprintf (stderr, "Error: %s\n", error.message); return EXIT_FAILURE; } while (mongoc_change_stream_next (stream, &doc)) { char *as_json = bson_as_relaxed_extended_json (doc, NULL); fprintf (stderr, "Got document: %s\n", as_json); bson_free (as_json); } if (mongoc_change_stream_error_document (stream, &error, &err_doc)) { if (!bson_empty (err_doc)) { fprintf (stderr, "Server Error: %s\n", bson_as_relaxed_extended_json (err_doc, NULL)); } else { fprintf (stderr, "Client Error: %s\n", error.message); } return EXIT_FAILURE; } bson_destroy (to_insert); mongoc_write_concern_destroy (wc); bson_destroy (&opts); mongoc_change_stream_destroy (stream); mongoc_collection_destroy (coll); mongoc_uri_destroy (uri); mongoc_client_destroy (client); mongoc_cleanup (); return EXIT_SUCCESS; }
void mock_server_reply_multi (request_t *request, mongoc_reply_flags_t flags, const bson_t *docs, int n_docs, int64_t cursor_id) { const mongoc_rpc_t *request_rpc; mock_server_t *server; mongoc_stream_t *client; char *doc_json; bson_string_t *docs_json; mongoc_iovec_t *iov; mongoc_array_t ar; mongoc_rpc_t r = {{ 0 }}; size_t expected = 0; ssize_t n_written; int iovcnt; int i; uint8_t *buf; uint8_t *ptr; size_t len; BSON_ASSERT (request); BSON_ASSERT (docs); request_rpc = &request->request_rpc; server = request->server; client = request->client; docs_json = bson_string_new (""); for (i = 0; i < n_docs; i++) { doc_json = bson_as_json (&docs[i], NULL); bson_string_append (docs_json, doc_json); bson_free (doc_json); if (i < n_docs - 1) { bson_string_append (docs_json, ", "); } } if (mock_server_get_verbose (request->server)) { printf ("%5.2f %hu <- %hu \t%s\n", mock_server_get_uptime_sec (request->server), request->client_port, mock_server_get_port (request->server), docs_json->str); fflush (stdout); } len = 0; for (i = 0; i < n_docs; i++) { len += docs[i].len; } ptr = buf = bson_malloc (len); for (i = 0; i < n_docs; i++) { memcpy (ptr, bson_get_data (&docs[i]), docs[i].len); ptr += docs[i].len; } _mongoc_array_init (&ar, sizeof (mongoc_iovec_t)); if (!(request->opcode == MONGOC_OPCODE_QUERY && request_rpc->query.flags & MONGOC_QUERY_EXHAUST)) { server->last_response_id++; } mongoc_mutex_lock (&server->mutex); r.reply.request_id = server->last_response_id; mongoc_mutex_unlock (&server->mutex); r.reply.msg_len = 0; r.reply.response_to = request_rpc->header.request_id; r.reply.opcode = MONGOC_OPCODE_REPLY; r.reply.flags = flags; r.reply.cursor_id = cursor_id; r.reply.start_from = 0; r.reply.n_returned = 1; r.reply.documents = buf; r.reply.documents_len = (uint32_t)len; _mongoc_rpc_gather (&r, &ar); _mongoc_rpc_swab_to_le (&r); iov = (mongoc_iovec_t *)ar.data; iovcnt = (int) ar.len; for (i = 0; i < iovcnt; i++) { expected += iov[i].iov_len; } n_written = mongoc_stream_writev (client, iov, (size_t) iovcnt, -1); assert (n_written == expected); bson_string_free (docs_json, true); _mongoc_array_destroy (&ar); bson_free (buf); }
static bool mongoc_database_add_user_legacy (mongoc_database_t *database, const char *username, const char *password, bson_error_t *error) { mongoc_collection_t *collection; mongoc_cursor_t *cursor = NULL; const bson_t *doc; bool ret = false; bson_t query; bson_t user; char *input; char *pwd = NULL; ENTRY; bson_return_val_if_fail(database, false); bson_return_val_if_fail(username, false); bson_return_val_if_fail(password, false); /* * Users are stored in the <dbname>.system.users virtual collection. */ collection = mongoc_client_get_collection(database->client, database->name, "system.users"); BSON_ASSERT(collection); /* * Hash the users password. */ input = bson_strdup_printf("%s:mongo:%s", username, password); pwd = _mongoc_hex_md5(input); bson_free(input); /* * Check to see if the user exists. If so, we will update the * password instead of inserting a new user. */ bson_init(&query); bson_append_utf8(&query, "user", 4, username, -1); cursor = mongoc_collection_find(collection, MONGOC_QUERY_NONE, 0, 1, 0, &query, NULL, NULL); if (!mongoc_cursor_next(cursor, &doc)) { if (mongoc_cursor_error(cursor, error)) { GOTO (failure); } bson_init(&user); bson_append_utf8(&user, "user", 4, username, -1); bson_append_bool(&user, "readOnly", 8, false); bson_append_utf8(&user, "pwd", 3, pwd, -1); } else { bson_init(&user); bson_copy_to_excluding_noinit(doc, &user, "pwd", (char *)NULL); bson_append_utf8(&user, "pwd", 3, pwd, -1); } if (!mongoc_collection_save(collection, &user, NULL, error)) { GOTO (failure_with_user); } ret = true; failure_with_user: bson_destroy(&user); failure: if (cursor) { mongoc_cursor_destroy(cursor); } mongoc_collection_destroy(collection); bson_destroy(&query); bson_free(pwd); RETURN (ret); }
static void _test_heartbeat_events (bool pooled, bool succeeded) { context_t context; mock_server_t *server; mongoc_uri_t *uri; mongoc_client_t *client; mongoc_client_pool_t *pool = NULL; future_t *future; request_t *request; char *expected_json; bson_error_t error; context_init (&context); /* auto-respond to "foo" command */ server = mock_server_new (); mock_server_run (server); mock_server_autoresponds (server, responder, NULL, NULL); uri = mongoc_uri_copy (mock_server_get_uri (server)); mongoc_uri_set_option_as_int32 (uri, "serverSelectionTimeoutMS", 400); if (pooled) { pool = mongoc_client_pool_new (uri); pool_set_heartbeat_event_callbacks (pool, &context); client = mongoc_client_pool_pop (pool); } else { client = mongoc_client_new_from_uri (uri); client_set_heartbeat_event_callbacks (client, &context); } /* trigger "ismaster" handshake */ future = future_client_command_simple (client, "admin", tmp_bson ("{'foo': 1}"), NULL, NULL, &error); /* topology scanner calls ismaster once */ request = mock_server_receives_ismaster (server); if (succeeded) { mock_server_replies_ok_and_destroys (request); } else { mock_server_hangs_up (request); request_destroy (request); } /* pooled client opens new socket, handshakes it by calling ismaster again */ if (pooled && succeeded) { request = mock_server_receives_ismaster (server); mock_server_replies_ok_and_destroys (request); } if (succeeded) { /* "foo" command succeeds */ ASSERT_OR_PRINT (future_get_bool (future), error); } else { ASSERT (!future_get_bool (future)); } if (pooled) { mongoc_client_pool_push (pool, client); mongoc_client_pool_destroy (pool); } else { mongoc_client_destroy (client); } /* even if pooled, only topology scanner sends events, so we get one pair */ if (succeeded) { expected_json = bson_strdup_printf ( "{'0': {'heartbeat_started_event': {'host': '%s'}}," " '1': {'heartbeat_succeeded_event': {'host': '%s'}}}", mock_server_get_host_and_port (server), mock_server_get_host_and_port (server)); } else { expected_json = bson_strdup_printf ( "{'0': {'heartbeat_started_event': {'host': '%s'}}," " '1': {'heartbeat_failed_event': {'host': '%s'}}}", mock_server_get_host_and_port (server), mock_server_get_host_and_port (server)); } check_json_apm_events (&context.events, tmp_bson (expected_json)); future_destroy (future); bson_free (expected_json); mongoc_uri_destroy (uri); mock_server_destroy (server); context_destroy (&context); }
/** * mongoc_database_add_user: * @database: A #mongoc_database_t. * @username: A string containing the username. * @password: (allow-none): A string containing password, or NULL. * @roles: (allow-none): An optional bson_t of roles. * @custom_data: (allow-none): An optional bson_t of data to store. * @error: (out) (allow-none): A location for a bson_error_t or %NULL. * * Creates a new user with access to @database. * * Returns: None. * Side effects: None. */ bool mongoc_database_add_user (mongoc_database_t *database, const char *username, const char *password, const bson_t *roles, const bson_t *custom_data, bson_error_t *error) { bson_error_t lerror; bson_t cmd; bson_t ar; char *input; char *hashed_password; bool ret = false; ENTRY; BSON_ASSERT (database); BSON_ASSERT (username); /* * CDRIVER-232: * * Perform a (slow and tedious) round trip to mongod to determine if * we can safely call createUser. Otherwise, we will fallback and * perform legacy insertion into users collection. */ bson_init (&cmd); BSON_APPEND_UTF8 (&cmd, "usersInfo", username); ret = mongoc_database_command_simple (database, &cmd, NULL, NULL, &lerror); bson_destroy (&cmd); if (!ret && (lerror.code == MONGOC_ERROR_QUERY_COMMAND_NOT_FOUND)) { ret = mongoc_database_add_user_legacy (database, username, password, error); } else if (ret || (lerror.code == 13)) { /* usersInfo succeeded or failed with auth err, we're on modern mongod */ input = bson_strdup_printf ("%s:mongo:%s", username, password); hashed_password = _mongoc_hex_md5 (input); bson_free (input); bson_init (&cmd); BSON_APPEND_UTF8 (&cmd, "createUser", username); BSON_APPEND_UTF8 (&cmd, "pwd", hashed_password); BSON_APPEND_BOOL (&cmd, "digestPassword", false); if (custom_data) { BSON_APPEND_DOCUMENT (&cmd, "customData", custom_data); } if (roles) { BSON_APPEND_ARRAY (&cmd, "roles", roles); } else { bson_append_array_begin (&cmd, "roles", 5, &ar); bson_append_array_end (&cmd, &ar); } ret = mongoc_database_command_simple (database, &cmd, NULL, NULL, error); bson_free (hashed_password); bson_destroy (&cmd); } else if (error) { memcpy (error, &lerror, sizeof *error); } RETURN (ret); }
static void test_get_collection_names (void) { mongoc_database_t *database; mongoc_collection_t *collection; mongoc_client_t *client; bson_error_t error = { 0 }; bson_t options; int r; int namecount = 0; char **names; char **name; char *curname; char *dbname; char *name1; char *name2; char *name3; char *name4; char *name5; const char *system_prefix = "system."; 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); name1 = gen_collection_name ("name1"); name2 = gen_collection_name ("name2"); name3 = gen_collection_name ("name3"); name4 = gen_collection_name ("name4"); name5 = gen_collection_name ("name5"); collection = mongoc_database_create_collection (database, name1, &options, &error); assert (collection); mongoc_collection_destroy (collection); collection = mongoc_database_create_collection (database, name2, &options, &error); assert (collection); mongoc_collection_destroy (collection); collection = mongoc_database_create_collection (database, name3, &options, &error); assert (collection); mongoc_collection_destroy (collection); collection = mongoc_database_create_collection (database, name4, &options, &error); assert (collection); mongoc_collection_destroy (collection); collection = mongoc_database_create_collection (database, name5, &options, &error); assert (collection); mongoc_collection_destroy (collection); names = mongoc_database_get_collection_names (database, &error); assert (!error.domain); assert (!error.code); for (name = names; *name; ++name) { /* inefficient, but OK for a unit test. */ curname = *name; if (0 == strcmp (curname, name1) || 0 == strcmp (curname, name2) || 0 == strcmp (curname, name3) || 0 == strcmp (curname, name4) || 0 == strcmp (curname, name5)) { ++namecount; } else if (0 == strncmp (curname, system_prefix, strlen (system_prefix))) { /* Collections prefixed with 'system.' are system collections */ } else { assert (false); } bson_free (curname); } assert (namecount == 5); bson_free (name1); bson_free (name2); bson_free (name3); bson_free (name4); bson_free (name5); bson_free (names); r = mongoc_database_drop (database, &error); assert (r); assert (!error.domain); assert (!error.code); mongoc_database_destroy (database); mongoc_client_destroy (client); }
void mongoc_topology_description_suitable_servers ( mongoc_array_t *set, /* OUT */ mongoc_ss_optype_t optype, mongoc_topology_description_t *topology, const mongoc_read_prefs_t *read_pref, size_t local_threshold_ms) { mongoc_suitable_data_t data; mongoc_server_description_t **candidates; mongoc_server_description_t *server; int64_t nearest = -1; int i; mongoc_read_mode_t read_mode = mongoc_read_prefs_get_mode(read_pref); candidates = (mongoc_server_description_t **)bson_malloc0(sizeof(*candidates) * topology->servers->items_len); data.read_mode = read_mode; data.topology_type = topology->type; data.primary = NULL; data.candidates = candidates; data.candidates_len = 0; data.has_secondary = false; /* Single server -- * Either it is suitable or it isn't */ if (topology->type == MONGOC_TOPOLOGY_SINGLE) { server = (mongoc_server_description_t *)mongoc_set_get_item (topology->servers, 0); if (_mongoc_topology_description_server_is_candidate (server->type, read_mode, topology->type)) { _mongoc_array_append_val (set, server); } goto DONE; } /* Replica sets -- * Find suitable servers based on read mode */ if (topology->type == MONGOC_TOPOLOGY_RS_NO_PRIMARY || topology->type == MONGOC_TOPOLOGY_RS_WITH_PRIMARY) { if (optype == MONGOC_SS_READ) { mongoc_set_for_each(topology->servers, _mongoc_replica_set_read_suitable_cb, &data); /* if we have a primary, it's a candidate, for some read modes we are done */ if (read_mode == MONGOC_READ_PRIMARY || read_mode == MONGOC_READ_PRIMARY_PREFERRED) { if (data.primary) { _mongoc_array_append_val (set, data.primary); goto DONE; } } if (! mongoc_server_description_filter_eligible (data.candidates, data.candidates_len, read_pref)) { if (read_mode == MONGOC_READ_NEAREST) { goto DONE; } else { data.has_secondary = false; } } if (data.has_secondary && (read_mode == MONGOC_READ_SECONDARY || read_mode == MONGOC_READ_SECONDARY_PREFERRED)) { /* secondary or secondary preferred and we have one. */ for (i = 0; i < data.candidates_len; i++) { if (candidates[i] && candidates[i]->type == MONGOC_SERVER_RS_PRIMARY) { candidates[i] = NULL; } } } else if (read_mode == MONGOC_READ_SECONDARY_PREFERRED && data.primary) { /* secondary preferred, but only the one primary is a candidate */ _mongoc_array_append_val (set, data.primary); goto DONE; } } else if (topology->type == MONGOC_TOPOLOGY_RS_WITH_PRIMARY) { /* includes optype == MONGOC_SS_WRITE as the exclusion of the above if */ mongoc_set_for_each(topology->servers, _mongoc_topology_description_has_primary_cb, &data.primary); if (data.primary) { _mongoc_array_append_val (set, data.primary); goto DONE; } } } /* Sharded clusters -- * All candidates in the latency window are suitable */ if (topology->type == MONGOC_TOPOLOGY_SHARDED) { mongoc_set_for_each (topology->servers, _mongoc_find_suitable_mongos_cb, &data); } /* Ways to get here: * - secondary read * - secondary preferred read * - primary_preferred and no primary read * - sharded anything * Find the nearest, then select within the window */ for (i = 0; i < data.candidates_len; i++) { if (candidates[i] && (nearest == -1 || nearest > candidates[i]->round_trip_time)) { nearest = candidates[i]->round_trip_time; } } for (i = 0; i < data.candidates_len; i++) { if (candidates[i] && (candidates[i]->round_trip_time <= nearest + local_threshold_ms)) { _mongoc_array_append_val (set, candidates[i]); } } DONE: bson_free (candidates); return; }
void gridfile_write_buffer( gridfile *gfile, const char *data, gridfs_offset length ) { int bytes_left = 0; int data_partial_len = 0; int chunks_to_write = 0; char *buffer; bson *oChunk; gridfs_offset to_write = length + gfile->pending_len; if ( to_write < DEFAULT_CHUNK_SIZE ) { /* Less than one chunk to write */ if( gfile->pending_data ) { gfile->pending_data = ( char * )bson_realloc( ( void * )gfile->pending_data, gfile->pending_len + to_write ); memcpy( gfile->pending_data + gfile->pending_len, data, length ); } else if ( to_write > 0 ) { gfile->pending_data = ( char * )bson_malloc( to_write ); memcpy( gfile->pending_data, data, length ); } gfile->pending_len += length; } else { /* At least one chunk of data to write */ /* If there's a pending chunk to be written, we need to combine * the buffer provided up to DEFAULT_CHUNK_SIZE. */ if ( gfile->pending_len > 0 ) { chunks_to_write = to_write / DEFAULT_CHUNK_SIZE; bytes_left = to_write % DEFAULT_CHUNK_SIZE; data_partial_len = DEFAULT_CHUNK_SIZE - gfile->pending_len; buffer = ( char * )bson_malloc( DEFAULT_CHUNK_SIZE ); memcpy( buffer, gfile->pending_data, gfile->pending_len ); memcpy( buffer + gfile->pending_len, data, data_partial_len ); oChunk = chunk_new( gfile->id, gfile->chunk_num, buffer, DEFAULT_CHUNK_SIZE ); mongo_insert( gfile->gfs->client, gfile->gfs->chunks_ns, oChunk ); chunk_free( oChunk ); gfile->chunk_num++; gfile->length += DEFAULT_CHUNK_SIZE; data += data_partial_len; chunks_to_write--; bson_free( buffer ); } while( chunks_to_write > 0 ) { oChunk = chunk_new( gfile->id, gfile->chunk_num, data, DEFAULT_CHUNK_SIZE ); mongo_insert( gfile->gfs->client, gfile->gfs->chunks_ns, oChunk ); chunk_free( oChunk ); gfile->chunk_num++; chunks_to_write--; gfile->length += DEFAULT_CHUNK_SIZE; data += DEFAULT_CHUNK_SIZE; } bson_free( gfile->pending_data ); /* If there are any leftover bytes, store them as pending data. */ if( bytes_left == 0 ) gfile->pending_data = NULL; else { gfile->pending_data = ( char * )bson_malloc( bytes_left ); memcpy( gfile->pending_data, data, bytes_left ); } gfile->pending_len = bytes_left; } }
int main (int argc, char *argv[]) { mongoc_client_t *client; mongoc_collection_t *collection; mongoc_cursor_t *cursor; bson_error_t error; const bson_t *doc; const char *uristr = "mongodb://*****:*****@localhost/?authMechanism=PLAIN&authSource=$external"; const char *database_name = "test"; const char *collection_name = "query1"; const char *user_role = "ro"; if (argc == 2 && !strcmp("--help",argv[1])) { printf ("Usage: [uri [database [collection [ro|rw]]]]\n"); return EXIT_FAILURE; } if (argc > 1) { uristr = argv [1]; } if (argc > 2) { database_name = argv [2]; } if (argc > 3) { collection_name = argv [3]; } if (argc > 4) { user_role = argv [4]; } mongoc_init (); client = mongoc_client_new (uristr); collection = mongoc_client_get_collection (client, database_name, collection_name); if (!client) { fprintf (stderr, "Failed to parse URI.\n"); return EXIT_FAILURE; } // write if (!strcasecmp(user_role,"rw")) { bson_t *rwbson; bson_error_t rwerror; rwbson = bson_new(); time_t now = time(NULL); bson_append_utf8(rwbson,"db",-1,database_name,-1); bson_append_time_t(rwbson,"date",-1,now); mongoc_client_get_database(client, database_name); bool ret = mongoc_collection_insert(collection, MONGOC_INSERT_NONE, rwbson, NULL, &rwerror); bson_destroy(rwbson); if (!ret) return EXIT_FAILURE; } // read bson_t roquery; bson_init (&roquery); char *str; #if 0 eson_append_utf8 (&roquery, "hello", -1, "world", -1); #endif cursor = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, 0, &roquery, NULL, /* Fields, NULL for all. */ NULL); /* Read Prefs, NULL for default */ while (mongoc_cursor_next (cursor, &doc)) { str = bson_as_json (doc, NULL); fprintf (stdout, "%s\n", str); bson_free (str); } if (mongoc_cursor_error (cursor, &error)) { fprintf (stderr, "Cursor Failure: %s\n", error.message); return EXIT_FAILURE; } bson_destroy (&roquery); // close server connection mongoc_cursor_destroy (cursor); mongoc_collection_destroy (collection); mongoc_client_destroy (client); mongoc_cleanup (); return EXIT_SUCCESS; }
int gridfs_init( mongo *client, const char *dbname, const char *prefix, gridfs *gfs ) { int options; bson b; bson_bool_t success; gfs->client = client; /* Allocate space to own the dbname */ gfs->dbname = ( const char * )bson_malloc( strlen( dbname )+1 ); strcpy( ( char * )gfs->dbname, dbname ); /* Allocate space to own the prefix */ if ( prefix == NULL ) prefix = "fs"; gfs->prefix = ( const char * )bson_malloc( strlen( prefix )+1 ); strcpy( ( char * )gfs->prefix, prefix ); /* Allocate space to own files_ns */ gfs->files_ns = ( const char * ) bson_malloc ( strlen( prefix )+strlen( dbname )+strlen( ".files" )+2 ); strcpy( ( char * )gfs->files_ns, dbname ); strcat( ( char * )gfs->files_ns, "." ); strcat( ( char * )gfs->files_ns, prefix ); strcat( ( char * )gfs->files_ns, ".files" ); /* Allocate space to own chunks_ns */ gfs->chunks_ns = ( const char * ) bson_malloc( strlen( prefix ) + strlen( dbname ) + strlen( ".chunks" ) + 2 ); strcpy( ( char * )gfs->chunks_ns, dbname ); strcat( ( char * )gfs->chunks_ns, "." ); strcat( ( char * )gfs->chunks_ns, prefix ); strcat( ( char * )gfs->chunks_ns, ".chunks" ); bson_init( &b ); bson_append_int( &b, "filename", 1 ); bson_finish( &b ); options = 0; success = ( mongo_create_index( gfs->client, gfs->files_ns, &b, options, NULL ) == MONGO_OK ); bson_destroy( &b ); if ( !success ) { bson_free( ( char * )gfs->dbname ); bson_free( ( char * )gfs->prefix ); bson_free( ( char * )gfs->files_ns ); bson_free( ( char * )gfs->chunks_ns ); return MONGO_ERROR; } bson_init( &b ); bson_append_int( &b, "files_id", 1 ); bson_append_int( &b, "n", 1 ); bson_finish( &b ); options = MONGO_INDEX_UNIQUE; success = ( mongo_create_index( gfs->client, gfs->chunks_ns, &b, options, NULL ) == MONGO_OK ); bson_destroy( &b ); if ( !success ) { bson_free( ( char * )gfs->dbname ); bson_free( ( char * )gfs->prefix ); bson_free( ( char * )gfs->files_ns ); bson_free( ( char * )gfs->chunks_ns ); return MONGO_ERROR; } return MONGO_OK; }
void test_bson_js_code_w_scope (void) { bson *b, *scope; scope = bson_new (); bson_append_string (scope, "foo", "bar", -1); bson_finish (scope); /* Test #1: A single JS element, with default size. */ b = bson_new (); ok (bson_append_javascript_w_scope (b, "f", "alert ('hello');", -1, scope), "bson_append_javascript_w_scope() works"); bson_finish (b); cmp_ok (bson_size (b), "==", 51, "BSON javascript w/ element size check"); ok (memcmp (bson_data (b), "\063\000\000\000\017\146\000\053\000\000\000\021\000\000\000" "\141\154\145\162\164\040\050\047\150\145\154\154\157\047\051" "\073\000\022\000\000\000\002\146\157\157\000\004\000\000\000" "\142\141\162\000\000\000", bson_size (b)) == 0, "BSON javascript w/ scope element contents check"); bson_free (b); /* Test #2: A single javascript element, with explicit length. */ b = bson_new (); ok (bson_append_javascript_w_scope (b, "f", "alert ('hello'); garbage", strlen ("alert ('hello');"), scope), "bson_append_javascript_w_scope() with explicit length works"); bson_finish (b); cmp_ok (bson_size (b), "==", 51, "BSON javascript w/ element size check"); ok (memcmp (bson_data (b), "\063\000\000\000\017\146\000\053\000\000\000\021\000\000\000" "\141\154\145\162\164\040\050\047\150\145\154\154\157\047\051" "\073\000\022\000\000\000\002\146\157\157\000\004\000\000\000" "\142\141\162\000\000\000", bson_size (b)) == 0, "BSON javascript w/ scope element contents check"); bson_free (b); /* Test #3: Negative test, passing an invalid arguments. */ b = bson_new (); ok (bson_append_javascript_w_scope (b, "hello", "print();", -42, scope) == FALSE, "bson_append_javascript_w_scope() with an invalid length should fail"); ok (bson_append_javascript_w_scope (b, NULL, "print();", -1, scope) == FALSE, "bson_append_javascript_w_scope() should fail without a key name"); ok (bson_append_javascript_w_scope (b, "hello", NULL, -1, scope) == FALSE, "bson_append_javascript_w_scope() should fail without javascript code"); ok (bson_append_javascript_w_scope (NULL, "hello", "print();", -1, scope) == FALSE, "bson_append_javascript_w_scope() should fail without a BSON object"); ok (bson_append_javascript_w_scope (b, "hello", "print();", -1, NULL) == FALSE, "bson_append_javascript_w_scope() should fail without a scope object"); bson_finish (b); cmp_ok (bson_size (b), "==", 5, "BSON object should be empty"); ok (bson_append_javascript_w_scope (b, "js", "print();", -1, scope) == FALSE, "Appending to a finished element should fail"); bson_free (b); }
int main (int argc, char *argv[]) { bson_reader_t *reader; const bson_t *b; const char *filename; char *str; int fd; int i; /* * Print program usage if no arguments are provided. */ if (argc == 1) { fprintf(stderr, "usage: %s FILE...\n", argv[0]); return 1; } /* * Process command line arguments expecting each to be a filename. */ for (i = 1; i < argc; i++) { filename = argv[i]; /* * Open the filename provided in command line arguments. */ if (0 == strcmp(filename, "-")) { fd = STDIN_FILENO; } else { errno = 0; fd = open(filename, O_RDONLY); if (fd == -1) { fprintf(stderr, "Failed to open %s: %s\n", filename, strerror(errno)); continue; } } /* * Initialize a new reader for this file descriptor. */ reader = bson_reader_new_from_fd(fd, TRUE); /* * Convert each incoming document to JSON and print to stdout. */ while ((b = bson_reader_read(reader, NULL))) { str = bson_as_json(b, NULL); fprintf(stdout, "%s\n", str); bson_free(str); } /* * Cleanup after our reader, which closes the file descriptor. */ bson_reader_destroy(reader); } return 0; }
static void alarm_send(void) { mongoc_client_t *curclient = mongoc_client_new ("mongodb://172.16.0.7:27017/"); mongoc_collection_t *collection; mongoc_collection_t *sensorcoll; mongoc_collection_t *alarmcoll; mongoc_collection_t *contactcoll; mongoc_collection_t *alarmlogcoll; collection = mongoc_client_get_collection (curclient, "smart_trash_development", "devices"); sensorcoll = mongoc_client_get_collection (curclient, "smart_trash_development", "sensors"); alarmcoll = mongoc_client_get_collection (curclient, "smart_trash_development", "alarms"); alarmlogcoll = mongoc_client_get_collection (curclient, "smart_trash_development", "alarmlogs"); contactcoll = mongoc_client_get_collection (curclient, "smart_trash_development", "contacts"); mongoc_cursor_t *cursor; bson_t *doc; bson_t *query; char *str; query = bson_new (); cursor = mongoc_collection_find (alarmcoll, MONGOC_QUERY_NONE, 0, 0, 0, query, NULL, NULL); bson_oid_t se_oid; char se_id[1024]; memset(se_id,0,1024); char de_id[1024]; memset(de_id,'\0',1024); char alarmType[1024]; memset(alarmType,0,1024); char lowerBoundC[1024]; memset(lowerBoundC,0,1024); char upperBoundC[1024]; memset(upperBoundC,0,1024); char duration[1024]; memset(duration,0,1024); char target[1024]; memset(target,0,1024); char contactId[1024]; memset(contactId,0,1024); char userId[1024]; memset(userId,0,1024); while (mongoc_cursor_next (cursor, &doc)) { str = bson_as_json (doc, NULL); bson_free (str); bson_iter_t iter; bson_iter_t sub_iter; if (bson_iter_init (&iter, doc)) { while (bson_iter_next (&iter)) { bson_value_t *value; value = bson_iter_value (&iter); if (value->value_type == BSON_TYPE_UTF8) { if(strcmp(bson_iter_key (&iter),"sensorId")==0){ strcpy(se_id,value->value.v_utf8.str); }else if (strcmp(bson_iter_key (&iter),"alarmType")==0){ strcpy(alarmType,value->value.v_utf8.str); }else if (strcmp(bson_iter_key (&iter),"lowerBoundC")==0){ strcpy(lowerBoundC,value->value.v_utf8.str); }else if (strcmp(bson_iter_key (&iter),"upperBoundC")==0){ strcpy(upperBoundC,value->value.v_utf8.str); }else if (strcmp(bson_iter_key (&iter),"duration")==0){ strcpy(duration,value->value.v_utf8.str); }else if (strcmp(bson_iter_key (&iter),"target")==0){ strcpy(target,value->value.v_utf8.str); }else if (strcmp(bson_iter_key (&iter),"contactId")==0){ strcpy(contactId,value->value.v_utf8.str); }else if (strcmp(bson_iter_key (&iter),"userId")==0){ strcpy(userId,value->value.v_utf8.str); }else if (strcmp(bson_iter_key (&iter),"deviceId")==0){ strcpy(de_id,value->value.v_utf8.str); } } } } char mobile[256]; char addr[1024]; char device_name[2048]; memset(mobile,'\0',256); memset(addr,'\0',1024); memset(device_name,'\0',2048); getPhone(contactcoll,contactId,mobile); printf("\ndev_id:%s,lowerBoundC:%s,upperBoundC:%s\n",de_id,lowerBoundC,upperBoundC); getaddressbyID(addr,collection,de_id,device_name); do_alarm(sensorcoll,se_id,alarmType,upperBoundC,lowerBoundC,duration,target,mobile,addr,alarmlogcoll,userId,device_name,de_id); } bson_destroy (query); mongoc_collection_destroy (collection); mongoc_collection_destroy (sensorcoll); mongoc_collection_destroy (alarmcoll); mongoc_collection_destroy (alarmlogcoll); mongoc_client_destroy (curclient); }