diff --git a/.clang-format b/.clang-format index e1bfdc0671..3361014dd6 100644 --- a/.clang-format +++ b/.clang-format @@ -86,7 +86,7 @@ BreakBeforeTernaryOperators: true BreakConstructorInitializers: BeforeColon BreakInheritanceList: BeforeColon BreakStringLiterals: true -ColumnLimit: 80 +ColumnLimit: 120 CommentPragmas: '^ IWYU pragma:' CompactNamespaces: false ConstructorInitializerIndentWidth: 4 diff --git a/src/common/bson-dsl.h b/src/common/bson-dsl.h index 84d757008a..58a14e28e4 100644 --- a/src/common/bson-dsl.h +++ b/src/common/bson-dsl.h @@ -23,8 +23,7 @@ enum { BSON_DSL_DEBUG = 0 }; -#define _bson_thread_local \ - BSON_IF_GNU_LIKE (__thread) BSON_IF_MSVC (__declspec (thread)) +#define _bson_thread_local BSON_IF_GNU_LIKE (__thread) BSON_IF_MSVC (__declspec (thread)) #define _bson_comdat \ BSON_IF_WINDOWS (__declspec (selectany)) \ @@ -97,21 +96,19 @@ BSON_IF_GNU_LIKE (_Pragma ("GCC diagnostic ignored \"-Wshadow\"")) * @brief Expands to a call to bson_append_{Kind}, with the three first * arguments filled in by the DSL context variables. */ -#define _bsonBuildAppendArgs \ - bsonBuildContext.doc, bsonBuildContext.key, bsonBuildContext.key_len +#define _bsonBuildAppendArgs bsonBuildContext.doc, bsonBuildContext.key, bsonBuildContext.key_len /** * The _bsonDocOperation_XYZ macros handle the top-level bsonBuild() * items, and any nested doc() items, with XYZ being the doc-building * subcommand. */ -#define _bsonDocOperation(Command, _ignore, _count) \ - if (!bsonBuildError) { \ - _bsonDocOperation_##Command; \ - if (bsonBuildError) { \ - _bsonDSLDebug ("Stopping doc() due to bsonBuildError: [%s]", \ - bsonBuildError); \ - } \ +#define _bsonDocOperation(Command, _ignore, _count) \ + if (!bsonBuildError) { \ + _bsonDocOperation_##Command; \ + if (bsonBuildError) { \ + _bsonDSLDebug ("Stopping doc() due to bsonBuildError: [%s]", bsonBuildError); \ + } \ } #define _bsonValueOperation(P) _bsonValueOperation_##P @@ -131,8 +128,7 @@ BSON_IF_GNU_LIKE (_Pragma ("GCC diagnostic ignored \"-Wshadow\"")) _bsonDSL_end /// Key-value pair with a C-string -#define _bsonDocOperation_kv(String, Element) \ - _bsonDocOperation_kvl ((String), strlen ((String)), Element) +#define _bsonDocOperation_kv(String, Element) _bsonDocOperation_kvl ((String), strlen ((String)), Element) /// Execute arbitrary code #define _bsonDocOperation_do(...) \ @@ -146,104 +142,89 @@ BSON_IF_GNU_LIKE (_Pragma ("GCC diagnostic ignored \"-Wshadow\"")) _bsonDSL_end /// We must defer expansion of the nested doc() to allow "recursive" evaluation -#define _bsonValueOperation_doc \ - _bsonValueOperationDeferred_doc _bsonDSL_nothing () +#define _bsonValueOperation_doc _bsonValueOperationDeferred_doc _bsonDSL_nothing () #define _bsonArrayOperation_doc(...) _bsonArrayAppendValue (doc (__VA_ARGS__)) -#define _bsonValueOperationDeferred_doc(...) \ - _bsonDSL_begin ("doc(%s)", _bsonDSL_strElide (30, __VA_ARGS__)); \ - /* Write to this variable as the child: */ \ - bson_t _bbChildDoc = BSON_INITIALIZER; \ - if (!bson_append_document_begin (_bsonBuildAppendArgs, &_bbChildDoc)) { \ - bsonBuildError = \ - "Error while initializing child document: " _bsonDSL_str ( \ - __VA_ARGS__); \ - } else { \ - _bsonBuildAppend (_bbChildDoc, __VA_ARGS__); \ - if (!bsonBuildError) { \ - if (!bson_append_document_end (bsonBuildContext.doc, &_bbChildDoc)) { \ - bsonBuildError = \ - "Error while finalizing document: " _bsonDSL_str (__VA_ARGS__); \ - } \ - } \ - } \ +#define _bsonValueOperationDeferred_doc(...) \ + _bsonDSL_begin ("doc(%s)", _bsonDSL_strElide (30, __VA_ARGS__)); \ + /* Write to this variable as the child: */ \ + bson_t _bbChildDoc = BSON_INITIALIZER; \ + if (!bson_append_document_begin (_bsonBuildAppendArgs, &_bbChildDoc)) { \ + bsonBuildError = "Error while initializing child document: " _bsonDSL_str (__VA_ARGS__); \ + } else { \ + _bsonBuildAppend (_bbChildDoc, __VA_ARGS__); \ + if (!bsonBuildError) { \ + if (!bson_append_document_end (bsonBuildContext.doc, &_bbChildDoc)) { \ + bsonBuildError = "Error while finalizing document: " _bsonDSL_str (__VA_ARGS__); \ + } \ + } \ + } \ _bsonDSL_end /// We must defer expansion of the nested array() to allow "recursive" /// evaluation -#define _bsonValueOperation_array \ - _bsonValueOperationDeferred_array _bsonDSL_nothing () -#define _bsonArrayOperation_array(...) \ - _bsonArrayAppendValue (array (__VA_ARGS__)) - -#define _bsonValueOperationDeferred_array(...) \ - _bsonDSL_begin ("array(%s)", _bsonDSL_strElide (30, __VA_ARGS__)); \ - /* Write to this variable as the child array: */ \ - bson_t _bbArray = BSON_INITIALIZER; \ - if (!bson_append_array_begin (_bsonBuildAppendArgs, &_bbArray)) { \ - bsonBuildError = \ - "Error while initializing child array: " _bsonDSL_str (__VA_ARGS__); \ - } else { \ - _bsonBuildArray (_bbArray, __VA_ARGS__); \ - if (!bsonBuildError) { \ - if (!bson_append_array_end (bsonBuildContext.doc, &_bbArray)) { \ - bsonBuildError = \ - "Error while finalizing child array: " _bsonDSL_str ( \ - __VA_ARGS__); \ - } \ - } else { \ - _bsonDSLDebug ("Got bsonBuildError: [%s]", bsonBuildError); \ - } \ - } \ +#define _bsonValueOperation_array _bsonValueOperationDeferred_array _bsonDSL_nothing () +#define _bsonArrayOperation_array(...) _bsonArrayAppendValue (array (__VA_ARGS__)) + +#define _bsonValueOperationDeferred_array(...) \ + _bsonDSL_begin ("array(%s)", _bsonDSL_strElide (30, __VA_ARGS__)); \ + /* Write to this variable as the child array: */ \ + bson_t _bbArray = BSON_INITIALIZER; \ + if (!bson_append_array_begin (_bsonBuildAppendArgs, &_bbArray)) { \ + bsonBuildError = "Error while initializing child array: " _bsonDSL_str (__VA_ARGS__); \ + } else { \ + _bsonBuildArray (_bbArray, __VA_ARGS__); \ + if (!bsonBuildError) { \ + if (!bson_append_array_end (bsonBuildContext.doc, &_bbArray)) { \ + bsonBuildError = "Error while finalizing child array: " _bsonDSL_str (__VA_ARGS__); \ + } \ + } else { \ + _bsonDSLDebug ("Got bsonBuildError: [%s]", bsonBuildError); \ + } \ + } \ _bsonDSL_end /// Append a UTF-8 string with an explicit length -#define _bsonValueOperation_utf8_w_len(String, Len) \ - if (!bson_append_utf8 (_bsonBuildAppendArgs, (String), (int) (Len))) { \ - bsonBuildError = \ - "Error while appending utf8 string: " _bsonDSL_str (String); \ - } else \ +#define _bsonValueOperation_utf8_w_len(String, Len) \ + if (!bson_append_utf8 (_bsonBuildAppendArgs, (String), (int) (Len))) { \ + bsonBuildError = "Error while appending utf8 string: " _bsonDSL_str (String); \ + } else \ ((void) 0) #define _bsonArrayOperation_utf8_w_len(X) _bsonArrayAppendValue (utf8_w_len (X)) /// Append a "cstr" as UTF-8 -#define _bsonValueOperation_cstr(String) \ - _bsonValueOperation_utf8_w_len ((String), strlen (String)) +#define _bsonValueOperation_cstr(String) _bsonValueOperation_utf8_w_len ((String), strlen (String)) #define _bsonArrayOperation_cstr(X) _bsonArrayAppendValue (cstr (X)) /// Append an int32 -#define _bsonValueOperation_int32(Integer) \ - if (!bson_append_int32 (_bsonBuildAppendArgs, (Integer))) { \ - bsonBuildError = \ - "Error while appending int32(" _bsonDSL_str (Integer) ")"; \ - } else \ +#define _bsonValueOperation_int32(Integer) \ + if (!bson_append_int32 (_bsonBuildAppendArgs, (Integer))) { \ + bsonBuildError = "Error while appending int32(" _bsonDSL_str (Integer) ")"; \ + } else \ ((void) 0) #define _bsonArrayOperation_int32(X) _bsonArrayAppendValue (int32 (X)) /// Append an int64 -#define _bsonValueOperation_int64(Integer) \ - if (!bson_append_int64 (_bsonBuildAppendArgs, (Integer))) { \ - bsonBuildError = \ - "Error while appending int64(" _bsonDSL_str (Integer) ")"; \ - } else \ +#define _bsonValueOperation_int64(Integer) \ + if (!bson_append_int64 (_bsonBuildAppendArgs, (Integer))) { \ + bsonBuildError = "Error while appending int64(" _bsonDSL_str (Integer) ")"; \ + } else \ ((void) 0) #define _bsonArrayOperation_int64(X) _bsonArrayAppendValue (int64 (X)) /// Append the value referenced by a given iterator -#define _bsonValueOperation_iterValue(Iter) \ - if (!bson_append_iter (_bsonBuildAppendArgs, &(Iter))) { \ - bsonBuildError = \ - "Error while appending iterValue(" _bsonDSL_str (Iter) ")"; \ - } else \ +#define _bsonValueOperation_iterValue(Iter) \ + if (!bson_append_iter (_bsonBuildAppendArgs, &(Iter))) { \ + bsonBuildError = "Error while appending iterValue(" _bsonDSL_str (Iter) ")"; \ + } else \ ((void) 0) #define _bsonArrayOperation_iterValue(X) _bsonArrayAppendValue (iterValue (X)) /// Append the BSON document referenced by the given pointer -#define _bsonValueOperation_bson(Doc) \ - if (!bson_append_document (_bsonBuildAppendArgs, &(Doc))) { \ - bsonBuildError = \ - "Error while appending subdocument: bson(" _bsonDSL_str (Doc) ")"; \ - } else \ +#define _bsonValueOperation_bson(Doc) \ + if (!bson_append_document (_bsonBuildAppendArgs, &(Doc))) { \ + bsonBuildError = "Error while appending subdocument: bson(" _bsonDSL_str (Doc) ")"; \ + } else \ ((void) 0) #define _bsonArrayOperation_bson(X) _bsonArrayAppendValue (bson (X)) @@ -274,63 +255,51 @@ BSON_IF_GNU_LIKE (_Pragma ("GCC diagnostic ignored \"-Wshadow\"")) #define _bsonArrayOperation_value(X) _bsonArrayAppendValue (value (X)) -#define _bsonValueOperation_value(Value) \ - _bsonDSL_begin ("value(%s)", _bsonDSL_str (Value)); \ - if (!bson_append_value (_bsonBuildAppendArgs, &(Value))) { \ - bsonBuildError = \ - "Error while appending value(" _bsonDSL_str (Value) ")"; \ - } \ +#define _bsonValueOperation_value(Value) \ + _bsonDSL_begin ("value(%s)", _bsonDSL_str (Value)); \ + if (!bson_append_value (_bsonBuildAppendArgs, &(Value))) { \ + bsonBuildError = "Error while appending value(" _bsonDSL_str (Value) ")"; \ + } \ _bsonDSL_end /// Insert the given BSON document into the parent document in-place -#define _bsonDocOperation_insert(OtherBSON, Pred) \ - _bsonDSL_begin ("Insert other document: [%s]", _bsonDSL_str (OtherBSON)); \ - const bool _bvHalt = false; /* Required for _bsonVisitEach() */ \ - _bsonVisitEach ( \ - OtherBSON, \ - if (Pred, then (do (_bsonDocOperation_iterElement (bsonVisitIter))))); \ +#define _bsonDocOperation_insert(OtherBSON, Pred) \ + _bsonDSL_begin ("Insert other document: [%s]", _bsonDSL_str (OtherBSON)); \ + const bool _bvHalt = false; /* Required for _bsonVisitEach() */ \ + _bsonVisitEach (OtherBSON, if (Pred, then (do (_bsonDocOperation_iterElement (bsonVisitIter))))); \ _bsonDSL_end -#define _bsonDocOperation_insertFromIter(Iter, Pred) \ - _bsonDSL_begin ("Insert document from iterator: [%s]", \ - _bsonDSL_str (Iter)); \ - bson_t _bbDocFromIter = _bson_dsl_iter_as_doc (&(Iter)); \ - if (_bbDocFromIter.len == 0) { \ - _bsonDSLDebug ( \ - "NOTE: Skipping insert of non-document value from iterator"); \ - } else { \ - _bsonDocOperation_insert (_bbDocFromIter, Pred); \ - } \ +#define _bsonDocOperation_insertFromIter(Iter, Pred) \ + _bsonDSL_begin ("Insert document from iterator: [%s]", _bsonDSL_str (Iter)); \ + bson_t _bbDocFromIter = _bson_dsl_iter_as_doc (&(Iter)); \ + if (_bbDocFromIter.len == 0) { \ + _bsonDSLDebug ("NOTE: Skipping insert of non-document value from iterator"); \ + } else { \ + _bsonDocOperation_insert (_bbDocFromIter, Pred); \ + } \ _bsonDSL_end -#define _bsonDocOperation_iterElement(Iter) \ - _bsonDSL_begin ("Insert element from bson_iter_t [%s]", \ - _bsonDSL_str (Iter)); \ - bson_iter_t _bbIter = (Iter); \ - _bsonDocOperation_kvl (bson_iter_key (&_bbIter), \ - bson_iter_key_len (&_bbIter), \ - iterValue (_bbIter)); \ +#define _bsonDocOperation_iterElement(Iter) \ + _bsonDSL_begin ("Insert element from bson_iter_t [%s]", _bsonDSL_str (Iter)); \ + bson_iter_t _bbIter = (Iter); \ + _bsonDocOperation_kvl (bson_iter_key (&_bbIter), bson_iter_key_len (&_bbIter), iterValue (_bbIter)); \ _bsonDSL_end /// Insert the given BSON document into the parent array. Keys of the given /// document are discarded and it is treated as an array of values. -#define _bsonArrayOperation_insert(OtherArr, Pred) \ - _bsonDSL_begin ("Insert other array: [%s]", _bsonDSL_str (OtherArr)); \ - _bsonVisitEach ( \ - OtherArr, \ - if (Pred, then (do (_bsonArrayOperation_iterValue (bsonVisitIter))))); \ +#define _bsonArrayOperation_insert(OtherArr, Pred) \ + _bsonDSL_begin ("Insert other array: [%s]", _bsonDSL_str (OtherArr)); \ + _bsonVisitEach (OtherArr, if (Pred, then (do (_bsonArrayOperation_iterValue (bsonVisitIter))))); \ _bsonDSL_end -#define _bsonArrayAppendValue(ValueOperation) \ - _bsonDSL_begin ("[%d] => [%s]", \ - (int) bsonBuildContext.index, \ - _bsonDSL_strElide (30, ValueOperation)); \ - /* Set the doc key to the array index as a string: */ \ - _bsonBuild_setKeyToArrayIndex (bsonBuildContext.index); \ - /* Append a value: */ \ - _bsonValueOperation_##ValueOperation; \ - /* Increment the array index: */ \ - ++_bbCtx.index; \ +#define _bsonArrayAppendValue(ValueOperation) \ + _bsonDSL_begin ("[%d] => [%s]", (int) bsonBuildContext.index, _bsonDSL_strElide (30, ValueOperation)); \ + /* Set the doc key to the array index as a string: */ \ + _bsonBuild_setKeyToArrayIndex (bsonBuildContext.index); \ + /* Append a value: */ \ + _bsonValueOperation_##ValueOperation; \ + /* Increment the array index: */ \ + ++_bbCtx.index; \ _bsonDSL_end @@ -352,12 +321,11 @@ BSON_IF_GNU_LIKE (_Pragma ("GCC diagnostic ignored \"-Wshadow\"")) _bsonDocOperationIfThen_##Then; \ } -#define _bsonDocOperation_if(Condition, ...) \ - _bsonDSL_begin ("Conditional append on [%s]", _bsonDSL_str (Condition)); \ - /* Pick a sub-macro depending on if there are one or two args */ \ - _bsonDSL_ifElse (_bsonDSL_hasComma (__VA_ARGS__), \ - _bsonDocOperationIfThenElse, \ - _bsonDocOperationIfThen) (Condition, __VA_ARGS__); \ +#define _bsonDocOperation_if(Condition, ...) \ + _bsonDSL_begin ("Conditional append on [%s]", _bsonDSL_str (Condition)); \ + /* Pick a sub-macro depending on if there are one or two args */ \ + _bsonDSL_ifElse (_bsonDSL_hasComma (__VA_ARGS__), _bsonDocOperationIfThenElse, _bsonDocOperationIfThen) ( \ + Condition, __VA_ARGS__); \ _bsonDSL_end #define _bsonArrayOperationIfThen_then _bsonBuildArrayWithCurrentContext @@ -378,12 +346,11 @@ BSON_IF_GNU_LIKE (_Pragma ("GCC diagnostic ignored \"-Wshadow\"")) _bsonArrayOperationIfThen_##Then; \ } -#define _bsonArrayOperation_if(Condition, ...) \ - _bsonDSL_begin ("Conditional value on [%s]", _bsonDSL_str (Condition)); \ - /* Pick a sub-macro depending on if there are one or two args */ \ - _bsonDSL_ifElse (_bsonDSL_hasComma (__VA_ARGS__), \ - _bsonArrayOperationIfThenElse, \ - _bsonArrayOperationIfThen) (Condition, __VA_ARGS__); \ +#define _bsonArrayOperation_if(Condition, ...) \ + _bsonDSL_begin ("Conditional value on [%s]", _bsonDSL_str (Condition)); \ + /* Pick a sub-macro depending on if there are one or two args */ \ + _bsonDSL_ifElse (_bsonDSL_hasComma (__VA_ARGS__), _bsonArrayOperationIfThenElse, _bsonArrayOperationIfThen) ( \ + Condition, __VA_ARGS__); \ _bsonDSL_end #define _bsonValueOperationIf_then(X) _bsonValueOperation_##X @@ -398,11 +365,8 @@ BSON_IF_GNU_LIKE (_Pragma ("GCC diagnostic ignored \"-Wshadow\"")) _bsonValueOperationIf_##Else; \ } -#define _bsonBuild_setKeyToArrayIndex(Idx) \ - _bbCtx.key_len = bson_snprintf (_bbCtx.index_key_str, \ - sizeof _bbCtx.index_key_str, \ - "%d", \ - (int) _bbCtx.index); \ +#define _bsonBuild_setKeyToArrayIndex(Idx) \ + _bbCtx.key_len = bson_snprintf (_bbCtx.index_key_str, sizeof _bbCtx.index_key_str, "%d", (int) _bbCtx.index); \ _bbCtx.key = _bbCtx.index_key_str /// Handle an element of array() @@ -411,11 +375,9 @@ BSON_IF_GNU_LIKE (_Pragma ("GCC diagnostic ignored \"-Wshadow\"")) _bsonArrayOperation_##Element; \ } -#define _bsonBuildAppendWithCurrentContext(...) \ - _bsonDSL_mapMacro (_bsonDocOperation, ~, __VA_ARGS__) +#define _bsonBuildAppendWithCurrentContext(...) _bsonDSL_mapMacro (_bsonDocOperation, ~, __VA_ARGS__) -#define _bsonBuildArrayWithCurrentContext(...) \ - _bsonDSL_mapMacro (_bsonArrayOperation, ~, __VA_ARGS__) +#define _bsonBuildArrayWithCurrentContext(...) _bsonDSL_mapMacro (_bsonArrayOperation, ~, __VA_ARGS__) #define _bsonDSL_Type_double BSON_TYPE_DOUBLE #define _bsonDSL_Type_utf8 BSON_TYPE_UTF8 @@ -442,11 +404,10 @@ BSON_IF_GNU_LIKE (_Pragma ("GCC diagnostic ignored \"-Wshadow\"")) #define _bsonVisitOperation_halt _bvHalt = true -#define _bsonVisitOperation_if(Predicate, ...) \ - _bsonDSL_begin ("if(%s)", _bsonDSL_str (Predicate)); \ - _bsonDSL_ifElse (_bsonDSL_hasComma (__VA_ARGS__), \ - _bsonVisit_ifThenElse, \ - _bsonVisit_ifThen) (Predicate, __VA_ARGS__); \ +#define _bsonVisitOperation_if(Predicate, ...) \ + _bsonDSL_begin ("if(%s)", _bsonDSL_str (Predicate)); \ + _bsonDSL_ifElse (_bsonDSL_hasComma (__VA_ARGS__), _bsonVisit_ifThenElse, _bsonVisit_ifThen) (Predicate, \ + __VA_ARGS__); \ _bsonDSL_end #define _bsonVisit_ifThenElse(Predicate, Then, Else) \ @@ -519,14 +480,12 @@ BSON_IF_GNU_LIKE (_Pragma ("GCC diagnostic ignored \"-Wshadow\"")) } while (0); \ _bsonDSL_end -#define _bsonVisitOperation_appendTo(BSON) \ - _bsonDSL_begin ("appendTo(%s)", _bsonDSL_str (BSON)); \ - if (!bson_append_iter (&(BSON), \ - bson_iter_key (&bsonVisitIter), \ - (int) bson_iter_key_len (&bsonVisitIter), \ - &bsonVisitIter)) { \ - bsonParseError = "Error in appendTo(" _bsonDSL_str (BSON) ")"; \ - } \ +#define _bsonVisitOperation_appendTo(BSON) \ + _bsonDSL_begin ("appendTo(%s)", _bsonDSL_str (BSON)); \ + if (!bson_append_iter ( \ + &(BSON), bson_iter_key (&bsonVisitIter), (int) bson_iter_key_len (&bsonVisitIter), &bsonVisitIter)) { \ + bsonParseError = "Error in appendTo(" _bsonDSL_str (BSON) ")"; \ + } \ _bsonDSL_end #define _bsonVisitCase_when(Pred, ...) \ @@ -555,51 +514,46 @@ BSON_IF_GNU_LIKE (_Pragma ("GCC diagnostic ignored \"-Wshadow\"")) _bsonDSL_mapMacro (_bsonVisitCase, ~, __VA_ARGS__); \ _bsonDSL_end -#define _bsonVisitOperation_append \ - _bsonVisitOneApplyDeferred_append _bsonDSL_nothing () -#define _bsonVisitOneApplyDeferred_append(Doc, ...) \ - _bsonDSL_begin ("append to [%s] : %s", \ - _bsonDSL_str (Doc), \ - _bsonDSL_strElide (30, __VA_ARGS__)); \ - _bsonBuildAppend (Doc, __VA_ARGS__); \ - if (bsonBuildError) { \ - bsonParseError = bsonBuildError; \ - } \ +#define _bsonVisitOperation_append _bsonVisitOneApplyDeferred_append _bsonDSL_nothing () +#define _bsonVisitOneApplyDeferred_append(Doc, ...) \ + _bsonDSL_begin ("append to [%s] : %s", _bsonDSL_str (Doc), _bsonDSL_strElide (30, __VA_ARGS__)); \ + _bsonBuildAppend (Doc, __VA_ARGS__); \ + if (bsonBuildError) { \ + bsonParseError = bsonBuildError; \ + } \ _bsonDSL_end -#define _bsonVisitEach(Doc, ...) \ - _bsonDSL_begin ("visitEach(%s)", _bsonDSL_str (Doc)); \ - do { \ - /* Reset the context */ \ - struct _bsonVisitContext_t _bvCtx = { \ - .doc = &(Doc), \ - .parent = _bsonVisitContextThreadLocalPtr, \ - .index = 0, \ - }; \ - _bsonVisitContextThreadLocalPtr = &_bvCtx; \ - bsonParseError = NULL; \ - /* Iterate over each element of the document */ \ - if (!bson_iter_init (&_bvCtx.iter, &(Doc))) { \ - bsonParseError = "Invalid BSON data [a]"; \ - } \ - BSON_MAYBE_UNUSED bool _bvBreak = false; \ - BSON_MAYBE_UNUSED bool _bvContinue = false; \ - while (bson_iter_next (&_bvCtx.iter) && !_bvHalt && !bsonParseError && \ - !_bvBreak) { \ - _bvContinue = false; \ - _bsonVisit_applyOps (__VA_ARGS__); \ - ++_bvCtx.index; \ - } \ - if (bsonVisitIter.err_off) { \ - bsonParseError = "Invalid BSON data [b]"; \ - } \ - /* Restore the dsl context */ \ - _bsonVisitContextThreadLocalPtr = _bvCtx.parent; \ - } while (0); \ +#define _bsonVisitEach(Doc, ...) \ + _bsonDSL_begin ("visitEach(%s)", _bsonDSL_str (Doc)); \ + do { \ + /* Reset the context */ \ + struct _bsonVisitContext_t _bvCtx = { \ + .doc = &(Doc), \ + .parent = _bsonVisitContextThreadLocalPtr, \ + .index = 0, \ + }; \ + _bsonVisitContextThreadLocalPtr = &_bvCtx; \ + bsonParseError = NULL; \ + /* Iterate over each element of the document */ \ + if (!bson_iter_init (&_bvCtx.iter, &(Doc))) { \ + bsonParseError = "Invalid BSON data [a]"; \ + } \ + BSON_MAYBE_UNUSED bool _bvBreak = false; \ + BSON_MAYBE_UNUSED bool _bvContinue = false; \ + while (bson_iter_next (&_bvCtx.iter) && !_bvHalt && !bsonParseError && !_bvBreak) { \ + _bvContinue = false; \ + _bsonVisit_applyOps (__VA_ARGS__); \ + ++_bvCtx.index; \ + } \ + if (bsonVisitIter.err_off) { \ + bsonParseError = "Invalid BSON data [b]"; \ + } \ + /* Restore the dsl context */ \ + _bsonVisitContextThreadLocalPtr = _bvCtx.parent; \ + } while (0); \ _bsonDSL_end -#define _bsonVisitOperation_visitEach \ - _bsonVisitOperation_visitEachDeferred _bsonDSL_nothing () +#define _bsonVisitOperation_visitEach _bsonVisitOperation_visitEachDeferred _bsonDSL_nothing () #define _bsonVisitOperation_visitEachDeferred(...) \ _bsonDSL_begin ("visitEach:%s", ""); \ do { \ @@ -641,17 +595,15 @@ BSON_IF_GNU_LIKE (_Pragma ("GCC diagnostic ignored \"-Wshadow\"")) #define _bsonVisitOperation_continue _bvContinue = true #define _bsonVisitOperation_break _bvBreak = _bvContinue = true -#define _bsonVisitOperation_require(Predicate) \ - _bsonDSL_begin ("require(%s)", _bsonDSL_str (Predicate)); \ - if (!bsonPredicate (Predicate)) { \ - bsonParseError = \ - "Element requirement failed: " _bsonDSL_str (Predicate); \ - } \ +#define _bsonVisitOperation_require(Predicate) \ + _bsonDSL_begin ("require(%s)", _bsonDSL_str (Predicate)); \ + if (!bsonPredicate (Predicate)) { \ + bsonParseError = "Element requirement failed: " _bsonDSL_str (Predicate); \ + } \ _bsonDSL_end #define _bsonVisitOperation_error(S) bsonParseError = (S) -#define _bsonVisitOperation_errorf(S, ...) \ - (bsonParseError = _bson_dsl_errorf (&(S), __VA_ARGS__)) +#define _bsonVisitOperation_errorf(S, ...) (bsonParseError = _bson_dsl_errorf (&(S), __VA_ARGS__)) #define _bsonVisitOperation_dupPath(S) \ _bsonDSL_begin ("dupPath(%s)", _bsonDSL_str (S)); \ _bson_dsl_dupPath (&(S)); \ @@ -664,24 +616,22 @@ BSON_IF_GNU_LIKE (_Pragma ("GCC diagnostic ignored \"-Wshadow\"")) } \ } while (0); -#define _bsonParse(Doc, ...) \ - do { \ - BSON_MAYBE_UNUSED const bson_t *_bpDoc = &(Doc); \ - /* Keep track of which elements have been visited based on their index*/ \ - uint64_t _bpVisitBits_static[4] = {0}; \ - BSON_MAYBE_UNUSED uint64_t *_bpVisitBits = _bpVisitBits_static; \ - BSON_MAYBE_UNUSED size_t _bpNumVisitBitInts = \ - sizeof _bpVisitBits_static / sizeof (uint64_t); \ - BSON_MAYBE_UNUSED bool _bpFoundElement = false; \ - _bsonParse_applyOps (__VA_ARGS__); \ - /* We may have allocated for visit bits */ \ - if (_bpVisitBits != _bpVisitBits_static) { \ - bson_free (_bpVisitBits); \ - } \ +#define _bsonParse(Doc, ...) \ + do { \ + BSON_MAYBE_UNUSED const bson_t *_bpDoc = &(Doc); \ + /* Keep track of which elements have been visited based on their index*/ \ + uint64_t _bpVisitBits_static[4] = {0}; \ + BSON_MAYBE_UNUSED uint64_t *_bpVisitBits = _bpVisitBits_static; \ + BSON_MAYBE_UNUSED size_t _bpNumVisitBitInts = sizeof _bpVisitBits_static / sizeof (uint64_t); \ + BSON_MAYBE_UNUSED bool _bpFoundElement = false; \ + _bsonParse_applyOps (__VA_ARGS__); \ + /* We may have allocated for visit bits */ \ + if (_bpVisitBits != _bpVisitBits_static) { \ + bson_free (_bpVisitBits); \ + } \ } while (0) -#define _bsonParse_applyOps(...) \ - _bsonDSL_mapMacro (_bsonParse_applyOp, ~, __VA_ARGS__) +#define _bsonParse_applyOps(...) _bsonDSL_mapMacro (_bsonParse_applyOp, ~, __VA_ARGS__) /// Parse one entry referrenced by the context iterator #define _bsonParse_applyOp(P, _nil, Counter) \ @@ -691,90 +641,69 @@ BSON_IF_GNU_LIKE (_Pragma ("GCC diagnostic ignored \"-Wshadow\"")) } \ } while (0); -#define _bsonParseMarkVisited(Index) \ - if (1) { \ - const size_t nth_int = Index / 64u; \ - const size_t nth_bit = Index % 64u; \ - while (nth_int >= _bpNumVisitBitInts) { \ - /* Say that five times, fast: */ \ - size_t new_num_visit_bit_ints = _bpNumVisitBitInts * 2u; \ - uint64_t *new_visit_bit_ints = \ - bson_malloc0 (sizeof (uint64_t) * new_num_visit_bit_ints); \ - memcpy (new_visit_bit_ints, \ - _bpVisitBits, \ - sizeof (uint64_t) * _bpNumVisitBitInts); \ - if (_bpVisitBits != _bpVisitBits_static) { \ - bson_free (_bpVisitBits); \ - } \ - _bpVisitBits = new_visit_bit_ints; \ - _bpNumVisitBitInts = new_num_visit_bit_ints; \ - } \ - \ - _bpVisitBits[nth_int] |= (UINT64_C (1) << nth_bit); \ - } else \ +#define _bsonParseMarkVisited(Index) \ + if (1) { \ + const size_t nth_int = Index / 64u; \ + const size_t nth_bit = Index % 64u; \ + while (nth_int >= _bpNumVisitBitInts) { \ + /* Say that five times, fast: */ \ + size_t new_num_visit_bit_ints = _bpNumVisitBitInts * 2u; \ + uint64_t *new_visit_bit_ints = bson_malloc0 (sizeof (uint64_t) * new_num_visit_bit_ints); \ + memcpy (new_visit_bit_ints, _bpVisitBits, sizeof (uint64_t) * _bpNumVisitBitInts); \ + if (_bpVisitBits != _bpVisitBits_static) { \ + bson_free (_bpVisitBits); \ + } \ + _bpVisitBits = new_visit_bit_ints; \ + _bpNumVisitBitInts = new_num_visit_bit_ints; \ + } \ + \ + _bpVisitBits[nth_int] |= (UINT64_C (1) << nth_bit); \ + } else \ ((void) 0) -#define _bsonParseDidVisitNth(Index) \ - _bsonParseDidVisitNth_1 (Index / 64u, Index % 64u) +#define _bsonParseDidVisitNth(Index) _bsonParseDidVisitNth_1 (Index / 64u, Index % 64u) #define _bsonParseDidVisitNth_1(NthInt, NthBit) \ - (NthInt < _bpNumVisitBitInts && \ - (_bpVisitBits[NthInt] & (UINT64_C (1) << NthBit))) - -#define _bsonParseOperation_find(Predicate, ...) \ - _bsonDSL_begin ("find(%s)", _bsonDSL_str (Predicate)); \ - _bpFoundElement = false; \ - _bsonVisitEach ( \ - *_bpDoc, \ - if (Predicate, \ - then (do (_bsonParseMarkVisited (bsonVisitContext.index); \ - _bpFoundElement = true), \ - __VA_ARGS__, \ - break))); \ - if (!_bpFoundElement && !bsonParseError) { \ - _bsonDSLDebug ("[not found]"); \ - } \ + (NthInt < _bpNumVisitBitInts && (_bpVisitBits[NthInt] & (UINT64_C (1) << NthBit))) + +#define _bsonParseOperation_find(Predicate, ...) \ + _bsonDSL_begin ("find(%s)", _bsonDSL_str (Predicate)); \ + _bpFoundElement = false; \ + _bsonVisitEach ( \ + *_bpDoc, \ + if (Predicate, \ + then (do (_bsonParseMarkVisited (bsonVisitContext.index); _bpFoundElement = true), __VA_ARGS__, break))); \ + if (!_bpFoundElement && !bsonParseError) { \ + _bsonDSLDebug ("[not found]"); \ + } \ _bsonDSL_end -#define _bsonParseOperation_require(Predicate, ...) \ - _bsonDSL_begin ("require(%s)", _bsonDSL_str (Predicate)); \ - _bpFoundElement = false; \ - _bsonVisitEach ( \ - *_bpDoc, \ - if (Predicate, \ - then (do (_bsonParseMarkVisited (bsonVisitContext.index); \ - _bpFoundElement = true), \ - __VA_ARGS__, \ - break))); \ - if (!_bpFoundElement && !bsonParseError) { \ - bsonParseError = \ - "Failed to find a required element: " _bsonDSL_str (Predicate); \ - } \ +#define _bsonParseOperation_require(Predicate, ...) \ + _bsonDSL_begin ("require(%s)", _bsonDSL_str (Predicate)); \ + _bpFoundElement = false; \ + _bsonVisitEach ( \ + *_bpDoc, \ + if (Predicate, \ + then (do (_bsonParseMarkVisited (bsonVisitContext.index); _bpFoundElement = true), __VA_ARGS__, break))); \ + if (!_bpFoundElement && !bsonParseError) { \ + bsonParseError = "Failed to find a required element: " _bsonDSL_str (Predicate); \ + } \ _bsonDSL_end -#define _bsonParseOperation_visitOthers(...) \ - _bsonDSL_begin ("visitOthers(%s)", _bsonDSL_strElide (30, __VA_ARGS__)); \ - _bsonVisitEach ( \ - *_bpDoc, \ - if (not(eval (_bsonParseDidVisitNth (bsonVisitContext.index))), \ - then (__VA_ARGS__))); \ +#define _bsonParseOperation_visitOthers(...) \ + _bsonDSL_begin ("visitOthers(%s)", _bsonDSL_strElide (30, __VA_ARGS__)); \ + _bsonVisitEach (*_bpDoc, if (not(eval (_bsonParseDidVisitNth (bsonVisitContext.index))), then (__VA_ARGS__))); \ _bsonDSL_end #define bsonPredicate(P) _bsonPredicate _bsonDSL_nothing () (P) #define _bsonPredicate(P) _bsonPredicate_Condition_##P -#define _bsonPredicate_Condition_ \ - __NOTE__Missing_name_for_a_predicate_expression +#define _bsonPredicate_Condition_ __NOTE__Missing_name_for_a_predicate_expression -#define _bsonPredicate_Condition_allOf(...) \ - (1 _bsonDSL_mapMacro (_bsonPredicateAnd, ~, __VA_ARGS__)) -#define _bsonPredicate_Condition_anyOf(...) \ - (0 _bsonDSL_mapMacro (_bsonPredicateOr, ~, __VA_ARGS__)) -#define _bsonPredicate_Condition_not(...) \ - (!(0 _bsonDSL_mapMacro (_bsonPredicateOr, ~, __VA_ARGS__))) -#define _bsonPredicateAnd(Pred, _ignore, _ignore1) \ - &&_bsonPredicate _bsonDSL_nothing () (Pred) -#define _bsonPredicateOr(Pred, _ignore, _ignore2) \ - || _bsonPredicate _bsonDSL_nothing () (Pred) +#define _bsonPredicate_Condition_allOf(...) (1 _bsonDSL_mapMacro (_bsonPredicateAnd, ~, __VA_ARGS__)) +#define _bsonPredicate_Condition_anyOf(...) (0 _bsonDSL_mapMacro (_bsonPredicateOr, ~, __VA_ARGS__)) +#define _bsonPredicate_Condition_not(...) (!(0 _bsonDSL_mapMacro (_bsonPredicateOr, ~, __VA_ARGS__))) +#define _bsonPredicateAnd(Pred, _ignore, _ignore1) &&_bsonPredicate _bsonDSL_nothing () (Pred) +#define _bsonPredicateOr(Pred, _ignore, _ignore2) || _bsonPredicate _bsonDSL_nothing () (Pred) #define _bsonPredicate_Condition_eval(X) (X) @@ -792,21 +721,17 @@ BSON_IF_GNU_LIKE (_Pragma ("GCC diagnostic ignored \"-Wshadow\"")) __VA_ARGS__, \ NULL)) -#define _bsonPredicate_Condition_type(Type) \ - (bson_iter_type (&bsonVisitIter) == _bsonDSL_Type_##Type) +#define _bsonPredicate_Condition_type(Type) (bson_iter_type (&bsonVisitIter) == _bsonDSL_Type_##Type) #define _bsonPredicate_Condition_keyWithType(Key, Type) \ (_bsonPredicate_Condition_allOf _bsonDSL_nothing () (key (Key), type (Type))) -#define _bsonPredicate_Condition_iKeyWithType(Key, Type) \ - (_bsonPredicate_Condition_allOf _bsonDSL_nothing () (iKey (Key), \ - type (Type))) +#define _bsonPredicate_Condition_iKeyWithType(Key, Type) \ + (_bsonPredicate_Condition_allOf _bsonDSL_nothing () (iKey (Key), type (Type))) -#define _bsonPredicate_Condition_lastElement \ - (_bson_dsl_iter_is_last_element (&bsonVisitIter)) +#define _bsonPredicate_Condition_lastElement (_bson_dsl_iter_is_last_element (&bsonVisitIter)) -#define _bsonPredicate_Condition_isNumeric \ - BSON_ITER_HOLDS_NUMBER (&bsonVisitIter) +#define _bsonPredicate_Condition_isNumeric BSON_ITER_HOLDS_NUMBER (&bsonVisitIter) #define _bsonPredicate_Condition_1 1 #define _bsonPredicate_Condition_0 0 @@ -815,15 +740,12 @@ BSON_IF_GNU_LIKE (_Pragma ("GCC diagnostic ignored \"-Wshadow\"")) #define _bsonPredicate_Condition_isTrue (bson_iter_as_bool (&bsonVisitIter)) #define _bsonPredicate_Condition_isFalse (!bson_iter_as_bool (&bsonVisitIter)) -#define _bsonPredicate_Condition_empty \ - (_bson_dsl_is_empty_bson (&bsonVisitIter)) +#define _bsonPredicate_Condition_empty (_bson_dsl_is_empty_bson (&bsonVisitIter)) #define _bsonPredicate_Condition_strEqual(S) (_bson_dsl_test_strequal (S, true)) -#define _bsonPredicate_Condition_iStrEqual(S) \ - (_bson_dsl_test_strequal (S, false)) +#define _bsonPredicate_Condition_iStrEqual(S) (_bson_dsl_test_strequal (S, false)) -#define _bsonPredicate_Condition_eq(Type, Value) \ - (_bsonPredicate_Condition_type (Type) && bsonAs (Type) == Value) +#define _bsonPredicate_Condition_eq(Type, Value) (_bsonPredicate_Condition_type (Type) && bsonAs (Type) == Value) #define _bsonParseOperation_else _bsonParse_deferredElse _bsonDSL_nothing () #define _bsonParse_deferredElse(...) \ @@ -844,16 +766,14 @@ BSON_IF_GNU_LIKE (_Pragma ("GCC diagnostic ignored \"-Wshadow\"")) #define _bsonParseOperation_halt _bvHalt = true #define _bsonParseOperation_error(S) bsonParseError = (S) -#define _bsonParseOperation_errorf(S, ...) \ - (bsonParseError = _bson_dsl_errorf (&(S), __VA_ARGS__)) +#define _bsonParseOperation_errorf(S, ...) (bsonParseError = _bson_dsl_errorf (&(S), __VA_ARGS__)) /// Perform conditional parsing -#define _bsonParseOperation_if(Condition, ...) \ - _bsonDSL_begin ("if(%s)", _bsonDSL_str (Condition)); \ - /* Pick a sub-macro depending on if there are one or two args */ \ - _bsonDSL_ifElse (_bsonDSL_hasComma (__VA_ARGS__), \ - _bsonParse_ifThenElse, \ - _bsonParse_ifThen) (Condition, __VA_ARGS__); \ +#define _bsonParseOperation_if(Condition, ...) \ + _bsonDSL_begin ("if(%s)", _bsonDSL_str (Condition)); \ + /* Pick a sub-macro depending on if there are one or two args */ \ + _bsonDSL_ifElse (_bsonDSL_hasComma (__VA_ARGS__), _bsonParse_ifThenElse, _bsonParse_ifThen) (Condition, \ + __VA_ARGS__); \ _bsonDSL_end #define _bsonParse_ifThen_then _bsonParse_applyOps @@ -876,16 +796,13 @@ BSON_IF_GNU_LIKE (_Pragma ("GCC diagnostic ignored \"-Wshadow\"")) _bsonDSLDebug ("[else nothing]"); \ } -#define _bsonParseOperation_append \ - _bsonParseOperationDeferred_append _bsonDSL_nothing () -#define _bsonParseOperationDeferred_append(Doc, ...) \ - _bsonDSL_begin ("append to [%s] : %s", \ - _bsonDSL_str (Doc), \ - _bsonDSL_strElide (30, __VA_ARGS__)); \ - _bsonBuildAppend (Doc, __VA_ARGS__); \ - if (bsonBuildError) { \ - bsonParseError = bsonBuildError; \ - } \ +#define _bsonParseOperation_append _bsonParseOperationDeferred_append _bsonDSL_nothing () +#define _bsonParseOperationDeferred_append(Doc, ...) \ + _bsonDSL_begin ("append to [%s] : %s", _bsonDSL_str (Doc), _bsonDSL_strElide (30, __VA_ARGS__)); \ + _bsonBuildAppend (Doc, __VA_ARGS__); \ + if (bsonBuildError) { \ + bsonParseError = bsonBuildError; \ + } \ _bsonDSL_end #define _bsonVisit_applyOps _bsonVisit_applyOpsDeferred _bsonDSL_nothing () @@ -894,11 +811,9 @@ BSON_IF_GNU_LIKE (_Pragma ("GCC diagnostic ignored \"-Wshadow\"")) _bsonDSL_mapMacro (_bsonVisit_applyOp, ~, __VA_ARGS__); \ } while (0); -#define bsonBuildArray(BSON, ...) \ - _bsonDSL_begin ("bsonBuildArray(%s, %s)", \ - _bsonDSL_str (BSON), \ - _bsonDSL_strElide (30, __VA_ARGS__)); \ - _bsonDSL_eval (_bsonBuildArray (BSON, __VA_ARGS__)); \ +#define bsonBuildArray(BSON, ...) \ + _bsonDSL_begin ("bsonBuildArray(%s, %s)", _bsonDSL_str (BSON), _bsonDSL_strElide (30, __VA_ARGS__)); \ + _bsonDSL_eval (_bsonBuildArray (BSON, __VA_ARGS__)); \ _bsonDSL_end #define _bsonBuildArray(BSON, ...) \ @@ -921,8 +836,7 @@ BSON_IF_GNU_LIKE (_Pragma ("GCC diagnostic ignored \"-Wshadow\"")) * @param Pointer The document upon which to append * @param ... The Document elements to append to the document */ -#define bsonBuildAppend(BSON, ...) \ - _bsonDSL_eval (_bsonBuildAppend (BSON, __VA_ARGS__)) +#define bsonBuildAppend(BSON, ...) _bsonDSL_eval (_bsonBuildAppend (BSON, __VA_ARGS__)) #define _bsonBuildAppend(BSON, ...) \ _bsonDSL_begin ("Appending to document '%s'", _bsonDSL_str (BSON)); \ _bsonDSL_disableWarnings (); \ @@ -975,8 +889,7 @@ struct _bsonBuildContext_t { }; /// A pointer to the current thread's bsonBuild context -_bson_thread_local _bson_comdat struct _bsonBuildContext_t - *_bsonBuildContextThreadLocalPtr = NULL; +_bson_thread_local _bson_comdat struct _bsonBuildContext_t *_bsonBuildContextThreadLocalPtr = NULL; struct _bsonVisitContext_t { const bson_t *doc; @@ -986,8 +899,7 @@ struct _bsonVisitContext_t { }; /// A pointer to the current thread's bsonVisit/bsonParse context -_bson_thread_local _bson_comdat struct _bsonVisitContext_t const - *_bsonVisitContextThreadLocalPtr = NULL; +_bson_thread_local _bson_comdat struct _bsonVisitContext_t const *_bsonVisitContextThreadLocalPtr = NULL; /** * @brief The most recent error from a bsonBuild() DSL command. @@ -1010,8 +922,7 @@ _bson_thread_local _bson_comdat const char *bsonBuildError = NULL; */ _bson_thread_local _bson_comdat const char *bsonParseError = NULL; -#define _bsonDSLDebug(...) \ - _bson_dsl_debug (BSON_DSL_DEBUG, __FILE__, __LINE__, BSON_FUNC, __VA_ARGS__) +#define _bsonDSLDebug(...) _bson_dsl_debug (BSON_DSL_DEBUG, __FILE__, __LINE__, BSON_FUNC, __VA_ARGS__) static BSON_INLINE bool @@ -1034,10 +945,7 @@ _bson_dsl_test_strequal (const char *string, bool case_sensitive) } static BSON_INLINE bool -_bson_dsl_key_is_anyof (const char *key, - const size_t keylen, - int case_sensitive, - ...) +_bson_dsl_key_is_anyof (const char *key, const size_t keylen, int case_sensitive, ...) { va_list va; va_start (va, case_sensitive); @@ -1096,12 +1004,7 @@ _bson_dsl_iter_is_last_element (const bson_iter_t *it) _bson_thread_local _bson_comdat int _bson_dsl_indent = 0; static BSON_INLINE void BSON_GNUC_PRINTF (5, 6) - _bson_dsl_debug (bool do_debug, - const char *file, - int line, - const char *func, - const char *string, - ...) + _bson_dsl_debug (bool do_debug, const char *file, int line, const char *func, const char *string, ...) { if (do_debug) { fprintf (stderr, "%s:%d: [%s] bson_dsl: ", file, line, func); @@ -1117,8 +1020,7 @@ static BSON_INLINE void BSON_GNUC_PRINTF (5, 6) } } -static BSON_INLINE char *BSON_GNUC_PRINTF (2, 3) - _bson_dsl_errorf (char **const into, const char *const fmt, ...) +static BSON_INLINE char *BSON_GNUC_PRINTF (2, 3) _bson_dsl_errorf (char **const into, const char *const fmt, ...) { if (*into) { bson_free (*into); @@ -1139,8 +1041,7 @@ _bson_dsl_dupPath (char **into) *into = NULL; } char *acc = bson_strdup (""); - for (const struct _bsonVisitContext_t *ctx = &bsonVisitContext; ctx; - ctx = ctx->parent) { + for (const struct _bsonVisitContext_t *ctx = &bsonVisitContext; ctx; ctx = ctx->parent) { char *prev = acc; if (ctx->parent && BSON_ITER_HOLDS_ARRAY (&ctx->parent->iter)) { // We're an array element @@ -1187,10 +1088,8 @@ _bsonVisitIterAs__Bool (void) // where empty #__VA_ARGS__ just vanishes. #define _bsonDSL_str_1(...) "" #__VA_ARGS__ -#define _bsonDSL_strElide(MaxLen, ...) \ - (strlen (_bsonDSL_str (__VA_ARGS__)) > (MaxLen) \ - ? "[...]" \ - : _bsonDSL_str (__VA_ARGS__)) +#define _bsonDSL_strElide(MaxLen, ...) \ + (strlen (_bsonDSL_str (__VA_ARGS__)) > (MaxLen) ? "[...]" : _bsonDSL_str (__VA_ARGS__)) /// Paste two tokens: #define _bsonDSL_paste(a, ...) _bsonDSL_paste_impl (a, __VA_ARGS__) @@ -1199,8 +1098,7 @@ _bsonVisitIterAs__Bool (void) /// Paste three tokens: #define _bsonDSL_paste3(a, b, c) _bsonDSL_paste (a, _bsonDSL_paste (b, c)) /// Paste four tokens: -#define _bsonDSL_paste4(a, b, c, d) \ - _bsonDSL_paste (a, _bsonDSL_paste3 (b, c, d)) +#define _bsonDSL_paste4(a, b, c, d) _bsonDSL_paste (a, _bsonDSL_paste3 (b, c, d)) // clang-format off diff --git a/src/common/common-b64-private.h b/src/common/common-b64-private.h index 531cfc5f6d..7f5c4e35d7 100644 --- a/src/common/common-b64-private.h +++ b/src/common/common-b64-private.h @@ -21,10 +21,8 @@ #include -#define mcommon_b64_ntop_calculate_target_size \ - COMMON_NAME (b64_ntop_calculate_target_size) -#define mcommon_b64_pton_calculate_target_size \ - COMMON_NAME (b64_pton_calculate_target_size) +#define mcommon_b64_ntop_calculate_target_size COMMON_NAME (b64_ntop_calculate_target_size) +#define mcommon_b64_pton_calculate_target_size COMMON_NAME (b64_pton_calculate_target_size) #define mcommon_b64_ntop COMMON_NAME (b64_ntop) #define mcommon_b64_pton COMMON_NAME (b64_pton) @@ -47,10 +45,7 @@ mcommon_b64_pton_calculate_target_size (size_t base64_encoded_size); * hence the obscure name "ntop". */ int -mcommon_b64_ntop (uint8_t const *src, - size_t srclength, - char *target, - size_t targsize); +mcommon_b64_ntop (uint8_t const *src, size_t srclength, char *target, size_t targsize); /** If target is not NULL, the number of bytes written to target on success or * -1 on error. If target is NULL, returns the exact number of bytes that would diff --git a/src/common/common-b64.c b/src/common/common-b64.c index 71e197f4b6..051ca644a8 100644 --- a/src/common/common-b64.c +++ b/src/common/common-b64.c @@ -47,8 +47,7 @@ if (!(Cond)) \ abort () -static const char Base64[] = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +static const char Base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; static const char Pad64 = '='; /* (From RFC1521 and draft-ietf-dnssec-secext-03.txt) @@ -114,10 +113,7 @@ static const char Pad64 = '='; */ int -mcommon_b64_ntop (uint8_t const *src, - size_t srclength, - char *target, - size_t targsize) +mcommon_b64_ntop (uint8_t const *src, size_t srclength, char *target, size_t targsize) { size_t datalength = 0; uint8_t input[3]; @@ -275,8 +271,7 @@ static const uint8_t mongoc_b64rmap_invalid = 0xff; #define mongoc_common_once_t INIT_ONCE #define MONGOC_COMMON_ONCE_INIT INIT_ONCE_STATIC_INIT #define mongoc_common_once(o, c) InitOnceExecuteOnce (o, c, NULL, NULL) -#define MONGOC_COMMON_ONCE_FUN(n) \ - BOOL CALLBACK n (PINIT_ONCE _ignored_a, PVOID _ignored_b, PVOID *_ignored_c) +#define MONGOC_COMMON_ONCE_FUN(n) BOOL CALLBACK n (PINIT_ONCE _ignored_a, PVOID _ignored_b, PVOID *_ignored_c) #define MONGOC_COMMON_ONCE_RETURN return true #endif diff --git a/src/common/common-md5.c b/src/common/common-md5.c index 865b9b225a..71fa989960 100644 --- a/src/common/common-md5.c +++ b/src/common/common-md5.c @@ -376,10 +376,9 @@ mcommon_md5_append (bson_md5_t *pms, const uint8_t *data, uint32_t nbytes) void mcommon_md5_finish (bson_md5_t *pms, uint8_t digest[16]) { - static const uint8_t pad[64] = { - 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + static const uint8_t pad[64] = {0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; uint8_t data[8]; int i; diff --git a/src/common/common-prelude.h b/src/common/common-prelude.h index 3fbd0cb27d..4f3a5fdd02 100644 --- a/src/common/common-prelude.h +++ b/src/common/common-prelude.h @@ -14,8 +14,7 @@ * limitations under the License. */ -#if !defined(MONGOC_INSIDE) && !defined(MONGOC_COMPILATION) && \ - !defined(BSON_COMPILATION) && !defined(BSON_INSIDE) +#if !defined(MONGOC_INSIDE) && !defined(MONGOC_COMPILATION) && !defined(BSON_COMPILATION) && !defined(BSON_INSIDE) #error "Only or can be included directly." #endif diff --git a/src/common/common-thread-private.h b/src/common/common-thread-private.h index 300bdb506c..291af21a90 100644 --- a/src/common/common-thread-private.h +++ b/src/common/common-thread-private.h @@ -44,8 +44,7 @@ BSON_BEGIN_DECLS } while (0) #define bson_once_t pthread_once_t #define bson_thread_t pthread_t -#define BSON_THREAD_FUN(_function_name, _arg_name) \ - void *(_function_name) (void *(_arg_name)) +#define BSON_THREAD_FUN(_function_name, _arg_name) void *(_function_name) (void *(_arg_name)) #define BSON_THREAD_FUN_TYPE(_function_name) void *(*(_function_name)) (void *) #define BSON_THREAD_RETURN return NULL @@ -114,8 +113,7 @@ typedef struct { #else #include -#define BSON_ONCE_FUN(n) \ - BOOL CALLBACK n (PINIT_ONCE _ignored_a, PVOID _ignored_b, PVOID *_ignored_c) +#define BSON_ONCE_FUN(n) BOOL CALLBACK n (PINIT_ONCE _ignored_a, PVOID _ignored_b, PVOID *_ignored_c) #define BSON_ONCE_INIT INIT_ONCE_STATIC_INIT #define BSON_ONCE_RETURN return true #define bson_mutex_destroy DeleteCriticalSection @@ -129,10 +127,8 @@ typedef struct { } while (0) #define bson_once_t INIT_ONCE #define bson_thread_t HANDLE -#define BSON_THREAD_FUN(_function_name, _arg_name) \ - unsigned (__stdcall _function_name) (void *(_arg_name)) -#define BSON_THREAD_FUN_TYPE(_function_name) \ - unsigned (__stdcall * _function_name) (void *) +#define BSON_THREAD_FUN(_function_name, _arg_name) unsigned (__stdcall _function_name) (void *(_arg_name)) +#define BSON_THREAD_FUN_TYPE(_function_name) unsigned (__stdcall * _function_name) (void *) #define BSON_THREAD_RETURN return 0 #endif @@ -145,9 +141,7 @@ mcommon_thread_join (bson_thread_t thread); // error. Callers may use `bson_strerror_r` to get an error message from the // returned error code. int -mcommon_thread_create (bson_thread_t *thread, - BSON_THREAD_FUN_TYPE (func), - void *arg); +mcommon_thread_create (bson_thread_t *thread, BSON_THREAD_FUN_TYPE (func), void *arg); #if defined(MONGOC_ENABLE_DEBUG_ASSERTIONS) && defined(BSON_OS_UNIX) #define mcommon_mutex_is_locked COMMON_NAME (mutex_is_locked) diff --git a/src/common/common-thread.c b/src/common/common-thread.c index 037a6490b6..9b26f6e956 100644 --- a/src/common/common-thread.c +++ b/src/common/common-thread.c @@ -20,9 +20,7 @@ #if defined(BSON_OS_UNIX) int -mcommon_thread_create (bson_thread_t *thread, - BSON_THREAD_FUN_TYPE (func), - void *arg) +mcommon_thread_create (bson_thread_t *thread, BSON_THREAD_FUN_TYPE (func), void *arg) { BSON_ASSERT_PARAM (thread); BSON_ASSERT_PARAM (func); @@ -39,16 +37,13 @@ mcommon_thread_join (bson_thread_t thread) bool mcommon_mutex_is_locked (bson_mutex_t *mutex) { - return mutex->valid_tid && - pthread_equal (pthread_self (), mutex->lock_owner); + return mutex->valid_tid && pthread_equal (pthread_self (), mutex->lock_owner); } #endif #else int -mcommon_thread_create (bson_thread_t *thread, - BSON_THREAD_FUN_TYPE (func), - void *arg) +mcommon_thread_create (bson_thread_t *thread, BSON_THREAD_FUN_TYPE (func), void *arg) { BSON_ASSERT_PARAM (thread); BSON_ASSERT_PARAM (func); diff --git a/src/libbson/examples/bcon-col-view.c b/src/libbson/examples/bcon-col-view.c index 39f34f5e9f..281f6747b0 100644 --- a/src/libbson/examples/bcon-col-view.c +++ b/src/libbson/examples/bcon-col-view.c @@ -82,8 +82,7 @@ main (void) bson_t *bson; char *json; - bson = COL_VIEW_CREATE ( - SORT ("a", BCON_INT32 (1)), QUERY ("hello", "world"), LIMIT (10)); + bson = COL_VIEW_CREATE (SORT ("a", BCON_INT32 (1)), QUERY ("hello", "world"), LIMIT (10)); json = bson_as_canonical_extended_json (bson, NULL); printf ("%s\n", json); diff --git a/src/libbson/examples/bcon-speed.c b/src/libbson/examples/bcon-speed.c index ffb6df02ad..12a5ce6ee7 100644 --- a/src/libbson/examples/bcon-speed.c +++ b/src/libbson/examples/bcon-speed.c @@ -58,19 +58,8 @@ main (int argc, char *argv[]) for (i = 0; i < n; i++) { if (bcon) { - BCON_APPEND (&bson, - "foo", - "{", - "bar", - "{", - "baz", - "[", - BCON_INT32 (1), - BCON_INT32 (2), - BCON_INT32 (3), - "]", - "}", - "}"); + BCON_APPEND ( + &bson, "foo", "{", "bar", "{", "baz", "[", BCON_INT32 (1), BCON_INT32 (2), BCON_INT32 (3), "]", "}", "}"); } else { bson_append_document_begin (&bson, "foo", -1, &foo); bson_append_document_begin (&foo, "bar", -1, &bar); diff --git a/src/libbson/examples/bson-check-depth.c b/src/libbson/examples/bson-check-depth.c index 032001a32d..7de3a47641 100644 --- a/src/libbson/examples/bson-check-depth.c +++ b/src/libbson/examples/bson-check-depth.c @@ -30,10 +30,7 @@ typedef struct { } check_depth_t; bool -_check_depth_document (const bson_iter_t *iter, - const char *key, - const bson_t *v_document, - void *data); +_check_depth_document (const bson_iter_t *iter, const char *key, const bson_t *v_document, void *data); static const bson_visitor_t check_depth_funcs = { NULL, @@ -47,10 +44,7 @@ static const bson_visitor_t check_depth_funcs = { }; bool -_check_depth_document (const bson_iter_t *iter, - const char *key, - const bson_t *v_document, - void *data) +_check_depth_document (const bson_iter_t *iter, const char *key, const bson_t *v_document, void *data) { check_depth_t *state = (check_depth_t *) data; bson_iter_t child; @@ -88,8 +82,7 @@ check_depth (const bson_t *bson, uint32_t max_depth) state.max_depth = max_depth; _check_depth_document (&iter, NULL, bson, &state); if (!state.valid) { - printf ("document exceeds maximum depth of %" PRIu32 "\n", - state.max_depth); + printf ("document exceeds maximum depth of %" PRIu32 "\n", state.max_depth); } else { char *as_json = bson_as_canonical_extended_json (bson, NULL); printf ("document %s ", as_json); diff --git a/src/libbson/examples/bson-metrics.c b/src/libbson/examples/bson-metrics.c index 2cd4acd6dc..ac873863be 100644 --- a/src/libbson/examples/bson-metrics.c +++ b/src/libbson/examples/bson-metrics.c @@ -48,33 +48,32 @@ typedef struct { bson_type_metrics_t bson_type_metrics[256]; } bson_metrics_state_t; -static bson_metrics_state_t initial_state = { - 0L, - 0L, - 0L, - 0L, - 0L, - 0L, - {{/* BSON_TYPE_EOD = 0x00 */ 0L, "End of document"}, - {/* BSON_TYPE_DOUBLE = 0x01 */ 0L, "Floating point"}, - {/* BSON_TYPE_UTF8 = 0x02 */ 0L, "UTF-8 string"}, - {/* BSON_TYPE_DOCUMENT = 0x03 */ 0L, "Embedded document"}, - {/* BSON_TYPE_ARRAY = 0x04 */ 0L, "Array"}, - {/* BSON_TYPE_BINARY = 0x05 */ 0L, "Binary data"}, - {/* BSON_TYPE_UNDEFINED = 0x06 */ 0L, "Undefined - Deprecated"}, - {/* BSON_TYPE_OID = 0x07 */ 0L, "ObjectId"}, - {/* BSON_TYPE_BOOL = 0x08 */ 0L, "Boolean"}, - {/* BSON_TYPE_DATE_TIME = 0x09 */ 0L, "UTC datetime"}, - {/* BSON_TYPE_NULL = 0x0A */ 0L, "Null value"}, - {/* BSON_TYPE_REGEX = 0x0B */ 0L, "Regular expression"}, - {/* BSON_TYPE_DBPOINTER = 0x0C */ 0L, "DBPointer - Deprecated"}, - {/* BSON_TYPE_CODE = 0x0D */ 0L, "JavaScript code"}, - {/* BSON_TYPE_SYMBOL = 0x0E */ 0L, "Symbol - Deprecated"}, - {/* BSON_TYPE_CODEWSCOPE = 0x0F */ 0L, "JavaScript code w/ scope"}, - {/* BSON_TYPE_INT32 = 0x10 */ 0L, "32-bit Integer"}, - {/* BSON_TYPE_TIMESTAMP = 0x11 */ 0L, "Timestamp"}, - {/* BSON_TYPE_INT64 = 0x12 */ 0L, "64-bit Integer"}, - {0L, NULL}}}; +static bson_metrics_state_t initial_state = {0L, + 0L, + 0L, + 0L, + 0L, + 0L, + {{/* BSON_TYPE_EOD = 0x00 */ 0L, "End of document"}, + {/* BSON_TYPE_DOUBLE = 0x01 */ 0L, "Floating point"}, + {/* BSON_TYPE_UTF8 = 0x02 */ 0L, "UTF-8 string"}, + {/* BSON_TYPE_DOCUMENT = 0x03 */ 0L, "Embedded document"}, + {/* BSON_TYPE_ARRAY = 0x04 */ 0L, "Array"}, + {/* BSON_TYPE_BINARY = 0x05 */ 0L, "Binary data"}, + {/* BSON_TYPE_UNDEFINED = 0x06 */ 0L, "Undefined - Deprecated"}, + {/* BSON_TYPE_OID = 0x07 */ 0L, "ObjectId"}, + {/* BSON_TYPE_BOOL = 0x08 */ 0L, "Boolean"}, + {/* BSON_TYPE_DATE_TIME = 0x09 */ 0L, "UTC datetime"}, + {/* BSON_TYPE_NULL = 0x0A */ 0L, "Null value"}, + {/* BSON_TYPE_REGEX = 0x0B */ 0L, "Regular expression"}, + {/* BSON_TYPE_DBPOINTER = 0x0C */ 0L, "DBPointer - Deprecated"}, + {/* BSON_TYPE_CODE = 0x0D */ 0L, "JavaScript code"}, + {/* BSON_TYPE_SYMBOL = 0x0E */ 0L, "Symbol - Deprecated"}, + {/* BSON_TYPE_CODEWSCOPE = 0x0F */ 0L, "JavaScript code w/ scope"}, + {/* BSON_TYPE_INT32 = 0x10 */ 0L, "32-bit Integer"}, + {/* BSON_TYPE_TIMESTAMP = 0x11 */ 0L, "Timestamp"}, + {/* BSON_TYPE_INT64 = 0x12 */ 0L, "64-bit Integer"}, + {0L, NULL}}}; static bson_metrics_state_t state; @@ -93,22 +92,12 @@ compar_bson_type_metrics (const void *a, const void *b) * Forward declarations. */ static bool -bson_metrics_visit_array (const bson_iter_t *iter, - const char *key, - const bson_t *v_array, - void *data); +bson_metrics_visit_array (const bson_iter_t *iter, const char *key, const bson_t *v_array, void *data); static bool -bson_metrics_visit_document (const bson_iter_t *iter, - const char *key, - const bson_t *v_document, - void *data); +bson_metrics_visit_document (const bson_iter_t *iter, const char *key, const bson_t *v_document, void *data); static bool -bson_metrics_visit_utf8 (const bson_iter_t *iter, - const char *key, - size_t v_utf8_len, - const char *v_utf8, - void *data) +bson_metrics_visit_utf8 (const bson_iter_t *iter, const char *key, size_t v_utf8_len, const char *v_utf8, void *data) { bson_metrics_state_t *s = data; @@ -161,10 +150,7 @@ static const bson_visitor_t bson_metrics_visitors = { }; static bool -bson_metrics_visit_document (const bson_iter_t *iter, - const char *key, - const bson_t *v_document, - void *data) +bson_metrics_visit_document (const bson_iter_t *iter, const char *key, const bson_t *v_document, void *data) { bson_metrics_state_t *s = data; bson_iter_t child; @@ -187,10 +173,7 @@ bson_metrics_visit_document (const bson_iter_t *iter, } static bool -bson_metrics_visit_array (const bson_iter_t *iter, - const char *key, - const bson_t *v_array, - void *data) +bson_metrics_visit_array (const bson_iter_t *iter, const char *key, const bson_t *v_array, void *data) { bson_metrics_state_t *s = data; bson_iter_t child; @@ -260,8 +243,7 @@ main (int argc, char *argv[]) * Initialize a new reader for this file descriptor. */ if (!(reader = bson_reader_new_from_file (filename, &error))) { - fprintf ( - stderr, "Failed to open \"%s\": %s\n", filename, error.message); + fprintf (stderr, "Failed to open \"%s\": %s\n", filename, error.message); continue; } @@ -278,50 +260,39 @@ main (int argc, char *argv[]) dtime_delta = BSON_MAX (dtime_after - dtime_before, 0.000001); state.bson_type_metrics[BSON_TYPE_MAXKEY].description = "Max key"; state.bson_type_metrics[BSON_TYPE_MINKEY].description = "Min key"; - aggregate_count = state.bson_type_metrics[BSON_TYPE_DOCUMENT].count + - state.bson_type_metrics[BSON_TYPE_ARRAY].count; - qsort (state.bson_type_metrics, - 256, - sizeof (bson_type_metrics_t), - compar_bson_type_metrics); + aggregate_count = + state.bson_type_metrics[BSON_TYPE_DOCUMENT].count + state.bson_type_metrics[BSON_TYPE_ARRAY].count; + qsort (state.bson_type_metrics, 256, sizeof (bson_type_metrics_t), compar_bson_type_metrics); printf ("\n {\n"); printf (" \"file\": \"%s\",\n", filename); printf (" \"secs\": %.2f,\n", dtime_delta); - printf (" \"docs_per_sec\": %" PRIu64 ",\n", - (uint64_t) floor (state.doc_count / dtime_delta)); + printf (" \"docs_per_sec\": %" PRIu64 ",\n", (uint64_t) floor (state.doc_count / dtime_delta)); printf (" \"docs\": %" PRIu64 ",\n", state.doc_count); printf (" \"elements\": %" PRIu64 ",\n", state.element_count); printf (" \"elements_per_doc\": %" PRIu64 ",\n", - (uint64_t) floor ((double) state.element_count / - (double) BSON_MAX (state.doc_count, 1))); + (uint64_t) floor ((double) state.element_count / (double) BSON_MAX (state.doc_count, 1))); printf (" \"aggregates\": %" PRIu64 ",\n", aggregate_count); printf (" \"aggregates_per_doc\": %" PRIu64 ",\n", - (uint64_t) floor ((double) aggregate_count / - (double) BSON_MAX (state.doc_count, 1))); - printf (" \"degree\": %" PRIu64 ",\n", - (uint64_t) floor ( - (double) state.element_count / - ((double) BSON_MAX (state.doc_count + aggregate_count, 1)))); + (uint64_t) floor ((double) aggregate_count / (double) BSON_MAX (state.doc_count, 1))); + printf ( + " \"degree\": %" PRIu64 ",\n", + (uint64_t) floor ((double) state.element_count / ((double) BSON_MAX (state.doc_count + aggregate_count, 1)))); printf (" \"doc_size_max\": %" PRIu64 ",\n", state.doc_size_max); printf (" \"doc_size_average\": %" PRIu64 ",\n", - (uint64_t) floor ((double) bson_reader_tell (reader) / - (double) BSON_MAX (state.doc_count, 1))); + (uint64_t) floor ((double) bson_reader_tell (reader) / (double) BSON_MAX (state.doc_count, 1))); printf (" \"key_size_average\": %" PRIu64 ",\n", - (uint64_t) floor ((double) state.key_size_tally / - (double) BSON_MAX (state.element_count, 1))); + (uint64_t) floor ((double) state.key_size_tally / (double) BSON_MAX (state.element_count, 1))); printf (" \"string_size_average\": %" PRIu64 ",\n", - (uint64_t) floor ( - (double) state.utf8_size_tally / - (double) BSON_MAX ( - state.bson_type_metrics[BSON_TYPE_UTF8].count, 1))); + (uint64_t) floor ((double) state.utf8_size_tally / + (double) BSON_MAX (state.bson_type_metrics[BSON_TYPE_UTF8].count, 1))); printf (" \"percent_by_type\": {\n"); for (j = 0; state.bson_type_metrics[j].count > 0; j++) { bson_type_metrics_t bson_type_metrics = state.bson_type_metrics[j]; - printf (" \"%s\": %" PRIu64 ",\n", - bson_type_metrics.description, - (uint64_t) floor ((double) bson_type_metrics.count * 100.0 / - (double) BSON_MAX (state.element_count, 1))); + printf ( + " \"%s\": %" PRIu64 ",\n", + bson_type_metrics.description, + (uint64_t) floor ((double) bson_type_metrics.count * 100.0 / (double) BSON_MAX (state.element_count, 1))); } printf (" }\n"); printf (" }"); diff --git a/src/libbson/examples/bson-streaming-reader.c b/src/libbson/examples/bson-streaming-reader.c index e9d5f9566b..a446b2ec8b 100644 --- a/src/libbson/examples/bson-streaming-reader.c +++ b/src/libbson/examples/bson-streaming-reader.c @@ -64,16 +64,13 @@ bson_streaming_remote_open (const char *hostname, const char *port) hints.ai_family = PF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; - error = - getaddrinfo ((!hostname || !strlen (hostname)) ? DEFAULT_HOST : hostname, - (!port || !strlen (port)) ? DEFAULT_PORT : port, - &hints, - &server_list); + error = getaddrinfo ((!hostname || !strlen (hostname)) ? DEFAULT_HOST : hostname, + (!port || !strlen (port)) ? DEFAULT_PORT : port, + &hints, + &server_list); if (error) { - fprintf (stderr, - "bson-streaming-remote-open: Failed to get server info: %s\n", - gai_strerror (error)); + fprintf (stderr, "bson-streaming-remote-open: Failed to get server info: %s\n", gai_strerror (error)); return -1; } @@ -103,8 +100,7 @@ bson_streaming_remote_open (const char *hostname, const char *port) freeaddrinfo (server_list); if (ptr == NULL) { - fprintf (stderr, - "bson-streaming-remote-open: failed to connect to server\n"); + fprintf (stderr, "bson-streaming-remote-open: failed to connect to server\n"); return -1; } @@ -141,8 +137,7 @@ main (int argc, char *argv[]) while ((opt = getopt (argc, argv, "hs:p:")) != -1) { switch (opt) { case 'h': - fprintf ( - stdout, "Usage: %s [-s SERVER_NAME] [-p PORT_NUM]\n", argv[0]); + fprintf (stdout, "Usage: %s [-s SERVER_NAME] [-p PORT_NUM]\n", argv[0]); bson_free (hostname); bson_free (port); return EXIT_SUCCESS; diff --git a/src/libbson/examples/bson-to-json.c b/src/libbson/examples/bson-to-json.c index e4e7139ac2..a889a1c34e 100644 --- a/src/libbson/examples/bson-to-json.c +++ b/src/libbson/examples/bson-to-json.c @@ -56,8 +56,7 @@ main (int argc, char *argv[]) reader = bson_reader_new_from_fd (STDIN_FILENO, false); } else { if (!(reader = bson_reader_new_from_file (filename, &error))) { - fprintf ( - stderr, "Failed to open \"%s\": %s\n", filename, error.message); + fprintf (stderr, "Failed to open \"%s\": %s\n", filename, error.message); continue; } } diff --git a/src/libbson/examples/bson-validate.c b/src/libbson/examples/bson-validate.c index baeb4e7e72..3853a8892b 100644 --- a/src/libbson/examples/bson-validate.c +++ b/src/libbson/examples/bson-validate.c @@ -63,8 +63,7 @@ main (int argc, char *argv[]) * Initialize a new reader for this file descriptor. */ if (!(reader = bson_reader_new_from_file (filename, &error))) { - fprintf ( - stderr, "Failed to open \"%s\": %s\n", filename, error.message); + fprintf (stderr, "Failed to open \"%s\": %s\n", filename, error.message); continue; } @@ -73,15 +72,8 @@ main (int argc, char *argv[]) */ while ((b = bson_reader_read (reader, NULL))) { docnum++; - if (!bson_validate ( - b, - (BSON_VALIDATE_UTF8 | BSON_VALIDATE_UTF8_ALLOW_NULL), - &offset)) { - fprintf (stderr, - "Document %u in \"%s\" is invalid at offset %u.\n", - docnum, - filename, - (int) offset); + if (!bson_validate (b, (BSON_VALIDATE_UTF8 | BSON_VALIDATE_UTF8_ALLOW_NULL), &offset)) { + fprintf (stderr, "Document %u in \"%s\" is invalid at offset %u.\n", docnum, filename, (int) offset); bson_reader_destroy (reader); return 1; } diff --git a/src/libbson/examples/json-to-bson.c b/src/libbson/examples/json-to-bson.c index 7339d2d2c9..032a6d94f1 100644 --- a/src/libbson/examples/json-to-bson.c +++ b/src/libbson/examples/json-to-bson.c @@ -61,8 +61,7 @@ main (int argc, char *argv[]) reader = bson_json_reader_new_from_fd (STDIN_FILENO, false); } else { if (!(reader = bson_json_reader_new_from_file (filename, &error))) { - fprintf ( - stderr, "Failed to open \"%s\": %s\n", filename, error.message); + fprintf (stderr, "Failed to open \"%s\": %s\n", filename, error.message); continue; } } diff --git a/src/libbson/src/bson/bcon.c b/src/libbson/src/bson/bcon.c index 53ae80fe9e..0779d89a96 100644 --- a/src/libbson/src/bson/bcon.c +++ b/src/libbson/src/bson/bcon.c @@ -31,11 +31,9 @@ #define STACK_ELE(_delta, _name) (ctx->stack[(_delta) + ctx->n]._name) -#define STACK_BSON(_delta) \ - (((_delta) + ctx->n) == 0 ? bson : &STACK_ELE (_delta, bson)) +#define STACK_BSON(_delta) (((_delta) + ctx->n) == 0 ? bson : &STACK_ELE (_delta, bson)) -#define STACK_ITER(_delta) \ - (((_delta) + ctx->n) == 0 ? &root_iter : &STACK_ELE (_delta, iter)) +#define STACK_ITER(_delta) (((_delta) + ctx->n) == 0 ? &root_iter : &STACK_ELE (_delta, iter)) #define STACK_BSON_PARENT STACK_BSON (-1) #define STACK_BSON_CHILD STACK_BSON (0) @@ -205,10 +203,7 @@ _noop (void) /* appends val to the passed bson object. Meant to be a super simple dispatch * table */ static void -_bcon_append_single (bson_t *bson, - bcon_type_t type, - const char *key, - bcon_append_t *val) +_bcon_append_single (bson_t *bson, bcon_type_t type, const char *key, bcon_append_t *val) { switch ((int) type) { case BCON_TYPE_UTF8: @@ -218,8 +213,7 @@ _bcon_append_single (bson_t *bson, BSON_ASSERT (bson_append_double (bson, key, -1, val->DOUBLE)); break; case BCON_TYPE_BIN: { - BSON_ASSERT (bson_append_binary ( - bson, key, -1, val->BIN.subtype, val->BIN.binary, val->BIN.length)); + BSON_ASSERT (bson_append_binary (bson, key, -1, val->BIN.subtype, val->BIN.binary, val->BIN.length)); break; } case BCON_TYPE_UNDEFINED: @@ -238,13 +232,11 @@ _bcon_append_single (bson_t *bson, BSON_ASSERT (bson_append_null (bson, key, -1)); break; case BCON_TYPE_REGEX: { - BSON_ASSERT ( - bson_append_regex (bson, key, -1, val->REGEX.regex, val->REGEX.flags)); + BSON_ASSERT (bson_append_regex (bson, key, -1, val->REGEX.regex, val->REGEX.flags)); break; } case BCON_TYPE_DBPOINTER: { - BSON_ASSERT (bson_append_dbpointer ( - bson, key, -1, val->DBPOINTER.collection, val->DBPOINTER.oid)); + BSON_ASSERT (bson_append_dbpointer (bson, key, -1, val->DBPOINTER.collection, val->DBPOINTER.oid)); break; } case BCON_TYPE_CODE: @@ -254,15 +246,13 @@ _bcon_append_single (bson_t *bson, BSON_ASSERT (bson_append_symbol (bson, key, -1, val->SYMBOL, -1)); break; case BCON_TYPE_CODEWSCOPE: - BSON_ASSERT (bson_append_code_with_scope ( - bson, key, -1, val->CODEWSCOPE.js, val->CODEWSCOPE.scope)); + BSON_ASSERT (bson_append_code_with_scope (bson, key, -1, val->CODEWSCOPE.js, val->CODEWSCOPE.scope)); break; case BCON_TYPE_INT32: BSON_ASSERT (bson_append_int32 (bson, key, -1, val->INT32)); break; case BCON_TYPE_TIMESTAMP: { - BSON_ASSERT (bson_append_timestamp ( - bson, key, -1, val->TIMESTAMP.timestamp, val->TIMESTAMP.increment)); + BSON_ASSERT (bson_append_timestamp (bson, key, -1, val->TIMESTAMP.timestamp, val->TIMESTAMP.increment)); break; } case BCON_TYPE_INT64: @@ -315,9 +305,7 @@ _bcon_append_single (bson_t *bson, * procedural verification (if a parameter could have multiple types). * */ static bool -_bcon_extract_single (const bson_iter_t *iter, - bcon_type_t type, - bcon_extract_t *val) +_bcon_extract_single (const bson_iter_t *iter, bcon_type_t type, bcon_extract_t *val) { switch ((int) type) { case BCON_TYPE_UTF8: @@ -330,8 +318,7 @@ _bcon_extract_single (const bson_iter_t *iter, break; case BCON_TYPE_BIN: CHECK_TYPE (BSON_TYPE_BINARY); - bson_iter_binary ( - iter, val->BIN.subtype, val->BIN.length, val->BIN.binary); + bson_iter_binary (iter, val->BIN.subtype, val->BIN.length, val->BIN.binary); break; case BCON_TYPE_UNDEFINED: CHECK_TYPE (BSON_TYPE_UNDEFINED); @@ -358,8 +345,7 @@ _bcon_extract_single (const bson_iter_t *iter, break; case BCON_TYPE_DBPOINTER: CHECK_TYPE (BSON_TYPE_DBPOINTER); - bson_iter_dbpointer ( - iter, NULL, val->DBPOINTER.collection, val->DBPOINTER.oid); + bson_iter_dbpointer (iter, NULL, val->DBPOINTER.collection, val->DBPOINTER.oid); break; case BCON_TYPE_CODE: CHECK_TYPE (BSON_TYPE_CODE); @@ -386,8 +372,7 @@ _bcon_extract_single (const bson_iter_t *iter, break; case BCON_TYPE_TIMESTAMP: CHECK_TYPE (BSON_TYPE_TIMESTAMP); - bson_iter_timestamp ( - iter, val->TIMESTAMP.timestamp, val->TIMESTAMP.increment); + bson_iter_timestamp (iter, val->TIMESTAMP.timestamp, val->TIMESTAMP.increment); break; case BCON_TYPE_INT64: CHECK_TYPE (BSON_TYPE_INT64); @@ -772,8 +757,7 @@ bcon_append_ctx_va (bson_t *bson, bcon_append_ctx_t *ctx, va_list *ap) } if (type == BCON_TYPE_DOC_END) { - STACK_POP_DOC ( - bson_append_document_end (STACK_BSON_PARENT, STACK_BSON_CHILD)); + STACK_POP_DOC (bson_append_document_end (STACK_BSON_PARENT, STACK_BSON_CHILD)); continue; } @@ -797,20 +781,16 @@ bcon_append_ctx_va (bson_t *bson, bcon_append_ctx_t *ctx, va_list *ap) break; case BCON_TYPE_DOC_START: - STACK_PUSH_DOC (bson_append_document_begin ( - STACK_BSON_PARENT, key, -1, STACK_BSON_CHILD)); + STACK_PUSH_DOC (bson_append_document_begin (STACK_BSON_PARENT, key, -1, STACK_BSON_CHILD)); break; case BCON_TYPE_DOC_END: - STACK_POP_DOC ( - bson_append_document_end (STACK_BSON_PARENT, STACK_BSON_CHILD)); + STACK_POP_DOC (bson_append_document_end (STACK_BSON_PARENT, STACK_BSON_CHILD)); break; case BCON_TYPE_ARRAY_START: - STACK_PUSH_ARRAY (bson_append_array_begin ( - STACK_BSON_PARENT, key, -1, STACK_BSON_CHILD)); + STACK_PUSH_ARRAY (bson_append_array_begin (STACK_BSON_PARENT, key, -1, STACK_BSON_CHILD)); break; case BCON_TYPE_ARRAY_END: - STACK_POP_ARRAY ( - bson_append_array_end (STACK_BSON_PARENT, STACK_BSON_CHILD)); + STACK_POP_ARRAY (bson_append_array_end (STACK_BSON_PARENT, STACK_BSON_CHILD)); break; default: _bcon_append_single (STACK_BSON_CHILD, type, key, &u); @@ -897,8 +877,7 @@ bcon_extract_ctx_va (bson_t *bson, bcon_extract_ctx_t *ctx, va_list *ap) return false; } - STACK_PUSH_DOC ( - bson_iter_recurse (¤t_iter, STACK_ITER_CHILD)); + STACK_PUSH_DOC (bson_iter_recurse (¤t_iter, STACK_ITER_CHILD)); break; case BCON_TYPE_ARRAY_START: @@ -906,8 +885,7 @@ bcon_extract_ctx_va (bson_t *bson, bcon_extract_ctx_t *ctx, va_list *ap) return false; } - STACK_PUSH_ARRAY ( - bson_iter_recurse (¤t_iter, STACK_ITER_CHILD)); + STACK_PUSH_ARRAY (bson_iter_recurse (¤t_iter, STACK_ITER_CHILD)); break; default: diff --git a/src/libbson/src/bson/bcon.h b/src/libbson/src/bson/bcon.h index 80b5a489bc..d35365e6e6 100644 --- a/src/libbson/src/bson/bcon.h +++ b/src/libbson/src/bson/bcon.h @@ -66,109 +66,69 @@ BCON_ENSURE_DECLARE (bson_type, bson_type_t) BCON_ENSURE_DECLARE (bson_iter_ptr, bson_iter_t *) BCON_ENSURE_DECLARE (const_bson_iter_ptr, const bson_iter_t *) -#define BCON_UTF8(_val) \ - BCON_MAGIC, BCON_TYPE_UTF8, BCON_ENSURE (const_char_ptr, (_val)) -#define BCON_DOUBLE(_val) \ - BCON_MAGIC, BCON_TYPE_DOUBLE, BCON_ENSURE (double, (_val)) -#define BCON_DOCUMENT(_val) \ - BCON_MAGIC, BCON_TYPE_DOCUMENT, BCON_ENSURE (const_bson_ptr, (_val)) -#define BCON_ARRAY(_val) \ - BCON_MAGIC, BCON_TYPE_ARRAY, BCON_ENSURE (const_bson_ptr, (_val)) -#define BCON_BIN(_subtype, _binary, _length) \ - BCON_MAGIC, BCON_TYPE_BIN, BCON_ENSURE (subtype, (_subtype)), \ - BCON_ENSURE (const_uint8_ptr, (_binary)), \ +#define BCON_UTF8(_val) BCON_MAGIC, BCON_TYPE_UTF8, BCON_ENSURE (const_char_ptr, (_val)) +#define BCON_DOUBLE(_val) BCON_MAGIC, BCON_TYPE_DOUBLE, BCON_ENSURE (double, (_val)) +#define BCON_DOCUMENT(_val) BCON_MAGIC, BCON_TYPE_DOCUMENT, BCON_ENSURE (const_bson_ptr, (_val)) +#define BCON_ARRAY(_val) BCON_MAGIC, BCON_TYPE_ARRAY, BCON_ENSURE (const_bson_ptr, (_val)) +#define BCON_BIN(_subtype, _binary, _length) \ + BCON_MAGIC, BCON_TYPE_BIN, BCON_ENSURE (subtype, (_subtype)), BCON_ENSURE (const_uint8_ptr, (_binary)), \ BCON_ENSURE (uint32, (_length)) #define BCON_UNDEFINED BCON_MAGIC, BCON_TYPE_UNDEFINED -#define BCON_OID(_val) \ - BCON_MAGIC, BCON_TYPE_OID, BCON_ENSURE (const_oid_ptr, (_val)) +#define BCON_OID(_val) BCON_MAGIC, BCON_TYPE_OID, BCON_ENSURE (const_oid_ptr, (_val)) #define BCON_BOOL(_val) BCON_MAGIC, BCON_TYPE_BOOL, BCON_ENSURE (bool, (_val)) -#define BCON_DATE_TIME(_val) \ - BCON_MAGIC, BCON_TYPE_DATE_TIME, BCON_ENSURE (int64, (_val)) +#define BCON_DATE_TIME(_val) BCON_MAGIC, BCON_TYPE_DATE_TIME, BCON_ENSURE (int64, (_val)) #define BCON_NULL BCON_MAGIC, BCON_TYPE_NULL -#define BCON_REGEX(_regex, _flags) \ - BCON_MAGIC, BCON_TYPE_REGEX, BCON_ENSURE (const_char_ptr, (_regex)), \ - BCON_ENSURE (const_char_ptr, (_flags)) -#define BCON_DBPOINTER(_collection, _oid) \ - BCON_MAGIC, BCON_TYPE_DBPOINTER, \ - BCON_ENSURE (const_char_ptr, (_collection)), \ - BCON_ENSURE (const_oid_ptr, (_oid)) -#define BCON_CODE(_val) \ - BCON_MAGIC, BCON_TYPE_CODE, BCON_ENSURE (const_char_ptr, (_val)) -#define BCON_SYMBOL(_val) \ - BCON_MAGIC, BCON_TYPE_SYMBOL, BCON_ENSURE (const_char_ptr, (_val)) -#define BCON_CODEWSCOPE(_js, _scope) \ - BCON_MAGIC, BCON_TYPE_CODEWSCOPE, BCON_ENSURE (const_char_ptr, (_js)), \ - BCON_ENSURE (const_bson_ptr, (_scope)) -#define BCON_INT32(_val) \ - BCON_MAGIC, BCON_TYPE_INT32, BCON_ENSURE (int32, (_val)) -#define BCON_TIMESTAMP(_timestamp, _increment) \ - BCON_MAGIC, BCON_TYPE_TIMESTAMP, BCON_ENSURE (int32, (_timestamp)), \ - BCON_ENSURE (int32, (_increment)) -#define BCON_INT64(_val) \ - BCON_MAGIC, BCON_TYPE_INT64, BCON_ENSURE (int64, (_val)) -#define BCON_DECIMAL128(_val) \ - BCON_MAGIC, BCON_TYPE_DECIMAL128, BCON_ENSURE (const_decimal128_ptr, (_val)) +#define BCON_REGEX(_regex, _flags) \ + BCON_MAGIC, BCON_TYPE_REGEX, BCON_ENSURE (const_char_ptr, (_regex)), BCON_ENSURE (const_char_ptr, (_flags)) +#define BCON_DBPOINTER(_collection, _oid) \ + BCON_MAGIC, BCON_TYPE_DBPOINTER, BCON_ENSURE (const_char_ptr, (_collection)), BCON_ENSURE (const_oid_ptr, (_oid)) +#define BCON_CODE(_val) BCON_MAGIC, BCON_TYPE_CODE, BCON_ENSURE (const_char_ptr, (_val)) +#define BCON_SYMBOL(_val) BCON_MAGIC, BCON_TYPE_SYMBOL, BCON_ENSURE (const_char_ptr, (_val)) +#define BCON_CODEWSCOPE(_js, _scope) \ + BCON_MAGIC, BCON_TYPE_CODEWSCOPE, BCON_ENSURE (const_char_ptr, (_js)), BCON_ENSURE (const_bson_ptr, (_scope)) +#define BCON_INT32(_val) BCON_MAGIC, BCON_TYPE_INT32, BCON_ENSURE (int32, (_val)) +#define BCON_TIMESTAMP(_timestamp, _increment) \ + BCON_MAGIC, BCON_TYPE_TIMESTAMP, BCON_ENSURE (int32, (_timestamp)), BCON_ENSURE (int32, (_increment)) +#define BCON_INT64(_val) BCON_MAGIC, BCON_TYPE_INT64, BCON_ENSURE (int64, (_val)) +#define BCON_DECIMAL128(_val) BCON_MAGIC, BCON_TYPE_DECIMAL128, BCON_ENSURE (const_decimal128_ptr, (_val)) #define BCON_MAXKEY BCON_MAGIC, BCON_TYPE_MAXKEY #define BCON_MINKEY BCON_MAGIC, BCON_TYPE_MINKEY -#define BCON(_val) \ - BCON_MAGIC, BCON_TYPE_BCON, BCON_ENSURE (const_bson_ptr, (_val)) -#define BCON_ITER(_val) \ - BCON_MAGIC, BCON_TYPE_ITER, BCON_ENSURE (const_bson_iter_ptr, (_val)) - -#define BCONE_UTF8(_val) \ - BCONE_MAGIC, BCON_TYPE_UTF8, BCON_ENSURE_STORAGE (const_char_ptr_ptr, (_val)) -#define BCONE_DOUBLE(_val) \ - BCONE_MAGIC, BCON_TYPE_DOUBLE, BCON_ENSURE_STORAGE (double_ptr, (_val)) -#define BCONE_DOCUMENT(_val) \ - BCONE_MAGIC, BCON_TYPE_DOCUMENT, BCON_ENSURE_STORAGE (bson_ptr, (_val)) -#define BCONE_ARRAY(_val) \ - BCONE_MAGIC, BCON_TYPE_ARRAY, BCON_ENSURE_STORAGE (bson_ptr, (_val)) +#define BCON(_val) BCON_MAGIC, BCON_TYPE_BCON, BCON_ENSURE (const_bson_ptr, (_val)) +#define BCON_ITER(_val) BCON_MAGIC, BCON_TYPE_ITER, BCON_ENSURE (const_bson_iter_ptr, (_val)) + +#define BCONE_UTF8(_val) BCONE_MAGIC, BCON_TYPE_UTF8, BCON_ENSURE_STORAGE (const_char_ptr_ptr, (_val)) +#define BCONE_DOUBLE(_val) BCONE_MAGIC, BCON_TYPE_DOUBLE, BCON_ENSURE_STORAGE (double_ptr, (_val)) +#define BCONE_DOCUMENT(_val) BCONE_MAGIC, BCON_TYPE_DOCUMENT, BCON_ENSURE_STORAGE (bson_ptr, (_val)) +#define BCONE_ARRAY(_val) BCONE_MAGIC, BCON_TYPE_ARRAY, BCON_ENSURE_STORAGE (bson_ptr, (_val)) #define BCONE_BIN(subtype, binary, length) \ BCONE_MAGIC, BCON_TYPE_BIN, BCON_ENSURE_STORAGE (subtype_ptr, (subtype)), \ - BCON_ENSURE_STORAGE (const_uint8_ptr_ptr, (binary)), \ - BCON_ENSURE_STORAGE (uint32_ptr, (length)) + BCON_ENSURE_STORAGE (const_uint8_ptr_ptr, (binary)), BCON_ENSURE_STORAGE (uint32_ptr, (length)) #define BCONE_UNDEFINED BCONE_MAGIC, BCON_TYPE_UNDEFINED -#define BCONE_OID(_val) \ - BCONE_MAGIC, BCON_TYPE_OID, BCON_ENSURE_STORAGE (const_oid_ptr_ptr, (_val)) -#define BCONE_BOOL(_val) \ - BCONE_MAGIC, BCON_TYPE_BOOL, BCON_ENSURE_STORAGE (bool_ptr, (_val)) -#define BCONE_DATE_TIME(_val) \ - BCONE_MAGIC, BCON_TYPE_DATE_TIME, BCON_ENSURE_STORAGE (int64_ptr, (_val)) +#define BCONE_OID(_val) BCONE_MAGIC, BCON_TYPE_OID, BCON_ENSURE_STORAGE (const_oid_ptr_ptr, (_val)) +#define BCONE_BOOL(_val) BCONE_MAGIC, BCON_TYPE_BOOL, BCON_ENSURE_STORAGE (bool_ptr, (_val)) +#define BCONE_DATE_TIME(_val) BCONE_MAGIC, BCON_TYPE_DATE_TIME, BCON_ENSURE_STORAGE (int64_ptr, (_val)) #define BCONE_NULL BCONE_MAGIC, BCON_TYPE_NULL -#define BCONE_REGEX(_regex, _flags) \ - BCONE_MAGIC, BCON_TYPE_REGEX, \ - BCON_ENSURE_STORAGE (const_char_ptr_ptr, (_regex)), \ +#define BCONE_REGEX(_regex, _flags) \ + BCONE_MAGIC, BCON_TYPE_REGEX, BCON_ENSURE_STORAGE (const_char_ptr_ptr, (_regex)), \ BCON_ENSURE_STORAGE (const_char_ptr_ptr, (_flags)) -#define BCONE_DBPOINTER(_collection, _oid) \ - BCONE_MAGIC, BCON_TYPE_DBPOINTER, \ - BCON_ENSURE_STORAGE (const_char_ptr_ptr, (_collection)), \ +#define BCONE_DBPOINTER(_collection, _oid) \ + BCONE_MAGIC, BCON_TYPE_DBPOINTER, BCON_ENSURE_STORAGE (const_char_ptr_ptr, (_collection)), \ BCON_ENSURE_STORAGE (const_oid_ptr_ptr, (_oid)) -#define BCONE_CODE(_val) \ - BCONE_MAGIC, BCON_TYPE_CODE, BCON_ENSURE_STORAGE (const_char_ptr_ptr, (_val)) -#define BCONE_SYMBOL(_val) \ - BCONE_MAGIC, BCON_TYPE_SYMBOL, \ - BCON_ENSURE_STORAGE (const_char_ptr_ptr, (_val)) -#define BCONE_CODEWSCOPE(_js, _scope) \ - BCONE_MAGIC, BCON_TYPE_CODEWSCOPE, \ - BCON_ENSURE_STORAGE (const_char_ptr_ptr, (_js)), \ +#define BCONE_CODE(_val) BCONE_MAGIC, BCON_TYPE_CODE, BCON_ENSURE_STORAGE (const_char_ptr_ptr, (_val)) +#define BCONE_SYMBOL(_val) BCONE_MAGIC, BCON_TYPE_SYMBOL, BCON_ENSURE_STORAGE (const_char_ptr_ptr, (_val)) +#define BCONE_CODEWSCOPE(_js, _scope) \ + BCONE_MAGIC, BCON_TYPE_CODEWSCOPE, BCON_ENSURE_STORAGE (const_char_ptr_ptr, (_js)), \ BCON_ENSURE_STORAGE (bson_ptr, (_scope)) -#define BCONE_INT32(_val) \ - BCONE_MAGIC, BCON_TYPE_INT32, BCON_ENSURE_STORAGE (int32_ptr, (_val)) -#define BCONE_TIMESTAMP(_timestamp, _increment) \ - BCONE_MAGIC, BCON_TYPE_TIMESTAMP, \ - BCON_ENSURE_STORAGE (int32_ptr, (_timestamp)), \ +#define BCONE_INT32(_val) BCONE_MAGIC, BCON_TYPE_INT32, BCON_ENSURE_STORAGE (int32_ptr, (_val)) +#define BCONE_TIMESTAMP(_timestamp, _increment) \ + BCONE_MAGIC, BCON_TYPE_TIMESTAMP, BCON_ENSURE_STORAGE (int32_ptr, (_timestamp)), \ BCON_ENSURE_STORAGE (int32_ptr, (_increment)) -#define BCONE_INT64(_val) \ - BCONE_MAGIC, BCON_TYPE_INT64, BCON_ENSURE_STORAGE (int64_ptr, (_val)) -#define BCONE_DECIMAL128(_val) \ - BCONE_MAGIC, BCON_TYPE_DECIMAL128, \ - BCON_ENSURE_STORAGE (const_decimal128_ptr, (_val)) +#define BCONE_INT64(_val) BCONE_MAGIC, BCON_TYPE_INT64, BCON_ENSURE_STORAGE (int64_ptr, (_val)) +#define BCONE_DECIMAL128(_val) BCONE_MAGIC, BCON_TYPE_DECIMAL128, BCON_ENSURE_STORAGE (const_decimal128_ptr, (_val)) #define BCONE_MAXKEY BCONE_MAGIC, BCON_TYPE_MAXKEY #define BCONE_MINKEY BCONE_MAGIC, BCON_TYPE_MINKEY -#define BCONE_SKIP(_val) \ - BCONE_MAGIC, BCON_TYPE_SKIP, BCON_ENSURE (bson_type, (_val)) -#define BCONE_ITER(_val) \ - BCONE_MAGIC, BCON_TYPE_ITER, BCON_ENSURE_STORAGE (bson_iter_ptr, (_val)) +#define BCONE_SKIP(_val) BCONE_MAGIC, BCON_TYPE_SKIP, BCON_ENSURE (bson_type, (_val)) +#define BCONE_ITER(_val) BCONE_MAGIC, BCON_TYPE_ITER, BCON_ENSURE_STORAGE (bson_iter_ptr, (_val)) #define BCON_MAGIC bson_bcon_magic () #define BCONE_MAGIC bson_bcone_magic () @@ -232,9 +192,7 @@ typedef struct _bcon_extract_ctx_t { BSON_EXPORT (void) bcon_append (bson_t *bson, ...) BSON_GNUC_NULL_TERMINATED; BSON_EXPORT (void) -bcon_append_ctx (bson_t *bson, - bcon_append_ctx_t *ctx, - ...) BSON_GNUC_NULL_TERMINATED; +bcon_append_ctx (bson_t *bson, bcon_append_ctx_t *ctx, ...) BSON_GNUC_NULL_TERMINATED; BSON_EXPORT (void) bcon_append_ctx_va (bson_t *bson, bcon_append_ctx_t *ctx, va_list *va); BSON_EXPORT (void) @@ -244,9 +202,7 @@ BSON_EXPORT (void) bcon_extract_ctx_init (bcon_extract_ctx_t *ctx); BSON_EXPORT (void) -bcon_extract_ctx (bson_t *bson, - bcon_extract_ctx_t *ctx, - ...) BSON_GNUC_NULL_TERMINATED; +bcon_extract_ctx (bson_t *bson, bcon_extract_ctx_t *ctx, ...) BSON_GNUC_NULL_TERMINATED; BSON_EXPORT (bool) bcon_extract_ctx_va (bson_t *bson, bcon_extract_ctx_t *ctx, va_list *ap); @@ -255,9 +211,7 @@ BSON_EXPORT (bool) bcon_extract (bson_t *bson, ...) BSON_GNUC_NULL_TERMINATED; BSON_EXPORT (bool) -bcon_extract_va (bson_t *bson, - bcon_extract_ctx_t *ctx, - ...) BSON_GNUC_NULL_TERMINATED; +bcon_extract_va (bson_t *bson, bcon_extract_ctx_t *ctx, ...) BSON_GNUC_NULL_TERMINATED; BSON_EXPORT (bson_t *) bcon_new (void *unused, ...) BSON_GNUC_NULL_TERMINATED; @@ -270,16 +224,12 @@ bcon_new (void *unused, ...) BSON_GNUC_NULL_TERMINATED; * integer type then you need to add an explicit cast." * Case in point: GCC on Solaris (at least) */ -#define BCON_APPEND(_bson, ...) \ - bcon_append ((_bson), __VA_ARGS__, (void *) NULL) -#define BCON_APPEND_CTX(_bson, _ctx, ...) \ - bcon_append_ctx ((_bson), (_ctx), __VA_ARGS__, (void *) NULL) +#define BCON_APPEND(_bson, ...) bcon_append ((_bson), __VA_ARGS__, (void *) NULL) +#define BCON_APPEND_CTX(_bson, _ctx, ...) bcon_append_ctx ((_bson), (_ctx), __VA_ARGS__, (void *) NULL) -#define BCON_EXTRACT(_bson, ...) \ - bcon_extract ((_bson), __VA_ARGS__, (void *) NULL) +#define BCON_EXTRACT(_bson, ...) bcon_extract ((_bson), __VA_ARGS__, (void *) NULL) -#define BCON_EXTRACT_CTX(_bson, _ctx, ...) \ - bcon_extract ((_bson), (_ctx), __VA_ARGS__, (void *) NULL) +#define BCON_EXTRACT_CTX(_bson, _ctx, ...) bcon_extract ((_bson), (_ctx), __VA_ARGS__, (void *) NULL) #define BCON_NEW(...) bcon_new (NULL, __VA_ARGS__, (void *) NULL) diff --git a/src/libbson/src/bson/bson-atomic.c b/src/libbson/src/bson/bson-atomic.c index bb8eefcf8b..18dd4edb25 100644 --- a/src/libbson/src/bson/bson-atomic.c +++ b/src/libbson/src/bson/bson-atomic.c @@ -25,9 +25,7 @@ int32_t bson_atomic_int_add (volatile int32_t *p, int32_t n) { - return n + bson_atomic_int32_fetch_add ((DECL_ATOMIC_INTEGRAL_INT32 *) p, - n, - bson_memory_order_seq_cst); + return n + bson_atomic_int32_fetch_add ((DECL_ATOMIC_INTEGRAL_INT32 *) p, n, bson_memory_order_seq_cst); } int64_t @@ -59,22 +57,19 @@ static void _lock_emul_atomic (void) { int i; - if (bson_atomic_int8_compare_exchange_weak ( - &gEmulAtomicLock, 0, 1, bson_memory_order_acquire) == 0) { + if (bson_atomic_int8_compare_exchange_weak (&gEmulAtomicLock, 0, 1, bson_memory_order_acquire) == 0) { /* Successfully took the spinlock */ return; } /* Failed. Try taking ten more times, then begin sleeping. */ for (i = 0; i < 10; ++i) { - if (bson_atomic_int8_compare_exchange_weak ( - &gEmulAtomicLock, 0, 1, bson_memory_order_acquire) == 0) { + if (bson_atomic_int8_compare_exchange_weak (&gEmulAtomicLock, 0, 1, bson_memory_order_acquire) == 0) { /* Succeeded in taking the lock */ return; } } /* Still don't have the lock. Spin and yield */ - while (bson_atomic_int8_compare_exchange_weak ( - &gEmulAtomicLock, 0, 1, bson_memory_order_acquire) != 0) { + while (bson_atomic_int8_compare_exchange_weak (&gEmulAtomicLock, 0, 1, bson_memory_order_acquire) != 0) { bson_thrd_yield (); } } @@ -82,15 +77,12 @@ _lock_emul_atomic (void) static void _unlock_emul_atomic (void) { - int64_t rv = bson_atomic_int8_exchange ( - &gEmulAtomicLock, 0, bson_memory_order_release); + int64_t rv = bson_atomic_int8_exchange (&gEmulAtomicLock, 0, bson_memory_order_release); BSON_ASSERT (rv == 1 && "Released atomic lock while not holding it"); } int64_t -_bson_emul_atomic_int64_fetch_add (volatile int64_t *p, - int64_t n, - enum bson_memory_order _unused) +_bson_emul_atomic_int64_fetch_add (volatile int64_t *p, int64_t n, enum bson_memory_order _unused) { int64_t ret; @@ -104,9 +96,7 @@ _bson_emul_atomic_int64_fetch_add (volatile int64_t *p, } int64_t -_bson_emul_atomic_int64_exchange (volatile int64_t *p, - int64_t n, - enum bson_memory_order _unused) +_bson_emul_atomic_int64_exchange (volatile int64_t *p, int64_t n, enum bson_memory_order _unused) { int64_t ret; @@ -145,15 +135,12 @@ _bson_emul_atomic_int64_compare_exchange_weak (volatile int64_t *p, enum bson_memory_order order) { /* We're emulating. We can't do a weak version. */ - return _bson_emul_atomic_int64_compare_exchange_strong ( - p, expect_value, new_value, order); + return _bson_emul_atomic_int64_compare_exchange_strong (p, expect_value, new_value, order); } int32_t -_bson_emul_atomic_int32_fetch_add (volatile int32_t *p, - int32_t n, - enum bson_memory_order _unused) +_bson_emul_atomic_int32_fetch_add (volatile int32_t *p, int32_t n, enum bson_memory_order _unused) { int32_t ret; @@ -167,9 +154,7 @@ _bson_emul_atomic_int32_fetch_add (volatile int32_t *p, } int32_t -_bson_emul_atomic_int32_exchange (volatile int32_t *p, - int32_t n, - enum bson_memory_order _unused) +_bson_emul_atomic_int32_exchange (volatile int32_t *p, int32_t n, enum bson_memory_order _unused) { int32_t ret; @@ -208,15 +193,12 @@ _bson_emul_atomic_int32_compare_exchange_weak (volatile int32_t *p, enum bson_memory_order order) { /* We're emulating. We can't do a weak version. */ - return _bson_emul_atomic_int32_compare_exchange_strong ( - p, expect_value, new_value, order); + return _bson_emul_atomic_int32_compare_exchange_strong (p, expect_value, new_value, order); } int -_bson_emul_atomic_int_fetch_add (volatile int *p, - int n, - enum bson_memory_order _unused) +_bson_emul_atomic_int_fetch_add (volatile int *p, int n, enum bson_memory_order _unused) { int ret; @@ -230,9 +212,7 @@ _bson_emul_atomic_int_fetch_add (volatile int *p, } int -_bson_emul_atomic_int_exchange (volatile int *p, - int n, - enum bson_memory_order _unused) +_bson_emul_atomic_int_exchange (volatile int *p, int n, enum bson_memory_order _unused) { int ret; @@ -271,14 +251,11 @@ _bson_emul_atomic_int_compare_exchange_weak (volatile int *p, enum bson_memory_order order) { /* We're emulating. We can't do a weak version. */ - return _bson_emul_atomic_int_compare_exchange_strong ( - p, expect_value, new_value, order); + return _bson_emul_atomic_int_compare_exchange_strong (p, expect_value, new_value, order); } void * -_bson_emul_atomic_ptr_exchange (void *volatile *p, - void *n, - enum bson_memory_order _unused) +_bson_emul_atomic_ptr_exchange (void *volatile *p, void *n, enum bson_memory_order _unused) { void *ret; diff --git a/src/libbson/src/bson/bson-atomic.h b/src/libbson/src/bson/bson-atomic.h index a28c0be65d..60ab74c87e 100644 --- a/src/libbson/src/bson/bson-atomic.h +++ b/src/libbson/src/bson/bson-atomic.h @@ -47,8 +47,7 @@ enum bson_memory_order { #define MSVC_MEMORDER_SUFFIX(X) #endif -#if defined(USE_LEGACY_GCC_ATOMICS) || \ - (!defined(__clang__) && __GNUC__ == 4) || defined(__xlC__) +#if defined(USE_LEGACY_GCC_ATOMICS) || (!defined(__clang__) && __GNUC__ == 4) || defined(__xlC__) #define BSON_USE_LEGACY_GCC_ATOMICS #else #undef BSON_USE_LEGACY_GCC_ATOMICS @@ -81,273 +80,198 @@ enum bson_memory_order { #define BSON_EMULATE_PTR #endif -#define DEF_ATOMIC_OP( \ - MSVC_Intrinsic, GNU_Intrinsic, GNU_Legacy_Intrinsic, Order, ...) \ - do { \ - switch (Order) { \ - case bson_memory_order_acq_rel: \ - BSON_IF_MSVC (return MSVC_Intrinsic (__VA_ARGS__);) \ - BSON_IF_GNU_LIKE ( \ - return GNU_Intrinsic (__VA_ARGS__, __ATOMIC_ACQ_REL);) \ - BSON_IF_GNU_LEGACY_ATOMICS ( \ - return GNU_Legacy_Intrinsic (__VA_ARGS__);) \ - case bson_memory_order_seq_cst: \ - BSON_IF_MSVC (return MSVC_Intrinsic (__VA_ARGS__);) \ - BSON_IF_GNU_LIKE ( \ - return GNU_Intrinsic (__VA_ARGS__, __ATOMIC_SEQ_CST);) \ - BSON_IF_GNU_LEGACY_ATOMICS ( \ - return GNU_Legacy_Intrinsic (__VA_ARGS__);) \ - case bson_memory_order_acquire: \ - BSON_IF_MSVC ( \ - return BSON_CONCAT (MSVC_Intrinsic, \ - MSVC_MEMORDER_SUFFIX (_acq)) (__VA_ARGS__);) \ - BSON_IF_GNU_LIKE ( \ - return GNU_Intrinsic (__VA_ARGS__, __ATOMIC_ACQUIRE);) \ - BSON_IF_GNU_LEGACY_ATOMICS ( \ - return GNU_Legacy_Intrinsic (__VA_ARGS__);) \ - case bson_memory_order_consume: \ - BSON_IF_MSVC ( \ - return BSON_CONCAT (MSVC_Intrinsic, \ - MSVC_MEMORDER_SUFFIX (_acq)) (__VA_ARGS__);) \ - BSON_IF_GNU_LIKE ( \ - return GNU_Intrinsic (__VA_ARGS__, __ATOMIC_CONSUME);) \ - BSON_IF_GNU_LEGACY_ATOMICS ( \ - return GNU_Legacy_Intrinsic (__VA_ARGS__);) \ - case bson_memory_order_release: \ - BSON_IF_MSVC ( \ - return BSON_CONCAT (MSVC_Intrinsic, \ - MSVC_MEMORDER_SUFFIX (_rel)) (__VA_ARGS__);) \ - BSON_IF_GNU_LIKE ( \ - return GNU_Intrinsic (__VA_ARGS__, __ATOMIC_RELEASE);) \ - BSON_IF_GNU_LEGACY_ATOMICS ( \ - return GNU_Legacy_Intrinsic (__VA_ARGS__);) \ - case bson_memory_order_relaxed: \ - BSON_IF_MSVC ( \ - return BSON_CONCAT (MSVC_Intrinsic, \ - MSVC_MEMORDER_SUFFIX (_nf)) (__VA_ARGS__);) \ - BSON_IF_GNU_LIKE ( \ - return GNU_Intrinsic (__VA_ARGS__, __ATOMIC_RELAXED);) \ - BSON_IF_GNU_LEGACY_ATOMICS ( \ - return GNU_Legacy_Intrinsic (__VA_ARGS__);) \ - default: \ - BSON_UNREACHABLE ("Invalid bson_memory_order value"); \ - } \ +#define DEF_ATOMIC_OP(MSVC_Intrinsic, GNU_Intrinsic, GNU_Legacy_Intrinsic, Order, ...) \ + do { \ + switch (Order) { \ + case bson_memory_order_acq_rel: \ + BSON_IF_MSVC (return MSVC_Intrinsic (__VA_ARGS__);) \ + BSON_IF_GNU_LIKE (return GNU_Intrinsic (__VA_ARGS__, __ATOMIC_ACQ_REL);) \ + BSON_IF_GNU_LEGACY_ATOMICS (return GNU_Legacy_Intrinsic (__VA_ARGS__);) \ + case bson_memory_order_seq_cst: \ + BSON_IF_MSVC (return MSVC_Intrinsic (__VA_ARGS__);) \ + BSON_IF_GNU_LIKE (return GNU_Intrinsic (__VA_ARGS__, __ATOMIC_SEQ_CST);) \ + BSON_IF_GNU_LEGACY_ATOMICS (return GNU_Legacy_Intrinsic (__VA_ARGS__);) \ + case bson_memory_order_acquire: \ + BSON_IF_MSVC (return BSON_CONCAT (MSVC_Intrinsic, MSVC_MEMORDER_SUFFIX (_acq)) (__VA_ARGS__);) \ + BSON_IF_GNU_LIKE (return GNU_Intrinsic (__VA_ARGS__, __ATOMIC_ACQUIRE);) \ + BSON_IF_GNU_LEGACY_ATOMICS (return GNU_Legacy_Intrinsic (__VA_ARGS__);) \ + case bson_memory_order_consume: \ + BSON_IF_MSVC (return BSON_CONCAT (MSVC_Intrinsic, MSVC_MEMORDER_SUFFIX (_acq)) (__VA_ARGS__);) \ + BSON_IF_GNU_LIKE (return GNU_Intrinsic (__VA_ARGS__, __ATOMIC_CONSUME);) \ + BSON_IF_GNU_LEGACY_ATOMICS (return GNU_Legacy_Intrinsic (__VA_ARGS__);) \ + case bson_memory_order_release: \ + BSON_IF_MSVC (return BSON_CONCAT (MSVC_Intrinsic, MSVC_MEMORDER_SUFFIX (_rel)) (__VA_ARGS__);) \ + BSON_IF_GNU_LIKE (return GNU_Intrinsic (__VA_ARGS__, __ATOMIC_RELEASE);) \ + BSON_IF_GNU_LEGACY_ATOMICS (return GNU_Legacy_Intrinsic (__VA_ARGS__);) \ + case bson_memory_order_relaxed: \ + BSON_IF_MSVC (return BSON_CONCAT (MSVC_Intrinsic, MSVC_MEMORDER_SUFFIX (_nf)) (__VA_ARGS__);) \ + BSON_IF_GNU_LIKE (return GNU_Intrinsic (__VA_ARGS__, __ATOMIC_RELAXED);) \ + BSON_IF_GNU_LEGACY_ATOMICS (return GNU_Legacy_Intrinsic (__VA_ARGS__);) \ + default: \ + BSON_UNREACHABLE ("Invalid bson_memory_order value"); \ + } \ } while (0) -#define DEF_ATOMIC_CMPEXCH_STRONG( \ - VCSuffix1, VCSuffix2, GNU_MemOrder, Ptr, ExpectActualVar, NewValue) \ - do { \ - BSON_IF_MSVC (ExpectActualVar = BSON_CONCAT3 ( \ - _InterlockedCompareExchange, VCSuffix1, VCSuffix2) ( \ - Ptr, NewValue, ExpectActualVar);) \ - BSON_IF_GNU_LIKE ( \ - (void) __atomic_compare_exchange_n (Ptr, \ - &ExpectActualVar, \ - NewValue, \ - false, /* Not weak */ \ - GNU_MemOrder, \ - GNU_MemOrder);) \ - BSON_IF_GNU_LEGACY_ATOMICS ( \ - __typeof__ (ExpectActualVar) _val; \ - _val = __sync_val_compare_and_swap (Ptr, ExpectActualVar, NewValue); \ - ExpectActualVar = _val;) \ +#define DEF_ATOMIC_CMPEXCH_STRONG(VCSuffix1, VCSuffix2, GNU_MemOrder, Ptr, ExpectActualVar, NewValue) \ + do { \ + BSON_IF_MSVC (ExpectActualVar = BSON_CONCAT3 (_InterlockedCompareExchange, VCSuffix1, VCSuffix2) ( \ + Ptr, NewValue, ExpectActualVar);) \ + BSON_IF_GNU_LIKE ((void) __atomic_compare_exchange_n (Ptr, \ + &ExpectActualVar, \ + NewValue, \ + false, /* Not weak */ \ + GNU_MemOrder, \ + GNU_MemOrder);) \ + BSON_IF_GNU_LEGACY_ATOMICS (__typeof__ (ExpectActualVar) _val; \ + _val = __sync_val_compare_and_swap (Ptr, ExpectActualVar, NewValue); \ + ExpectActualVar = _val;) \ } while (0) -#define DEF_ATOMIC_CMPEXCH_WEAK( \ - VCSuffix1, VCSuffix2, GNU_MemOrder, Ptr, ExpectActualVar, NewValue) \ - do { \ - BSON_IF_MSVC (ExpectActualVar = BSON_CONCAT3 ( \ - _InterlockedCompareExchange, VCSuffix1, VCSuffix2) ( \ - Ptr, NewValue, ExpectActualVar);) \ - BSON_IF_GNU_LIKE ( \ - (void) __atomic_compare_exchange_n (Ptr, \ - &ExpectActualVar, \ - NewValue, \ - true, /* Yes weak */ \ - GNU_MemOrder, \ - GNU_MemOrder);) \ - BSON_IF_GNU_LEGACY_ATOMICS ( \ - __typeof__ (ExpectActualVar) _val; \ - _val = __sync_val_compare_and_swap (Ptr, ExpectActualVar, NewValue); \ - ExpectActualVar = _val;) \ +#define DEF_ATOMIC_CMPEXCH_WEAK(VCSuffix1, VCSuffix2, GNU_MemOrder, Ptr, ExpectActualVar, NewValue) \ + do { \ + BSON_IF_MSVC (ExpectActualVar = BSON_CONCAT3 (_InterlockedCompareExchange, VCSuffix1, VCSuffix2) ( \ + Ptr, NewValue, ExpectActualVar);) \ + BSON_IF_GNU_LIKE ((void) __atomic_compare_exchange_n (Ptr, \ + &ExpectActualVar, \ + NewValue, \ + true, /* Yes weak */ \ + GNU_MemOrder, \ + GNU_MemOrder);) \ + BSON_IF_GNU_LEGACY_ATOMICS (__typeof__ (ExpectActualVar) _val; \ + _val = __sync_val_compare_and_swap (Ptr, ExpectActualVar, NewValue); \ + ExpectActualVar = _val;) \ } while (0) -#define DECL_ATOMIC_INTEGRAL(NamePart, Type, VCIntrinSuffix) \ - static BSON_INLINE Type bson_atomic_##NamePart##_fetch_add ( \ - Type volatile *a, Type addend, enum bson_memory_order ord) \ - { \ - DEF_ATOMIC_OP (BSON_CONCAT (_InterlockedExchangeAdd, VCIntrinSuffix), \ - __atomic_fetch_add, \ - __sync_fetch_and_add, \ - ord, \ - a, \ - addend); \ - } \ - \ - static BSON_INLINE Type bson_atomic_##NamePart##_fetch_sub ( \ - Type volatile *a, Type subtrahend, enum bson_memory_order ord) \ - { \ - /* MSVC doesn't have a subtract intrinsic, so just reuse addition */ \ - BSON_IF_MSVC ( \ - return bson_atomic_##NamePart##_fetch_add (a, -subtrahend, ord);) \ - BSON_IF_GNU_LIKE ( \ - DEF_ATOMIC_OP (~, __atomic_fetch_sub, ~, ord, a, subtrahend);) \ - BSON_IF_GNU_LEGACY_ATOMICS ( \ - DEF_ATOMIC_OP (~, ~, __sync_fetch_and_sub, ord, a, subtrahend);) \ - } \ - \ - static BSON_INLINE Type bson_atomic_##NamePart##_fetch ( \ - Type volatile const *a, enum bson_memory_order order) \ - { \ - /* MSVC doesn't have a load intrinsic, so just add zero */ \ - BSON_IF_MSVC (return bson_atomic_##NamePart##_fetch_add ( \ - (Type volatile *) a, 0, order);) \ - /* GNU doesn't want RELEASE order for the fetch operation, so we can't \ - * just use DEF_ATOMIC_OP. */ \ - BSON_IF_GNU_LIKE (switch (order) { \ - case bson_memory_order_release: /* Fall back to seqcst */ \ - case bson_memory_order_acq_rel: /* Fall back to seqcst */ \ - case bson_memory_order_seq_cst: \ - return __atomic_load_n (a, __ATOMIC_SEQ_CST); \ - case bson_memory_order_acquire: \ - return __atomic_load_n (a, __ATOMIC_ACQUIRE); \ - case bson_memory_order_consume: \ - return __atomic_load_n (a, __ATOMIC_CONSUME); \ - case bson_memory_order_relaxed: \ - return __atomic_load_n (a, __ATOMIC_RELAXED); \ - default: \ - BSON_UNREACHABLE ("Invalid bson_memory_order value"); \ - }) \ - BSON_IF_GNU_LEGACY_ATOMICS ({ \ - __sync_synchronize (); \ - return *a; \ - }) \ - } \ - \ - static BSON_INLINE Type bson_atomic_##NamePart##_exchange ( \ - Type volatile *a, Type value, enum bson_memory_order ord) \ - { \ - BSON_IF_MSVC ( \ - DEF_ATOMIC_OP (BSON_CONCAT (_InterlockedExchange, VCIntrinSuffix), \ - ~, \ - ~, \ - ord, \ - a, \ - value);) \ - /* GNU doesn't want CONSUME order for the exchange operation, so we \ - * cannot use DEF_ATOMIC_OP. */ \ - BSON_IF_GNU_LIKE (switch (ord) { \ - case bson_memory_order_acq_rel: \ - return __atomic_exchange_n (a, value, __ATOMIC_ACQ_REL); \ - case bson_memory_order_release: \ - return __atomic_exchange_n (a, value, __ATOMIC_RELEASE); \ - case bson_memory_order_seq_cst: \ - return __atomic_exchange_n (a, value, __ATOMIC_SEQ_CST); \ - case bson_memory_order_consume: /* Fall back to acquire */ \ - case bson_memory_order_acquire: \ - return __atomic_exchange_n (a, value, __ATOMIC_ACQUIRE); \ - case bson_memory_order_relaxed: \ - return __atomic_exchange_n (a, value, __ATOMIC_RELAXED); \ - default: \ - BSON_UNREACHABLE ("Invalid bson_memory_order value"); \ - }) \ - BSON_IF_GNU_LEGACY_ATOMICS ( \ - return __sync_val_compare_and_swap (a, *a, value);) \ - } \ - \ - static BSON_INLINE Type bson_atomic_##NamePart##_compare_exchange_strong ( \ - Type volatile *a, \ - Type expect, \ - Type new_value, \ - enum bson_memory_order ord) \ - { \ - Type actual = expect; \ - switch (ord) { \ - case bson_memory_order_release: \ - case bson_memory_order_acq_rel: \ - case bson_memory_order_seq_cst: \ - DEF_ATOMIC_CMPEXCH_STRONG ( \ - VCIntrinSuffix, , __ATOMIC_SEQ_CST, a, actual, new_value); \ - break; \ - case bson_memory_order_acquire: \ - DEF_ATOMIC_CMPEXCH_STRONG (VCIntrinSuffix, \ - MSVC_MEMORDER_SUFFIX (_acq), \ - __ATOMIC_ACQUIRE, \ - a, \ - actual, \ - new_value); \ - break; \ - case bson_memory_order_consume: \ - DEF_ATOMIC_CMPEXCH_STRONG (VCIntrinSuffix, \ - MSVC_MEMORDER_SUFFIX (_acq), \ - __ATOMIC_CONSUME, \ - a, \ - actual, \ - new_value); \ - break; \ - case bson_memory_order_relaxed: \ - DEF_ATOMIC_CMPEXCH_STRONG (VCIntrinSuffix, \ - MSVC_MEMORDER_SUFFIX (_nf), \ - __ATOMIC_RELAXED, \ - a, \ - actual, \ - new_value); \ - break; \ - default: \ - BSON_UNREACHABLE ("Invalid bson_memory_order value"); \ - } \ - return actual; \ - } \ - \ - static BSON_INLINE Type bson_atomic_##NamePart##_compare_exchange_weak ( \ - Type volatile *a, \ - Type expect, \ - Type new_value, \ - enum bson_memory_order ord) \ - { \ - Type actual = expect; \ - switch (ord) { \ - case bson_memory_order_release: \ - case bson_memory_order_acq_rel: \ - case bson_memory_order_seq_cst: \ - DEF_ATOMIC_CMPEXCH_WEAK ( \ - VCIntrinSuffix, , __ATOMIC_SEQ_CST, a, actual, new_value); \ - break; \ - case bson_memory_order_acquire: \ - DEF_ATOMIC_CMPEXCH_WEAK (VCIntrinSuffix, \ - MSVC_MEMORDER_SUFFIX (_acq), \ - __ATOMIC_ACQUIRE, \ - a, \ - actual, \ - new_value); \ - break; \ - case bson_memory_order_consume: \ - DEF_ATOMIC_CMPEXCH_WEAK (VCIntrinSuffix, \ - MSVC_MEMORDER_SUFFIX (_acq), \ - __ATOMIC_CONSUME, \ - a, \ - actual, \ - new_value); \ - break; \ - case bson_memory_order_relaxed: \ - DEF_ATOMIC_CMPEXCH_WEAK (VCIntrinSuffix, \ - MSVC_MEMORDER_SUFFIX (_nf), \ - __ATOMIC_RELAXED, \ - a, \ - actual, \ - new_value); \ - break; \ - default: \ - BSON_UNREACHABLE ("Invalid bson_memory_order value"); \ - } \ - return actual; \ +#define DECL_ATOMIC_INTEGRAL(NamePart, Type, VCIntrinSuffix) \ + static BSON_INLINE Type bson_atomic_##NamePart##_fetch_add ( \ + Type volatile *a, Type addend, enum bson_memory_order ord) \ + { \ + DEF_ATOMIC_OP (BSON_CONCAT (_InterlockedExchangeAdd, VCIntrinSuffix), \ + __atomic_fetch_add, \ + __sync_fetch_and_add, \ + ord, \ + a, \ + addend); \ + } \ + \ + static BSON_INLINE Type bson_atomic_##NamePart##_fetch_sub ( \ + Type volatile *a, Type subtrahend, enum bson_memory_order ord) \ + { \ + /* MSVC doesn't have a subtract intrinsic, so just reuse addition */ \ + BSON_IF_MSVC (return bson_atomic_##NamePart##_fetch_add (a, -subtrahend, ord);) \ + BSON_IF_GNU_LIKE (DEF_ATOMIC_OP (~, __atomic_fetch_sub, ~, ord, a, subtrahend);) \ + BSON_IF_GNU_LEGACY_ATOMICS (DEF_ATOMIC_OP (~, ~, __sync_fetch_and_sub, ord, a, subtrahend);) \ + } \ + \ + static BSON_INLINE Type bson_atomic_##NamePart##_fetch (Type volatile const *a, enum bson_memory_order order) \ + { \ + /* MSVC doesn't have a load intrinsic, so just add zero */ \ + BSON_IF_MSVC (return bson_atomic_##NamePart##_fetch_add ((Type volatile *) a, 0, order);) \ + /* GNU doesn't want RELEASE order for the fetch operation, so we can't \ + * just use DEF_ATOMIC_OP. */ \ + BSON_IF_GNU_LIKE (switch (order) { \ + case bson_memory_order_release: /* Fall back to seqcst */ \ + case bson_memory_order_acq_rel: /* Fall back to seqcst */ \ + case bson_memory_order_seq_cst: \ + return __atomic_load_n (a, __ATOMIC_SEQ_CST); \ + case bson_memory_order_acquire: \ + return __atomic_load_n (a, __ATOMIC_ACQUIRE); \ + case bson_memory_order_consume: \ + return __atomic_load_n (a, __ATOMIC_CONSUME); \ + case bson_memory_order_relaxed: \ + return __atomic_load_n (a, __ATOMIC_RELAXED); \ + default: \ + BSON_UNREACHABLE ("Invalid bson_memory_order value"); \ + }) \ + BSON_IF_GNU_LEGACY_ATOMICS ({ \ + __sync_synchronize (); \ + return *a; \ + }) \ + } \ + \ + static BSON_INLINE Type bson_atomic_##NamePart##_exchange ( \ + Type volatile *a, Type value, enum bson_memory_order ord) \ + { \ + BSON_IF_MSVC (DEF_ATOMIC_OP (BSON_CONCAT (_InterlockedExchange, VCIntrinSuffix), ~, ~, ord, a, value);) \ + /* GNU doesn't want CONSUME order for the exchange operation, so we \ + * cannot use DEF_ATOMIC_OP. */ \ + BSON_IF_GNU_LIKE (switch (ord) { \ + case bson_memory_order_acq_rel: \ + return __atomic_exchange_n (a, value, __ATOMIC_ACQ_REL); \ + case bson_memory_order_release: \ + return __atomic_exchange_n (a, value, __ATOMIC_RELEASE); \ + case bson_memory_order_seq_cst: \ + return __atomic_exchange_n (a, value, __ATOMIC_SEQ_CST); \ + case bson_memory_order_consume: /* Fall back to acquire */ \ + case bson_memory_order_acquire: \ + return __atomic_exchange_n (a, value, __ATOMIC_ACQUIRE); \ + case bson_memory_order_relaxed: \ + return __atomic_exchange_n (a, value, __ATOMIC_RELAXED); \ + default: \ + BSON_UNREACHABLE ("Invalid bson_memory_order value"); \ + }) \ + BSON_IF_GNU_LEGACY_ATOMICS (return __sync_val_compare_and_swap (a, *a, value);) \ + } \ + \ + static BSON_INLINE Type bson_atomic_##NamePart##_compare_exchange_strong ( \ + Type volatile *a, Type expect, Type new_value, enum bson_memory_order ord) \ + { \ + Type actual = expect; \ + switch (ord) { \ + case bson_memory_order_release: \ + case bson_memory_order_acq_rel: \ + case bson_memory_order_seq_cst: \ + DEF_ATOMIC_CMPEXCH_STRONG (VCIntrinSuffix, , __ATOMIC_SEQ_CST, a, actual, new_value); \ + break; \ + case bson_memory_order_acquire: \ + DEF_ATOMIC_CMPEXCH_STRONG ( \ + VCIntrinSuffix, MSVC_MEMORDER_SUFFIX (_acq), __ATOMIC_ACQUIRE, a, actual, new_value); \ + break; \ + case bson_memory_order_consume: \ + DEF_ATOMIC_CMPEXCH_STRONG ( \ + VCIntrinSuffix, MSVC_MEMORDER_SUFFIX (_acq), __ATOMIC_CONSUME, a, actual, new_value); \ + break; \ + case bson_memory_order_relaxed: \ + DEF_ATOMIC_CMPEXCH_STRONG ( \ + VCIntrinSuffix, MSVC_MEMORDER_SUFFIX (_nf), __ATOMIC_RELAXED, a, actual, new_value); \ + break; \ + default: \ + BSON_UNREACHABLE ("Invalid bson_memory_order value"); \ + } \ + return actual; \ + } \ + \ + static BSON_INLINE Type bson_atomic_##NamePart##_compare_exchange_weak ( \ + Type volatile *a, Type expect, Type new_value, enum bson_memory_order ord) \ + { \ + Type actual = expect; \ + switch (ord) { \ + case bson_memory_order_release: \ + case bson_memory_order_acq_rel: \ + case bson_memory_order_seq_cst: \ + DEF_ATOMIC_CMPEXCH_WEAK (VCIntrinSuffix, , __ATOMIC_SEQ_CST, a, actual, new_value); \ + break; \ + case bson_memory_order_acquire: \ + DEF_ATOMIC_CMPEXCH_WEAK ( \ + VCIntrinSuffix, MSVC_MEMORDER_SUFFIX (_acq), __ATOMIC_ACQUIRE, a, actual, new_value); \ + break; \ + case bson_memory_order_consume: \ + DEF_ATOMIC_CMPEXCH_WEAK ( \ + VCIntrinSuffix, MSVC_MEMORDER_SUFFIX (_acq), __ATOMIC_CONSUME, a, actual, new_value); \ + break; \ + case bson_memory_order_relaxed: \ + DEF_ATOMIC_CMPEXCH_WEAK (VCIntrinSuffix, MSVC_MEMORDER_SUFFIX (_nf), __ATOMIC_RELAXED, a, actual, new_value); \ + break; \ + default: \ + BSON_UNREACHABLE ("Invalid bson_memory_order value"); \ + } \ + return actual; \ } -#define DECL_ATOMIC_STDINT(Name, VCSuffix) \ - DECL_ATOMIC_INTEGRAL (Name, Name##_t, VCSuffix) +#define DECL_ATOMIC_STDINT(Name, VCSuffix) DECL_ATOMIC_INTEGRAL (Name, Name##_t, VCSuffix) #if defined(_MSC_VER) || defined(BSON_USE_LEGACY_GCC_ATOMICS) /* MSVC and GCC require built-in types (not typedefs) for their atomic @@ -386,13 +310,9 @@ DECL_ATOMIC_INTEGRAL (int, int, ) #endif BSON_EXPORT (int64_t) -_bson_emul_atomic_int64_fetch_add (int64_t volatile *val, - int64_t v, - enum bson_memory_order); +_bson_emul_atomic_int64_fetch_add (int64_t volatile *val, int64_t v, enum bson_memory_order); BSON_EXPORT (int64_t) -_bson_emul_atomic_int64_exchange (int64_t volatile *val, - int64_t v, - enum bson_memory_order); +_bson_emul_atomic_int64_exchange (int64_t volatile *val, int64_t v, enum bson_memory_order); BSON_EXPORT (int64_t) _bson_emul_atomic_int64_compare_exchange_strong (int64_t volatile *val, int64_t expect_value, @@ -406,13 +326,9 @@ _bson_emul_atomic_int64_compare_exchange_weak (int64_t volatile *val, enum bson_memory_order); BSON_EXPORT (int32_t) -_bson_emul_atomic_int32_fetch_add (int32_t volatile *val, - int32_t v, - enum bson_memory_order); +_bson_emul_atomic_int32_fetch_add (int32_t volatile *val, int32_t v, enum bson_memory_order); BSON_EXPORT (int32_t) -_bson_emul_atomic_int32_exchange (int32_t volatile *val, - int32_t v, - enum bson_memory_order); +_bson_emul_atomic_int32_exchange (int32_t volatile *val, int32_t v, enum bson_memory_order); BSON_EXPORT (int32_t) _bson_emul_atomic_int32_compare_exchange_strong (int32_t volatile *val, int32_t expect_value, @@ -426,13 +342,9 @@ _bson_emul_atomic_int32_compare_exchange_weak (int32_t volatile *val, enum bson_memory_order); BSON_EXPORT (int) -_bson_emul_atomic_int_fetch_add (int volatile *val, - int v, - enum bson_memory_order); +_bson_emul_atomic_int_fetch_add (int volatile *val, int v, enum bson_memory_order); BSON_EXPORT (int) -_bson_emul_atomic_int_exchange (int volatile *val, - int v, - enum bson_memory_order); +_bson_emul_atomic_int_exchange (int volatile *val, int v, enum bson_memory_order); BSON_EXPORT (int) _bson_emul_atomic_int_compare_exchange_strong (int volatile *val, int expect_value, @@ -446,9 +358,7 @@ _bson_emul_atomic_int_compare_exchange_weak (int volatile *val, enum bson_memory_order); BSON_EXPORT (void *) -_bson_emul_atomic_ptr_exchange (void *volatile *val, - void *v, - enum bson_memory_order); +_bson_emul_atomic_ptr_exchange (void *volatile *val, void *v, enum bson_memory_order); BSON_EXPORT (void) bson_thrd_yield (void); @@ -462,33 +372,25 @@ DECL_ATOMIC_STDINT (int64, 64) #endif #else static BSON_INLINE int64_t -bson_atomic_int64_fetch (const int64_t volatile *val, - enum bson_memory_order order) +bson_atomic_int64_fetch (const int64_t volatile *val, enum bson_memory_order order) { - return _bson_emul_atomic_int64_fetch_add ( - (int64_t volatile *) val, 0, order); + return _bson_emul_atomic_int64_fetch_add ((int64_t volatile *) val, 0, order); } static BSON_INLINE int64_t -bson_atomic_int64_fetch_add (int64_t volatile *val, - int64_t v, - enum bson_memory_order order) +bson_atomic_int64_fetch_add (int64_t volatile *val, int64_t v, enum bson_memory_order order) { return _bson_emul_atomic_int64_fetch_add (val, v, order); } static BSON_INLINE int64_t -bson_atomic_int64_fetch_sub (int64_t volatile *val, - int64_t v, - enum bson_memory_order order) +bson_atomic_int64_fetch_sub (int64_t volatile *val, int64_t v, enum bson_memory_order order) { return _bson_emul_atomic_int64_fetch_add (val, -v, order); } static BSON_INLINE int64_t -bson_atomic_int64_exchange (int64_t volatile *val, - int64_t v, - enum bson_memory_order order) +bson_atomic_int64_exchange (int64_t volatile *val, int64_t v, enum bson_memory_order order) { return _bson_emul_atomic_int64_exchange (val, v, order); } @@ -499,8 +401,7 @@ bson_atomic_int64_compare_exchange_strong (int64_t volatile *val, int64_t new_value, enum bson_memory_order order) { - return _bson_emul_atomic_int64_compare_exchange_strong ( - val, expect_value, new_value, order); + return _bson_emul_atomic_int64_compare_exchange_strong (val, expect_value, new_value, order); } static BSON_INLINE int64_t @@ -509,40 +410,31 @@ bson_atomic_int64_compare_exchange_weak (int64_t volatile *val, int64_t new_value, enum bson_memory_order order) { - return _bson_emul_atomic_int64_compare_exchange_weak ( - val, expect_value, new_value, order); + return _bson_emul_atomic_int64_compare_exchange_weak (val, expect_value, new_value, order); } #endif #if defined(BSON_EMULATE_INT32) static BSON_INLINE int32_t -bson_atomic_int32_fetch (const int32_t volatile *val, - enum bson_memory_order order) +bson_atomic_int32_fetch (const int32_t volatile *val, enum bson_memory_order order) { - return _bson_emul_atomic_int32_fetch_add ( - (int32_t volatile *) val, 0, order); + return _bson_emul_atomic_int32_fetch_add ((int32_t volatile *) val, 0, order); } static BSON_INLINE int32_t -bson_atomic_int32_fetch_add (int32_t volatile *val, - int32_t v, - enum bson_memory_order order) +bson_atomic_int32_fetch_add (int32_t volatile *val, int32_t v, enum bson_memory_order order) { return _bson_emul_atomic_int32_fetch_add (val, v, order); } static BSON_INLINE int32_t -bson_atomic_int32_fetch_sub (int32_t volatile *val, - int32_t v, - enum bson_memory_order order) +bson_atomic_int32_fetch_sub (int32_t volatile *val, int32_t v, enum bson_memory_order order) { return _bson_emul_atomic_int32_fetch_add (val, -v, order); } static BSON_INLINE int32_t -bson_atomic_int32_exchange (int32_t volatile *val, - int32_t v, - enum bson_memory_order order) +bson_atomic_int32_exchange (int32_t volatile *val, int32_t v, enum bson_memory_order order) { return _bson_emul_atomic_int32_exchange (val, v, order); } @@ -553,8 +445,7 @@ bson_atomic_int32_compare_exchange_strong (int32_t volatile *val, int32_t new_value, enum bson_memory_order order) { - return _bson_emul_atomic_int32_compare_exchange_strong ( - val, expect_value, new_value, order); + return _bson_emul_atomic_int32_compare_exchange_strong (val, expect_value, new_value, order); } static BSON_INLINE int32_t @@ -563,8 +454,7 @@ bson_atomic_int32_compare_exchange_weak (int32_t volatile *val, int32_t new_value, enum bson_memory_order order) { - return _bson_emul_atomic_int32_compare_exchange_weak ( - val, expect_value, new_value, order); + return _bson_emul_atomic_int32_compare_exchange_weak (val, expect_value, new_value, order); } #endif /* BSON_EMULATE_INT32 */ @@ -576,25 +466,19 @@ bson_atomic_int_fetch (const int volatile *val, enum bson_memory_order order) } static BSON_INLINE int -bson_atomic_int_fetch_add (int volatile *val, - int v, - enum bson_memory_order order) +bson_atomic_int_fetch_add (int volatile *val, int v, enum bson_memory_order order) { return _bson_emul_atomic_int_fetch_add (val, v, order); } static BSON_INLINE int -bson_atomic_int_fetch_sub (int volatile *val, - int v, - enum bson_memory_order order) +bson_atomic_int_fetch_sub (int volatile *val, int v, enum bson_memory_order order) { return _bson_emul_atomic_int_fetch_add (val, -v, order); } static BSON_INLINE int -bson_atomic_int_exchange (int volatile *val, - int v, - enum bson_memory_order order) +bson_atomic_int_exchange (int volatile *val, int v, enum bson_memory_order order) { return _bson_emul_atomic_int_exchange (val, v, order); } @@ -605,79 +489,46 @@ bson_atomic_int_compare_exchange_strong (int volatile *val, int new_value, enum bson_memory_order order) { - return _bson_emul_atomic_int_compare_exchange_strong ( - val, expect_value, new_value, order); + return _bson_emul_atomic_int_compare_exchange_strong (val, expect_value, new_value, order); } static BSON_INLINE int -bson_atomic_int_compare_exchange_weak (int volatile *val, - int expect_value, - int new_value, - enum bson_memory_order order) +bson_atomic_int_compare_exchange_weak (int volatile *val, int expect_value, int new_value, enum bson_memory_order order) { - return _bson_emul_atomic_int_compare_exchange_weak ( - val, expect_value, new_value, order); + return _bson_emul_atomic_int_compare_exchange_weak (val, expect_value, new_value, order); } #endif /* BSON_EMULATE_INT */ static BSON_INLINE void * -bson_atomic_ptr_exchange (void *volatile *ptr, - void *new_value, - enum bson_memory_order ord) +bson_atomic_ptr_exchange (void *volatile *ptr, void *new_value, enum bson_memory_order ord) { #if defined(BSON_EMULATE_PTR) return _bson_emul_atomic_ptr_exchange (ptr, new_value, ord); #elif defined(BSON_USE_LEGACY_GCC_ATOMICS) /* The older __sync_val_compare_and_swap also takes oldval */ - DEF_ATOMIC_OP (_InterlockedExchangePointer, - , - __sync_val_compare_and_swap, - ord, - ptr, - *ptr, - new_value); + DEF_ATOMIC_OP (_InterlockedExchangePointer, , __sync_val_compare_and_swap, ord, ptr, *ptr, new_value); #else - DEF_ATOMIC_OP ( - _InterlockedExchangePointer, __atomic_exchange_n, , ord, ptr, new_value); + DEF_ATOMIC_OP (_InterlockedExchangePointer, __atomic_exchange_n, , ord, ptr, new_value); #endif } static BSON_INLINE void * -bson_atomic_ptr_compare_exchange_strong (void *volatile *ptr, - void *expect, - void *new_value, - enum bson_memory_order ord) +bson_atomic_ptr_compare_exchange_strong (void *volatile *ptr, void *expect, void *new_value, enum bson_memory_order ord) { switch (ord) { case bson_memory_order_release: case bson_memory_order_acq_rel: case bson_memory_order_seq_cst: - DEF_ATOMIC_CMPEXCH_STRONG ( - Pointer, , __ATOMIC_SEQ_CST, ptr, expect, new_value); + DEF_ATOMIC_CMPEXCH_STRONG (Pointer, , __ATOMIC_SEQ_CST, ptr, expect, new_value); return expect; case bson_memory_order_relaxed: - DEF_ATOMIC_CMPEXCH_STRONG (Pointer, - MSVC_MEMORDER_SUFFIX (_nf), - __ATOMIC_RELAXED, - ptr, - expect, - new_value); + DEF_ATOMIC_CMPEXCH_STRONG (Pointer, MSVC_MEMORDER_SUFFIX (_nf), __ATOMIC_RELAXED, ptr, expect, new_value); return expect; case bson_memory_order_consume: - DEF_ATOMIC_CMPEXCH_STRONG (Pointer, - MSVC_MEMORDER_SUFFIX (_acq), - __ATOMIC_CONSUME, - ptr, - expect, - new_value); + DEF_ATOMIC_CMPEXCH_STRONG (Pointer, MSVC_MEMORDER_SUFFIX (_acq), __ATOMIC_CONSUME, ptr, expect, new_value); return expect; case bson_memory_order_acquire: - DEF_ATOMIC_CMPEXCH_STRONG (Pointer, - MSVC_MEMORDER_SUFFIX (_acq), - __ATOMIC_ACQUIRE, - ptr, - expect, - new_value); + DEF_ATOMIC_CMPEXCH_STRONG (Pointer, MSVC_MEMORDER_SUFFIX (_acq), __ATOMIC_ACQUIRE, ptr, expect, new_value); return expect; default: BSON_UNREACHABLE ("Invalid bson_memory_order value"); @@ -686,41 +537,22 @@ bson_atomic_ptr_compare_exchange_strong (void *volatile *ptr, static BSON_INLINE void * -bson_atomic_ptr_compare_exchange_weak (void *volatile *ptr, - void *expect, - void *new_value, - enum bson_memory_order ord) +bson_atomic_ptr_compare_exchange_weak (void *volatile *ptr, void *expect, void *new_value, enum bson_memory_order ord) { switch (ord) { case bson_memory_order_release: case bson_memory_order_acq_rel: case bson_memory_order_seq_cst: - DEF_ATOMIC_CMPEXCH_WEAK ( - Pointer, , __ATOMIC_SEQ_CST, ptr, expect, new_value); + DEF_ATOMIC_CMPEXCH_WEAK (Pointer, , __ATOMIC_SEQ_CST, ptr, expect, new_value); return expect; case bson_memory_order_relaxed: - DEF_ATOMIC_CMPEXCH_WEAK (Pointer, - MSVC_MEMORDER_SUFFIX (_nf), - __ATOMIC_RELAXED, - ptr, - expect, - new_value); + DEF_ATOMIC_CMPEXCH_WEAK (Pointer, MSVC_MEMORDER_SUFFIX (_nf), __ATOMIC_RELAXED, ptr, expect, new_value); return expect; case bson_memory_order_consume: - DEF_ATOMIC_CMPEXCH_WEAK (Pointer, - MSVC_MEMORDER_SUFFIX (_acq), - __ATOMIC_CONSUME, - ptr, - expect, - new_value); + DEF_ATOMIC_CMPEXCH_WEAK (Pointer, MSVC_MEMORDER_SUFFIX (_acq), __ATOMIC_CONSUME, ptr, expect, new_value); return expect; case bson_memory_order_acquire: - DEF_ATOMIC_CMPEXCH_WEAK (Pointer, - MSVC_MEMORDER_SUFFIX (_acq), - __ATOMIC_ACQUIRE, - ptr, - expect, - new_value); + DEF_ATOMIC_CMPEXCH_WEAK (Pointer, MSVC_MEMORDER_SUFFIX (_acq), __ATOMIC_ACQUIRE, ptr, expect, new_value); return expect; default: BSON_UNREACHABLE ("Invalid bson_memory_order value"); @@ -731,8 +563,7 @@ bson_atomic_ptr_compare_exchange_weak (void *volatile *ptr, static BSON_INLINE void * bson_atomic_ptr_fetch (void *volatile const *ptr, enum bson_memory_order ord) { - return bson_atomic_ptr_compare_exchange_strong ( - (void *volatile *) ptr, NULL, NULL, ord); + return bson_atomic_ptr_compare_exchange_strong ((void *volatile *) ptr, NULL, NULL, ord); } #undef DECL_ATOMIC_STDINT diff --git a/src/libbson/src/bson/bson-cmp.h b/src/libbson/src/bson/bson-cmp.h index 8db9ed950a..5a90d0f1a6 100644 --- a/src/libbson/src/bson/bson-cmp.h +++ b/src/libbson/src/bson/bson-cmp.h @@ -54,36 +54,28 @@ BSON_BEGIN_DECLS */ -#define BSON_CMP_SET(op, ss, uu, su, us) \ - static BSON_INLINE bool BSON_CONCAT3 (bson_cmp_, op, _ss) (int64_t t, \ - int64_t u) \ - { \ - return (ss); \ - } \ - \ - static BSON_INLINE bool BSON_CONCAT3 (bson_cmp_, op, _uu) (uint64_t t, \ - uint64_t u) \ - { \ - return (uu); \ - } \ - \ - static BSON_INLINE bool BSON_CONCAT3 (bson_cmp_, op, _su) (int64_t t, \ - uint64_t u) \ - { \ - return (su); \ - } \ - \ - static BSON_INLINE bool BSON_CONCAT3 (bson_cmp_, op, _us) (uint64_t t, \ - int64_t u) \ - { \ - return (us); \ +#define BSON_CMP_SET(op, ss, uu, su, us) \ + static BSON_INLINE bool BSON_CONCAT3 (bson_cmp_, op, _ss) (int64_t t, int64_t u) \ + { \ + return (ss); \ + } \ + \ + static BSON_INLINE bool BSON_CONCAT3 (bson_cmp_, op, _uu) (uint64_t t, uint64_t u) \ + { \ + return (uu); \ + } \ + \ + static BSON_INLINE bool BSON_CONCAT3 (bson_cmp_, op, _su) (int64_t t, uint64_t u) \ + { \ + return (su); \ + } \ + \ + static BSON_INLINE bool BSON_CONCAT3 (bson_cmp_, op, _us) (uint64_t t, int64_t u) \ + { \ + return (us); \ } -BSON_CMP_SET (equal, - t == u, - t == u, - t < 0 ? false : (uint64_t) (t) == u, - u < 0 ? false : t == (uint64_t) (u)) +BSON_CMP_SET (equal, t == u, t == u, t < 0 ? false : (uint64_t) (t) == u, u < 0 ? false : t == (uint64_t) (u)) BSON_CMP_SET (not_equal, !bson_cmp_equal_ss (t, u), @@ -91,17 +83,10 @@ BSON_CMP_SET (not_equal, !bson_cmp_equal_su (t, u), !bson_cmp_equal_us (t, u)) -BSON_CMP_SET (less, - t < u, - t < u, - t < 0 ? true : (uint64_t) (t) < u, - u < 0 ? false : t < (uint64_t) (u)) +BSON_CMP_SET (less, t < u, t < u, t < 0 ? true : (uint64_t) (t) < u, u < 0 ? false : t < (uint64_t) (u)) -BSON_CMP_SET (greater, - bson_cmp_less_ss (u, t), - bson_cmp_less_uu (u, t), - bson_cmp_less_us (u, t), - bson_cmp_less_su (u, t)) +BSON_CMP_SET ( + greater, bson_cmp_less_ss (u, t), bson_cmp_less_uu (u, t), bson_cmp_less_us (u, t), bson_cmp_less_su (u, t)) BSON_CMP_SET (less_equal, !bson_cmp_greater_ss (t, u), @@ -120,35 +105,28 @@ BSON_CMP_SET (greater_equal, /* Return true if the given value is within the range of the corresponding * signed type. The suffix must match the signedness of the given value. */ -#define BSON_IN_RANGE_SET_SIGNED(Type, min, max) \ - static BSON_INLINE bool BSON_CONCAT3 (bson_in_range, _##Type, _signed) ( \ - int64_t value) \ - { \ - return bson_cmp_greater_equal_ss (value, min) && \ - bson_cmp_less_equal_ss (value, max); \ - } \ - \ - static BSON_INLINE bool BSON_CONCAT3 (bson_in_range, _##Type, _unsigned) ( \ - uint64_t value) \ - { \ - return bson_cmp_greater_equal_us (value, min) && \ - bson_cmp_less_equal_us (value, max); \ +#define BSON_IN_RANGE_SET_SIGNED(Type, min, max) \ + static BSON_INLINE bool BSON_CONCAT3 (bson_in_range, _##Type, _signed) (int64_t value) \ + { \ + return bson_cmp_greater_equal_ss (value, min) && bson_cmp_less_equal_ss (value, max); \ + } \ + \ + static BSON_INLINE bool BSON_CONCAT3 (bson_in_range, _##Type, _unsigned) (uint64_t value) \ + { \ + return bson_cmp_greater_equal_us (value, min) && bson_cmp_less_equal_us (value, max); \ } /* Return true if the given value is within the range of the corresponding * unsigned type. The suffix must match the signedness of the given value. */ -#define BSON_IN_RANGE_SET_UNSIGNED(Type, max) \ - static BSON_INLINE bool BSON_CONCAT3 (bson_in_range, _##Type, _signed) ( \ - int64_t value) \ - { \ - return bson_cmp_greater_equal_su (value, 0u) && \ - bson_cmp_less_equal_su (value, max); \ - } \ - \ - static BSON_INLINE bool BSON_CONCAT3 (bson_in_range, _##Type, _unsigned) ( \ - uint64_t value) \ - { \ - return bson_cmp_less_equal_uu (value, max); \ +#define BSON_IN_RANGE_SET_UNSIGNED(Type, max) \ + static BSON_INLINE bool BSON_CONCAT3 (bson_in_range, _##Type, _signed) (int64_t value) \ + { \ + return bson_cmp_greater_equal_su (value, 0u) && bson_cmp_less_equal_su (value, max); \ + } \ + \ + static BSON_INLINE bool BSON_CONCAT3 (bson_in_range, _##Type, _unsigned) (uint64_t value) \ + { \ + return bson_cmp_less_equal_uu (value, max); \ } BSON_IN_RANGE_SET_SIGNED (signed_char, SCHAR_MIN, SCHAR_MAX) @@ -182,13 +160,11 @@ BSON_IN_RANGE_SET_UNSIGNED (size_t, SIZE_MAX) /* Return true if the value with *signed* type is in the representable range of * Type and false otherwise. */ -#define bson_in_range_signed(Type, value) \ - BSON_CONCAT3 (bson_in_range, _##Type, _signed) (value) +#define bson_in_range_signed(Type, value) BSON_CONCAT3 (bson_in_range, _##Type, _signed) (value) /* Return true if the value with *unsigned* type is in the representable range * of Type and false otherwise. */ -#define bson_in_range_unsigned(Type, value) \ - BSON_CONCAT3 (bson_in_range, _##Type, _unsigned) (value) +#define bson_in_range_unsigned(Type, value) BSON_CONCAT3 (bson_in_range, _##Type, _unsigned) (value) BSON_END_DECLS diff --git a/src/libbson/src/bson/bson-compat.h b/src/libbson/src/bson/bson-compat.h index 5f8e092f28..f403fb4c77 100644 --- a/src/libbson/src/bson/bson-compat.h +++ b/src/libbson/src/bson/bson-compat.h @@ -133,8 +133,7 @@ typedef SSIZE_T ssize_t; /* Derive the maximum representable value of signed integer type T using the * formula 2^(N - 1) - 1 where N is the number of bits in type T. This assumes * T is represented using two's complement. */ -#define BSON_NUMERIC_LIMITS_MAX_SIGNED(T) \ - ((T) ((((size_t) 0x01u) << (sizeof (T) * (size_t) CHAR_BIT - 1u)) - 1u)) +#define BSON_NUMERIC_LIMITS_MAX_SIGNED(T) ((T) ((((size_t) 0x01u) << (sizeof (T) * (size_t) CHAR_BIT - 1u)) - 1u)) /* Derive the minimum representable value of signed integer type T as one less * than the negation of its maximum representable value. This assumes T is @@ -173,8 +172,7 @@ typedef signed char bool; #if defined(__GNUC__) #if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 1) #define bson_sync_synchronize() __sync_synchronize () -#elif defined(__i386__) || defined(__i486__) || defined(__i586__) || \ - defined(__i686__) || defined(__x86_64__) +#elif defined(__i386__) || defined(__i486__) || defined(__i586__) || defined(__i686__) || defined(__x86_64__) #define bson_sync_synchronize() asm volatile ("mfence" ::: "memory") #else #define bson_sync_synchronize() asm volatile ("sync" ::: "memory") diff --git a/src/libbson/src/bson/bson-context.c b/src/libbson/src/bson/bson-context.c index d1adfc4706..f9f545f77e 100644 --- a/src/libbson/src/bson/bson-context.c +++ b/src/libbson/src/bson/bson-context.c @@ -62,13 +62,9 @@ _bson_context_set_oid_seq32 (bson_context_t *context, /* IN */ bson_oid_t *oid) /* OUT */ { uint32_t seq = (uint32_t) bson_atomic_int32_fetch_add ( - (DECL_ATOMIC_INTEGRAL_INT32 *) &context->seq32, - 1, - bson_memory_order_seq_cst); + (DECL_ATOMIC_INTEGRAL_INT32 *) &context->seq32, 1, bson_memory_order_seq_cst); seq = BSON_UINT32_TO_BE (seq); - memcpy (&oid->bytes[BSON_OID_SEQ32_OFFSET], - ((uint8_t *) &seq) + 1, - BSON_OID_SEQ32_SIZE); + memcpy (&oid->bytes[BSON_OID_SEQ32_OFFSET], ((uint8_t *) &seq) + 1, BSON_OID_SEQ32_SIZE); } @@ -76,8 +72,7 @@ void _bson_context_set_oid_seq64 (bson_context_t *context, /* IN */ bson_oid_t *oid) /* OUT */ { - uint64_t seq = (uint64_t) bson_atomic_int64_fetch_add ( - (int64_t *) &context->seq64, 1, bson_memory_order_seq_cst); + uint64_t seq = (uint64_t) bson_atomic_int64_fetch_add ((int64_t *) &context->seq64, 1, bson_memory_order_seq_cst); seq = BSON_UINT64_TO_BE (seq); memcpy (&oid->bytes[BSON_OID_SEQ64_OFFSET], &seq, BSON_OID_SEQ64_SIZE); @@ -98,9 +93,7 @@ _bson_context_get_hostname (char out[HOST_NAME_MAX]) { if (gethostname (out, HOST_NAME_MAX) != 0) { if (errno == ENAMETOOLONG) { - fprintf (stderr, - "hostname exceeds %d characters, truncating.", - HOST_NAME_MAX); + fprintf (stderr, "hostname exceeds %d characters, truncating.", HOST_NAME_MAX); } else { fprintf (stderr, "unable to get hostname: %d", errno); } @@ -160,10 +153,7 @@ _sip_round (uint64_t *v0, uint64_t *v1, uint64_t *v2, uint64_t *v3) } void -_siphash (const void *in, - const size_t inlen, - const uint64_t key[2], - uint64_t digest[2]) +_siphash (const void *in, const size_t inlen, const uint64_t key[2], uint64_t digest[2]) { const unsigned char *ni = (const unsigned char *) in; const unsigned char *kk = (const unsigned char *) key; @@ -288,8 +278,7 @@ _bson_context_init_random (bson_context_t *context, bool init_seq) bson_gettimeofday (&rand_params.time); rand_params.pid = _bson_getpid (); _bson_context_get_hostname (rand_params.hostname); - rand_params.rand_call_counter = bson_atomic_int64_fetch_add ( - &s_rand_call_counter, 1, bson_memory_order_seq_cst); + rand_params.rand_call_counter = bson_atomic_int64_fetch_add (&s_rand_call_counter, 1, bson_memory_order_seq_cst); /* Generate a SipHash key. We do not care about secrecy or determinism, only * uniqueness. */ @@ -334,14 +323,11 @@ _bson_context_set_oid_rand (bson_context_t *context, bson_oid_t *oid) * after a call to fork() */ uint64_t now_pid = _bson_getpid (); if (now_pid != context->pid) { - _bson_context_init_random ( - context, false /* Do not update the sequence counters */); + _bson_context_init_random (context, false /* Do not update the sequence counters */); } } /* Copy the stored randomness into the OID */ - memcpy (oid->bytes + BSON_OID_RANDOMESS_OFFSET, - &context->randomness, - BSON_OID_RANDOMNESS_SIZE); + memcpy (oid->bytes + BSON_OID_RANDOMESS_OFFSET, &context->randomness, BSON_OID_RANDOMNESS_SIZE); } diff --git a/src/libbson/src/bson/bson-decimal128.c b/src/libbson/src/bson/bson-decimal128.c index 5940ffb9a5..786963c24c 100644 --- a/src/libbson/src/bson/bson-decimal128.c +++ b/src/libbson/src/bson/bson-decimal128.c @@ -85,8 +85,7 @@ _bson_uint128_divide1B (_bson_uint128_t value, /* IN */ uint64_t _rem = 0; int i = 0; - if (!value.parts[0] && !value.parts[1] && !value.parts[2] && - !value.parts[3]) { + if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) { *quotient = value; *rem = 0; return; @@ -94,7 +93,7 @@ _bson_uint128_divide1B (_bson_uint128_t value, /* IN */ for (i = 0; i <= 3; i++) { - _rem <<= 32; /* Adjust remainder to match value of next dividend */ + _rem <<= 32; /* Adjust remainder to match value of next dividend */ _rem += value.parts[i]; /* Add the divided to _rem */ value.parts[i] = (uint32_t) (_rem / DIVISOR); _rem %= DIVISOR; /* Store the remainder */ @@ -141,23 +140,22 @@ bson_decimal128_to_string (const bson_decimal128_t *dec, /* IN */ /* Note: bits in this routine are referred to starting at 0, */ /* from the sign bit, towards the coefficient. */ - uint32_t high; /* bits 0 - 31 */ - uint32_t midh; /* bits 32 - 63 */ - uint32_t midl; /* bits 64 - 95 */ - uint32_t low; /* bits 96 - 127 */ - uint32_t combination; /* bits 1 - 5 */ - uint32_t biased_exponent; /* decoded biased exponent (14 bits) */ - uint32_t significand_digits = 0; /* the number of significand digits */ - uint32_t significand[36] = {0}; /* the base-10 digits in the significand */ + uint32_t high; /* bits 0 - 31 */ + uint32_t midh; /* bits 32 - 63 */ + uint32_t midl; /* bits 64 - 95 */ + uint32_t low; /* bits 96 - 127 */ + uint32_t combination; /* bits 1 - 5 */ + uint32_t biased_exponent; /* decoded biased exponent (14 bits) */ + uint32_t significand_digits = 0; /* the number of significand digits */ + uint32_t significand[36] = {0}; /* the base-10 digits in the significand */ uint32_t *significand_read = significand; /* read pointer into significand */ int32_t exponent; /* unbiased exponent */ - int32_t scientific_exponent; /* the exponent if scientific notation is - * used */ - bool is_zero = false; /* true if the number is zero */ + int32_t scientific_exponent; /* the exponent if scientific notation is + * used */ + bool is_zero = false; /* true if the number is zero */ - uint8_t significand_msb; /* the most signifcant significand bits (50-46) */ - _bson_uint128_t - significand128; /* temporary storage for significand decoding */ + uint8_t significand_msb; /* the most signifcant significand bits (50-46) */ + _bson_uint128_t significand128; /* temporary storage for significand decoding */ memset (significand_str, 0, sizeof (significand_str)); @@ -203,8 +201,8 @@ bson_decimal128_to_string (const bson_decimal128_t *dec, /* IN */ significand128.parts[2] = midl; significand128.parts[3] = low; - if (significand128.parts[0] == 0 && significand128.parts[1] == 0 && - significand128.parts[2] == 0 && significand128.parts[3] == 0) { + if (significand128.parts[0] == 0 && significand128.parts[1] == 0 && significand128.parts[2] == 0 && + significand128.parts[3] == 0) { is_zero = true; } else if (significand128.parts[0] >= (1 << 17)) { /* The significand is non-canonical or zero. @@ -217,8 +215,7 @@ bson_decimal128_to_string (const bson_decimal128_t *dec, /* IN */ } else { for (int k = 3; k >= 0; k--) { uint32_t least_digits = 0; - _bson_uint128_divide1B ( - significand128, &significand128, &least_digits); + _bson_uint128_divide1B (significand128, &significand128, &least_digits); /* We now have the 9 least significant digits (in base 2). */ /* Convert and output to string. */ @@ -267,8 +264,7 @@ bson_decimal128_to_string (const bson_decimal128_t *dec, /* IN */ *(str_out++) = '.'; } - for (uint32_t i = 0; i < significand_digits && (str_out - str) < 36; - i++) { + for (uint32_t i = 0; i < significand_digits && (str_out - str) < 36; i++) { *(str_out++) = *(significand_read++) + '0'; } /* Exponent */ @@ -277,8 +273,7 @@ bson_decimal128_to_string (const bson_decimal128_t *dec, /* IN */ } else { /* Regular format with no decimal place */ if (exponent >= 0) { - for (uint32_t i = 0; i < significand_digits && (str_out - str) < 36; - i++) { + for (uint32_t i = 0; i < significand_digits && (str_out - str) < 36; i++) { *(str_out++) = *(significand_read++) + '0'; } *str_out = '\0'; @@ -286,9 +281,7 @@ bson_decimal128_to_string (const bson_decimal128_t *dec, /* IN */ int32_t radix_position = significand_digits + exponent; if (radix_position > 0) { /* non-zero digits before radix */ - for (int32_t i = 0; - i < radix_position && (str_out - str) < BSON_DECIMAL128_STRING; - i++) { + for (int32_t i = 0; i < radix_position && (str_out - str) < BSON_DECIMAL128_STRING; i++) { *(str_out++) = *(significand_read++) + '0'; } } else { /* leading zero before radix point */ @@ -300,10 +293,8 @@ bson_decimal128_to_string (const bson_decimal128_t *dec, /* IN */ *(str_out++) = '0'; } - for (uint32_t i = 0; - bson_cmp_greater_us (significand_digits - i, - BSON_MAX (radix_position - 1, 0)) && - (str_out - str) < BSON_DECIMAL128_STRING; + for (uint32_t i = 0; bson_cmp_greater_us (significand_digits - i, BSON_MAX (radix_position - 1, 0)) && + (str_out - str) < BSON_DECIMAL128_STRING; i++) { *(str_out++) = *(significand_read++) + '0'; } @@ -337,8 +328,7 @@ _mul_64x64 (uint64_t left, /* IN */ uint64_t right, /* IN */ _bson_uint128_6464_t *product) /* OUT */ { - uint64_t left_high, left_low, right_high, right_low, product_high, - product_mid, product_mid2, product_low; + uint64_t left_high, left_low, right_high, right_low, product_high, product_mid, product_mid2, product_low; _bson_uint128_6464_t rt = {0}; if (!left && !right) { @@ -495,9 +485,9 @@ bson_decimal128_from_string_w_len (const char *string, /* IN */ size_t significant_digits = 0; /* Total number of significant digits * (no leading or trailing zero) */ size_t ndigits_read = 0; /* Total number of significand digits read */ - size_t ndigits = 0; /* Total number of digits (no leading zeros) */ - size_t radix_position = 0; /* The number of the digits after radix */ - size_t first_nonzero = 0; /* The index of the first non-zero in *str* */ + size_t ndigits = 0; /* Total number of digits (no leading zeros) */ + size_t radix_position = 0; /* The number of the digits after radix */ + size_t first_nonzero = 0; /* The index of the first non-zero in *str* */ uint16_t digits[BSON_DECIMAL128_MAX_DIGITS] = {0}; uint16_t ndigits_stored = 0; /* The number of digits in digits */ @@ -521,8 +511,7 @@ bson_decimal128_from_string_w_len (const char *string, /* IN */ /* Check for Infinity or NaN */ if (!isdigit (*str_read) && *str_read != '.') { - if (_dec128_istreq (str_read, "inf") || - _dec128_istreq (str_read, "infinity")) { + if (_dec128_istreq (str_read, "inf") || _dec128_istreq (str_read, "infinity")) { BSON_DECIMAL128_SET_INF (*dec, is_negative); return true; } else if (_dec128_istreq (str_read, "nan")) { @@ -535,8 +524,7 @@ bson_decimal128_from_string_w_len (const char *string, /* IN */ } /* Read digits */ - while (((isdigit (*str_read) || *str_read == '.')) && - (len == -1 || str_read < string + len)) { + while (((isdigit (*str_read) || *str_read == '.')) && (len == -1 || str_read < string + len)) { if (*str_read == '.') { if (saw_radix) { BSON_DECIMAL128_SET_NAN (*dec); @@ -586,12 +574,10 @@ bson_decimal128_from_string_w_len (const char *string, /* IN */ #define SSCANF sscanf #endif int64_t temp_exponent = 0; - int read_exponent = - SSCANF (++str_read, "%" SCNd64 "%n", &temp_exponent, &nread); + int read_exponent = SSCANF (++str_read, "%" SCNd64 "%n", &temp_exponent, &nread); str_read += nread; - if (!read_exponent || nread == 0 || - !bson_in_range_int32_t_signed (temp_exponent)) { + if (!read_exponent || nread == 0 || !bson_in_range_int32_t_signed (temp_exponent)) { BSON_DECIMAL128_SET_NAN (*dec); return false; } @@ -620,8 +606,7 @@ bson_decimal128_from_string_w_len (const char *string, /* IN */ last_digit = ndigits_stored - 1; significant_digits = ndigits; /* Mark trailing zeros as non-significant */ - while (string[first_nonzero + significant_digits - 1 + includes_sign + - saw_radix] == '0') { + while (string[first_nonzero + significant_digits - 1 + includes_sign + saw_radix] == '0') { significant_digits--; } } @@ -676,8 +661,7 @@ bson_decimal128_from_string_w_len (const char *string, /* IN */ } if (ndigits_stored < ndigits) { - if (string[ndigits - 1 + includes_sign + saw_radix] - '0' != 0 && - significant_digits != 0) { + if (string[ndigits - 1 + includes_sign + saw_radix] - '0' != 0 && significant_digits != 0) { BSON_DECIMAL128_SET_NAN (*dec); return false; } @@ -709,9 +693,7 @@ bson_decimal128_from_string_w_len (const char *string, /* IN */ /* There are non-zero digits after last_digit that need rounding. */ /* We round to nearest, ties to even */ - round_digit = - string[first_nonzero + last_digit + includes_sign + saw_radix + 1] - - '0'; + round_digit = string[first_nonzero + last_digit + includes_sign + saw_radix + 1] - '0'; if (round_digit != 0) { /* Inexact (non-zero) rounding is not allowed */ diff --git a/src/libbson/src/bson/bson-decimal128.h b/src/libbson/src/bson/bson-decimal128.h index 0ab7288970..aa1d53afb0 100644 --- a/src/libbson/src/bson/bson-decimal128.h +++ b/src/libbson/src/bson/bson-decimal128.h @@ -54,9 +54,7 @@ BSON_EXPORT (bool) bson_decimal128_from_string (const char *string, bson_decimal128_t *dec); BSON_EXPORT (bool) -bson_decimal128_from_string_w_len (const char *string, - int len, - bson_decimal128_t *dec); +bson_decimal128_from_string_w_len (const char *string, int len, bson_decimal128_t *dec); BSON_END_DECLS diff --git a/src/libbson/src/bson/bson-endian.h b/src/libbson/src/bson/bson-endian.h index 85ae95fb58..1527f10887 100644 --- a/src/libbson/src/bson/bson-endian.h +++ b/src/libbson/src/bson/bson-endian.h @@ -41,8 +41,7 @@ BSON_BEGIN_DECLS #define BSON_UINT16_SWAP_LE_BE(v) BSWAP_16 ((uint16_t) v) #define BSON_UINT32_SWAP_LE_BE(v) BSWAP_32 ((uint32_t) v) #define BSON_UINT64_SWAP_LE_BE(v) BSWAP_64 ((uint64_t) v) -#elif defined(__clang__) && defined(__clang_major__) && \ - defined(__clang_minor__) && (__clang_major__ >= 3) && \ +#elif defined(__clang__) && defined(__clang_major__) && defined(__clang_minor__) && (__clang_major__ >= 3) && \ (__clang_minor__ >= 1) #if __has_builtin(__builtin_bswap16) #define BSON_UINT16_SWAP_LE_BE(v) __builtin_bswap16 (v) @@ -156,8 +155,7 @@ __bson_uint16_swap_slow (uint16_t v) /* IN */ static BSON_INLINE uint32_t __bson_uint32_swap_slow (uint32_t v) /* IN */ { - return ((v & 0x000000FFU) << 24) | ((v & 0x0000FF00U) << 8) | - ((v & 0x00FF0000U) >> 8) | ((v & 0xFF000000U) >> 24); + return ((v & 0x000000FFU) << 24) | ((v & 0x0000FF00U) << 8) | ((v & 0x00FF0000U) >> 8) | ((v & 0xFF000000U) >> 24); } @@ -180,14 +178,10 @@ __bson_uint32_swap_slow (uint32_t v) /* IN */ static BSON_INLINE uint64_t __bson_uint64_swap_slow (uint64_t v) /* IN */ { - return ((v & 0x00000000000000FFULL) << 56) | - ((v & 0x000000000000FF00ULL) << 40) | - ((v & 0x0000000000FF0000ULL) << 24) | - ((v & 0x00000000FF000000ULL) << 8) | - ((v & 0x000000FF00000000ULL) >> 8) | - ((v & 0x0000FF0000000000ULL) >> 24) | - ((v & 0x00FF000000000000ULL) >> 40) | - ((v & 0xFF00000000000000ULL) >> 56); + return ((v & 0x00000000000000FFULL) << 56) | ((v & 0x000000000000FF00ULL) << 40) | + ((v & 0x0000000000FF0000ULL) << 24) | ((v & 0x00000000FF000000ULL) << 8) | + ((v & 0x000000FF00000000ULL) >> 8) | ((v & 0x0000FF0000000000ULL) >> 24) | + ((v & 0x00FF000000000000ULL) >> 40) | ((v & 0xFF00000000000000ULL) >> 56); } diff --git a/src/libbson/src/bson/bson-error.h b/src/libbson/src/bson/bson-error.h index 7bfb21bf47..7d17b84cdc 100644 --- a/src/libbson/src/bson/bson-error.h +++ b/src/libbson/src/bson/bson-error.h @@ -35,11 +35,7 @@ BSON_BEGIN_DECLS BSON_EXPORT (void) -bson_set_error (bson_error_t *error, - uint32_t domain, - uint32_t code, - const char *format, - ...) BSON_GNUC_PRINTF (4, 5); +bson_set_error (bson_error_t *error, uint32_t domain, uint32_t code, const char *format, ...) BSON_GNUC_PRINTF (4, 5); BSON_EXPORT (char *) bson_strerror_r (int err_code, char *buf, size_t buflen); diff --git a/src/libbson/src/bson/bson-iso8601-private.h b/src/libbson/src/bson/bson-iso8601-private.h index f76cb56a32..81909a7910 100644 --- a/src/libbson/src/bson/bson-iso8601-private.h +++ b/src/libbson/src/bson/bson-iso8601-private.h @@ -29,10 +29,7 @@ BSON_BEGIN_DECLS bool -_bson_iso8601_date_parse (const char *str, - int32_t len, - int64_t *out, - bson_error_t *error); +_bson_iso8601_date_parse (const char *str, int32_t len, int64_t *out, bson_error_t *error); /** * _bson_iso8601_date_format: diff --git a/src/libbson/src/bson/bson-iso8601.c b/src/libbson/src/bson/bson-iso8601.c index 2161f85dc3..2acb5b4af5 100644 --- a/src/libbson/src/bson/bson-iso8601.c +++ b/src/libbson/src/bson/bson-iso8601.c @@ -24,11 +24,7 @@ static bool -get_tok (const char *terminals, - const char **ptr, - int32_t *remaining, - const char **out, - int32_t *out_len) +get_tok (const char *terminals, const char **ptr, int32_t *remaining, const char **out, int32_t *out_len) { const char *terminal; bool found_terminal = false; @@ -41,8 +37,7 @@ get_tok (const char *terminals, *out = *ptr; *out_len = -1; - for (; *remaining && !found_terminal; - (*ptr)++, (*remaining)--, (*out_len)++) { + for (; *remaining && !found_terminal; (*ptr)++, (*remaining)--, (*out_len)++) { for (terminal = terminals; *terminal; terminal++) { if (**ptr == *terminal) { found_terminal = true; @@ -73,12 +68,7 @@ digits_only (const char *str, int32_t len) } static bool -parse_num (const char *str, - int32_t len, - int32_t digits, - int32_t min, - int32_t max, - int32_t *out) +parse_num (const char *str, int32_t len, int32_t digits, int32_t min, int32_t max, int32_t *out) { int i; int magnitude = 1; @@ -102,10 +92,7 @@ parse_num (const char *str, } bool -_bson_iso8601_date_parse (const char *str, - int32_t len, - int64_t *out, - bson_error_t *error) +_bson_iso8601_date_parse (const char *str, int32_t len, int64_t *out, bson_error_t *error) { const char *ptr; int32_t remaining = len; @@ -139,12 +126,9 @@ _bson_iso8601_date_parse (const char *str, struct bson_tm posix_date = {0}; -#define DATE_PARSE_ERR(msg) \ - bson_set_error (error, \ - BSON_ERROR_JSON, \ - BSON_JSON_ERROR_READ_INVALID_PARAM, \ - "Could not parse \"%s\" as date: " msg, \ - str); \ +#define DATE_PARSE_ERR(msg) \ + bson_set_error ( \ + error, BSON_ERROR_JSON, BSON_JSON_ERROR_READ_INVALID_PARAM, "Could not parse \"%s\" as date: " msg, str); \ return false #define DEFAULT_DATE_PARSE_ERR \ @@ -156,8 +140,7 @@ _bson_iso8601_date_parse (const char *str, /* we have to match at least yyyy-mm-ddThh:mm */ if (!(get_tok ("-", &ptr, &remaining, &year_ptr, &year_len) && get_tok ("-", &ptr, &remaining, &month_ptr, &month_len) && - get_tok ("T", &ptr, &remaining, &day_ptr, &day_len) && - get_tok (":", &ptr, &remaining, &hour_ptr, &hour_len) && + get_tok ("T", &ptr, &remaining, &day_ptr, &day_len) && get_tok (":", &ptr, &remaining, &hour_ptr, &hour_len) && get_tok (":+-Z", &ptr, &remaining, &min_ptr, &min_len))) { DEFAULT_DATE_PARSE_ERR; } @@ -245,8 +228,7 @@ _bson_iso8601_date_parse (const char *str, /* we inflect the meaning of a 'positive' timezone. Those are hours * we have to subtract, and vice versa */ - tz_adjustment = - (tz_ptr[0] == '-' ? 1 : -1) * ((tz_min * 60) + (tz_hour * 60 * 60)); + tz_adjustment = (tz_ptr[0] == '-' ? 1 : -1) * ((tz_min * 60) + (tz_hour * 60 * 60)); if (!(tz_adjustment > -86400 && tz_adjustment < 86400)) { DATE_PARSE_ERR ("timezone offset must be less than 24 hours"); diff --git a/src/libbson/src/bson/bson-iter.c b/src/libbson/src/bson/bson-iter.c index a71b2b59ee..9fdd6dd103 100644 --- a/src/libbson/src/bson/bson-iter.c +++ b/src/libbson/src/bson/bson-iter.c @@ -239,8 +239,7 @@ bson_iter_init_find_w_len (bson_iter_t *iter, /* INOUT */ BSON_ASSERT (bson); BSON_ASSERT (key); - return bson_iter_init (iter, bson) && - bson_iter_find_w_len (iter, key, keylen); + return bson_iter_init (iter, bson) && bson_iter_find_w_len (iter, key, keylen); } @@ -1530,8 +1529,7 @@ bson_iter_dbpointer (const bson_iter_t *iter, /* IN */ if (ITER_TYPE (iter) == BSON_TYPE_DBPOINTER) { if (collection_len) { - memcpy ( - collection_len, (iter->raw + iter->d1), sizeof (*collection_len)); + memcpy (collection_len, (iter->raw + iter->d1), sizeof (*collection_len)); *collection_len = BSON_UINT32_FROM_LE (*collection_len); if ((*collection_len) > 0) { @@ -1946,8 +1944,7 @@ bson_iter_visit_all (bson_iter_t *iter, /* INOUT */ bson_iter_document (iter, &doclen, &docbuf); - if (bson_init_static (&b, docbuf, doclen) && - VISIT_DOCUMENT (iter, key, &b, data)) { + if (bson_init_static (&b, docbuf, doclen) && VISIT_DOCUMENT (iter, key, &b, data)) { return true; } } break; @@ -1958,8 +1955,7 @@ bson_iter_visit_all (bson_iter_t *iter, /* INOUT */ bson_iter_array (iter, &doclen, &docbuf); - if (bson_init_static (&b, docbuf, doclen) && - VISIT_ARRAY (iter, key, &b, data)) { + if (bson_init_static (&b, docbuf, doclen) && VISIT_ARRAY (iter, key, &b, data)) { return true; } } break; @@ -2035,8 +2031,7 @@ bson_iter_visit_all (bson_iter_t *iter, /* INOUT */ return true; } - if (VISIT_DBPOINTER ( - iter, key, collection_len, collection, oid, data)) { + if (VISIT_DBPOINTER (iter, key, collection_len, collection, oid, data)) { return true; } } break; @@ -2084,8 +2079,7 @@ bson_iter_visit_all (bson_iter_t *iter, /* INOUT */ return true; } - if (bson_init_static (&b, docbuf, doclen) && - VISIT_CODEWSCOPE (iter, key, length, code, &b, data)) { + if (bson_init_static (&b, docbuf, doclen) && VISIT_CODEWSCOPE (iter, key, length, code, &b, data)) { return true; } } break; @@ -2145,8 +2139,7 @@ bson_iter_visit_all (bson_iter_t *iter, /* INOUT */ } if (iter->err_off) { - if (unsupported && visitor->visit_unsupported_type && - bson_utf8_validate (key, strlen (key), false)) { + if (unsupported && visitor->visit_unsupported_type && bson_utf8_validate (key, strlen (key), false)) { visitor->visit_unsupported_type (iter, key, bson_type, data); return false; } @@ -2195,16 +2188,13 @@ bson_iter_overwrite_oid (bson_iter_t *iter, const bson_oid_t *value) BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_OID) { - memcpy ( - (void *) (iter->raw + iter->d1), value->bytes, sizeof (value->bytes)); + memcpy ((void *) (iter->raw + iter->d1), value->bytes, sizeof (value->bytes)); } } void -bson_iter_overwrite_timestamp (bson_iter_t *iter, - uint32_t timestamp, - uint32_t increment) +bson_iter_overwrite_timestamp (bson_iter_t *iter, uint32_t timestamp, uint32_t increment) { uint64_t value; BSON_ASSERT (iter); @@ -2392,18 +2382,13 @@ bson_iter_value (bson_iter_t *iter) /* IN */ value->value.v_double = bson_iter_double (iter); break; case BSON_TYPE_UTF8: - value->value.v_utf8.str = - (char *) bson_iter_utf8 (iter, &value->value.v_utf8.len); + value->value.v_utf8.str = (char *) bson_iter_utf8 (iter, &value->value.v_utf8.len); break; case BSON_TYPE_DOCUMENT: - bson_iter_document (iter, - &value->value.v_doc.data_len, - (const uint8_t **) &value->value.v_doc.data); + bson_iter_document (iter, &value->value.v_doc.data_len, (const uint8_t **) &value->value.v_doc.data); break; case BSON_TYPE_ARRAY: - bson_iter_array (iter, - &value->value.v_doc.data_len, - (const uint8_t **) &value->value.v_doc.data); + bson_iter_array (iter, &value->value.v_doc.data_len, (const uint8_t **) &value->value.v_doc.data); break; case BSON_TYPE_BINARY: bson_iter_binary (iter, @@ -2421,41 +2406,34 @@ bson_iter_value (bson_iter_t *iter) /* IN */ value->value.v_datetime = bson_iter_date_time (iter); break; case BSON_TYPE_REGEX: - value->value.v_regex.regex = (char *) bson_iter_regex ( - iter, (const char **) &value->value.v_regex.options); + value->value.v_regex.regex = (char *) bson_iter_regex (iter, (const char **) &value->value.v_regex.options); break; case BSON_TYPE_DBPOINTER: { const bson_oid_t *oid; - bson_iter_dbpointer (iter, - &value->value.v_dbpointer.collection_len, - (const char **) &value->value.v_dbpointer.collection, - &oid); + bson_iter_dbpointer ( + iter, &value->value.v_dbpointer.collection_len, (const char **) &value->value.v_dbpointer.collection, &oid); bson_oid_copy (oid, &value->value.v_dbpointer.oid); break; } case BSON_TYPE_CODE: - value->value.v_code.code = - (char *) bson_iter_code (iter, &value->value.v_code.code_len); + value->value.v_code.code = (char *) bson_iter_code (iter, &value->value.v_code.code_len); break; case BSON_TYPE_SYMBOL: - value->value.v_symbol.symbol = - (char *) bson_iter_symbol (iter, &value->value.v_symbol.len); + value->value.v_symbol.symbol = (char *) bson_iter_symbol (iter, &value->value.v_symbol.len); break; case BSON_TYPE_CODEWSCOPE: - value->value.v_codewscope.code = (char *) bson_iter_codewscope ( - iter, - &value->value.v_codewscope.code_len, - &value->value.v_codewscope.scope_len, - (const uint8_t **) &value->value.v_codewscope.scope_data); + value->value.v_codewscope.code = + (char *) bson_iter_codewscope (iter, + &value->value.v_codewscope.code_len, + &value->value.v_codewscope.scope_len, + (const uint8_t **) &value->value.v_codewscope.scope_data); break; case BSON_TYPE_INT32: value->value.v_int32 = bson_iter_int32 (iter); break; case BSON_TYPE_TIMESTAMP: - bson_iter_timestamp (iter, - &value->value.v_timestamp.timestamp, - &value->value.v_timestamp.increment); + bson_iter_timestamp (iter, &value->value.v_timestamp.timestamp, &value->value.v_timestamp.increment); break; case BSON_TYPE_INT64: value->value.v_int64 = bson_iter_int64 (iter); @@ -2491,11 +2469,8 @@ bson_iter_key_len (const bson_iter_t *iter) } bool -bson_iter_init_from_data_at_offset (bson_iter_t *iter, - const uint8_t *data, - size_t length, - uint32_t offset, - uint32_t keylen) +bson_iter_init_from_data_at_offset ( + bson_iter_t *iter, const uint8_t *data, size_t length, uint32_t offset, uint32_t keylen) { const char *key; uint32_t bson_type; @@ -2517,8 +2492,7 @@ bson_iter_init_from_data_at_offset (bson_iter_t *iter, iter->next_off = offset; iter->err_off = 0; - if (!_bson_iter_next_internal ( - iter, keylen, &key, &bson_type, &unsupported)) { + if (!_bson_iter_next_internal (iter, keylen, &key, &bson_type, &unsupported)) { memset (iter, 0, sizeof *iter); return false; } diff --git a/src/libbson/src/bson/bson-iter.h b/src/libbson/src/bson/bson-iter.h index 22af2e45d2..5370922d6d 100644 --- a/src/libbson/src/bson/bson-iter.h +++ b/src/libbson/src/bson/bson-iter.h @@ -30,68 +30,53 @@ BSON_BEGIN_DECLS -#define BSON_ITER_HOLDS_DOUBLE(iter) \ - (bson_iter_type ((iter)) == BSON_TYPE_DOUBLE) +#define BSON_ITER_HOLDS_DOUBLE(iter) (bson_iter_type ((iter)) == BSON_TYPE_DOUBLE) #define BSON_ITER_HOLDS_UTF8(iter) (bson_iter_type ((iter)) == BSON_TYPE_UTF8) -#define BSON_ITER_HOLDS_DOCUMENT(iter) \ - (bson_iter_type ((iter)) == BSON_TYPE_DOCUMENT) +#define BSON_ITER_HOLDS_DOCUMENT(iter) (bson_iter_type ((iter)) == BSON_TYPE_DOCUMENT) #define BSON_ITER_HOLDS_ARRAY(iter) (bson_iter_type ((iter)) == BSON_TYPE_ARRAY) -#define BSON_ITER_HOLDS_BINARY(iter) \ - (bson_iter_type ((iter)) == BSON_TYPE_BINARY) +#define BSON_ITER_HOLDS_BINARY(iter) (bson_iter_type ((iter)) == BSON_TYPE_BINARY) -#define BSON_ITER_HOLDS_UNDEFINED(iter) \ - (bson_iter_type ((iter)) == BSON_TYPE_UNDEFINED) +#define BSON_ITER_HOLDS_UNDEFINED(iter) (bson_iter_type ((iter)) == BSON_TYPE_UNDEFINED) #define BSON_ITER_HOLDS_OID(iter) (bson_iter_type ((iter)) == BSON_TYPE_OID) #define BSON_ITER_HOLDS_BOOL(iter) (bson_iter_type ((iter)) == BSON_TYPE_BOOL) -#define BSON_ITER_HOLDS_DATE_TIME(iter) \ - (bson_iter_type ((iter)) == BSON_TYPE_DATE_TIME) +#define BSON_ITER_HOLDS_DATE_TIME(iter) (bson_iter_type ((iter)) == BSON_TYPE_DATE_TIME) #define BSON_ITER_HOLDS_NULL(iter) (bson_iter_type ((iter)) == BSON_TYPE_NULL) #define BSON_ITER_HOLDS_REGEX(iter) (bson_iter_type ((iter)) == BSON_TYPE_REGEX) -#define BSON_ITER_HOLDS_DBPOINTER(iter) \ - (bson_iter_type ((iter)) == BSON_TYPE_DBPOINTER) +#define BSON_ITER_HOLDS_DBPOINTER(iter) (bson_iter_type ((iter)) == BSON_TYPE_DBPOINTER) #define BSON_ITER_HOLDS_CODE(iter) (bson_iter_type ((iter)) == BSON_TYPE_CODE) -#define BSON_ITER_HOLDS_SYMBOL(iter) \ - (bson_iter_type ((iter)) == BSON_TYPE_SYMBOL) +#define BSON_ITER_HOLDS_SYMBOL(iter) (bson_iter_type ((iter)) == BSON_TYPE_SYMBOL) -#define BSON_ITER_HOLDS_CODEWSCOPE(iter) \ - (bson_iter_type ((iter)) == BSON_TYPE_CODEWSCOPE) +#define BSON_ITER_HOLDS_CODEWSCOPE(iter) (bson_iter_type ((iter)) == BSON_TYPE_CODEWSCOPE) #define BSON_ITER_HOLDS_INT32(iter) (bson_iter_type ((iter)) == BSON_TYPE_INT32) -#define BSON_ITER_HOLDS_TIMESTAMP(iter) \ - (bson_iter_type ((iter)) == BSON_TYPE_TIMESTAMP) +#define BSON_ITER_HOLDS_TIMESTAMP(iter) (bson_iter_type ((iter)) == BSON_TYPE_TIMESTAMP) #define BSON_ITER_HOLDS_INT64(iter) (bson_iter_type ((iter)) == BSON_TYPE_INT64) -#define BSON_ITER_HOLDS_DECIMAL128(iter) \ - (bson_iter_type ((iter)) == BSON_TYPE_DECIMAL128) +#define BSON_ITER_HOLDS_DECIMAL128(iter) (bson_iter_type ((iter)) == BSON_TYPE_DECIMAL128) -#define BSON_ITER_HOLDS_MAXKEY(iter) \ - (bson_iter_type ((iter)) == BSON_TYPE_MAXKEY) +#define BSON_ITER_HOLDS_MAXKEY(iter) (bson_iter_type ((iter)) == BSON_TYPE_MAXKEY) -#define BSON_ITER_HOLDS_MINKEY(iter) \ - (bson_iter_type ((iter)) == BSON_TYPE_MINKEY) +#define BSON_ITER_HOLDS_MINKEY(iter) (bson_iter_type ((iter)) == BSON_TYPE_MINKEY) -#define BSON_ITER_HOLDS_INT(iter) \ - (BSON_ITER_HOLDS_INT32 (iter) || BSON_ITER_HOLDS_INT64 (iter)) +#define BSON_ITER_HOLDS_INT(iter) (BSON_ITER_HOLDS_INT32 (iter) || BSON_ITER_HOLDS_INT64 (iter)) -#define BSON_ITER_HOLDS_NUMBER(iter) \ - (BSON_ITER_HOLDS_INT (iter) || BSON_ITER_HOLDS_DOUBLE (iter)) +#define BSON_ITER_HOLDS_NUMBER(iter) (BSON_ITER_HOLDS_INT (iter) || BSON_ITER_HOLDS_DOUBLE (iter)) -#define BSON_ITER_IS_KEY(iter, key) \ - (0 == strcmp ((key), bson_iter_key ((iter)))) +#define BSON_ITER_IS_KEY(iter, key) (0 == strcmp ((key), bson_iter_key ((iter)))) BSON_EXPORT (const bson_value_t *) @@ -122,16 +107,11 @@ bson_iter_utf8_len_unsafe (const bson_iter_t *iter) BSON_EXPORT (void) -bson_iter_array (const bson_iter_t *iter, - uint32_t *array_len, - const uint8_t **array); +bson_iter_array (const bson_iter_t *iter, uint32_t *array_len, const uint8_t **array); BSON_EXPORT (void) -bson_iter_binary (const bson_iter_t *iter, - bson_subtype_t *subtype, - uint32_t *binary_len, - const uint8_t **binary); +bson_iter_binary (const bson_iter_t *iter, bson_subtype_t *subtype, uint32_t *binary_len, const uint8_t **binary); BSON_EXPORT (const char *) @@ -156,10 +136,7 @@ bson_iter_code_unsafe (const bson_iter_t *iter, uint32_t *length) BSON_EXPORT (const char *) -bson_iter_codewscope (const bson_iter_t *iter, - uint32_t *length, - uint32_t *scope_len, - const uint8_t **scope); +bson_iter_codewscope (const bson_iter_t *iter, uint32_t *length, uint32_t *scope_len, const uint8_t **scope); BSON_EXPORT (void) @@ -170,9 +147,7 @@ bson_iter_dbpointer (const bson_iter_t *iter, BSON_EXPORT (void) -bson_iter_document (const bson_iter_t *iter, - uint32_t *document_len, - const uint8_t **document); +bson_iter_document (const bson_iter_t *iter, uint32_t *document_len, const uint8_t **document); BSON_EXPORT (double) @@ -203,9 +178,7 @@ BSON_EXPORT (bool) bson_iter_init (bson_iter_t *iter, const bson_t *bson); BSON_EXPORT (bool) -bson_iter_init_from_data (bson_iter_t *iter, - const uint8_t *data, - size_t length); +bson_iter_init_from_data (bson_iter_t *iter, const uint8_t *data, size_t length); BSON_EXPORT (bool) @@ -213,23 +186,15 @@ bson_iter_init_find (bson_iter_t *iter, const bson_t *bson, const char *key); BSON_EXPORT (bool) -bson_iter_init_find_w_len (bson_iter_t *iter, - const bson_t *bson, - const char *key, - int keylen); +bson_iter_init_find_w_len (bson_iter_t *iter, const bson_t *bson, const char *key, int keylen); BSON_EXPORT (bool) -bson_iter_init_find_case (bson_iter_t *iter, - const bson_t *bson, - const char *key); +bson_iter_init_find_case (bson_iter_t *iter, const bson_t *bson, const char *key); BSON_EXPORT (bool) -bson_iter_init_from_data_at_offset (bson_iter_t *iter, - const uint8_t *data, - size_t length, - uint32_t offset, - uint32_t keylen); +bson_iter_init_from_data_at_offset ( + bson_iter_t *iter, const uint8_t *data, size_t length, uint32_t offset, uint32_t keylen); BSON_EXPORT (int32_t) bson_iter_int32 (const bson_iter_t *iter); @@ -300,9 +265,7 @@ bson_iter_find_case (bson_iter_t *iter, const char *key); BSON_EXPORT (bool) -bson_iter_find_descendant (bson_iter_t *iter, - const char *dotkey, - bson_iter_t *descendant); +bson_iter_find_descendant (bson_iter_t *iter, const char *dotkey, bson_iter_t *descendant); BSON_EXPORT (bool) @@ -449,9 +412,7 @@ bson_iter_timeval_unsafe (const bson_iter_t *iter, struct timeval *tv) BSON_EXPORT (void) -bson_iter_timestamp (const bson_iter_t *iter, - uint32_t *timestamp, - uint32_t *increment); +bson_iter_timestamp (const bson_iter_t *iter, uint32_t *timestamp, uint32_t *increment); BSON_EXPORT (bool) @@ -524,8 +485,7 @@ bson_iter_overwrite_double (bson_iter_t *iter, double value); BSON_EXPORT (void) -bson_iter_overwrite_decimal128 (bson_iter_t *iter, - const bson_decimal128_t *value); +bson_iter_overwrite_decimal128 (bson_iter_t *iter, const bson_decimal128_t *value); BSON_EXPORT (void) @@ -537,9 +497,7 @@ bson_iter_overwrite_oid (bson_iter_t *iter, const bson_oid_t *value); BSON_EXPORT (void) -bson_iter_overwrite_timestamp (bson_iter_t *iter, - uint32_t timestamp, - uint32_t increment); +bson_iter_overwrite_timestamp (bson_iter_t *iter, uint32_t timestamp, uint32_t increment); BSON_EXPORT (void) @@ -547,9 +505,7 @@ bson_iter_overwrite_date_time (bson_iter_t *iter, int64_t value); BSON_EXPORT (bool) -bson_iter_visit_all (bson_iter_t *iter, - const bson_visitor_t *visitor, - void *data); +bson_iter_visit_all (bson_iter_t *iter, const bson_visitor_t *visitor, void *data); BSON_EXPORT (uint32_t) bson_iter_offset (bson_iter_t *iter); diff --git a/src/libbson/src/bson/bson-json.c b/src/libbson/src/bson/bson-json.c index 3a56fa64e8..a2e35376e2 100644 --- a/src/libbson/src/bson/bson-json.c +++ b/src/libbson/src/bson/bson-json.c @@ -105,9 +105,7 @@ static const char *read_state_names[] = {FOREACH_READ_STATE (GENERATE_STRING)}; BS (SYMBOL) \ BS (UUID) -typedef enum { - FOREACH_BSON_STATE (BSON_STATE_ENUM) -} bson_json_read_bson_state_t; +typedef enum { FOREACH_BSON_STATE (BSON_STATE_ENUM) } bson_json_read_bson_state_t; static const char *bson_state_names[] = {FOREACH_BSON_STATE (GENERATE_STRING)}; @@ -251,9 +249,7 @@ typedef struct { /* forward decl */ static void -_bson_json_save_map_key (bson_json_reader_bson_t *bson, - const uint8_t *val, - size_t len); +_bson_json_save_map_key (bson_json_reader_bson_t *bson, const uint8_t *val, size_t len); static void @@ -262,8 +258,7 @@ _noop (void) } #define STACK_ELE(_delta, _name) (bson->stack[(_delta) + bson->n]._name) -#define STACK_BSON(_delta) \ - (((_delta) + bson->n) == 0 ? bson->bson : &STACK_ELE (_delta, bson)) +#define STACK_BSON(_delta) (((_delta) + bson->n) == 0 ? bson->bson : &STACK_ELE (_delta, bson)) #define STACK_BSON_PARENT STACK_BSON (-1) #define STACK_BSON_CHILD STACK_BSON (0) #define STACK_I STACK_ELE (0, i) @@ -273,8 +268,7 @@ _noop (void) #define STACK_IS_DOC (STACK_FRAME_TYPE == BSON_JSON_FRAME_DOC) #define STACK_IS_SCOPE (STACK_FRAME_TYPE == BSON_JSON_FRAME_SCOPE) #define STACK_IS_DBPOINTER (STACK_FRAME_TYPE == BSON_JSON_FRAME_DBPOINTER) -#define FRAME_TYPE_HAS_BSON(_type) \ - ((_type) == BSON_JSON_FRAME_SCOPE || (_type) == BSON_JSON_FRAME_DBPOINTER) +#define FRAME_TYPE_HAS_BSON(_type) ((_type) == BSON_JSON_FRAME_SCOPE || (_type) == BSON_JSON_FRAME_DBPOINTER) #define STACK_HAS_BSON FRAME_TYPE_HAS_BSON (STACK_FRAME_TYPE) #define STACK_PUSH(frame_type) \ do { \ @@ -357,36 +351,31 @@ _noop (void) key = bson->key; \ len = bson->key_buf.len; \ (void) 0 -#define BASIC_CB_BAIL_IF_NOT_NORMAL(_type) \ - if (bson->read_state != BSON_JSON_REGULAR) { \ - _bson_json_read_set_error (reader, \ - "Invalid read of %s in state %s", \ - (_type), \ - read_state_names[bson->read_state]); \ - return; \ - } else if (!key) { \ - _bson_json_read_set_error (reader, \ - "Invalid read of %s without key in state %s", \ - (_type), \ - read_state_names[bson->read_state]); \ - return; \ - } else \ +#define BASIC_CB_BAIL_IF_NOT_NORMAL(_type) \ + if (bson->read_state != BSON_JSON_REGULAR) { \ + _bson_json_read_set_error ( \ + reader, "Invalid read of %s in state %s", (_type), read_state_names[bson->read_state]); \ + return; \ + } else if (!key) { \ + _bson_json_read_set_error ( \ + reader, "Invalid read of %s without key in state %s", (_type), read_state_names[bson->read_state]); \ + return; \ + } else \ (void) 0 -#define HANDLE_OPTION(_selection_statement, _key, _type, _state) \ - _selection_statement (len == strlen (_key) && \ - strncmp ((const char *) val, (_key), len) == 0) \ - { \ - if (bson->bson_type && bson->bson_type != (_type)) { \ - _bson_json_read_set_error (reader, \ - "Invalid key \"%s\". Looking for values " \ - "for type \"%s\", got \"%s\"", \ - (_key), \ - _bson_json_type_name (bson->bson_type), \ - _bson_json_type_name (_type)); \ - return; \ - } \ - bson->bson_type = (_type); \ - bson->bson_state = (_state); \ +#define HANDLE_OPTION(_selection_statement, _key, _type, _state) \ + _selection_statement (len == strlen (_key) && strncmp ((const char *) val, (_key), len) == 0) \ + { \ + if (bson->bson_type && bson->bson_type != (_type)) { \ + _bson_json_read_set_error (reader, \ + "Invalid key \"%s\". Looking for values " \ + "for type \"%s\", got \"%s\"", \ + (_key), \ + _bson_json_type_name (bson->bson_type), \ + _bson_json_type_name (_type)); \ + return; \ + } \ + bson->bson_type = (_type); \ + bson->bson_state = (_state); \ } @@ -412,8 +401,7 @@ bson_json_opts_destroy (bson_json_opts_t *opts) } static void -_bson_json_read_set_error (bson_json_reader_t *reader, const char *fmt, ...) - BSON_GNUC_PRINTF (2, 3); +_bson_json_read_set_error (bson_json_reader_t *reader, const char *fmt, ...) BSON_GNUC_PRINTF (2, 3); static void @@ -427,8 +415,7 @@ _bson_json_read_set_error (bson_json_reader_t *reader, /* IN */ reader->error->domain = BSON_ERROR_JSON; reader->error->code = BSON_JSON_ERROR_READ_INVALID_PARAM; va_start (ap, fmt); - bson_vsnprintf ( - reader->error->message, sizeof reader->error->message, fmt, ap); + bson_vsnprintf (reader->error->message, sizeof reader->error->message, fmt, ap); va_end (ap); reader->error->message[sizeof reader->error->message - 1] = '\0'; } @@ -439,8 +426,7 @@ _bson_json_read_set_error (bson_json_reader_t *reader, /* IN */ static void -_bson_json_read_corrupt (bson_json_reader_t *reader, const char *fmt, ...) - BSON_GNUC_PRINTF (2, 3); +_bson_json_read_corrupt (bson_json_reader_t *reader, const char *fmt, ...) BSON_GNUC_PRINTF (2, 3); static void @@ -454,8 +440,7 @@ _bson_json_read_corrupt (bson_json_reader_t *reader, /* IN */ reader->error->domain = BSON_ERROR_JSON; reader->error->code = BSON_JSON_ERROR_READ_CORRUPT_JS; va_start (ap, fmt); - bson_vsnprintf ( - reader->error->message, sizeof reader->error->message, fmt, ap); + bson_vsnprintf (reader->error->message, sizeof reader->error->message, fmt, ap); va_end (ap); reader->error->message[sizeof reader->error->message - 1] = '\0'; } @@ -567,8 +552,7 @@ _bson_json_read_fixup_key (bson_json_reader_bson_t *bson) /* IN */ if (bson->n >= 0 && STACK_IS_ARRAY && rs == BSON_JSON_REGULAR) { _bson_json_buf_ensure (&bson->key_buf, 12); - bson->key_buf.len = bson_uint32_to_string ( - STACK_I, &bson->key, (char *) bson->key_buf.buf, 12); + bson->key_buf.len = bson_uint32_to_string (STACK_I, &bson->key, (char *) bson->key_buf.buf, 12); STACK_I++; } } @@ -590,8 +574,7 @@ _bson_json_read_boolean (bson_json_reader_t *reader, /* IN */ { BASIC_CB_PREAMBLE; - if (bson->read_state == BSON_JSON_IN_BSON_TYPE && - bson->bson_state == BSON_JSON_LF_UNDEFINED) { + if (bson->read_state == BSON_JSON_IN_BSON_TYPE && bson->bson_state == BSON_JSON_LF_UNDEFINED) { bson->bson_type_data.undefined.has_undefined = true; return; } @@ -612,13 +595,11 @@ _bson_json_read_integer (bson_json_reader_t *reader, uint64_t val, int64_t sign) BASIC_CB_PREAMBLE; if (sign == 1 && val > INT64_MAX) { - _bson_json_read_set_error ( - reader, "Number \"%" PRIu64 "\" is out of range", val); + _bson_json_read_set_error (reader, "Number \"%" PRIu64 "\" is out of range", val); return; } else if (sign == -1 && val > ((uint64_t) INT64_MAX + 1)) { - _bson_json_read_set_error ( - reader, "Number \"-%" PRIu64 "\" is out of range", val); + _bson_json_read_set_error (reader, "Number \"-%" PRIu64 "\" is out of range", val); return; } @@ -630,8 +611,7 @@ _bson_json_read_integer (bson_json_reader_t *reader, uint64_t val, int64_t sign) BASIC_CB_BAIL_IF_NOT_NORMAL ("integer"); if (val <= INT32_MAX || (sign == -1 && val <= (uint64_t) INT32_MAX + 1)) { - bson_append_int32 ( - STACK_BSON_CHILD, key, (int) len, (int) (val * sign)); + bson_append_int32 (STACK_BSON_CHILD, key, (int) len, (int) (val * sign)); } else if (sign == -1) { #if defined(_WIN32) && !defined(__MINGW32__) // Unary negation of unsigned integer is deliberate. @@ -643,8 +623,7 @@ _bson_json_read_integer (bson_json_reader_t *reader, uint64_t val, int64_t sign) } else { bson_append_int64 (STACK_BSON_CHILD, key, (int) len, (int64_t) val); } - } else if (rs == BSON_JSON_IN_BSON_TYPE || - rs == BSON_JSON_IN_BSON_TYPE_TIMESTAMP_VALUES) { + } else if (rs == BSON_JSON_IN_BSON_TYPE || rs == BSON_JSON_IN_BSON_TYPE_TIMESTAMP_VALUES) { switch (bs) { case BSON_JSON_LF_DATE: bson->bson_type_data.date.has_date = true; @@ -652,8 +631,7 @@ _bson_json_read_integer (bson_json_reader_t *reader, uint64_t val, int64_t sign) break; case BSON_JSON_LF_TIMESTAMP_T: if (sign == -1) { - _bson_json_read_set_error ( - reader, "Invalid timestamp value: \"-%" PRIu64 "\"", val); + _bson_json_read_set_error (reader, "Invalid timestamp value: \"-%" PRIu64 "\"", val); return; } @@ -662,8 +640,7 @@ _bson_json_read_integer (bson_json_reader_t *reader, uint64_t val, int64_t sign) break; case BSON_JSON_LF_TIMESTAMP_I: if (sign == -1) { - _bson_json_read_set_error ( - reader, "Invalid timestamp value: \"-%" PRIu64 "\"", val); + _bson_json_read_set_error (reader, "Invalid timestamp value: \"-%" PRIu64 "\"", val); return; } @@ -672,35 +649,30 @@ _bson_json_read_integer (bson_json_reader_t *reader, uint64_t val, int64_t sign) break; case BSON_JSON_LF_MINKEY: if (sign == -1) { - _bson_json_read_set_error ( - reader, "Invalid MinKey value: \"-%" PRIu64 "\"", val); + _bson_json_read_set_error (reader, "Invalid MinKey value: \"-%" PRIu64 "\"", val); return; } else if (val != 1) { - _bson_json_read_set_error ( - reader, "Invalid MinKey value: \"%" PRIu64 "\"", val); + _bson_json_read_set_error (reader, "Invalid MinKey value: \"%" PRIu64 "\"", val); } bson->bson_type_data.minkey.has_minkey = true; break; case BSON_JSON_LF_MAXKEY: if (sign == -1) { - _bson_json_read_set_error ( - reader, "Invalid MinKey value: \"-%" PRIu64 "\"", val); + _bson_json_read_set_error (reader, "Invalid MinKey value: \"-%" PRIu64 "\"", val); return; } else if (val != 1) { - _bson_json_read_set_error ( - reader, "Invalid MinKey value: \"%" PRIu64 "\"", val); + _bson_json_read_set_error (reader, "Invalid MinKey value: \"%" PRIu64 "\"", val); } bson->bson_type_data.maxkey.has_maxkey = true; break; case BSON_JSON_LF_INT32: case BSON_JSON_LF_INT64: - _bson_json_read_set_error ( - reader, - "Invalid state for integer read: %s, " - "expected number as quoted string like \"123\"", - bson_state_names[bs]); + _bson_json_read_set_error (reader, + "Invalid state for integer read: %s, " + "expected number as quoted string like \"123\"", + bson_state_names[bs]); break; case BSON_JSON_LF_REGEX: case BSON_JSON_LF_OPTIONS: @@ -719,28 +691,20 @@ _bson_json_read_integer (bson_json_reader_t *reader, uint64_t val, int64_t sign) case BSON_JSON_LF_SYMBOL: default: _bson_json_read_set_error (reader, - "Unexpected integer %s%" PRIu64 - " in type \"%s\"", + "Unexpected integer %s%" PRIu64 " in type \"%s\"", sign == -1 ? "-" : "", val, _bson_json_type_name (bson->bson_type)); } } else { - _bson_json_read_set_error (reader, - "Unexpected integer %s%" PRIu64 - " in state \"%s\"", - sign == -1 ? "-" : "", - val, - read_state_names[rs]); + _bson_json_read_set_error ( + reader, "Unexpected integer %s%" PRIu64 " in state \"%s\"", sign == -1 ? "-" : "", val, read_state_names[rs]); } } static bool -_bson_json_parse_double (bson_json_reader_t *reader, - const char *val, - size_t vlen, - double *d) +_bson_json_parse_double (bson_json_reader_t *reader, const char *val, size_t vlen, double *d) { errno = 0; *d = strtod (val, NULL); @@ -764,18 +728,15 @@ _bson_json_parse_double (bson_json_reader_t *reader, } if ((*d == HUGE_VAL || *d == -HUGE_VAL) && errno == ERANGE) { - _bson_json_read_set_error ( - reader, "Number \"%.*s\" is out of range", (int) vlen, val); + _bson_json_read_set_error (reader, "Number \"%.*s\" is out of range", (int) vlen, val); return false; } #else /* not MSVC - set err on overflow, but avoid err for infinity */ - if ((*d == HUGE_VAL || *d == -HUGE_VAL) && errno == ERANGE && - strncasecmp (val, "infinity", vlen) && + if ((*d == HUGE_VAL || *d == -HUGE_VAL) && errno == ERANGE && strncasecmp (val, "infinity", vlen) && strncasecmp (val, "-infinity", vlen)) { - _bson_json_read_set_error ( - reader, "Number \"%.*s\" is out of range", (int) vlen, val); + _bson_json_read_set_error (reader, "Number \"%.*s\" is out of range", (int) vlen, val); return false; } @@ -848,9 +809,7 @@ _unhexlify_uuid (const char *uuid, uint8_t *out, size_t max) /* parse a value for "base64", "subType", legacy "$binary" or "$type", or * "$uuid" */ static void -_bson_json_parse_binary_elem (bson_json_reader_t *reader, - const char *val_w_null, - size_t vlen) +_bson_json_parse_binary_elem (bson_json_reader_t *reader, const char *val_w_null, size_t vlen) { bson_json_read_bson_state_t bs; bson_json_bson_data_t *data; @@ -866,19 +825,13 @@ _bson_json_parse_binary_elem (bson_json_reader_t *reader, binary_len = mcommon_b64_pton (val_w_null, NULL, 0); if (binary_len < 0) { _bson_json_read_set_error ( - reader, - "Invalid input string \"%s\", looking for base64-encoded binary", - val_w_null); + reader, "Invalid input string \"%s\", looking for base64-encoded binary", val_w_null); } _bson_json_buf_ensure (&bson->bson_type_buf[0], (size_t) binary_len + 1); - if (mcommon_b64_pton (val_w_null, - bson->bson_type_buf[0].buf, - (size_t) binary_len + 1) < 0) { + if (mcommon_b64_pton (val_w_null, bson->bson_type_buf[0].buf, (size_t) binary_len + 1) < 0) { _bson_json_read_set_error ( - reader, - "Invalid input string \"%s\", looking for base64-encoded binary", - val_w_null); + reader, "Invalid input string \"%s\", looking for base64-encoded binary", val_w_null); } bson->bson_type_buf[0].len = (size_t) binary_len; @@ -889,21 +842,13 @@ _bson_json_parse_binary_elem (bson_json_reader_t *reader, if (!data->binary.is_legacy || data->binary.has_binary) { /* misformatted subtype, like {$binary: {base64: "", subType: "x"}}, * or legacy {$binary: "", $type: "x"} */ - _bson_json_read_set_error ( - reader, - "Invalid input string \"%s\", looking for binary subtype", - val_w_null); + _bson_json_read_set_error (reader, "Invalid input string \"%s\", looking for binary subtype", val_w_null); } else { /* actually a query operator: {x: {$type: "array"}}*/ bson->read_state = BSON_JSON_REGULAR; - STACK_PUSH_DOC (bson_append_document_begin ( - STACK_BSON_PARENT, key, (int) len, STACK_BSON_CHILD)); - - bson_append_utf8 (STACK_BSON_CHILD, - "$type", - 5, - (const char *) val_w_null, - (int) vlen); + STACK_PUSH_DOC (bson_append_document_begin (STACK_BSON_PARENT, key, (int) len, STACK_BSON_CHILD)); + + bson_append_utf8 (STACK_BSON_CHILD, "$type", 5, (const char *) val_w_null, (int) vlen); } } } else if (bs == BSON_JSON_LF_UUID) { @@ -931,14 +876,7 @@ _bson_json_parse_binary_elem (bson_json_reader_t *reader, 12, &nread); #else - SSCANF (val_w_null, - "%8c-%4c-%4c-%4c-%12c%n", - &uuid[0], - &uuid[8], - &uuid[12], - &uuid[16], - &uuid[20], - &nread); + SSCANF (val_w_null, "%8c-%4c-%4c-%4c-%12c%n", &uuid[0], &uuid[8], &uuid[12], &uuid[16], &uuid[20], &nread); #endif uuid[32] = '\0'; @@ -955,8 +893,7 @@ _bson_json_parse_binary_elem (bson_json_reader_t *reader, binary_len = 16; _bson_json_buf_ensure (&bson->bson_type_buf[0], (size_t) binary_len + 1); - if (!_unhexlify_uuid ( - &uuid[0], bson->bson_type_buf[0].buf, (size_t) binary_len)) { + if (!_unhexlify_uuid (&uuid[0], bson->bson_type_buf[0].buf, (size_t) binary_len)) { _bson_json_read_set_error (reader, "Invalid input string \"%s\", looking for " "a dash-separated UUID string", @@ -984,8 +921,7 @@ _bson_json_allow_embedded_nulls (bson_json_reader_t const *reader) } if (read_state == BSON_JSON_IN_BSON_TYPE) { - if (bson_state == BSON_JSON_LF_REGEX || - bson_state == BSON_JSON_LF_OPTIONS) { + if (bson_state == BSON_JSON_LF_REGEX || bson_state == BSON_JSON_LF_OPTIONS) { /* Prohibit embedded NULL bytes for legacy regex: * { $regex: "pattern", $options: "options" } */ return false; @@ -1017,24 +953,17 @@ _bson_json_read_string (bson_json_reader_t *reader, /* IN */ if (rs == BSON_JSON_REGULAR) { BASIC_CB_BAIL_IF_NOT_NORMAL ("string"); - bson_append_utf8 ( - STACK_BSON_CHILD, key, (int) len, (const char *) val, (int) vlen); - } else if (rs == BSON_JSON_IN_BSON_TYPE_SCOPE_STARTMAP || - rs == BSON_JSON_IN_BSON_TYPE_DBPOINTER_STARTMAP) { - _bson_json_read_set_error (reader, - "Invalid read of \"%s\" in state \"%s\"", - val, - read_state_names[rs]); + bson_append_utf8 (STACK_BSON_CHILD, key, (int) len, (const char *) val, (int) vlen); + } else if (rs == BSON_JSON_IN_BSON_TYPE_SCOPE_STARTMAP || rs == BSON_JSON_IN_BSON_TYPE_DBPOINTER_STARTMAP) { + _bson_json_read_set_error (reader, "Invalid read of \"%s\" in state \"%s\"", val, read_state_names[rs]); } else if (rs == BSON_JSON_IN_BSON_TYPE_BINARY_VALUES) { const char *val_w_null; _bson_json_buf_set (&bson->bson_type_buf[2], val, vlen); val_w_null = (const char *) bson->bson_type_buf[2].buf; _bson_json_parse_binary_elem (reader, val_w_null, vlen); - } else if (rs == BSON_JSON_IN_BSON_TYPE || - rs == BSON_JSON_IN_BSON_TYPE_TIMESTAMP_VALUES || - rs == BSON_JSON_IN_BSON_TYPE_REGEX_VALUES || - rs == BSON_JSON_IN_BSON_TYPE_DATE_NUMBERLONG) { + } else if (rs == BSON_JSON_IN_BSON_TYPE || rs == BSON_JSON_IN_BSON_TYPE_TIMESTAMP_VALUES || + rs == BSON_JSON_IN_BSON_TYPE_REGEX_VALUES || rs == BSON_JSON_IN_BSON_TYPE_DATE_NUMBERLONG) { const char *val_w_null; _bson_json_buf_set (&bson->bson_type_buf[2], val, vlen); val_w_null = (const char *) bson->bson_type_buf[2].buf; @@ -1096,8 +1025,7 @@ _bson_json_read_string (bson_json_reader_t *reader, /* IN */ if (bson->read_state == BSON_JSON_IN_BSON_TYPE) { bson->bson_type_data.v_int64.value = v64; - } else if (bson->read_state == - BSON_JSON_IN_BSON_TYPE_DATE_NUMBERLONG) { + } else if (bson->read_state == BSON_JSON_IN_BSON_TYPE_DATE_NUMBERLONG) { bson->bson_type_data.date.has_date = true; bson->bson_type_data.date.date = v64; } else { @@ -1105,10 +1033,7 @@ _bson_json_read_string (bson_json_reader_t *reader, /* IN */ } } break; case BSON_JSON_LF_DOUBLE: { - if (!_bson_json_parse_double (reader, - (const char *) val, - vlen, - &bson->bson_type_data.v_double.value)) { + if (!_bson_json_parse_double (reader, (const char *) val, vlen, &bson->bson_type_data.v_double.value)) { /* the error is set, return and let the reader exit */ return; } @@ -1116,8 +1041,7 @@ _bson_json_read_string (bson_json_reader_t *reader, /* IN */ case BSON_JSON_LF_DATE: { int64_t v64; - if (!_bson_iso8601_date_parse ( - (char *) val, (int) vlen, &v64, reader->error)) { + if (!_bson_iso8601_date_parse ((char *) val, (int) vlen, &v64, reader->error)) { jsonsl_stop (reader->json); } else { bson->bson_type_data.date.has_date = true; @@ -1127,8 +1051,7 @@ _bson_json_read_string (bson_json_reader_t *reader, /* IN */ case BSON_JSON_LF_DECIMAL128: { bson_decimal128_t decimal128; - if (bson_decimal128_from_string (val_w_null, &decimal128) && - bson->read_state == BSON_JSON_IN_BSON_TYPE) { + if (bson_decimal128_from_string (val_w_null, &decimal128) && bson->read_state == BSON_JSON_IN_BSON_TYPE) { bson->bson_type_data.v_decimal128.value = decimal128; } else { goto BAD_PARSE; @@ -1138,8 +1061,7 @@ _bson_json_read_string (bson_json_reader_t *reader, /* IN */ _bson_json_buf_set (&bson->code_data.code_buf, val, vlen); break; case BSON_JSON_LF_SYMBOL: - bson_append_symbol ( - STACK_BSON_CHILD, key, (int) len, (const char *) val, (int) vlen); + bson_append_symbol (STACK_BSON_CHILD, key, (int) len, (const char *) val, (int) vlen); break; case BSON_JSON_LF_SCOPE: case BSON_JSON_LF_TIMESTAMP_T: @@ -1154,13 +1076,10 @@ _bson_json_read_string (bson_json_reader_t *reader, /* IN */ return; BAD_PARSE: - _bson_json_read_set_error (reader, - "Invalid input string \"%s\", looking for %s", - val_w_null, - bson_state_names[bs]); - } else { _bson_json_read_set_error ( - reader, "Invalid state to look for string: %s", read_state_names[rs]); + reader, "Invalid input string \"%s\", looking for %s", val_w_null, bson_state_names[bs]); + } else { + _bson_json_read_set_error (reader, "Invalid state to look for string: %s", read_state_names[rs]); } } @@ -1184,8 +1103,7 @@ _bson_json_read_start_map (bson_json_reader_t *reader) /* IN */ * backtrack and parse $type query operator. */ bson->read_state = BSON_JSON_IN_START_MAP; BSON_ASSERT (bson_in_range_unsigned (int, len)); - STACK_PUSH_DOC (bson_append_document_begin ( - STACK_BSON_PARENT, key, (int) len, STACK_BSON_CHILD)); + STACK_PUSH_DOC (bson_append_document_begin (STACK_BSON_PARENT, key, (int) len, STACK_BSON_CHILD)); _bson_json_save_map_key (bson, (const uint8_t *) "$type", 5); break; case BSON_JSON_LF_CODE: @@ -1213,9 +1131,7 @@ _bson_json_read_start_map (bson_json_reader_t *reader) /* IN */ case BSON_JSON_LF_UUID: // These special keys do not expect objects as their values. Fail. _bson_json_read_set_error ( - reader, - "Unexpected nested object value for \"%s\" key", - reader->bson.unescaped.buf); + reader, "Unexpected nested object value for \"%s\" key", reader->bson.unescaped.buf); break; case BSON_JSON_LF_DBPOINTER: case BSON_JSON_LF_SCOPE: @@ -1223,8 +1139,7 @@ _bson_json_read_start_map (bson_json_reader_t *reader) /* IN */ case BSON_JSON_LF_TIMESTAMP_T: default: // These special LF keys aren't handled with BSON_JSON_IN_BSON_TYPE - BSON_UNREACHABLE ( - "These LF values are handled with a different read_state"); + BSON_UNREACHABLE ("These LF values are handled with a different read_state"); } } else if (bson->read_state == BSON_JSON_IN_BSON_TYPE_TIMESTAMP_STARTMAP) { bson->read_state = BSON_JSON_IN_BSON_TYPE_TIMESTAMP_VALUES; @@ -1251,15 +1166,11 @@ _is_known_key (const char *key, size_t len) #define IS_KEY(k) (len == strlen (k) && (0 == memcmp (k, key, len))) - ret = (IS_KEY ("$regularExpression") || IS_KEY ("$regex") || - IS_KEY ("$options") || IS_KEY ("$code") || IS_KEY ("$scope") || - IS_KEY ("$oid") || IS_KEY ("$binary") || IS_KEY ("$type") || - IS_KEY ("$date") || IS_KEY ("$undefined") || IS_KEY ("$maxKey") || - IS_KEY ("$minKey") || IS_KEY ("$timestamp") || - IS_KEY ("$numberInt") || IS_KEY ("$numberLong") || - IS_KEY ("$numberDouble") || IS_KEY ("$numberDecimal") || - IS_KEY ("$numberInt") || IS_KEY ("$numberLong") || - IS_KEY ("$numberDouble") || IS_KEY ("$numberDecimal") || + ret = (IS_KEY ("$regularExpression") || IS_KEY ("$regex") || IS_KEY ("$options") || IS_KEY ("$code") || + IS_KEY ("$scope") || IS_KEY ("$oid") || IS_KEY ("$binary") || IS_KEY ("$type") || IS_KEY ("$date") || + IS_KEY ("$undefined") || IS_KEY ("$maxKey") || IS_KEY ("$minKey") || IS_KEY ("$timestamp") || + IS_KEY ("$numberInt") || IS_KEY ("$numberLong") || IS_KEY ("$numberDouble") || IS_KEY ("$numberDecimal") || + IS_KEY ("$numberInt") || IS_KEY ("$numberLong") || IS_KEY ("$numberDouble") || IS_KEY ("$numberDecimal") || IS_KEY ("$dbPointer") || IS_KEY ("$symbol") || IS_KEY ("$uuid")); #undef IS_KEY @@ -1268,9 +1179,7 @@ _is_known_key (const char *key, size_t len) } static void -_bson_json_save_map_key (bson_json_reader_bson_t *bson, - const uint8_t *val, - size_t len) +_bson_json_save_map_key (bson_json_reader_bson_t *bson, const uint8_t *val, size_t len) { _bson_json_buf_set (&bson->key_buf, val, len); bson->key = (const char *) bson->key_buf.buf; @@ -1278,10 +1187,7 @@ _bson_json_save_map_key (bson_json_reader_bson_t *bson, static void -_bson_json_read_code_or_scope_key (bson_json_reader_bson_t *bson, - bool is_scope, - const uint8_t *val, - size_t len) +_bson_json_read_code_or_scope_key (bson_json_reader_bson_t *bson, bool is_scope, const uint8_t *val, size_t len) { bson_json_code_t *code = &bson->code_data; @@ -1289,17 +1195,14 @@ _bson_json_read_code_or_scope_key (bson_json_reader_bson_t *bson, /* we're reading something weirdly nested, e.g. we just read "$code" in * "$scope: {x: {$code: {}}}". just create the subdoc within the scope. */ bson->read_state = BSON_JSON_REGULAR; - STACK_PUSH_DOC (bson_append_document_begin (STACK_BSON_PARENT, - bson->key, - (int) bson->key_buf.len, - STACK_BSON_CHILD)); + STACK_PUSH_DOC ( + bson_append_document_begin (STACK_BSON_PARENT, bson->key, (int) bson->key_buf.len, STACK_BSON_CHILD)); _bson_json_save_map_key (bson, val, len); } else { if (!bson->code_data.key_buf.len) { /* save the key, e.g. {"key": {"$code": "return x", "$scope":{"x":1}}}, * in case it is overwritten while parsing scope sub-object */ - _bson_json_buf_set ( - &bson->code_data.key_buf, bson->key, bson->key_buf.len); + _bson_json_buf_set (&bson->code_data.key_buf, bson->key, bson->key_buf.len); } if (is_scope) { @@ -1323,10 +1226,7 @@ _bson_json_bad_key_in_type (bson_json_reader_t *reader, /* IN */ bson_json_reader_bson_t *bson = &reader->bson; _bson_json_read_set_error ( - reader, - "Invalid key \"%s\". Looking for values for type \"%s\"", - val, - _bson_json_type_name (bson->bson_type)); + reader, "Invalid key \"%s\". Looking for values for type \"%s\"", val, _bson_json_type_name (bson->bson_type)); } @@ -1350,10 +1250,8 @@ _bson_json_read_map_key (bson_json_reader_t *reader, /* IN */ memset (&bson->bson_type_data, 0, sizeof bson->bson_type_data); } else { bson->read_state = BSON_JSON_REGULAR; - STACK_PUSH_DOC (bson_append_document_begin (STACK_BSON_PARENT, - bson->key, - (int) bson->key_buf.len, - STACK_BSON_CHILD)); + STACK_PUSH_DOC ( + bson_append_document_begin (STACK_BSON_PARENT, bson->key, (int) bson->key_buf.len, STACK_BSON_CHILD)); } } else if (bson->read_state == BSON_JSON_IN_SCOPE) { /* we've read "key" in {$code: "", $scope: {key: ""}}*/ @@ -1375,20 +1273,14 @@ _bson_json_read_map_key (bson_json_reader_t *reader, /* IN */ HANDLE_OPTION (else if, "$type", BSON_TYPE_BINARY, BSON_JSON_LF_TYPE) HANDLE_OPTION (else if, "$uuid", BSON_TYPE_BINARY, BSON_JSON_LF_UUID) HANDLE_OPTION (else if, "$date", BSON_TYPE_DATE_TIME, BSON_JSON_LF_DATE) - HANDLE_OPTION ( - else if, "$undefined", BSON_TYPE_UNDEFINED, BSON_JSON_LF_UNDEFINED) + HANDLE_OPTION (else if, "$undefined", BSON_TYPE_UNDEFINED, BSON_JSON_LF_UNDEFINED) HANDLE_OPTION (else if, "$minKey", BSON_TYPE_MINKEY, BSON_JSON_LF_MINKEY) HANDLE_OPTION (else if, "$maxKey", BSON_TYPE_MAXKEY, BSON_JSON_LF_MAXKEY) HANDLE_OPTION (else if, "$numberInt", BSON_TYPE_INT32, BSON_JSON_LF_INT32) - HANDLE_OPTION ( - else if, "$numberLong", BSON_TYPE_INT64, BSON_JSON_LF_INT64) - HANDLE_OPTION ( - else if, "$numberDouble", BSON_TYPE_DOUBLE, BSON_JSON_LF_DOUBLE) + HANDLE_OPTION (else if, "$numberLong", BSON_TYPE_INT64, BSON_JSON_LF_INT64) + HANDLE_OPTION (else if, "$numberDouble", BSON_TYPE_DOUBLE, BSON_JSON_LF_DOUBLE) HANDLE_OPTION (else if, "$symbol", BSON_TYPE_SYMBOL, BSON_JSON_LF_SYMBOL) - HANDLE_OPTION (else if, - "$numberDecimal", - BSON_TYPE_DECIMAL128, - BSON_JSON_LF_DECIMAL128) + HANDLE_OPTION (else if, "$numberDecimal", BSON_TYPE_DECIMAL128, BSON_JSON_LF_DECIMAL128) else if (!strcmp ("$timestamp", (const char *) val)) { bson->bson_type = BSON_TYPE_TIMESTAMP; @@ -1402,21 +1294,18 @@ _bson_json_read_map_key (bson_json_reader_t *reader, /* IN */ else if (!strcmp ("$dbPointer", (const char *) val)) { /* start parsing "key": {"$dbPointer": {...}}, save "key" for later */ - _bson_json_buf_set ( - &bson->dbpointer_key, bson->key, bson->key_buf.len); + _bson_json_buf_set (&bson->dbpointer_key, bson->key, bson->key_buf.len); bson->bson_type = BSON_TYPE_DBPOINTER; bson->read_state = BSON_JSON_IN_BSON_TYPE_DBPOINTER_STARTMAP; } else if (!strcmp ("$code", (const char *) val)) { - _bson_json_read_code_or_scope_key ( - bson, false /* is_scope */, val, len); + _bson_json_read_code_or_scope_key (bson, false /* is_scope */, val, len); } else if (!strcmp ("$scope", (const char *) val)) { - _bson_json_read_code_or_scope_key ( - bson, true /* is_scope */, val, len); + _bson_json_read_code_or_scope_key (bson, true /* is_scope */, val, len); } else { @@ -1430,21 +1319,14 @@ _bson_json_read_map_key (bson_json_reader_t *reader, /* IN */ } } else if (bson->read_state == BSON_JSON_IN_BSON_TYPE_TIMESTAMP_VALUES) { HANDLE_OPTION (if, "t", BSON_TYPE_TIMESTAMP, BSON_JSON_LF_TIMESTAMP_T) - HANDLE_OPTION ( - else if, "i", BSON_TYPE_TIMESTAMP, BSON_JSON_LF_TIMESTAMP_I) + HANDLE_OPTION (else if, "i", BSON_TYPE_TIMESTAMP, BSON_JSON_LF_TIMESTAMP_I) else { _bson_json_bad_key_in_type (reader, val); } } else if (bson->read_state == BSON_JSON_IN_BSON_TYPE_REGEX_VALUES) { - HANDLE_OPTION (if, - "pattern", - BSON_TYPE_REGEX, - BSON_JSON_LF_REGULAR_EXPRESSION_PATTERN) - HANDLE_OPTION (else if, - "options", - BSON_TYPE_REGEX, - BSON_JSON_LF_REGULAR_EXPRESSION_OPTIONS) + HANDLE_OPTION (if, "pattern", BSON_TYPE_REGEX, BSON_JSON_LF_REGULAR_EXPRESSION_PATTERN) + HANDLE_OPTION (else if, "options", BSON_TYPE_REGEX, BSON_JSON_LF_REGULAR_EXPRESSION_OPTIONS) else { _bson_json_bad_key_in_type (reader, val); @@ -1470,26 +1352,18 @@ _bson_json_read_append_binary (bson_json_reader_t *reader, /* IN */ if (data->binary.is_legacy) { if (!data->binary.has_binary) { - _bson_json_read_set_error ( - reader, - "Missing \"$binary\" after \"$type\" reading type \"binary\""); + _bson_json_read_set_error (reader, "Missing \"$binary\" after \"$type\" reading type \"binary\""); return; } else if (!data->binary.has_subtype) { - _bson_json_read_set_error ( - reader, - "Missing \"$type\" after \"$binary\" reading type \"binary\""); + _bson_json_read_set_error (reader, "Missing \"$type\" after \"$binary\" reading type \"binary\""); return; } } else { if (!data->binary.has_binary) { - _bson_json_read_set_error ( - reader, - "Missing \"base64\" after \"subType\" reading type \"binary\""); + _bson_json_read_set_error (reader, "Missing \"base64\" after \"subType\" reading type \"binary\""); return; } else if (!data->binary.has_subtype) { - _bson_json_read_set_error ( - reader, - "Missing \"subType\" after \"base64\" reading type \"binary\""); + _bson_json_read_set_error (reader, "Missing \"subType\" after \"base64\" reading type \"binary\""); return; } } @@ -1512,17 +1386,14 @@ _bson_json_read_append_regex (bson_json_reader_t *reader, /* IN */ bson_json_bson_data_t *data = &bson->bson_type_data; if (data->regex.is_legacy) { if (!data->regex.has_pattern) { - _bson_json_read_set_error (reader, - "Missing \"$regex\" after \"$options\""); + _bson_json_read_set_error (reader, "Missing \"$regex\" after \"$options\""); return; } } else if (!data->regex.has_pattern) { - _bson_json_read_set_error ( - reader, "Missing \"pattern\" after \"options\" in regular expression"); + _bson_json_read_set_error (reader, "Missing \"pattern\" after \"options\" in regular expression"); return; } else if (!data->regex.has_options) { - _bson_json_read_set_error ( - reader, "Missing \"options\" after \"pattern\" in regular expression"); + _bson_json_read_set_error (reader, "Missing \"options\" after \"pattern\" in regular expression"); return; } @@ -1561,11 +1432,8 @@ _bson_json_read_append_code (bson_json_reader_t *reader, /* IN */ } /* creates BSON "code" elem, or "code with scope" if scope is not NULL */ - r = bson_append_code_with_scope (STACK_BSON_CHILD, - (const char *) code_data->key_buf.buf, - (int) code_data->key_buf.len, - code, - scope); + r = bson_append_code_with_scope ( + STACK_BSON_CHILD, (const char *) code_data->key_buf.buf, (int) code_data->key_buf.len, code, scope); if (!r) { _bson_json_read_set_error (reader, "Error storing Javascript code"); @@ -1598,40 +1466,31 @@ _bson_json_read_append_dbpointer (bson_json_reader_t *reader, /* IN */ while (bson_iter_next (&iter)) { if (!strcmp (bson_iter_key (&iter), "$id")) { if (!BSON_ITER_HOLDS_OID (&iter)) { - _bson_json_read_set_error ( - reader, "$dbPointer.$id must be like {\"$oid\": ...\"}"); + _bson_json_read_set_error (reader, "$dbPointer.$id must be like {\"$oid\": ...\"}"); return; } oid = bson_iter_oid (&iter); } else if (!strcmp (bson_iter_key (&iter), "$ref")) { if (!BSON_ITER_HOLDS_UTF8 (&iter)) { - _bson_json_read_set_error ( - reader, - "$dbPointer.$ref must be a string like \"db.collection\""); + _bson_json_read_set_error (reader, "$dbPointer.$ref must be a string like \"db.collection\""); return; } ns = bson_iter_utf8 (&iter, NULL); } else { - _bson_json_read_set_error (reader, - "$dbPointer contains invalid key: \"%s\"", - bson_iter_key (&iter)); + _bson_json_read_set_error (reader, "$dbPointer contains invalid key: \"%s\"", bson_iter_key (&iter)); return; } } if (!oid || !ns) { - _bson_json_read_set_error (reader, - "$dbPointer requires both $id and $ref"); + _bson_json_read_set_error (reader, "$dbPointer requires both $id and $ref"); return; } - r = bson_append_dbpointer (STACK_BSON_CHILD, - (char *) reader->bson.dbpointer_key.buf, - (int) reader->bson.dbpointer_key.len, - ns, - oid); + r = bson_append_dbpointer ( + STACK_BSON_CHILD, (char *) reader->bson.dbpointer_key.buf, (int) reader->bson.dbpointer_key.len, ns, oid); if (!r) { _bson_json_read_set_error (reader, "Error storing DBPointer"); @@ -1643,10 +1502,7 @@ static void _bson_json_read_append_oid (bson_json_reader_t *reader, /* IN */ bson_json_reader_bson_t *bson) /* IN */ { - if (!bson_append_oid (STACK_BSON_CHILD, - bson->key, - (int) bson->key_buf.len, - &bson->bson_type_data.oid.oid)) { + if (!bson_append_oid (STACK_BSON_CHILD, bson->key, (int) bson->key_buf.len, &bson->bson_type_data.oid.oid)) { _bson_json_read_set_error (reader, "Error storing ObjectId"); } } @@ -1656,10 +1512,7 @@ static void _bson_json_read_append_date_time (bson_json_reader_t *reader, /* IN */ bson_json_reader_bson_t *bson) /* IN */ { - if (!bson_append_date_time (STACK_BSON_CHILD, - bson->key, - (int) bson->key_buf.len, - bson->bson_type_data.date.date)) { + if (!bson_append_date_time (STACK_BSON_CHILD, bson->key, (int) bson->key_buf.len, bson->bson_type_data.date.date)) { _bson_json_read_set_error (reader, "Error storing datetime"); } } @@ -1670,12 +1523,10 @@ _bson_json_read_append_timestamp (bson_json_reader_t *reader, /* IN */ bson_json_reader_bson_t *bson) /* IN */ { if (!bson->bson_type_data.timestamp.has_t) { - _bson_json_read_set_error ( - reader, "Missing t after $timestamp in BSON_TYPE_TIMESTAMP"); + _bson_json_read_set_error (reader, "Missing t after $timestamp in BSON_TYPE_TIMESTAMP"); return; } else if (!bson->bson_type_data.timestamp.has_i) { - _bson_json_read_set_error ( - reader, "Missing i after $timestamp in BSON_TYPE_TIMESTAMP"); + _bson_json_read_set_error (reader, "Missing i after $timestamp in BSON_TYPE_TIMESTAMP"); return; } @@ -1702,10 +1553,8 @@ _bson_json_read_end_map (bson_json_reader_t *reader) /* IN */ if (bson->read_state == BSON_JSON_IN_START_MAP) { bson->read_state = BSON_JSON_REGULAR; - STACK_PUSH_DOC (bson_append_document_begin (STACK_BSON_PARENT, - bson->key, - (int) bson->key_buf.len, - STACK_BSON_CHILD)); + STACK_PUSH_DOC ( + bson_append_document_begin (STACK_BSON_PARENT, bson->key, (int) bson->key_buf.len, STACK_BSON_CHILD)); } else if (bson->read_state == BSON_JSON_IN_BSON_TYPE_SCOPE_STARTMAP) { bson->read_state = BSON_JSON_REGULAR; STACK_PUSH_SCOPE; @@ -1743,46 +1592,33 @@ _bson_json_read_end_map (bson_json_reader_t *reader) /* IN */ _bson_json_read_append_date_time (reader, bson); break; case BSON_TYPE_UNDEFINED: - r = bson_append_undefined ( - STACK_BSON_CHILD, bson->key, (int) bson->key_buf.len); + r = bson_append_undefined (STACK_BSON_CHILD, bson->key, (int) bson->key_buf.len); break; case BSON_TYPE_MINKEY: - r = bson_append_minkey ( - STACK_BSON_CHILD, bson->key, (int) bson->key_buf.len); + r = bson_append_minkey (STACK_BSON_CHILD, bson->key, (int) bson->key_buf.len); break; case BSON_TYPE_MAXKEY: - r = bson_append_maxkey ( - STACK_BSON_CHILD, bson->key, (int) bson->key_buf.len); + r = bson_append_maxkey (STACK_BSON_CHILD, bson->key, (int) bson->key_buf.len); break; case BSON_TYPE_INT32: - r = bson_append_int32 (STACK_BSON_CHILD, - bson->key, - (int) bson->key_buf.len, - bson->bson_type_data.v_int32.value); + r = bson_append_int32 ( + STACK_BSON_CHILD, bson->key, (int) bson->key_buf.len, bson->bson_type_data.v_int32.value); break; case BSON_TYPE_INT64: - r = bson_append_int64 (STACK_BSON_CHILD, - bson->key, - (int) bson->key_buf.len, - bson->bson_type_data.v_int64.value); + r = bson_append_int64 ( + STACK_BSON_CHILD, bson->key, (int) bson->key_buf.len, bson->bson_type_data.v_int64.value); break; case BSON_TYPE_DOUBLE: - r = bson_append_double (STACK_BSON_CHILD, - bson->key, - (int) bson->key_buf.len, - bson->bson_type_data.v_double.value); + r = bson_append_double ( + STACK_BSON_CHILD, bson->key, (int) bson->key_buf.len, bson->bson_type_data.v_double.value); break; case BSON_TYPE_DECIMAL128: - r = bson_append_decimal128 (STACK_BSON_CHILD, - bson->key, - (int) bson->key_buf.len, - &bson->bson_type_data.v_decimal128.value); + r = bson_append_decimal128 ( + STACK_BSON_CHILD, bson->key, (int) bson->key_buf.len, &bson->bson_type_data.v_decimal128.value); break; case BSON_TYPE_DBPOINTER: /* shouldn't set type to DBPointer unless inside $dbPointer: {...} */ - _bson_json_read_set_error ( - reader, - "Internal error: shouldn't be in state BSON_TYPE_DBPOINTER"); + _bson_json_read_set_error (reader, "Internal error: shouldn't be in state BSON_TYPE_DBPOINTER"); break; case BSON_TYPE_SYMBOL: break; @@ -1795,17 +1631,12 @@ _bson_json_read_end_map (bson_json_reader_t *reader) /* IN */ case BSON_TYPE_TIMESTAMP: default: _bson_json_read_set_error ( - reader, - "Internal error: can't parse JSON wrapper for type \"%s\"", - _bson_json_type_name (bson->bson_type)); + reader, "Internal error: can't parse JSON wrapper for type \"%s\"", _bson_json_type_name (bson->bson_type)); break; } if (!r) { - _bson_json_read_set_error ( - reader, - "Cannot append value at end of JSON object for key %s", - bson->key); + _bson_json_read_set_error (reader, "Cannot append value at end of JSON object for key %s", bson->key); } } else if (bson->read_state == BSON_JSON_IN_BSON_TYPE_TIMESTAMP_VALUES) { @@ -1862,8 +1693,7 @@ _bson_json_read_end_map (bson_json_reader_t *reader) /* IN */ bson->read_state = BSON_JSON_IN_BSON_TYPE_DBPOINTER_STARTMAP; STACK_POP_DBPOINTER; } else { - STACK_POP_DOC ( - bson_append_document_end (STACK_BSON_PARENT, STACK_BSON_CHILD)); + STACK_POP_DOC (bson_append_document_end (STACK_BSON_PARENT, STACK_BSON_CHILD)); } if (bson->n == -1) { @@ -1880,8 +1710,7 @@ _bson_json_read_end_map (bson_json_reader_t *reader) /* IN */ /* empty $dbPointer??? */ _bson_json_read_set_error (reader, "Empty $dbPointer"); } else { - _bson_json_read_set_error ( - reader, "Invalid state \"%s\"", read_state_names[bson->read_state]); + _bson_json_read_set_error (reader, "Invalid state \"%s\"", read_state_names[bson->read_state]); } } @@ -1894,9 +1723,7 @@ _bson_json_read_start_array (bson_json_reader_t *reader) /* IN */ bson_json_reader_bson_t *bson = &reader->bson; if (bson->read_state != BSON_JSON_REGULAR) { - _bson_json_read_set_error (reader, - "Invalid read of \"[\" in state \"%s\"", - read_state_names[bson->read_state]); + _bson_json_read_set_error (reader, "Invalid read of \"[\" in state \"%s\"", read_state_names[bson->read_state]); return; } @@ -1907,8 +1734,7 @@ _bson_json_read_start_array (bson_json_reader_t *reader) /* IN */ key = bson->key; len = bson->key_buf.len; - STACK_PUSH_ARRAY (bson_append_array_begin ( - STACK_BSON_PARENT, key, (int) len, STACK_BSON_CHILD)); + STACK_PUSH_ARRAY (bson_append_array_begin (STACK_BSON_PARENT, key, (int) len, STACK_BSON_CHILD)); } } @@ -1919,14 +1745,11 @@ _bson_json_read_end_array (bson_json_reader_t *reader) /* IN */ bson_json_reader_bson_t *bson = &reader->bson; if (bson->read_state != BSON_JSON_REGULAR) { - _bson_json_read_set_error (reader, - "Invalid read of \"]\" in state \"%s\"", - read_state_names[bson->read_state]); + _bson_json_read_set_error (reader, "Invalid read of \"]\" in state \"%s\"", read_state_names[bson->read_state]); return; } - STACK_POP_ARRAY ( - bson_append_array_end (STACK_BSON_PARENT, STACK_BSON_CHILD)); + STACK_POP_ARRAY (bson_append_array_end (STACK_BSON_PARENT, STACK_BSON_CHILD)); if (bson->n == -1) { bson->read_state = BSON_JSON_DONE; } @@ -1936,10 +1759,7 @@ _bson_json_read_end_array (bson_json_reader_t *reader) /* IN */ /* put unescaped text in reader->bson.unescaped, or set reader->error. * json_text has length len and it is not null-terminated. */ static bool -_bson_json_unescape (bson_json_reader_t *reader, - struct jsonsl_state_st *state, - const char *json_text, - ssize_t len) +_bson_json_unescape (bson_json_reader_t *reader, struct jsonsl_state_st *state, const char *json_text, ssize_t len) { bson_json_reader_bson_t *reader_bson; jsonsl_error_t err; @@ -1950,8 +1770,8 @@ _bson_json_unescape (bson_json_reader_t *reader, _bson_json_buf_ensure (&reader_bson->unescaped, (size_t) len + 1); /* length of unescaped str is always <= len */ - reader_bson->unescaped.len = jsonsl_util_unescape ( - json_text, (char *) reader_bson->unescaped.buf, (size_t) len, NULL, &err); + reader_bson->unescaped.len = + jsonsl_util_unescape (json_text, (char *) reader_bson->unescaped.buf, (size_t) len, NULL, &err); if (err != JSONSL_ERROR_SUCCESS) { bson_set_error (reader->error, @@ -1995,8 +1815,7 @@ _get_json_text (jsonsl_t json, /* IN */ ssize_t append = buf - json->base; if (append > 0) { - _bson_json_buf_append ( - &reader->tok_accumulator, buf - append, (size_t) append); + _bson_json_buf_append (&reader->tok_accumulator, buf - append, (size_t) append); } return (const char *) reader->tok_accumulator.buf; @@ -2005,10 +1824,7 @@ _get_json_text (jsonsl_t json, /* IN */ static void -_push_callback (jsonsl_t json, - jsonsl_action_t action, - struct jsonsl_state_st *state, - const char *buf) +_push_callback (jsonsl_t json, jsonsl_action_t action, struct jsonsl_state_st *state, const char *buf) { bson_json_reader_t *reader = (bson_json_reader_t *) json->data; @@ -2035,10 +1851,7 @@ _push_callback (jsonsl_t json, static void -_pop_callback (jsonsl_t json, - jsonsl_action_t action, - struct jsonsl_state_st *state, - const char *buf) +_pop_callback (jsonsl_t json, jsonsl_action_t action, struct jsonsl_state_st *state, const char *buf) { bson_json_reader_t *reader; bson_json_reader_bson_t *reader_bson; @@ -2067,11 +1880,9 @@ _pop_callback (jsonsl_t json, } if (state->type == JSONSL_T_HKEY) { - _bson_json_read_map_key ( - reader, reader_bson->unescaped.buf, reader_bson->unescaped.len); + _bson_json_read_map_key (reader, reader_bson->unescaped.buf, reader_bson->unescaped.len); } else { - _bson_json_read_string ( - reader, reader_bson->unescaped.buf, reader_bson->unescaped.len); + _bson_json_read_string (reader, reader_bson->unescaped.buf, reader_bson->unescaped.len); } break; case JSONSL_T_OBJECT: @@ -2088,10 +1899,7 @@ _pop_callback (jsonsl_t json, } } else if (state->special_flags & JSONSL_SPECIALf_NUMERIC) { /* jsonsl puts the unsigned value in state->nelem */ - _bson_json_read_integer ( - reader, - state->nelem, - state->special_flags & JSONSL_SPECIALf_SIGNED ? -1 : 1); + _bson_json_read_integer (reader, state->nelem, state->special_flags & JSONSL_SPECIALf_SIGNED ? -1 : 1); } else if (state->special_flags & JSONSL_SPECIALf_BOOLEAN) { _bson_json_read_boolean (reader, obj_text[0] == 't' ? 1 : 0); } else if (state->special_flags & JSONSL_SPECIALf_NULL) { @@ -2108,10 +1916,7 @@ _pop_callback (jsonsl_t json, static int -_error_callback (jsonsl_t json, - jsonsl_error_t err, - struct jsonsl_state_st *state, - char *errat) +_error_callback (jsonsl_t json, jsonsl_error_t err, struct jsonsl_state_st *state, char *errat) { bson_json_reader_t *reader = (bson_json_reader_t *) json->data; @@ -2197,10 +2002,7 @@ bson_json_reader_read (bson_json_reader_t *reader, /* IN */ if (r < 0) { if (error) { - bson_set_error (error, - BSON_ERROR_JSON, - BSON_JSON_ERROR_READ_CB_FAILURE, - "reader cb failed"); + bson_set_error (error, BSON_ERROR_JSON, BSON_JSON_ERROR_READ_CB_FAILURE, "reader cb failed"); } ret = -1; goto cleanup; @@ -2232,16 +2034,12 @@ bson_json_reader_read (bson_json_reader_t *reader, /* IN */ /* accumulate a key or string value */ if (reader->json_text_pos != -1) { if (bson_cmp_less_su (reader->json_text_pos, reader->json->pos)) { - BSON_ASSERT ( - bson_in_range_unsigned (ssize_t, reader->json->pos)); - accum = BSON_MIN ( - (ssize_t) reader->json->pos - reader->json_text_pos, r); + BSON_ASSERT (bson_in_range_unsigned (ssize_t, reader->json->pos)); + accum = BSON_MIN ((ssize_t) reader->json->pos - reader->json_text_pos, r); /* if this chunk stopped mid-token, buf_offset is how far into * our current chunk the token begins. */ buf_offset = AT_LEAST_0 (reader->json_text_pos - start_pos); - _bson_json_buf_append (&reader->tok_accumulator, - p->buf + buf_offset, - (size_t) accum); + _bson_json_buf_append (&reader->tok_accumulator, p->buf + buf_offset, (size_t) accum); } } @@ -2341,8 +2139,7 @@ bson_json_reader_destroy (bson_json_reader_t *reader) /* IN */ void -bson_json_opts_set_outermost_array (bson_json_opts_t *opts, - bool is_outermost_array) +bson_json_opts_set_outermost_array (bson_json_opts_t *opts, bool is_outermost_array) { opts->is_outermost_array = is_outermost_array; } @@ -2381,8 +2178,7 @@ bson_json_data_reader_new (bool allow_multiple, /* IN */ { bson_json_data_reader_t *dr = bson_malloc0 (sizeof *dr); - return bson_json_reader_new ( - dr, &_bson_json_data_reader_cb, &bson_free, allow_multiple, size); + return bson_json_reader_new (dr, &_bson_json_data_reader_cb, &bson_free, allow_multiple, size); } @@ -2391,8 +2187,7 @@ bson_json_data_reader_ingest (bson_json_reader_t *reader, /* IN */ const uint8_t *data, /* IN */ size_t len) /* IN */ { - bson_json_data_reader_t *ctx = - (bson_json_data_reader_t *) reader->producer.data; + bson_json_data_reader_t *ctx = (bson_json_data_reader_t *) reader->producer.data; ctx->data = data; ctx->len = len; @@ -2422,10 +2217,7 @@ bson_new_from_json (const uint8_t *data, /* IN */ bson_json_reader_destroy (reader); if (r == 0) { - bson_set_error (error, - BSON_ERROR_JSON, - BSON_JSON_ERROR_READ_INVALID_PARAM, - "Empty JSON string"); + bson_set_error (error, BSON_ERROR_JSON, BSON_JSON_ERROR_READ_INVALID_PARAM, "Empty JSON string"); } if (r != 1) { @@ -2461,10 +2253,7 @@ bson_init_from_json (bson_t *bson, /* OUT */ bson_json_reader_destroy (reader); if (r == 0) { - bson_set_error (error, - BSON_ERROR_JSON, - BSON_JSON_ERROR_READ_INVALID_PARAM, - "Empty JSON string"); + bson_set_error (error, BSON_ERROR_JSON, BSON_JSON_ERROR_READ_INVALID_PARAM, "Empty JSON string"); } if (r != 1) { @@ -2530,11 +2319,8 @@ bson_json_reader_new_from_fd (int fd, /* IN */ handle->fd = fd; handle->do_close = close_on_destroy; - return bson_json_reader_new (handle, - _bson_json_reader_handle_fd_read, - _bson_json_reader_handle_fd_destroy, - true, - BSON_JSON_DEFAULT_BUF_SIZE); + return bson_json_reader_new ( + handle, _bson_json_reader_handle_fd_read, _bson_json_reader_handle_fd_destroy, true, BSON_JSON_DEFAULT_BUF_SIZE); } @@ -2556,8 +2342,7 @@ bson_json_reader_new_from_file (const char *path, /* IN */ if (fd == -1) { errmsg = bson_strerror_r (errno, errmsg_buf, sizeof errmsg_buf); - bson_set_error ( - error, BSON_ERROR_READER, BSON_ERROR_READER_BADFD, "%s", errmsg); + bson_set_error (error, BSON_ERROR_READER, BSON_ERROR_READER_BADFD, "%s", errmsg); return NULL; } diff --git a/src/libbson/src/bson/bson-json.h b/src/libbson/src/bson/bson-json.h index 9efc8c3446..57f14a7196 100644 --- a/src/libbson/src/bson/bson-json.h +++ b/src/libbson/src/bson/bson-json.h @@ -62,21 +62,15 @@ bson_json_opts_new (bson_json_mode_t mode, int32_t max_len); BSON_EXPORT (void) bson_json_opts_destroy (bson_json_opts_t *opts); BSON_EXPORT (void) -bson_json_opts_set_outermost_array (bson_json_opts_t *opts, - bool is_outermost_array); +bson_json_opts_set_outermost_array (bson_json_opts_t *opts, bool is_outermost_array); -typedef ssize_t (*bson_json_reader_cb) (void *handle, - uint8_t *buf, - size_t count); +typedef ssize_t (*bson_json_reader_cb) (void *handle, uint8_t *buf, size_t count); typedef void (*bson_json_destroy_cb) (void *handle); BSON_EXPORT (bson_json_reader_t *) -bson_json_reader_new (void *data, - bson_json_reader_cb cb, - bson_json_destroy_cb dcb, - bool allow_multiple, - size_t buf_size); +bson_json_reader_new ( + void *data, bson_json_reader_cb cb, bson_json_destroy_cb dcb, bool allow_multiple, size_t buf_size); BSON_EXPORT (bson_json_reader_t *) bson_json_reader_new_from_fd (int fd, bool close_on_destroy); BSON_EXPORT (bson_json_reader_t *) @@ -84,15 +78,11 @@ bson_json_reader_new_from_file (const char *filename, bson_error_t *error); BSON_EXPORT (void) bson_json_reader_destroy (bson_json_reader_t *reader); BSON_EXPORT (int) -bson_json_reader_read (bson_json_reader_t *reader, - bson_t *bson, - bson_error_t *error); +bson_json_reader_read (bson_json_reader_t *reader, bson_t *bson, bson_error_t *error); BSON_EXPORT (bson_json_reader_t *) bson_json_data_reader_new (bool allow_multiple, size_t size); BSON_EXPORT (void) -bson_json_data_reader_ingest (bson_json_reader_t *reader, - const uint8_t *data, - size_t len); +bson_json_data_reader_ingest (bson_json_reader_t *reader, const uint8_t *data, size_t len); BSON_END_DECLS diff --git a/src/libbson/src/bson/bson-keys.c b/src/libbson/src/bson/bson-keys.c index 0f3f73553c..9ba141c6ce 100644 --- a/src/libbson/src/bson/bson-keys.c +++ b/src/libbson/src/bson/bson-keys.c @@ -22,97 +22,69 @@ static const char *gUint32Strs[] = { - "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", - "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", - "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", - "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", - "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", - "55", "56", "57", "58", "59", "60", "61", "62", "63", "64", "65", - "66", "67", "68", "69", "70", "71", "72", "73", "74", "75", "76", - "77", "78", "79", "80", "81", "82", "83", "84", "85", "86", "87", - "88", "89", "90", "91", "92", "93", "94", "95", "96", "97", "98", - "99", "100", "101", "102", "103", "104", "105", "106", "107", "108", "109", - "110", "111", "112", "113", "114", "115", "116", "117", "118", "119", "120", - "121", "122", "123", "124", "125", "126", "127", "128", "129", "130", "131", - "132", "133", "134", "135", "136", "137", "138", "139", "140", "141", "142", - "143", "144", "145", "146", "147", "148", "149", "150", "151", "152", "153", - "154", "155", "156", "157", "158", "159", "160", "161", "162", "163", "164", - "165", "166", "167", "168", "169", "170", "171", "172", "173", "174", "175", - "176", "177", "178", "179", "180", "181", "182", "183", "184", "185", "186", - "187", "188", "189", "190", "191", "192", "193", "194", "195", "196", "197", - "198", "199", "200", "201", "202", "203", "204", "205", "206", "207", "208", - "209", "210", "211", "212", "213", "214", "215", "216", "217", "218", "219", - "220", "221", "222", "223", "224", "225", "226", "227", "228", "229", "230", - "231", "232", "233", "234", "235", "236", "237", "238", "239", "240", "241", - "242", "243", "244", "245", "246", "247", "248", "249", "250", "251", "252", - "253", "254", "255", "256", "257", "258", "259", "260", "261", "262", "263", - "264", "265", "266", "267", "268", "269", "270", "271", "272", "273", "274", - "275", "276", "277", "278", "279", "280", "281", "282", "283", "284", "285", - "286", "287", "288", "289", "290", "291", "292", "293", "294", "295", "296", - "297", "298", "299", "300", "301", "302", "303", "304", "305", "306", "307", - "308", "309", "310", "311", "312", "313", "314", "315", "316", "317", "318", - "319", "320", "321", "322", "323", "324", "325", "326", "327", "328", "329", - "330", "331", "332", "333", "334", "335", "336", "337", "338", "339", "340", - "341", "342", "343", "344", "345", "346", "347", "348", "349", "350", "351", - "352", "353", "354", "355", "356", "357", "358", "359", "360", "361", "362", - "363", "364", "365", "366", "367", "368", "369", "370", "371", "372", "373", - "374", "375", "376", "377", "378", "379", "380", "381", "382", "383", "384", - "385", "386", "387", "388", "389", "390", "391", "392", "393", "394", "395", - "396", "397", "398", "399", "400", "401", "402", "403", "404", "405", "406", - "407", "408", "409", "410", "411", "412", "413", "414", "415", "416", "417", - "418", "419", "420", "421", "422", "423", "424", "425", "426", "427", "428", - "429", "430", "431", "432", "433", "434", "435", "436", "437", "438", "439", - "440", "441", "442", "443", "444", "445", "446", "447", "448", "449", "450", - "451", "452", "453", "454", "455", "456", "457", "458", "459", "460", "461", - "462", "463", "464", "465", "466", "467", "468", "469", "470", "471", "472", - "473", "474", "475", "476", "477", "478", "479", "480", "481", "482", "483", - "484", "485", "486", "487", "488", "489", "490", "491", "492", "493", "494", - "495", "496", "497", "498", "499", "500", "501", "502", "503", "504", "505", - "506", "507", "508", "509", "510", "511", "512", "513", "514", "515", "516", - "517", "518", "519", "520", "521", "522", "523", "524", "525", "526", "527", - "528", "529", "530", "531", "532", "533", "534", "535", "536", "537", "538", - "539", "540", "541", "542", "543", "544", "545", "546", "547", "548", "549", - "550", "551", "552", "553", "554", "555", "556", "557", "558", "559", "560", - "561", "562", "563", "564", "565", "566", "567", "568", "569", "570", "571", - "572", "573", "574", "575", "576", "577", "578", "579", "580", "581", "582", - "583", "584", "585", "586", "587", "588", "589", "590", "591", "592", "593", - "594", "595", "596", "597", "598", "599", "600", "601", "602", "603", "604", - "605", "606", "607", "608", "609", "610", "611", "612", "613", "614", "615", - "616", "617", "618", "619", "620", "621", "622", "623", "624", "625", "626", - "627", "628", "629", "630", "631", "632", "633", "634", "635", "636", "637", - "638", "639", "640", "641", "642", "643", "644", "645", "646", "647", "648", - "649", "650", "651", "652", "653", "654", "655", "656", "657", "658", "659", - "660", "661", "662", "663", "664", "665", "666", "667", "668", "669", "670", - "671", "672", "673", "674", "675", "676", "677", "678", "679", "680", "681", - "682", "683", "684", "685", "686", "687", "688", "689", "690", "691", "692", - "693", "694", "695", "696", "697", "698", "699", "700", "701", "702", "703", - "704", "705", "706", "707", "708", "709", "710", "711", "712", "713", "714", - "715", "716", "717", "718", "719", "720", "721", "722", "723", "724", "725", - "726", "727", "728", "729", "730", "731", "732", "733", "734", "735", "736", - "737", "738", "739", "740", "741", "742", "743", "744", "745", "746", "747", - "748", "749", "750", "751", "752", "753", "754", "755", "756", "757", "758", - "759", "760", "761", "762", "763", "764", "765", "766", "767", "768", "769", - "770", "771", "772", "773", "774", "775", "776", "777", "778", "779", "780", - "781", "782", "783", "784", "785", "786", "787", "788", "789", "790", "791", - "792", "793", "794", "795", "796", "797", "798", "799", "800", "801", "802", - "803", "804", "805", "806", "807", "808", "809", "810", "811", "812", "813", - "814", "815", "816", "817", "818", "819", "820", "821", "822", "823", "824", - "825", "826", "827", "828", "829", "830", "831", "832", "833", "834", "835", - "836", "837", "838", "839", "840", "841", "842", "843", "844", "845", "846", - "847", "848", "849", "850", "851", "852", "853", "854", "855", "856", "857", - "858", "859", "860", "861", "862", "863", "864", "865", "866", "867", "868", - "869", "870", "871", "872", "873", "874", "875", "876", "877", "878", "879", - "880", "881", "882", "883", "884", "885", "886", "887", "888", "889", "890", - "891", "892", "893", "894", "895", "896", "897", "898", "899", "900", "901", - "902", "903", "904", "905", "906", "907", "908", "909", "910", "911", "912", - "913", "914", "915", "916", "917", "918", "919", "920", "921", "922", "923", - "924", "925", "926", "927", "928", "929", "930", "931", "932", "933", "934", - "935", "936", "937", "938", "939", "940", "941", "942", "943", "944", "945", - "946", "947", "948", "949", "950", "951", "952", "953", "954", "955", "956", - "957", "958", "959", "960", "961", "962", "963", "964", "965", "966", "967", - "968", "969", "970", "971", "972", "973", "974", "975", "976", "977", "978", - "979", "980", "981", "982", "983", "984", "985", "986", "987", "988", "989", - "990", "991", "992", "993", "994", "995", "996", "997", "998", "999"}; + "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", + "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", + "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", + "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60", "61", "62", "63", + "64", "65", "66", "67", "68", "69", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", + "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "90", "91", "92", "93", "94", "95", + "96", "97", "98", "99", "100", "101", "102", "103", "104", "105", "106", "107", "108", "109", "110", "111", + "112", "113", "114", "115", "116", "117", "118", "119", "120", "121", "122", "123", "124", "125", "126", "127", + "128", "129", "130", "131", "132", "133", "134", "135", "136", "137", "138", "139", "140", "141", "142", "143", + "144", "145", "146", "147", "148", "149", "150", "151", "152", "153", "154", "155", "156", "157", "158", "159", + "160", "161", "162", "163", "164", "165", "166", "167", "168", "169", "170", "171", "172", "173", "174", "175", + "176", "177", "178", "179", "180", "181", "182", "183", "184", "185", "186", "187", "188", "189", "190", "191", + "192", "193", "194", "195", "196", "197", "198", "199", "200", "201", "202", "203", "204", "205", "206", "207", + "208", "209", "210", "211", "212", "213", "214", "215", "216", "217", "218", "219", "220", "221", "222", "223", + "224", "225", "226", "227", "228", "229", "230", "231", "232", "233", "234", "235", "236", "237", "238", "239", + "240", "241", "242", "243", "244", "245", "246", "247", "248", "249", "250", "251", "252", "253", "254", "255", + "256", "257", "258", "259", "260", "261", "262", "263", "264", "265", "266", "267", "268", "269", "270", "271", + "272", "273", "274", "275", "276", "277", "278", "279", "280", "281", "282", "283", "284", "285", "286", "287", + "288", "289", "290", "291", "292", "293", "294", "295", "296", "297", "298", "299", "300", "301", "302", "303", + "304", "305", "306", "307", "308", "309", "310", "311", "312", "313", "314", "315", "316", "317", "318", "319", + "320", "321", "322", "323", "324", "325", "326", "327", "328", "329", "330", "331", "332", "333", "334", "335", + "336", "337", "338", "339", "340", "341", "342", "343", "344", "345", "346", "347", "348", "349", "350", "351", + "352", "353", "354", "355", "356", "357", "358", "359", "360", "361", "362", "363", "364", "365", "366", "367", + "368", "369", "370", "371", "372", "373", "374", "375", "376", "377", "378", "379", "380", "381", "382", "383", + "384", "385", "386", "387", "388", "389", "390", "391", "392", "393", "394", "395", "396", "397", "398", "399", + "400", "401", "402", "403", "404", "405", "406", "407", "408", "409", "410", "411", "412", "413", "414", "415", + "416", "417", "418", "419", "420", "421", "422", "423", "424", "425", "426", "427", "428", "429", "430", "431", + "432", "433", "434", "435", "436", "437", "438", "439", "440", "441", "442", "443", "444", "445", "446", "447", + "448", "449", "450", "451", "452", "453", "454", "455", "456", "457", "458", "459", "460", "461", "462", "463", + "464", "465", "466", "467", "468", "469", "470", "471", "472", "473", "474", "475", "476", "477", "478", "479", + "480", "481", "482", "483", "484", "485", "486", "487", "488", "489", "490", "491", "492", "493", "494", "495", + "496", "497", "498", "499", "500", "501", "502", "503", "504", "505", "506", "507", "508", "509", "510", "511", + "512", "513", "514", "515", "516", "517", "518", "519", "520", "521", "522", "523", "524", "525", "526", "527", + "528", "529", "530", "531", "532", "533", "534", "535", "536", "537", "538", "539", "540", "541", "542", "543", + "544", "545", "546", "547", "548", "549", "550", "551", "552", "553", "554", "555", "556", "557", "558", "559", + "560", "561", "562", "563", "564", "565", "566", "567", "568", "569", "570", "571", "572", "573", "574", "575", + "576", "577", "578", "579", "580", "581", "582", "583", "584", "585", "586", "587", "588", "589", "590", "591", + "592", "593", "594", "595", "596", "597", "598", "599", "600", "601", "602", "603", "604", "605", "606", "607", + "608", "609", "610", "611", "612", "613", "614", "615", "616", "617", "618", "619", "620", "621", "622", "623", + "624", "625", "626", "627", "628", "629", "630", "631", "632", "633", "634", "635", "636", "637", "638", "639", + "640", "641", "642", "643", "644", "645", "646", "647", "648", "649", "650", "651", "652", "653", "654", "655", + "656", "657", "658", "659", "660", "661", "662", "663", "664", "665", "666", "667", "668", "669", "670", "671", + "672", "673", "674", "675", "676", "677", "678", "679", "680", "681", "682", "683", "684", "685", "686", "687", + "688", "689", "690", "691", "692", "693", "694", "695", "696", "697", "698", "699", "700", "701", "702", "703", + "704", "705", "706", "707", "708", "709", "710", "711", "712", "713", "714", "715", "716", "717", "718", "719", + "720", "721", "722", "723", "724", "725", "726", "727", "728", "729", "730", "731", "732", "733", "734", "735", + "736", "737", "738", "739", "740", "741", "742", "743", "744", "745", "746", "747", "748", "749", "750", "751", + "752", "753", "754", "755", "756", "757", "758", "759", "760", "761", "762", "763", "764", "765", "766", "767", + "768", "769", "770", "771", "772", "773", "774", "775", "776", "777", "778", "779", "780", "781", "782", "783", + "784", "785", "786", "787", "788", "789", "790", "791", "792", "793", "794", "795", "796", "797", "798", "799", + "800", "801", "802", "803", "804", "805", "806", "807", "808", "809", "810", "811", "812", "813", "814", "815", + "816", "817", "818", "819", "820", "821", "822", "823", "824", "825", "826", "827", "828", "829", "830", "831", + "832", "833", "834", "835", "836", "837", "838", "839", "840", "841", "842", "843", "844", "845", "846", "847", + "848", "849", "850", "851", "852", "853", "854", "855", "856", "857", "858", "859", "860", "861", "862", "863", + "864", "865", "866", "867", "868", "869", "870", "871", "872", "873", "874", "875", "876", "877", "878", "879", + "880", "881", "882", "883", "884", "885", "886", "887", "888", "889", "890", "891", "892", "893", "894", "895", + "896", "897", "898", "899", "900", "901", "902", "903", "904", "905", "906", "907", "908", "909", "910", "911", + "912", "913", "914", "915", "916", "917", "918", "919", "920", "921", "922", "923", "924", "925", "926", "927", + "928", "929", "930", "931", "932", "933", "934", "935", "936", "937", "938", "939", "940", "941", "942", "943", + "944", "945", "946", "947", "948", "949", "950", "951", "952", "953", "954", "955", "956", "957", "958", "959", + "960", "961", "962", "963", "964", "965", "966", "967", "968", "969", "970", "971", "972", "973", "974", "975", + "976", "977", "978", "979", "980", "981", "982", "983", "984", "985", "986", "987", "988", "989", "990", "991", + "992", "993", "994", "995", "996", "997", "998", "999"}; /* diff --git a/src/libbson/src/bson/bson-keys.h b/src/libbson/src/bson/bson-keys.h index ba4c0f7548..14f19f321b 100644 --- a/src/libbson/src/bson/bson-keys.h +++ b/src/libbson/src/bson/bson-keys.h @@ -29,10 +29,7 @@ BSON_BEGIN_DECLS BSON_EXPORT (size_t) -bson_uint32_to_string (uint32_t value, - const char **strptr, - char *str, - size_t size); +bson_uint32_to_string (uint32_t value, const char **strptr, char *str, size_t size); BSON_END_DECLS diff --git a/src/libbson/src/bson/bson-macros.h b/src/libbson/src/bson/bson-macros.h index d566713a6b..f9263914f1 100644 --- a/src/libbson/src/bson/bson-macros.h +++ b/src/libbson/src/bson/bson-macros.h @@ -50,16 +50,14 @@ #if defined(__GNUC__) #define BSON_GNUC_CHECK_VERSION(major, minor) \ - ((__GNUC__ > (major)) || \ - ((__GNUC__ == (major)) && (__GNUC_MINOR__ >= (minor)))) + ((__GNUC__ > (major)) || ((__GNUC__ == (major)) && (__GNUC_MINOR__ >= (minor)))) #else #define BSON_GNUC_CHECK_VERSION(major, minor) 0 #endif #if defined(__GNUC__) -#define BSON_GNUC_IS_VERSION(major, minor) \ - ((__GNUC__ == (major)) && (__GNUC_MINOR__ == (minor))) +#define BSON_GNUC_IS_VERSION(major, minor) ((__GNUC__ == (major)) && (__GNUC_MINOR__ == (minor))) #else #define BSON_GNUC_IS_VERSION(major, minor) 0 #endif @@ -177,9 +175,7 @@ #define BSON_ALIGNED_END(_N) #else #define BSON_ALIGNED_BEGIN(_N) -#define BSON_ALIGNED_END(_N) \ - __attribute__ (( \ - aligned ((_N) > BSON_ALIGN_OF_PTR ? BSON_ALIGN_OF_PTR : (_N)))) +#define BSON_ALIGNED_END(_N) __attribute__ ((aligned ((_N) > BSON_ALIGN_OF_PTR ? BSON_ALIGN_OF_PTR : (_N)))) #endif #endif @@ -194,33 +190,24 @@ #define BSON_FUNC __func__ #endif -#define BSON_ASSERT(test) \ - do { \ - if (!(BSON_LIKELY (test))) { \ - fprintf (stderr, \ - "%s:%d %s(): precondition failed: %s\n", \ - __FILE__, \ - __LINE__, \ - BSON_FUNC, \ - #test); \ - abort (); \ - } \ +#define BSON_ASSERT(test) \ + do { \ + if (!(BSON_LIKELY (test))) { \ + fprintf (stderr, "%s:%d %s(): precondition failed: %s\n", __FILE__, __LINE__, BSON_FUNC, #test); \ + abort (); \ + } \ } while (0) /** * @brief Assert the expression `Assertion`, and evaluates to `Value` on * success. */ -#define BSON_ASSERT_INLINE(Assertion, Value) \ - ((void) ((Assertion) ? (0) \ - : ((fprintf (stderr, \ - "%s:%d %s(): Assertion '%s' failed", \ - __FILE__, \ - __LINE__, \ - BSON_FUNC, \ - #Assertion), \ - abort ()), \ - 0)), \ +#define BSON_ASSERT_INLINE(Assertion, Value) \ + ((void) ((Assertion) \ + ? (0) \ + : ((fprintf (stderr, "%s:%d %s(): Assertion '%s' failed", __FILE__, __LINE__, BSON_FUNC, #Assertion), \ + abort ()), \ + 0)), \ Value) /** @@ -234,38 +221,29 @@ * bar* b = BSON_ASSERT_PTR_INLINE(f)->bar_value; * ``` */ -#define BSON_ASSERT_PTR_INLINE(Pointer) \ - BSON_ASSERT_INLINE ((Pointer) != NULL, (Pointer)) +#define BSON_ASSERT_PTR_INLINE(Pointer) BSON_ASSERT_INLINE ((Pointer) != NULL, (Pointer)) /* Used for asserting parameters to provide a more precise error message */ -#define BSON_ASSERT_PARAM(param) \ - do { \ - if ((BSON_UNLIKELY (param == NULL))) { \ - fprintf (stderr, \ - "The parameter: %s, in function %s, cannot be NULL\n", \ - #param, \ - BSON_FUNC); \ - abort (); \ - } \ +#define BSON_ASSERT_PARAM(param) \ + do { \ + if ((BSON_UNLIKELY (param == NULL))) { \ + fprintf (stderr, "The parameter: %s, in function %s, cannot be NULL\n", #param, BSON_FUNC); \ + abort (); \ + } \ } while (0) /* obsolete macros, preserved for compatibility */ #define BSON_STATIC_ASSERT(s) BSON_STATIC_ASSERT_ (s, __LINE__) #define BSON_STATIC_ASSERT_JOIN(a, b) BSON_STATIC_ASSERT_JOIN2 (a, b) #define BSON_STATIC_ASSERT_JOIN2(a, b) a##b -#define BSON_STATIC_ASSERT_(s, l) \ - typedef char BSON_STATIC_ASSERT_JOIN (static_assert_test_, \ - __LINE__)[(s) ? 1 : -1] +#define BSON_STATIC_ASSERT_(s, l) typedef char BSON_STATIC_ASSERT_JOIN (static_assert_test_, __LINE__)[(s) ? 1 : -1] /* modern macros */ -#define BSON_STATIC_ASSERT2(_name, _s) \ - BSON_STATIC_ASSERT2_ (_s, __LINE__, _name) -#define BSON_STATIC_ASSERT_JOIN3(_a, _b, _name) \ - BSON_STATIC_ASSERT_JOIN4 (_a, _b, _name) +#define BSON_STATIC_ASSERT2(_name, _s) BSON_STATIC_ASSERT2_ (_s, __LINE__, _name) +#define BSON_STATIC_ASSERT_JOIN3(_a, _b, _name) BSON_STATIC_ASSERT_JOIN4 (_a, _b, _name) #define BSON_STATIC_ASSERT_JOIN4(_a, _b, _name) _a##_b##_name #define BSON_STATIC_ASSERT2_(_s, _l, _name) \ - typedef char BSON_STATIC_ASSERT_JOIN3 ( \ - static_assert_test_, __LINE__, _name)[(_s) ? 1 : -1] + typedef char BSON_STATIC_ASSERT_JOIN3 (static_assert_test_, __LINE__, _name)[(_s) ? 1 : -1] #if defined(__GNUC__) @@ -336,12 +314,10 @@ #define BSON_CONCAT_IMPL(a, ...) a##__VA_ARGS__ #define BSON_CONCAT(a, ...) BSON_CONCAT_IMPL (a, __VA_ARGS__) #define BSON_CONCAT3(a, b, c) BSON_CONCAT (a, BSON_CONCAT (b, c)) -#define BSON_CONCAT4(a, b, c, d) \ - BSON_CONCAT (BSON_CONCAT (a, b), BSON_CONCAT (c, d)) +#define BSON_CONCAT4(a, b, c, d) BSON_CONCAT (BSON_CONCAT (a, b), BSON_CONCAT (c, d)) #if BSON_GNUC_CHECK_VERSION(4, 5) -#define BSON_GNUC_DEPRECATED_FOR(f) \ - __attribute__ ((deprecated ("Use " #f " instead"))) +#define BSON_GNUC_DEPRECATED_FOR(f) __attribute__ ((deprecated ("Use " #f " instead"))) #else #define BSON_GNUC_DEPRECATED_FOR(f) BSON_GNUC_DEPRECATED #endif @@ -369,15 +345,10 @@ * @param What A string to include in the error message if this point is ever * executed. */ -#define BSON_UNREACHABLE(What) \ - do { \ - fprintf (stderr, \ - "%s:%d %s(): Unreachable code reached: %s\n", \ - __FILE__, \ - __LINE__, \ - BSON_FUNC, \ - What); \ - abort (); \ +#define BSON_UNREACHABLE(What) \ + do { \ + fprintf (stderr, "%s:%d %s(): Unreachable code reached: %s\n", __FILE__, __LINE__, BSON_FUNC, What); \ + abort (); \ } while (0) /** diff --git a/src/libbson/src/bson/bson-md5.h b/src/libbson/src/bson/bson-md5.h index 46ca8b9846..77a1677e1a 100644 --- a/src/libbson/src/bson/bson-md5.h +++ b/src/libbson/src/bson/bson-md5.h @@ -76,9 +76,7 @@ typedef struct { BSON_EXPORT (void) bson_md5_init (bson_md5_t *pms) BSON_GNUC_DEPRECATED; BSON_EXPORT (void) -bson_md5_append (bson_md5_t *pms, - const uint8_t *data, - uint32_t nbytes) BSON_GNUC_DEPRECATED; +bson_md5_append (bson_md5_t *pms, const uint8_t *data, uint32_t nbytes) BSON_GNUC_DEPRECATED; BSON_EXPORT (void) bson_md5_finish (bson_md5_t *pms, uint8_t digest[16]) BSON_GNUC_DEPRECATED; diff --git a/src/libbson/src/bson/bson-memory.c b/src/libbson/src/bson/bson-memory.c index 03bc4dd599..6c37003f2b 100644 --- a/src/libbson/src/bson/bson-memory.c +++ b/src/libbson/src/bson/bson-memory.c @@ -26,15 +26,14 @@ // Ensure size of exported structs are stable. -BSON_STATIC_ASSERT2 (bson_mem_vtable_t, - sizeof (bson_mem_vtable_t) == sizeof (void *) * 8u); +BSON_STATIC_ASSERT2 (bson_mem_vtable_t, sizeof (bson_mem_vtable_t) == sizeof (void *) * 8u); // For compatibility with C standards prior to C11. static void * _aligned_alloc_impl (size_t alignment, size_t num_bytes) -#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L && \ - !defined(_WIN32) && !defined(__ANDROID__) && !defined(_AIX) +#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L && !defined(_WIN32) && !defined(__ANDROID__) && \ + !defined(_AIX) { return aligned_alloc (alignment, num_bytes); } @@ -98,9 +97,7 @@ bson_malloc (size_t num_bytes) /* IN */ if (BSON_LIKELY (num_bytes)) { if (BSON_UNLIKELY (!(mem = gMemVtable.malloc (num_bytes)))) { - fprintf (stderr, - "Failure to allocate memory in bson_malloc(). errno: %d.\n", - errno); + fprintf (stderr, "Failure to allocate memory in bson_malloc(). errno: %d.\n", errno); abort (); } } @@ -138,9 +135,7 @@ bson_malloc0 (size_t num_bytes) /* IN */ if (BSON_LIKELY (num_bytes)) { if (BSON_UNLIKELY (!(mem = gMemVtable.calloc (1, num_bytes)))) { - fprintf (stderr, - "Failure to allocate memory in bson_malloc0(). errno: %d.\n", - errno); + fprintf (stderr, "Failure to allocate memory in bson_malloc0(). errno: %d.\n", errno); abort (); } } @@ -181,10 +176,8 @@ bson_aligned_alloc (size_t alignment /* IN */, size_t num_bytes /* IN */) void *mem = NULL; if (BSON_LIKELY (num_bytes)) { - if (BSON_UNLIKELY ( - !(mem = gMemVtable.aligned_alloc (alignment, num_bytes)))) { - fprintf (stderr, - "Failure to allocate memory in bson_aligned_alloc()\n"); + if (BSON_UNLIKELY (!(mem = gMemVtable.aligned_alloc (alignment, num_bytes)))) { + fprintf (stderr, "Failure to allocate memory in bson_aligned_alloc()\n"); abort (); } } @@ -221,10 +214,8 @@ bson_aligned_alloc0 (size_t alignment /* IN */, size_t num_bytes /* IN */) void *mem = NULL; if (BSON_LIKELY (num_bytes)) { - if (BSON_UNLIKELY ( - !(mem = gMemVtable.aligned_alloc (alignment, num_bytes)))) { - fprintf (stderr, - "Failure to allocate memory in bson_aligned_alloc0()\n"); + if (BSON_UNLIKELY (!(mem = gMemVtable.aligned_alloc (alignment, num_bytes)))) { + fprintf (stderr, "Failure to allocate memory in bson_aligned_alloc0()\n"); abort (); } memset (mem, 0, num_bytes); @@ -273,9 +264,7 @@ bson_realloc (void *mem, /* IN */ mem = gMemVtable.realloc (mem, num_bytes); if (BSON_UNLIKELY (!mem)) { - fprintf (stderr, - "Failure to re-allocate memory in bson_realloc(). errno: %d.\n", - errno); + fprintf (stderr, "Failure to re-allocate memory in bson_realloc(). errno: %d.\n", errno); abort (); } @@ -414,8 +403,7 @@ bson_mem_set_vtable (const bson_mem_vtable_t *vtable) { BSON_ASSERT (vtable); - if (!vtable->malloc || !vtable->calloc || !vtable->realloc || - !vtable->free) { + if (!vtable->malloc || !vtable->calloc || !vtable->realloc || !vtable->free) { fprintf (stderr, "Failure to install BSON vtable, " "missing functions.\n"); diff --git a/src/libbson/src/bson/bson-memory.h b/src/libbson/src/bson/bson-memory.h index 99470701e9..bde15edaef 100644 --- a/src/libbson/src/bson/bson-memory.h +++ b/src/libbson/src/bson/bson-memory.h @@ -63,10 +63,8 @@ BSON_EXPORT (void) bson_zero_free (void *mem, size_t size); -#define BSON_ALIGNED_ALLOC(T) \ - ((T *) (bson_aligned_alloc (BSON_ALIGNOF (T), sizeof (T)))) -#define BSON_ALIGNED_ALLOC0(T) \ - ((T *) (bson_aligned_alloc0 (BSON_ALIGNOF (T), sizeof (T)))) +#define BSON_ALIGNED_ALLOC(T) ((T *) (bson_aligned_alloc (BSON_ALIGNOF (T), sizeof (T)))) +#define BSON_ALIGNED_ALLOC0(T) ((T *) (bson_aligned_alloc0 (BSON_ALIGNOF (T), sizeof (T)))) BSON_END_DECLS diff --git a/src/libbson/src/bson/bson-oid.c b/src/libbson/src/bson/bson-oid.c index 8834d7d365..e4171c711e 100644 --- a/src/libbson/src/bson/bson-oid.c +++ b/src/libbson/src/bson/bson-oid.c @@ -34,55 +34,43 @@ */ BSON_MAYBE_UNUSED static const uint16_t gHexCharPairs[] = { #if BSON_BYTE_ORDER == BSON_BIG_ENDIAN - 12336, 12337, 12338, 12339, 12340, 12341, 12342, 12343, 12344, 12345, 12385, - 12386, 12387, 12388, 12389, 12390, 12592, 12593, 12594, 12595, 12596, 12597, - 12598, 12599, 12600, 12601, 12641, 12642, 12643, 12644, 12645, 12646, 12848, - 12849, 12850, 12851, 12852, 12853, 12854, 12855, 12856, 12857, 12897, 12898, - 12899, 12900, 12901, 12902, 13104, 13105, 13106, 13107, 13108, 13109, 13110, - 13111, 13112, 13113, 13153, 13154, 13155, 13156, 13157, 13158, 13360, 13361, - 13362, 13363, 13364, 13365, 13366, 13367, 13368, 13369, 13409, 13410, 13411, - 13412, 13413, 13414, 13616, 13617, 13618, 13619, 13620, 13621, 13622, 13623, - 13624, 13625, 13665, 13666, 13667, 13668, 13669, 13670, 13872, 13873, 13874, - 13875, 13876, 13877, 13878, 13879, 13880, 13881, 13921, 13922, 13923, 13924, - 13925, 13926, 14128, 14129, 14130, 14131, 14132, 14133, 14134, 14135, 14136, - 14137, 14177, 14178, 14179, 14180, 14181, 14182, 14384, 14385, 14386, 14387, - 14388, 14389, 14390, 14391, 14392, 14393, 14433, 14434, 14435, 14436, 14437, - 14438, 14640, 14641, 14642, 14643, 14644, 14645, 14646, 14647, 14648, 14649, - 14689, 14690, 14691, 14692, 14693, 14694, 24880, 24881, 24882, 24883, 24884, - 24885, 24886, 24887, 24888, 24889, 24929, 24930, 24931, 24932, 24933, 24934, - 25136, 25137, 25138, 25139, 25140, 25141, 25142, 25143, 25144, 25145, 25185, - 25186, 25187, 25188, 25189, 25190, 25392, 25393, 25394, 25395, 25396, 25397, - 25398, 25399, 25400, 25401, 25441, 25442, 25443, 25444, 25445, 25446, 25648, - 25649, 25650, 25651, 25652, 25653, 25654, 25655, 25656, 25657, 25697, 25698, - 25699, 25700, 25701, 25702, 25904, 25905, 25906, 25907, 25908, 25909, 25910, - 25911, 25912, 25913, 25953, 25954, 25955, 25956, 25957, 25958, 26160, 26161, - 26162, 26163, 26164, 26165, 26166, 26167, 26168, 26169, 26209, 26210, 26211, - 26212, 26213, 26214 + 12336, 12337, 12338, 12339, 12340, 12341, 12342, 12343, 12344, 12345, 12385, 12386, 12387, 12388, 12389, + 12390, 12592, 12593, 12594, 12595, 12596, 12597, 12598, 12599, 12600, 12601, 12641, 12642, 12643, 12644, + 12645, 12646, 12848, 12849, 12850, 12851, 12852, 12853, 12854, 12855, 12856, 12857, 12897, 12898, 12899, + 12900, 12901, 12902, 13104, 13105, 13106, 13107, 13108, 13109, 13110, 13111, 13112, 13113, 13153, 13154, + 13155, 13156, 13157, 13158, 13360, 13361, 13362, 13363, 13364, 13365, 13366, 13367, 13368, 13369, 13409, + 13410, 13411, 13412, 13413, 13414, 13616, 13617, 13618, 13619, 13620, 13621, 13622, 13623, 13624, 13625, + 13665, 13666, 13667, 13668, 13669, 13670, 13872, 13873, 13874, 13875, 13876, 13877, 13878, 13879, 13880, + 13881, 13921, 13922, 13923, 13924, 13925, 13926, 14128, 14129, 14130, 14131, 14132, 14133, 14134, 14135, + 14136, 14137, 14177, 14178, 14179, 14180, 14181, 14182, 14384, 14385, 14386, 14387, 14388, 14389, 14390, + 14391, 14392, 14393, 14433, 14434, 14435, 14436, 14437, 14438, 14640, 14641, 14642, 14643, 14644, 14645, + 14646, 14647, 14648, 14649, 14689, 14690, 14691, 14692, 14693, 14694, 24880, 24881, 24882, 24883, 24884, + 24885, 24886, 24887, 24888, 24889, 24929, 24930, 24931, 24932, 24933, 24934, 25136, 25137, 25138, 25139, + 25140, 25141, 25142, 25143, 25144, 25145, 25185, 25186, 25187, 25188, 25189, 25190, 25392, 25393, 25394, + 25395, 25396, 25397, 25398, 25399, 25400, 25401, 25441, 25442, 25443, 25444, 25445, 25446, 25648, 25649, + 25650, 25651, 25652, 25653, 25654, 25655, 25656, 25657, 25697, 25698, 25699, 25700, 25701, 25702, 25904, + 25905, 25906, 25907, 25908, 25909, 25910, 25911, 25912, 25913, 25953, 25954, 25955, 25956, 25957, 25958, + 26160, 26161, 26162, 26163, 26164, 26165, 26166, 26167, 26168, 26169, 26209, 26210, 26211, 26212, 26213, + 26214 #else - 12336, 12592, 12848, 13104, 13360, 13616, 13872, 14128, 14384, 14640, 24880, - 25136, 25392, 25648, 25904, 26160, 12337, 12593, 12849, 13105, 13361, 13617, - 13873, 14129, 14385, 14641, 24881, 25137, 25393, 25649, 25905, 26161, 12338, - 12594, 12850, 13106, 13362, 13618, 13874, 14130, 14386, 14642, 24882, 25138, - 25394, 25650, 25906, 26162, 12339, 12595, 12851, 13107, 13363, 13619, 13875, - 14131, 14387, 14643, 24883, 25139, 25395, 25651, 25907, 26163, 12340, 12596, - 12852, 13108, 13364, 13620, 13876, 14132, 14388, 14644, 24884, 25140, 25396, - 25652, 25908, 26164, 12341, 12597, 12853, 13109, 13365, 13621, 13877, 14133, - 14389, 14645, 24885, 25141, 25397, 25653, 25909, 26165, 12342, 12598, 12854, - 13110, 13366, 13622, 13878, 14134, 14390, 14646, 24886, 25142, 25398, 25654, - 25910, 26166, 12343, 12599, 12855, 13111, 13367, 13623, 13879, 14135, 14391, - 14647, 24887, 25143, 25399, 25655, 25911, 26167, 12344, 12600, 12856, 13112, - 13368, 13624, 13880, 14136, 14392, 14648, 24888, 25144, 25400, 25656, 25912, - 26168, 12345, 12601, 12857, 13113, 13369, 13625, 13881, 14137, 14393, 14649, - 24889, 25145, 25401, 25657, 25913, 26169, 12385, 12641, 12897, 13153, 13409, - 13665, 13921, 14177, 14433, 14689, 24929, 25185, 25441, 25697, 25953, 26209, - 12386, 12642, 12898, 13154, 13410, 13666, 13922, 14178, 14434, 14690, 24930, - 25186, 25442, 25698, 25954, 26210, 12387, 12643, 12899, 13155, 13411, 13667, - 13923, 14179, 14435, 14691, 24931, 25187, 25443, 25699, 25955, 26211, 12388, - 12644, 12900, 13156, 13412, 13668, 13924, 14180, 14436, 14692, 24932, 25188, - 25444, 25700, 25956, 26212, 12389, 12645, 12901, 13157, 13413, 13669, 13925, - 14181, 14437, 14693, 24933, 25189, 25445, 25701, 25957, 26213, 12390, 12646, - 12902, 13158, 13414, 13670, 13926, 14182, 14438, 14694, 24934, 25190, 25446, - 25702, 25958, 26214 + 12336, 12592, 12848, 13104, 13360, 13616, 13872, 14128, 14384, 14640, 24880, 25136, 25392, 25648, 25904, + 26160, 12337, 12593, 12849, 13105, 13361, 13617, 13873, 14129, 14385, 14641, 24881, 25137, 25393, 25649, + 25905, 26161, 12338, 12594, 12850, 13106, 13362, 13618, 13874, 14130, 14386, 14642, 24882, 25138, 25394, + 25650, 25906, 26162, 12339, 12595, 12851, 13107, 13363, 13619, 13875, 14131, 14387, 14643, 24883, 25139, + 25395, 25651, 25907, 26163, 12340, 12596, 12852, 13108, 13364, 13620, 13876, 14132, 14388, 14644, 24884, + 25140, 25396, 25652, 25908, 26164, 12341, 12597, 12853, 13109, 13365, 13621, 13877, 14133, 14389, 14645, + 24885, 25141, 25397, 25653, 25909, 26165, 12342, 12598, 12854, 13110, 13366, 13622, 13878, 14134, 14390, + 14646, 24886, 25142, 25398, 25654, 25910, 26166, 12343, 12599, 12855, 13111, 13367, 13623, 13879, 14135, + 14391, 14647, 24887, 25143, 25399, 25655, 25911, 26167, 12344, 12600, 12856, 13112, 13368, 13624, 13880, + 14136, 14392, 14648, 24888, 25144, 25400, 25656, 25912, 26168, 12345, 12601, 12857, 13113, 13369, 13625, + 13881, 14137, 14393, 14649, 24889, 25145, 25401, 25657, 25913, 26169, 12385, 12641, 12897, 13153, 13409, + 13665, 13921, 14177, 14433, 14689, 24929, 25185, 25441, 25697, 25953, 26209, 12386, 12642, 12898, 13154, + 13410, 13666, 13922, 14178, 14434, 14690, 24930, 25186, 25442, 25698, 25954, 26210, 12387, 12643, 12899, + 13155, 13411, 13667, 13923, 14179, 14435, 14691, 24931, 25187, 25443, 25699, 25955, 26211, 12388, 12644, + 12900, 13156, 13412, 13668, 13924, 14180, 14436, 14692, 24932, 25188, 25444, 25700, 25956, 26212, 12389, + 12645, 12901, 13157, 13413, 13669, 13925, 14181, 14437, 14693, 24933, 25189, 25445, 25701, 25957, 26213, + 12390, 12646, 12902, 13158, 13414, 13670, 13926, 14182, 14438, 14694, 24934, 25190, 25446, 25702, 25958, + 26214 #endif }; @@ -157,8 +145,7 @@ void bson_oid_to_string (const bson_oid_t *oid, /* IN */ char str[BSON_ENSURE_ARRAY_PARAM_SIZE (25)]) /* OUT */ { -#if !defined(__i386__) && !defined(__x86_64__) && !defined(_M_IX86) && \ - !defined(_M_X64) +#if !defined(__i386__) && !defined(__x86_64__) && !defined(_M_IX86) && !defined(_M_X64) BSON_ASSERT (oid); BSON_ASSERT (str); diff --git a/src/libbson/src/bson/bson-oid.h b/src/libbson/src/bson/bson-oid.h index 5f4426a51c..4829e28f5e 100644 --- a/src/libbson/src/bson/bson-oid.h +++ b/src/libbson/src/bson/bson-oid.h @@ -51,8 +51,7 @@ bson_oid_init_from_data (bson_oid_t *oid, const uint8_t *data); BSON_EXPORT (void) bson_oid_init_from_string (bson_oid_t *oid, const char *str); BSON_EXPORT (void) -bson_oid_init_sequence (bson_oid_t *oid, bson_context_t *context) - BSON_GNUC_DEPRECATED_FOR (bson_oid_init); +bson_oid_init_sequence (bson_oid_t *oid, bson_context_t *context) BSON_GNUC_DEPRECATED_FOR (bson_oid_init); BSON_EXPORT (void) bson_oid_to_string (const bson_oid_t *oid, char str[25]); @@ -214,8 +213,8 @@ bson_oid_init_from_string_unsafe (bson_oid_t *oid, const char *str) int i; for (i = 0; i < 12; i++) { - oid->bytes[i] = (uint8_t) ((bson_oid_parse_hex_char (str[2 * i]) << 4) | - (bson_oid_parse_hex_char (str[2 * i + 1]))); + oid->bytes[i] = + (uint8_t) ((bson_oid_parse_hex_char (str[2 * i]) << 4) | (bson_oid_parse_hex_char (str[2 * i + 1]))); } } diff --git a/src/libbson/src/bson/bson-private.h b/src/libbson/src/bson/bson-private.h index 121a5ff2f6..3b006a3479 100644 --- a/src/libbson/src/bson/bson-private.h +++ b/src/libbson/src/bson/bson-private.h @@ -27,14 +27,12 @@ #if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6) -#define BEGIN_IGNORE_DEPRECATIONS \ - _Pragma ("GCC diagnostic push") \ - _Pragma ("GCC diagnostic ignored \"-Wdeprecated-declarations\"") +#define BEGIN_IGNORE_DEPRECATIONS \ + _Pragma ("GCC diagnostic push") _Pragma ("GCC diagnostic ignored \"-Wdeprecated-declarations\"") #define END_IGNORE_DEPRECATIONS _Pragma ("GCC diagnostic pop") #elif defined(__clang__) -#define BEGIN_IGNORE_DEPRECATIONS \ - _Pragma ("clang diagnostic push") \ - _Pragma ("clang diagnostic ignored \"-Wdeprecated-declarations\"") +#define BEGIN_IGNORE_DEPRECATIONS \ + _Pragma ("clang diagnostic push") _Pragma ("clang diagnostic ignored \"-Wdeprecated-declarations\"") #define END_IGNORE_DEPRECATIONS _Pragma ("clang diagnostic pop") #else #define BEGIN_IGNORE_DEPRECATIONS diff --git a/src/libbson/src/bson/bson-reader.c b/src/libbson/src/bson/bson-reader.c index 3250d14b4a..84ade05911 100644 --- a/src/libbson/src/bson/bson-reader.c +++ b/src/libbson/src/bson/bson-reader.c @@ -110,17 +110,14 @@ _bson_reader_handle_fill_buffer (bson_reader_handle_t *reader) /* IN */ /* * Move valid data to head. */ - memmove (&reader->data[0], - &reader->data[reader->offset], - reader->end - reader->offset); + memmove (&reader->data[0], &reader->data[reader->offset], reader->end - reader->offset); reader->end = reader->end - reader->offset; reader->offset = 0; /* * Read in data to fill the buffer. */ - ret = reader->read_func ( - reader->handle, &reader->data[reader->end], reader->len - reader->end); + ret = reader->read_func (reader->handle, &reader->data[reader->end], reader->len - reader->end); if (ret <= 0) { reader->done = true; @@ -159,9 +156,7 @@ _bson_reader_handle_fill_buffer (bson_reader_handle_t *reader) /* IN */ */ bson_reader_t * -bson_reader_new_from_handle (void *handle, - bson_reader_read_func_t rf, - bson_reader_destroy_func_t df) +bson_reader_new_from_handle (void *handle, bson_reader_read_func_t rf, bson_reader_destroy_func_t df) { bson_reader_handle_t *real; @@ -301,8 +296,7 @@ bson_reader_new_from_fd (int fd, /* IN */ handle->fd = fd; handle->do_close = close_on_destroy; - return bson_reader_new_from_handle ( - handle, _bson_reader_handle_fd_read, _bson_reader_handle_fd_destroy); + return bson_reader_new_from_handle (handle, _bson_reader_handle_fd_read, _bson_reader_handle_fd_destroy); } @@ -484,9 +478,7 @@ _bson_reader_handle_read (bson_reader_handle_t *reader, /* IN */ continue; } - if (!bson_init_static (&reader->inline_bson, - &reader->data[reader->offset], - (uint32_t) blen)) { + if (!bson_init_static (&reader->inline_bson, &reader->data[reader->offset], (uint32_t) blen)) { return NULL; } @@ -582,9 +574,7 @@ _bson_reader_data_read (bson_reader_data_t *reader, /* IN */ return NULL; } - if (!bson_init_static (&reader->inline_bson, - &reader->data[reader->offset], - (uint32_t) blen)) { + if (!bson_init_static (&reader->inline_bson, &reader->data[reader->offset], (uint32_t) blen)) { return NULL; } @@ -709,12 +699,10 @@ bson_reader_read (bson_reader_t *reader, /* IN */ switch (reader->type) { case BSON_READER_HANDLE: - return _bson_reader_handle_read ((bson_reader_handle_t *) reader, - reached_eof); + return _bson_reader_handle_read ((bson_reader_handle_t *) reader, reached_eof); case BSON_READER_DATA: - return _bson_reader_data_read ((bson_reader_data_t *) reader, - reached_eof); + return _bson_reader_data_read ((bson_reader_data_t *) reader, reached_eof); default: fprintf (stderr, "No such reader type: %02x\n", reader->type); @@ -800,8 +788,7 @@ bson_reader_new_from_file (const char *path, /* IN */ if (fd == -1) { errmsg = bson_strerror_r (errno, errmsg_buf, sizeof errmsg_buf); - bson_set_error ( - error, BSON_ERROR_READER, BSON_ERROR_READER_BADFD, "%s", errmsg); + bson_set_error (error, BSON_ERROR_READER, BSON_ERROR_READER_BADFD, "%s", errmsg); return NULL; } diff --git a/src/libbson/src/bson/bson-reader.h b/src/libbson/src/bson/bson-reader.h index 7c818659c2..827b0fe936 100644 --- a/src/libbson/src/bson/bson-reader.h +++ b/src/libbson/src/bson/bson-reader.h @@ -88,9 +88,7 @@ typedef void (*bson_reader_destroy_func_t) (void *handle); /* IN */ BSON_EXPORT (bson_reader_t *) -bson_reader_new_from_handle (void *handle, - bson_reader_read_func_t rf, - bson_reader_destroy_func_t df); +bson_reader_new_from_handle (void *handle, bson_reader_read_func_t rf, bson_reader_destroy_func_t df); BSON_EXPORT (bson_reader_t *) bson_reader_new_from_fd (int fd, bool close_on_destroy); BSON_EXPORT (bson_reader_t *) @@ -102,8 +100,7 @@ bson_reader_destroy (bson_reader_t *reader); BSON_EXPORT (void) bson_reader_set_read_func (bson_reader_t *reader, bson_reader_read_func_t func); BSON_EXPORT (void) -bson_reader_set_destroy_func (bson_reader_t *reader, - bson_reader_destroy_func_t func); +bson_reader_set_destroy_func (bson_reader_t *reader, bson_reader_destroy_func_t func); BSON_EXPORT (const bson_t *) bson_reader_read (bson_reader_t *reader, bool *reached_eof); BSON_EXPORT (off_t) diff --git a/src/libbson/src/bson/bson-string.c b/src/libbson/src/bson/bson-string.c index 36c4c5ab49..156003eee1 100644 --- a/src/libbson/src/bson/bson-string.c +++ b/src/libbson/src/bson/bson-string.c @@ -135,8 +135,7 @@ bson_string_append (bson_string_t *string, /* IN */ if ((string->alloc - string->len - 1) < len) { string->alloc += len; if (!bson_is_power_of_two (string->alloc)) { - string->alloc = - (uint32_t) bson_next_power_of_two ((size_t) string->alloc); + string->alloc = (uint32_t) bson_next_power_of_two ((size_t) string->alloc); } string->str = bson_realloc (string->str, string->alloc); } @@ -728,8 +727,7 @@ bson_ascii_strtoll (const char *s, char **e, int base) } /* from here down, inspired by NetBSD's strtoll */ - if ((base == 0 || base == 16) && c == '0' && - (tok[1] == 'x' || tok[1] == 'X')) { + if ((base == 0 || base == 16) && c == '0' && (tok[1] == 'x' || tok[1] == 'X')) { tok += 2; c = *tok; base = 16; diff --git a/src/libbson/src/bson/bson-string.h b/src/libbson/src/bson/bson-string.h index 467a4567cf..3759afff0b 100644 --- a/src/libbson/src/bson/bson-string.h +++ b/src/libbson/src/bson/bson-string.h @@ -48,8 +48,7 @@ bson_string_append_c (bson_string_t *string, char str); BSON_EXPORT (void) bson_string_append_unichar (bson_string_t *string, bson_unichar_t unichar); BSON_EXPORT (void) -bson_string_append_printf (bson_string_t *string, const char *format, ...) - BSON_GNUC_PRINTF (2, 3); +bson_string_append_printf (bson_string_t *string, const char *format, ...) BSON_GNUC_PRINTF (2, 3); BSON_EXPORT (void) bson_string_truncate (bson_string_t *string, uint32_t len); BSON_EXPORT (char *) @@ -63,11 +62,9 @@ bson_strndup (const char *str, size_t n_bytes); BSON_EXPORT (void) bson_strncpy (char *dst, const char *src, size_t size); BSON_EXPORT (int) -bson_vsnprintf (char *str, size_t size, const char *format, va_list ap) - BSON_GNUC_PRINTF (3, 0); +bson_vsnprintf (char *str, size_t size, const char *format, va_list ap) BSON_GNUC_PRINTF (3, 0); BSON_EXPORT (int) -bson_snprintf (char *str, size_t size, const char *format, ...) - BSON_GNUC_PRINTF (3, 4); +bson_snprintf (char *str, size_t size, const char *format, ...) BSON_GNUC_PRINTF (3, 4); BSON_EXPORT (void) bson_strfreev (char **strv); BSON_EXPORT (size_t) diff --git a/src/libbson/src/bson/bson-timegm.c b/src/libbson/src/bson/bson-timegm.c index cea7b2f519..3753aa9bf6 100644 --- a/src/libbson/src/bson/bson-timegm.c +++ b/src/libbson/src/bson/bson-timegm.c @@ -31,8 +31,7 @@ #define ATTRIBUTE_FORMAT(spec) /* empty */ #endif -#if !defined _Noreturn && \ - (!defined(__STDC_VERSION__) || __STDC_VERSION__ < 201112) +#if !defined _Noreturn && (!defined(__STDC_VERSION__) || __STDC_VERSION__ < 201112) #if 2 < __GNUC__ + (8 <= __GNUC_MINOR__) #define _Noreturn __attribute__ ((__noreturn__)) #else @@ -135,8 +134,7 @@ static int64_t const time_t_max = INT64_MAX; #endif /* !defined TZ_ABBR_MAX_LEN */ #ifndef TZ_ABBR_CHAR_SET -#define TZ_ABBR_CHAR_SET \ - "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 :+-._" +#define TZ_ABBR_CHAR_SET "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 :+-._" #endif /* !defined TZ_ABBR_CHAR_SET */ #ifndef TZ_ABBR_ERR_CHAR @@ -227,9 +225,7 @@ struct rule { static void gmtload (struct state *const sp); static struct bson_tm * -gmtsub (const int64_t *const timep, - const int_fast32_t offset, - struct bson_tm *const tmp); +gmtsub (const int64_t *const timep, const int_fast32_t offset, struct bson_tm *const tmp); static int64_t increment_overflow (int64_t *const ip, int64_t j); static int64_t @@ -237,31 +233,21 @@ leaps_thru_end_of (const int64_t y) ATTRIBUTE_PURE; static int64_t increment_overflow32 (int_fast32_t *const lp, int64_t const m); static int64_t -normalize_overflow32 (int_fast32_t *const tensptr, - int64_t *const unitsptr, - const int64_t base); +normalize_overflow32 (int_fast32_t *const tensptr, int64_t *const unitsptr, const int64_t base); static int64_t -normalize_overflow (int64_t *const tensptr, - int64_t *const unitsptr, - const int64_t base); +normalize_overflow (int64_t *const tensptr, int64_t *const unitsptr, const int64_t base); static int64_t time1 (struct bson_tm *const tmp, - struct bson_tm *(*const funcp) (const int64_t *, - int_fast32_t, - struct bson_tm *), + struct bson_tm *(*const funcp) (const int64_t *, int_fast32_t, struct bson_tm *), const int_fast32_t offset); static int64_t time2 (struct bson_tm *const tmp, - struct bson_tm *(*const funcp) (const int64_t *, - int_fast32_t, - struct bson_tm *), + struct bson_tm *(*const funcp) (const int64_t *, int_fast32_t, struct bson_tm *), const int_fast32_t offset, int64_t *const okayp); static int64_t time2sub (struct bson_tm *const tmp, - struct bson_tm *(*const funcp) (const int64_t *, - int_fast32_t, - struct bson_tm *), + struct bson_tm *(*const funcp) (const int64_t *, int_fast32_t, struct bson_tm *), const int_fast32_t offset, int64_t *const okayp, const int64_t do_norm_secs); @@ -278,9 +264,8 @@ static struct state gmtmem; static int gmt_is_set; -static const int mon_lengths[2][MONSPERYEAR] = { - {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}, - {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}}; +static const int mon_lengths[2][MONSPERYEAR] = {{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}, + {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}}; static const int year_lengths[2] = {DAYSPERNYEAR, DAYSPERLYEAR}; @@ -300,9 +285,7 @@ gmtload (struct state *const sp) */ static struct bson_tm * -gmtsub (const int64_t *const timep, - const int_fast32_t offset, - struct bson_tm *const tmp) +gmtsub (const int64_t *const timep, const int_fast32_t offset, struct bson_tm *const tmp) { struct bson_tm *result; @@ -330,15 +313,11 @@ gmtsub (const int64_t *const timep, static int64_t leaps_thru_end_of (const int64_t y) { - return (y >= 0) ? (y / 4 - y / 100 + y / 400) - : -(leaps_thru_end_of (-(y + 1)) + 1); + return (y >= 0) ? (y / 4 - y / 100 + y / 400) : -(leaps_thru_end_of (-(y + 1)) + 1); } static struct bson_tm * -timesub (const int64_t *const timep, - const int_fast32_t offset, - const struct state *const sp, - struct bson_tm *const tmp) +timesub (const int64_t *const timep, const int_fast32_t offset, const struct state *const sp, struct bson_tm *const tmp) { const struct lsinfo *lp; int64_t tdays; @@ -357,11 +336,9 @@ timesub (const int64_t *const timep, lp = &sp->lsis[i]; if (*timep >= lp->ls_trans) { if (*timep == lp->ls_trans) { - hit = ((i == 0 && lp->ls_corr > 0) || - lp->ls_corr > sp->lsis[i - 1].ls_corr); + hit = ((i == 0 && lp->ls_corr > 0) || lp->ls_corr > sp->lsis[i - 1].ls_corr); if (hit) - while (i > 0 && - sp->lsis[i].ls_trans == sp->lsis[i - 1].ls_trans + 1 && + while (i > 0 && sp->lsis[i].ls_trans == sp->lsis[i - 1].ls_trans + 1 && sp->lsis[i].ls_corr == sp->lsis[i - 1].ls_corr + 1) { ++hit; --i; @@ -429,10 +406,8 @@ timesub (const int64_t *const timep, /* ** The "extra" mods below avoid overflow problems. */ - tmp->tm_wday = - EPOCH_WDAY + - ((y - EPOCH_YEAR) % DAYSPERWEEK) * (DAYSPERNYEAR % DAYSPERWEEK) + - leaps_thru_end_of (y - 1) - leaps_thru_end_of (EPOCH_YEAR - 1) + idays; + tmp->tm_wday = EPOCH_WDAY + ((y - EPOCH_YEAR) % DAYSPERWEEK) * (DAYSPERNYEAR % DAYSPERWEEK) + + leaps_thru_end_of (y - 1) - leaps_thru_end_of (EPOCH_YEAR - 1) + idays; tmp->tm_wday %= DAYSPERWEEK; if (tmp->tm_wday < 0) tmp->tm_wday += DAYSPERWEEK; @@ -504,27 +479,21 @@ increment_overflow32 (int_fast32_t *const lp, int64_t const m) } static int64_t -normalize_overflow (int64_t *const tensptr, - int64_t *const unitsptr, - const int64_t base) +normalize_overflow (int64_t *const tensptr, int64_t *const unitsptr, const int64_t base) { int64_t tensdelta; - tensdelta = - (*unitsptr >= 0) ? (*unitsptr / base) : (-1 - (-1 - *unitsptr) / base); + tensdelta = (*unitsptr >= 0) ? (*unitsptr / base) : (-1 - (-1 - *unitsptr) / base); *unitsptr -= tensdelta * base; return increment_overflow (tensptr, tensdelta); } static int64_t -normalize_overflow32 (int_fast32_t *const tensptr, - int64_t *const unitsptr, - const int64_t base) +normalize_overflow32 (int_fast32_t *const tensptr, int64_t *const unitsptr, const int64_t base) { int64_t tensdelta; - tensdelta = - (*unitsptr >= 0) ? (*unitsptr / base) : (-1 - (-1 - *unitsptr) / base); + tensdelta = (*unitsptr >= 0) ? (*unitsptr / base) : (-1 - (-1 - *unitsptr) / base); *unitsptr -= tensdelta * base; return increment_overflow32 (tensptr, tensdelta); } @@ -536,19 +505,15 @@ tmcomp (const struct bson_tm *const atmp, const struct bson_tm *const btmp) if (atmp->tm_year != btmp->tm_year) return atmp->tm_year < btmp->tm_year ? -1 : 1; - if ((result = (atmp->tm_mon - btmp->tm_mon)) == 0 && - (result = (atmp->tm_mday - btmp->tm_mday)) == 0 && - (result = (atmp->tm_hour - btmp->tm_hour)) == 0 && - (result = (atmp->tm_min - btmp->tm_min)) == 0) + if ((result = (atmp->tm_mon - btmp->tm_mon)) == 0 && (result = (atmp->tm_mday - btmp->tm_mday)) == 0 && + (result = (atmp->tm_hour - btmp->tm_hour)) == 0 && (result = (atmp->tm_min - btmp->tm_min)) == 0) result = atmp->tm_sec - btmp->tm_sec; return result; } static int64_t time2sub (struct bson_tm *const tmp, - struct bson_tm *(*const funcp) (const int64_t *, - int_fast32_t, - struct bson_tm *), + struct bson_tm *(*const funcp) (const int64_t *, int_fast32_t, struct bson_tm *), const int_fast32_t offset, int64_t *const okayp, const int64_t do_norm_secs) @@ -717,9 +682,7 @@ time2sub (struct bson_tm *const tmp, static int64_t time2 (struct bson_tm *const tmp, - struct bson_tm *(*const funcp) (const int64_t *, - int_fast32_t, - struct bson_tm *), + struct bson_tm *(*const funcp) (const int64_t *, int_fast32_t, struct bson_tm *), const int_fast32_t offset, int64_t *const okayp) { @@ -736,9 +699,7 @@ time2 (struct bson_tm *const tmp, static int64_t time1 (struct bson_tm *const tmp, - struct bson_tm *(*const funcp) (const int64_t *, - int_fast32_t, - struct bson_tm *), + struct bson_tm *(*const funcp) (const int64_t *, int_fast32_t, struct bson_tm *), const int_fast32_t offset) { int64_t t; diff --git a/src/libbson/src/bson/bson-types.h b/src/libbson/src/bson/bson-types.h index fd62cec2af..3148668739 100644 --- a/src/libbson/src/bson/bson-types.h +++ b/src/libbson/src/bson/bson-types.h @@ -416,23 +416,10 @@ typedef struct { /* corrupt BSON, or unsupported type and visit_unsupported_type not set */ void (*visit_corrupt) (const bson_iter_t *iter, void *data); /* normal bson field callbacks */ - bool (*visit_double) (const bson_iter_t *iter, - const char *key, - double v_double, - void *data); - bool (*visit_utf8) (const bson_iter_t *iter, - const char *key, - size_t v_utf8_len, - const char *v_utf8, - void *data); - bool (*visit_document) (const bson_iter_t *iter, - const char *key, - const bson_t *v_document, - void *data); - bool (*visit_array) (const bson_iter_t *iter, - const char *key, - const bson_t *v_array, - void *data); + bool (*visit_double) (const bson_iter_t *iter, const char *key, double v_double, void *data); + bool (*visit_utf8) (const bson_iter_t *iter, const char *key, size_t v_utf8_len, const char *v_utf8, void *data); + bool (*visit_document) (const bson_iter_t *iter, const char *key, const bson_t *v_document, void *data); + bool (*visit_array) (const bson_iter_t *iter, const char *key, const bson_t *v_array, void *data); bool (*visit_binary) (const bson_iter_t *iter, const char *key, bson_subtype_t v_subtype, @@ -440,70 +427,37 @@ typedef struct { const uint8_t *v_binary, void *data); /* normal field with deprecated "Undefined" BSON type */ - bool (*visit_undefined) (const bson_iter_t *iter, - const char *key, - void *data); - bool (*visit_oid) (const bson_iter_t *iter, - const char *key, - const bson_oid_t *v_oid, - void *data); - bool (*visit_bool) (const bson_iter_t *iter, - const char *key, - bool v_bool, - void *data); - bool (*visit_date_time) (const bson_iter_t *iter, - const char *key, - int64_t msec_since_epoch, - void *data); + bool (*visit_undefined) (const bson_iter_t *iter, const char *key, void *data); + bool (*visit_oid) (const bson_iter_t *iter, const char *key, const bson_oid_t *v_oid, void *data); + bool (*visit_bool) (const bson_iter_t *iter, const char *key, bool v_bool, void *data); + bool (*visit_date_time) (const bson_iter_t *iter, const char *key, int64_t msec_since_epoch, void *data); bool (*visit_null) (const bson_iter_t *iter, const char *key, void *data); - bool (*visit_regex) (const bson_iter_t *iter, - const char *key, - const char *v_regex, - const char *v_options, - void *data); + bool (*visit_regex) ( + const bson_iter_t *iter, const char *key, const char *v_regex, const char *v_options, void *data); bool (*visit_dbpointer) (const bson_iter_t *iter, const char *key, size_t v_collection_len, const char *v_collection, const bson_oid_t *v_oid, void *data); - bool (*visit_code) (const bson_iter_t *iter, - const char *key, - size_t v_code_len, - const char *v_code, - void *data); - bool (*visit_symbol) (const bson_iter_t *iter, - const char *key, - size_t v_symbol_len, - const char *v_symbol, - void *data); + bool (*visit_code) (const bson_iter_t *iter, const char *key, size_t v_code_len, const char *v_code, void *data); + bool (*visit_symbol) ( + const bson_iter_t *iter, const char *key, size_t v_symbol_len, const char *v_symbol, void *data); bool (*visit_codewscope) (const bson_iter_t *iter, const char *key, size_t v_code_len, const char *v_code, const bson_t *v_scope, void *data); - bool (*visit_int32) (const bson_iter_t *iter, - const char *key, - int32_t v_int32, - void *data); - bool (*visit_timestamp) (const bson_iter_t *iter, - const char *key, - uint32_t v_timestamp, - uint32_t v_increment, - void *data); - bool (*visit_int64) (const bson_iter_t *iter, - const char *key, - int64_t v_int64, - void *data); + bool (*visit_int32) (const bson_iter_t *iter, const char *key, int32_t v_int32, void *data); + bool (*visit_timestamp) ( + const bson_iter_t *iter, const char *key, uint32_t v_timestamp, uint32_t v_increment, void *data); + bool (*visit_int64) (const bson_iter_t *iter, const char *key, int64_t v_int64, void *data); bool (*visit_maxkey) (const bson_iter_t *iter, const char *key, void *data); bool (*visit_minkey) (const bson_iter_t *iter, const char *key, void *data); /* if set, called instead of visit_corrupt when an apparently valid BSON * includes an unrecognized field type (reading future version of BSON) */ - void (*visit_unsupported_type) (const bson_iter_t *iter, - const char *key, - uint32_t type_code, - void *data); + void (*visit_unsupported_type) (const bson_iter_t *iter, const char *key, uint32_t type_code, void *data); bool (*visit_decimal128) (const bson_iter_t *iter, const char *key, const bson_decimal128_t *v_decimal128, diff --git a/src/libbson/src/bson/bson-utf8.c b/src/libbson/src/bson/bson-utf8.c index b1d95b6d61..61fa98598e 100644 --- a/src/libbson/src/bson/bson-utf8.c +++ b/src/libbson/src/bson/bson-utf8.c @@ -210,15 +210,13 @@ bson_utf8_validate (const char *utf8, /* IN */ return false; case 3: - if (((c >= 0x0800) && (c <= 0x0FFF)) || - ((c >= 0x1000) && (c <= 0xFFFF))) { + if (((c >= 0x0800) && (c <= 0x0FFF)) || ((c >= 0x1000) && (c <= 0xFFFF))) { continue; } return false; case 4: - if (((c >= 0x10000) && (c <= 0x3FFFF)) || - ((c >= 0x40000) && (c <= 0xFFFFF)) || + if (((c >= 0x10000) && (c <= 0x3FFFF)) || ((c >= 0x40000) && (c <= 0xFFFFF)) || ((c >= 0x100000) && (c <= 0x10FFFF))) { continue; } diff --git a/src/libbson/src/bson/bson-value.c b/src/libbson/src/bson/bson-value.c index 63f43a0c07..3e3c46890d 100644 --- a/src/libbson/src/bson/bson-value.c +++ b/src/libbson/src/bson/bson-value.c @@ -37,26 +37,21 @@ bson_value_copy (const bson_value_t *src, /* IN */ case BSON_TYPE_UTF8: dst->value.v_utf8.len = src->value.v_utf8.len; dst->value.v_utf8.str = bson_malloc (src->value.v_utf8.len + 1); - memcpy ( - dst->value.v_utf8.str, src->value.v_utf8.str, dst->value.v_utf8.len); + memcpy (dst->value.v_utf8.str, src->value.v_utf8.str, dst->value.v_utf8.len); dst->value.v_utf8.str[dst->value.v_utf8.len] = '\0'; break; case BSON_TYPE_DOCUMENT: case BSON_TYPE_ARRAY: dst->value.v_doc.data_len = src->value.v_doc.data_len; dst->value.v_doc.data = bson_malloc (src->value.v_doc.data_len); - memcpy (dst->value.v_doc.data, - src->value.v_doc.data, - dst->value.v_doc.data_len); + memcpy (dst->value.v_doc.data, src->value.v_doc.data, dst->value.v_doc.data_len); break; case BSON_TYPE_BINARY: dst->value.v_binary.subtype = src->value.v_binary.subtype; dst->value.v_binary.data_len = src->value.v_binary.data_len; dst->value.v_binary.data = bson_malloc (src->value.v_binary.data_len); if (dst->value.v_binary.data_len) { - memcpy (dst->value.v_binary.data, - src->value.v_binary.data, - dst->value.v_binary.data_len); + memcpy (dst->value.v_binary.data, src->value.v_binary.data, dst->value.v_binary.data_len); } break; case BSON_TYPE_OID: @@ -73,47 +68,34 @@ bson_value_copy (const bson_value_t *src, /* IN */ dst->value.v_regex.options = bson_strdup (src->value.v_regex.options); break; case BSON_TYPE_DBPOINTER: - dst->value.v_dbpointer.collection_len = - src->value.v_dbpointer.collection_len; - dst->value.v_dbpointer.collection = - bson_malloc (src->value.v_dbpointer.collection_len + 1); - memcpy (dst->value.v_dbpointer.collection, - src->value.v_dbpointer.collection, - dst->value.v_dbpointer.collection_len); - dst->value.v_dbpointer.collection[dst->value.v_dbpointer.collection_len] = - '\0'; + dst->value.v_dbpointer.collection_len = src->value.v_dbpointer.collection_len; + dst->value.v_dbpointer.collection = bson_malloc (src->value.v_dbpointer.collection_len + 1); + memcpy ( + dst->value.v_dbpointer.collection, src->value.v_dbpointer.collection, dst->value.v_dbpointer.collection_len); + dst->value.v_dbpointer.collection[dst->value.v_dbpointer.collection_len] = '\0'; bson_oid_copy (&src->value.v_dbpointer.oid, &dst->value.v_dbpointer.oid); break; case BSON_TYPE_CODE: dst->value.v_code.code_len = src->value.v_code.code_len; dst->value.v_code.code = bson_malloc (src->value.v_code.code_len + 1); - memcpy (dst->value.v_code.code, - src->value.v_code.code, - dst->value.v_code.code_len); + memcpy (dst->value.v_code.code, src->value.v_code.code, dst->value.v_code.code_len); dst->value.v_code.code[dst->value.v_code.code_len] = '\0'; break; case BSON_TYPE_SYMBOL: dst->value.v_symbol.len = src->value.v_symbol.len; dst->value.v_symbol.symbol = bson_malloc (src->value.v_symbol.len + 1); - memcpy (dst->value.v_symbol.symbol, - src->value.v_symbol.symbol, - dst->value.v_symbol.len); + memcpy (dst->value.v_symbol.symbol, src->value.v_symbol.symbol, dst->value.v_symbol.len); dst->value.v_symbol.symbol[dst->value.v_symbol.len] = '\0'; break; case BSON_TYPE_CODEWSCOPE: dst->value.v_codewscope.code_len = src->value.v_codewscope.code_len; - dst->value.v_codewscope.code = - bson_malloc (src->value.v_codewscope.code_len + 1); - memcpy (dst->value.v_codewscope.code, - src->value.v_codewscope.code, - dst->value.v_codewscope.code_len); + dst->value.v_codewscope.code = bson_malloc (src->value.v_codewscope.code_len + 1); + memcpy (dst->value.v_codewscope.code, src->value.v_codewscope.code, dst->value.v_codewscope.code_len); dst->value.v_codewscope.code[dst->value.v_codewscope.code_len] = '\0'; dst->value.v_codewscope.scope_len = src->value.v_codewscope.scope_len; - dst->value.v_codewscope.scope_data = - bson_malloc (src->value.v_codewscope.scope_len); - memcpy (dst->value.v_codewscope.scope_data, - src->value.v_codewscope.scope_data, - dst->value.v_codewscope.scope_len); + dst->value.v_codewscope.scope_data = bson_malloc (src->value.v_codewscope.scope_len); + memcpy ( + dst->value.v_codewscope.scope_data, src->value.v_codewscope.scope_data, dst->value.v_codewscope.scope_len); break; case BSON_TYPE_INT32: dst->value.v_int32 = src->value.v_int32; diff --git a/src/libbson/src/bson/bson-writer.c b/src/libbson/src/bson/bson-writer.c index b9d129415d..d547698aea 100644 --- a/src/libbson/src/bson/bson-writer.c +++ b/src/libbson/src/bson/bson-writer.c @@ -198,8 +198,7 @@ bson_writer_begin (bson_writer_t *writer, /* IN */ } if (grown) { - *writer->buf = writer->realloc_func ( - *writer->buf, *writer->buflen, writer->realloc_func_ctx); + *writer->buf = writer->realloc_func (*writer->buf, *writer->buflen, writer->realloc_func_ctx); } memset ((*writer->buf) + writer->offset + 1, 0, 5); diff --git a/src/libbson/src/bson/bson-writer.h b/src/libbson/src/bson/bson-writer.h index 969a049737..dd7d8988c9 100644 --- a/src/libbson/src/bson/bson-writer.h +++ b/src/libbson/src/bson/bson-writer.h @@ -42,11 +42,7 @@ typedef struct _bson_writer_t bson_writer_t; BSON_EXPORT (bson_writer_t *) -bson_writer_new (uint8_t **buf, - size_t *buflen, - size_t offset, - bson_realloc_func realloc_func, - void *realloc_func_ctx); +bson_writer_new (uint8_t **buf, size_t *buflen, size_t offset, bson_realloc_func realloc_func, void *realloc_func_ctx); BSON_EXPORT (void) bson_writer_destroy (bson_writer_t *writer); BSON_EXPORT (size_t) diff --git a/src/libbson/src/bson/bson.c b/src/libbson/src/bson/bson.c index ed20d4d59e..0bbdd9a8b8 100644 --- a/src/libbson/src/bson/bson.c +++ b/src/libbson/src/bson/bson.c @@ -72,21 +72,12 @@ typedef struct { * Forward declarations. */ static bool -_bson_as_json_visit_array (const bson_iter_t *iter, - const char *key, - const bson_t *v_array, - void *data); +_bson_as_json_visit_array (const bson_iter_t *iter, const char *key, const bson_t *v_array, void *data); static bool -_bson_as_json_visit_document (const bson_iter_t *iter, - const char *key, - const bson_t *v_document, - void *data); +_bson_as_json_visit_document (const bson_iter_t *iter, const char *key, const bson_t *v_document, void *data); static char * -_bson_as_json_visit_all (const bson_t *bson, - size_t *length, - bson_json_mode_t mode, - int32_t max_len, - bool is_outermost_array); +_bson_as_json_visit_all ( + const bson_t *bson, size_t *length, bson_json_mode_t mode, int32_t max_len, bool is_outermost_array); /* * Globals. @@ -476,8 +467,7 @@ _bson_append_bson_begin (bson_t *bson, /* IN */ BSON_ASSERT (!(bson->flags & BSON_FLAG_RDONLY)); BSON_ASSERT (!(bson->flags & BSON_FLAG_IN_CHILD)); BSON_ASSERT (key); - BSON_ASSERT ((child_type == BSON_TYPE_DOCUMENT) || - (child_type == BSON_TYPE_ARRAY)); + BSON_ASSERT ((child_type == BSON_TYPE_DOCUMENT) || (child_type == BSON_TYPE_ARRAY)); BSON_ASSERT (child); HANDLE_KEY_LENGTH (key, key_length); @@ -499,17 +489,7 @@ _bson_append_bson_begin (bson_t *bson, /* IN */ /* * Append the type and key for the field. */ - if (!_bson_append (bson, - 4, - (1 + key_length + 1 + 5), - 1, - &type, - key_length, - key, - 1, - &gZero, - 5, - empty)) { + if (!_bson_append (bson, 4, (1 + key_length + 1 + 5), 1, &type, key_length, key, 1, &gZero, 5, empty)) { return false; } @@ -629,8 +609,7 @@ bson_append_array_begin (bson_t *bson, /* IN */ BSON_ASSERT (key); BSON_ASSERT (child); - return _bson_append_bson_begin ( - bson, key, key_length, BSON_TYPE_ARRAY, child); + return _bson_append_bson_begin (bson, key, key_length, BSON_TYPE_ARRAY, child); } @@ -698,8 +677,7 @@ bson_append_document_begin (bson_t *bson, /* IN */ BSON_ASSERT (key); BSON_ASSERT (child); - return _bson_append_bson_begin ( - bson, key, key_length, BSON_TYPE_DOCUMENT, child); + return _bson_append_bson_begin (bson, key, key_length, BSON_TYPE_DOCUMENT, child); } @@ -784,17 +762,8 @@ bson_append_array (bson_t *bson, /* IN */ } } - return _bson_append (bson, - 4, - (1 + key_length + 1 + array->len), - 1, - &type, - key_length, - key, - 1, - &gZero, - array->len, - _bson_data (array)); + return _bson_append ( + bson, 4, (1 + key_length + 1 + array->len), 1, &type, key_length, key, 1, &gZero, array->len, _bson_data (array)); } @@ -915,17 +884,7 @@ bson_append_bool (bson_t *bson, /* IN */ HANDLE_KEY_LENGTH (key, key_length); - return _bson_append (bson, - 4, - (1 + key_length + 1 + 1), - 1, - &type, - key_length, - key, - 1, - &gZero, - 1, - &abyte); + return _bson_append (bson, 4, (1 + key_length + 1 + 1), 1, &type, key_length, key, 1, &gZero, 1, &abyte); } @@ -1145,17 +1104,8 @@ bson_append_document (bson_t *bson, /* IN */ HANDLE_KEY_LENGTH (key, key_length); - return _bson_append (bson, - 4, - (1 + key_length + 1 + value->len), - 1, - &type, - key_length, - key, - 1, - &gZero, - value->len, - _bson_data (value)); + return _bson_append ( + bson, 4, (1 + key_length + 1 + value->len), 1, &type, key_length, key, 1, &gZero, value->len, _bson_data (value)); } @@ -1173,17 +1123,7 @@ bson_append_double (bson_t *bson, const char *key, int key_length, double value) value = BSON_DOUBLE_TO_LE (value); #endif - return _bson_append (bson, - 4, - (1 + key_length + 1 + 8), - 1, - &type, - key_length, - key, - 1, - &gZero, - 8, - &value); + return _bson_append (bson, 4, (1 + key_length + 1 + 8), 1, &type, key_length, key, 1, &gZero, 8, &value); } @@ -1200,17 +1140,7 @@ bson_append_int32 (bson_t *bson, const char *key, int key_length, int32_t value) value_le = BSON_UINT32_TO_LE (value); - return _bson_append (bson, - 4, - (1 + key_length + 1 + 4), - 1, - &type, - key_length, - key, - 1, - &gZero, - 4, - &value_le); + return _bson_append (bson, 4, (1 + key_length + 1 + 4), 1, &type, key_length, key, 1, &gZero, 4, &value_le); } @@ -1227,25 +1157,12 @@ bson_append_int64 (bson_t *bson, const char *key, int key_length, int64_t value) value_le = BSON_UINT64_TO_LE (value); - return _bson_append (bson, - 4, - (1 + key_length + 1 + 8), - 1, - &type, - key_length, - key, - 1, - &gZero, - 8, - &value_le); + return _bson_append (bson, 4, (1 + key_length + 1 + 8), 1, &type, key_length, key, 1, &gZero, 8, &value_le); } bool -bson_append_decimal128 (bson_t *bson, - const char *key, - int key_length, - const bson_decimal128_t *value) +bson_append_decimal128 (bson_t *bson, const char *key, int key_length, const bson_decimal128_t *value) { static const uint8_t type = BSON_TYPE_DECIMAL128; uint64_t value_le[2]; @@ -1259,25 +1176,12 @@ bson_append_decimal128 (bson_t *bson, value_le[0] = BSON_UINT64_TO_LE (value->low); value_le[1] = BSON_UINT64_TO_LE (value->high); - return _bson_append (bson, - 4, - (1 + key_length + 1 + 16), - 1, - &type, - key_length, - key, - 1, - &gZero, - 16, - value_le); + return _bson_append (bson, 4, (1 + key_length + 1 + 16), 1, &type, key_length, key, 1, &gZero, 16, value_le); } bool -bson_append_iter (bson_t *bson, - const char *key, - int key_length, - const bson_iter_t *iter) +bson_append_iter (bson_t *bson, const char *key, int key_length, const bson_iter_t *iter) { bool ret = false; @@ -1344,8 +1248,7 @@ bson_append_iter (bson_t *bson, ret = bson_append_bool (bson, key, key_length, bson_iter_bool (iter)); break; case BSON_TYPE_DATE_TIME: - ret = bson_append_date_time ( - bson, key, key_length, bson_iter_date_time (iter)); + ret = bson_append_date_time (bson, key, key_length, bson_iter_date_time (iter)); break; case BSON_TYPE_NULL: ret = bson_append_null (bson, key, key_length); @@ -1389,8 +1292,7 @@ bson_append_iter (bson_t *bson, javascript = bson_iter_codewscope (iter, &len, &scope_len, &scope); if (bson_init_static (&doc, scope, scope_len)) { - ret = bson_append_code_with_scope ( - bson, key, key_length, javascript, &doc); + ret = bson_append_code_with_scope (bson, key, key_length, javascript, &doc); bson_destroy (&doc); } } break; @@ -1440,8 +1342,7 @@ bson_append_maxkey (bson_t *bson, const char *key, int key_length) HANDLE_KEY_LENGTH (key, key_length); - return _bson_append ( - bson, 3, (1 + key_length + 1), 1, &type, key_length, key, 1, &gZero); + return _bson_append (bson, 3, (1 + key_length + 1), 1, &type, key_length, key, 1, &gZero); } @@ -1455,8 +1356,7 @@ bson_append_minkey (bson_t *bson, const char *key, int key_length) HANDLE_KEY_LENGTH (key, key_length); - return _bson_append ( - bson, 3, (1 + key_length + 1), 1, &type, key_length, key, 1, &gZero); + return _bson_append (bson, 3, (1 + key_length + 1), 1, &type, key_length, key, 1, &gZero); } @@ -1470,16 +1370,12 @@ bson_append_null (bson_t *bson, const char *key, int key_length) HANDLE_KEY_LENGTH (key, key_length); - return _bson_append ( - bson, 3, (1 + key_length + 1), 1, &type, key_length, key, 1, &gZero); + return _bson_append (bson, 3, (1 + key_length + 1), 1, &type, key_length, key, 1, &gZero); } bool -bson_append_oid (bson_t *bson, - const char *key, - int key_length, - const bson_oid_t *value) +bson_append_oid (bson_t *bson, const char *key, int key_length, const bson_oid_t *value) { static const uint8_t type = BSON_TYPE_OID; @@ -1489,17 +1385,7 @@ bson_append_oid (bson_t *bson, HANDLE_KEY_LENGTH (key, key_length); - return _bson_append (bson, - 4, - (1 + key_length + 1 + 12), - 1, - &type, - key_length, - key, - 1, - &gZero, - 12, - value); + return _bson_append (bson, 4, (1 + key_length + 1 + 12), 1, &type, key_length, key, 1, &gZero, 12, value); } @@ -1539,23 +1425,15 @@ _bson_append_regex_options_sorted (bson_string_t *buffer, /* IN */ bool -bson_append_regex (bson_t *bson, - const char *key, - int key_length, - const char *regex, - const char *options) +bson_append_regex (bson_t *bson, const char *key, int key_length, const char *regex, const char *options) { return bson_append_regex_w_len (bson, key, key_length, regex, -1, options); } bool -bson_append_regex_w_len (bson_t *bson, - const char *key, - int key_length, - const char *regex, - int regex_length, - const char *options) +bson_append_regex_w_len ( + bson_t *bson, const char *key, int key_length, const char *regex, int regex_length, const char *options) { static const uint8_t type = BSON_TYPE_REGEX; bson_string_t *options_sorted; @@ -1587,22 +1465,21 @@ bson_append_regex_w_len (bson_t *bson, _bson_append_regex_options_sorted (options_sorted, options); - r = _bson_append ( - bson, - 6, - (1 + key_length + 1 + regex_length + 1 + options_sorted->len + 1), - 1, - &type, - key_length, - key, - 1, - &gZero, - regex_length, - regex, - 1, - &gZero, - options_sorted->len + 1, - options_sorted->str); + r = _bson_append (bson, + 6, + (1 + key_length + 1 + regex_length + 1 + options_sorted->len + 1), + 1, + &type, + key_length, + key, + 1, + &gZero, + regex_length, + regex, + 1, + &gZero, + options_sorted->len + 1, + options_sorted->str); bson_string_free (options_sorted, true); @@ -1611,8 +1488,7 @@ bson_append_regex_w_len (bson_t *bson, bool -bson_append_utf8 ( - bson_t *bson, const char *key, int key_length, const char *value, int length) +bson_append_utf8 (bson_t *bson, const char *key, int key_length, const char *value, int length) { static const uint8_t type = BSON_TYPE_UTF8; uint32_t length_le; @@ -1651,8 +1527,7 @@ bson_append_utf8 ( bool -bson_append_symbol ( - bson_t *bson, const char *key, int key_length, const char *value, int length) +bson_append_symbol (bson_t *bson, const char *key, int key_length, const char *value, int length) { static const uint8_t type = BSON_TYPE_SYMBOL; uint32_t length_le; @@ -1707,11 +1582,7 @@ bson_append_time_t (bson_t *bson, const char *key, int key_length, time_t value) bool -bson_append_timestamp (bson_t *bson, - const char *key, - int key_length, - uint32_t timestamp, - uint32_t increment) +bson_append_timestamp (bson_t *bson, const char *key, int key_length, uint32_t timestamp, uint32_t increment) { static const uint8_t type = BSON_TYPE_TIMESTAMP; uint64_t value; @@ -1724,17 +1595,7 @@ bson_append_timestamp (bson_t *bson, value = ((((uint64_t) timestamp) << 32) | ((uint64_t) increment)); value = BSON_UINT64_TO_LE (value); - return _bson_append (bson, - 4, - (1 + key_length + 1 + 8), - 1, - &type, - key_length, - key, - 1, - &gZero, - 8, - &value); + return _bson_append (bson, 4, (1 + key_length + 1 + 8), 1, &type, key_length, key, 1, &gZero, 8, &value); } @@ -1750,10 +1611,7 @@ bson_append_now_utc (bson_t *bson, const char *key, int key_length) bool -bson_append_date_time (bson_t *bson, - const char *key, - int key_length, - int64_t value) +bson_append_date_time (bson_t *bson, const char *key, int key_length, int64_t value) { static const uint8_t type = BSON_TYPE_DATE_TIME; uint64_t value_le; @@ -1765,25 +1623,12 @@ bson_append_date_time (bson_t *bson, value_le = BSON_UINT64_TO_LE (value); - return _bson_append (bson, - 4, - (1 + key_length + 1 + 8), - 1, - &type, - key_length, - key, - 1, - &gZero, - 8, - &value_le); + return _bson_append (bson, 4, (1 + key_length + 1 + 8), 1, &type, key_length, key, 1, &gZero, 8, &value_le); } bool -bson_append_timeval (bson_t *bson, - const char *key, - int key_length, - struct timeval *value) +bson_append_timeval (bson_t *bson, const char *key, int key_length, struct timeval *value) { uint64_t unix_msec; @@ -1791,8 +1636,7 @@ bson_append_timeval (bson_t *bson, BSON_ASSERT (key); BSON_ASSERT (value); - unix_msec = - (((uint64_t) value->tv_sec) * 1000UL) + (value->tv_usec / 1000UL); + unix_msec = (((uint64_t) value->tv_sec) * 1000UL) + (value->tv_usec / 1000UL); return bson_append_date_time (bson, key, key_length, unix_msec); } @@ -1807,16 +1651,12 @@ bson_append_undefined (bson_t *bson, const char *key, int key_length) HANDLE_KEY_LENGTH (key, key_length); - return _bson_append ( - bson, 3, (1 + key_length + 1), 1, &type, key_length, key, 1, &gZero); + return _bson_append (bson, 3, (1 + key_length + 1), 1, &type, key_length, key, 1, &gZero); } bool -bson_append_value (bson_t *bson, - const char *key, - int key_length, - const bson_value_t *value) +bson_append_value (bson_t *bson, const char *key, int key_length, const bson_value_t *value) { bson_t local; bool ret = false; @@ -1830,22 +1670,16 @@ bson_append_value (bson_t *bson, ret = bson_append_double (bson, key, key_length, value->value.v_double); break; case BSON_TYPE_UTF8: - ret = bson_append_utf8 (bson, - key, - key_length, - value->value.v_utf8.str, - value->value.v_utf8.len); + ret = bson_append_utf8 (bson, key, key_length, value->value.v_utf8.str, value->value.v_utf8.len); break; case BSON_TYPE_DOCUMENT: - if (bson_init_static ( - &local, value->value.v_doc.data, value->value.v_doc.data_len)) { + if (bson_init_static (&local, value->value.v_doc.data, value->value.v_doc.data_len)) { ret = bson_append_document (bson, key, key_length, &local); bson_destroy (&local); } break; case BSON_TYPE_ARRAY: - if (bson_init_static ( - &local, value->value.v_doc.data, value->value.v_doc.data_len)) { + if (bson_init_static (&local, value->value.v_doc.data, value->value.v_doc.data_len)) { ret = bson_append_array (bson, key, key_length, &local); bson_destroy (&local); } @@ -1868,42 +1702,27 @@ bson_append_value (bson_t *bson, ret = bson_append_bool (bson, key, key_length, value->value.v_bool); break; case BSON_TYPE_DATE_TIME: - ret = - bson_append_date_time (bson, key, key_length, value->value.v_datetime); + ret = bson_append_date_time (bson, key, key_length, value->value.v_datetime); break; case BSON_TYPE_NULL: ret = bson_append_null (bson, key, key_length); break; case BSON_TYPE_REGEX: - ret = bson_append_regex (bson, - key, - key_length, - value->value.v_regex.regex, - value->value.v_regex.options); + ret = bson_append_regex (bson, key, key_length, value->value.v_regex.regex, value->value.v_regex.options); break; case BSON_TYPE_DBPOINTER: - ret = bson_append_dbpointer (bson, - key, - key_length, - value->value.v_dbpointer.collection, - &value->value.v_dbpointer.oid); + ret = bson_append_dbpointer ( + bson, key, key_length, value->value.v_dbpointer.collection, &value->value.v_dbpointer.oid); break; case BSON_TYPE_CODE: ret = bson_append_code (bson, key, key_length, value->value.v_code.code); break; case BSON_TYPE_SYMBOL: - ret = bson_append_symbol (bson, - key, - key_length, - value->value.v_symbol.symbol, - value->value.v_symbol.len); + ret = bson_append_symbol (bson, key, key_length, value->value.v_symbol.symbol, value->value.v_symbol.len); break; case BSON_TYPE_CODEWSCOPE: - if (bson_init_static (&local, - value->value.v_codewscope.scope_data, - value->value.v_codewscope.scope_len)) { - ret = bson_append_code_with_scope ( - bson, key, key_length, value->value.v_codewscope.code, &local); + if (bson_init_static (&local, value->value.v_codewscope.scope_data, value->value.v_codewscope.scope_len)) { + ret = bson_append_code_with_scope (bson, key, key_length, value->value.v_codewscope.code, &local); bson_destroy (&local); } break; @@ -1911,18 +1730,14 @@ bson_append_value (bson_t *bson, ret = bson_append_int32 (bson, key, key_length, value->value.v_int32); break; case BSON_TYPE_TIMESTAMP: - ret = bson_append_timestamp (bson, - key, - key_length, - value->value.v_timestamp.timestamp, - value->value.v_timestamp.increment); + ret = bson_append_timestamp ( + bson, key, key_length, value->value.v_timestamp.timestamp, value->value.v_timestamp.increment); break; case BSON_TYPE_INT64: ret = bson_append_int64 (bson, key, key_length, value->value.v_int64); break; case BSON_TYPE_DECIMAL128: - ret = bson_append_decimal128 ( - bson, key, key_length, &(value->value.v_decimal128)); + ret = bson_append_decimal128 (bson, key, key_length, &(value->value.v_decimal128)); break; case BSON_TYPE_MAXKEY: ret = bson_append_maxkey (bson, key, key_length); @@ -2107,10 +1922,7 @@ bson_new_from_data (const uint8_t *data, size_t length) bson_t * -bson_new_from_buffer (uint8_t **buf, - size_t *buf_len, - bson_realloc_func realloc_func, - void *realloc_func_ctx) +bson_new_from_buffer (uint8_t **buf, size_t *buf_len, bson_realloc_func realloc_func, void *realloc_func_ctx) { bson_impl_alloc_t *impl; uint32_t len_le; @@ -2236,10 +2048,7 @@ should_ignore (const char *first_exclude, va_list args, const char *name) void -bson_copy_to_excluding_noinit_va (const bson_t *src, - bson_t *dst, - const char *first_exclude, - va_list args) +bson_copy_to_excluding_noinit_va (const bson_t *src, bson_t *dst, const char *first_exclude, va_list args) { bson_iter_t iter; @@ -2261,10 +2070,7 @@ bson_copy_to_excluding_noinit_va (const bson_t *src, void -bson_copy_to_excluding (const bson_t *src, - bson_t *dst, - const char *first_exclude, - ...) +bson_copy_to_excluding (const bson_t *src, bson_t *dst, const char *first_exclude, ...) { va_list args; @@ -2280,10 +2086,7 @@ bson_copy_to_excluding (const bson_t *src, } void -bson_copy_to_excluding_noinit (const bson_t *src, - bson_t *dst, - const char *first_exclude, - ...) +bson_copy_to_excluding_noinit (const bson_t *src, bson_t *dst, const char *first_exclude, ...) { va_list args; @@ -2303,8 +2106,7 @@ bson_destroy (bson_t *bson) return; } - if (!(bson->flags & - (BSON_FLAG_RDONLY | BSON_FLAG_INLINE | BSON_FLAG_NO_FREE))) { + if (!(bson->flags & (BSON_FLAG_RDONLY | BSON_FLAG_INLINE | BSON_FLAG_NO_FREE))) { bson_free (*((bson_impl_alloc_t *) bson)->buf); } @@ -2323,8 +2125,7 @@ bson_destroy (bson_t *bson) uint8_t * bson_reserve_buffer (bson_t *bson, uint32_t size) { - if (bson->flags & - (BSON_FLAG_CHILD | BSON_FLAG_IN_CHILD | BSON_FLAG_RDONLY)) { + if (bson->flags & (BSON_FLAG_CHILD | BSON_FLAG_IN_CHILD | BSON_FLAG_RDONLY)) { return NULL; } @@ -2408,8 +2209,7 @@ bson_destroy_with_steal (bson_t *bson, bool steal, uint32_t *length) return NULL; } - if ((bson->flags & - (BSON_FLAG_CHILD | BSON_FLAG_IN_CHILD | BSON_FLAG_RDONLY))) { + if ((bson->flags & (BSON_FLAG_CHILD | BSON_FLAG_IN_CHILD | BSON_FLAG_RDONLY))) { /* Do nothing */ } else if ((bson->flags & BSON_FLAG_INLINE)) { bson_impl_inline_t *inl; @@ -2468,8 +2268,7 @@ bson_has_field (const bson_t *bson, const char *key) BSON_ASSERT (key); if (NULL != strchr (key, '.')) { - return (bson_iter_init (&iter, bson) && - bson_iter_find_descendant (&iter, key, &child)); + return (bson_iter_init (&iter, bson) && bson_iter_find_descendant (&iter, key, &child)); } return bson_iter_init_find (&iter, bson, key); @@ -2513,11 +2312,7 @@ bson_equal (const bson_t *bson, const bson_t *other) static bool -_bson_as_json_visit_utf8 (const bson_iter_t *iter, - const char *key, - size_t v_utf8_len, - const char *v_utf8, - void *data) +_bson_as_json_visit_utf8 (const bson_iter_t *iter, const char *key, size_t v_utf8_len, const char *v_utf8, void *data) { bson_json_state_t *state = data; char *escaped; @@ -2540,10 +2335,7 @@ _bson_as_json_visit_utf8 (const bson_iter_t *iter, static bool -_bson_as_json_visit_int32 (const bson_iter_t *iter, - const char *key, - int32_t v_int32, - void *data) +_bson_as_json_visit_int32 (const bson_iter_t *iter, const char *key, int32_t v_int32, void *data) { bson_json_state_t *state = data; @@ -2551,8 +2343,7 @@ _bson_as_json_visit_int32 (const bson_iter_t *iter, BSON_UNUSED (key); if (state->mode == BSON_JSON_MODE_CANONICAL) { - bson_string_append_printf ( - state->str, "{ \"$numberInt\" : \"%" PRId32 "\" }", v_int32); + bson_string_append_printf (state->str, "{ \"$numberInt\" : \"%" PRId32 "\" }", v_int32); } else { bson_string_append_printf (state->str, "%" PRId32, v_int32); } @@ -2562,10 +2353,7 @@ _bson_as_json_visit_int32 (const bson_iter_t *iter, static bool -_bson_as_json_visit_int64 (const bson_iter_t *iter, - const char *key, - int64_t v_int64, - void *data) +_bson_as_json_visit_int64 (const bson_iter_t *iter, const char *key, int64_t v_int64, void *data) { bson_json_state_t *state = data; @@ -2573,8 +2361,7 @@ _bson_as_json_visit_int64 (const bson_iter_t *iter, BSON_UNUSED (key); if (state->mode == BSON_JSON_MODE_CANONICAL) { - bson_string_append_printf ( - state->str, "{ \"$numberLong\" : \"%" PRId64 "\" }", v_int64); + bson_string_append_printf (state->str, "{ \"$numberLong\" : \"%" PRId64 "\" }", v_int64); } else { bson_string_append_printf (state->str, "%" PRId64, v_int64); } @@ -2584,10 +2371,7 @@ _bson_as_json_visit_int64 (const bson_iter_t *iter, static bool -_bson_as_json_visit_decimal128 (const bson_iter_t *iter, - const char *key, - const bson_decimal128_t *value, - void *data) +_bson_as_json_visit_decimal128 (const bson_iter_t *iter, const char *key, const bson_decimal128_t *value, void *data) { bson_json_state_t *state = data; char decimal128_string[BSON_DECIMAL128_STRING]; @@ -2606,10 +2390,7 @@ _bson_as_json_visit_decimal128 (const bson_iter_t *iter, static bool -_bson_as_json_visit_double (const bson_iter_t *iter, - const char *key, - double v_double, - void *data) +_bson_as_json_visit_double (const bson_iter_t *iter, const char *key, double v_double, void *data) { bson_json_state_t *state = data; bson_string_t *str = state->str; @@ -2623,8 +2404,7 @@ _bson_as_json_visit_double (const bson_iter_t *iter, * will use this for nan and inf values, which we check manually since old * platforms may not have isinf or isnan. */ legacy = state->mode == BSON_JSON_MODE_LEGACY || - (state->mode == BSON_JSON_MODE_RELAXED && - !(v_double != v_double || v_double * 0 != 0)); + (state->mode == BSON_JSON_MODE_RELAXED && !(v_double != v_double || v_double * 0 != 0)); if (!legacy) { bson_string_append (state->str, "{ \"$numberDouble\" : \""); @@ -2643,8 +2423,7 @@ _bson_as_json_visit_double (const bson_iter_t *iter, bson_string_append_printf (str, "%.20g", v_double); /* ensure trailing ".0" to distinguish "3" from "3.0" */ - if (strspn (&str->str[start_len], "0123456789-") == - str->len - start_len) { + if (strspn (&str->str[start_len], "0123456789-") == str->len - start_len) { bson_string_append (str, ".0"); } } @@ -2658,9 +2437,7 @@ _bson_as_json_visit_double (const bson_iter_t *iter, static bool -_bson_as_json_visit_undefined (const bson_iter_t *iter, - const char *key, - void *data) +_bson_as_json_visit_undefined (const bson_iter_t *iter, const char *key, void *data) { bson_json_state_t *state = data; @@ -2688,10 +2465,7 @@ _bson_as_json_visit_null (const bson_iter_t *iter, const char *key, void *data) static bool -_bson_as_json_visit_oid (const bson_iter_t *iter, - const char *key, - const bson_oid_t *oid, - void *data) +_bson_as_json_visit_oid (const bson_iter_t *iter, const char *key, const bson_oid_t *oid, void *data) { bson_json_state_t *state = data; char str[25]; @@ -2727,8 +2501,7 @@ _bson_as_json_visit_binary (const bson_iter_t *iter, b64 = bson_malloc0 (b64_len); BSON_ASSERT (mcommon_b64_ntop (v_binary, v_binary_len, b64, b64_len) != -1); - if (state->mode == BSON_JSON_MODE_CANONICAL || - state->mode == BSON_JSON_MODE_RELAXED) { + if (state->mode == BSON_JSON_MODE_CANONICAL || state->mode == BSON_JSON_MODE_RELAXED) { bson_string_append (state->str, "{ \"$binary\" : { \"base64\" : \""); bson_string_append (state->str, b64); bson_string_append (state->str, "\", \"subType\" : \""); @@ -2749,10 +2522,7 @@ _bson_as_json_visit_binary (const bson_iter_t *iter, static bool -_bson_as_json_visit_bool (const bson_iter_t *iter, - const char *key, - bool v_bool, - void *data) +_bson_as_json_visit_bool (const bson_iter_t *iter, const char *key, bool v_bool, void *data) { bson_json_state_t *state = data; @@ -2766,18 +2536,14 @@ _bson_as_json_visit_bool (const bson_iter_t *iter, static bool -_bson_as_json_visit_date_time (const bson_iter_t *iter, - const char *key, - int64_t msec_since_epoch, - void *data) +_bson_as_json_visit_date_time (const bson_iter_t *iter, const char *key, int64_t msec_since_epoch, void *data) { bson_json_state_t *state = data; BSON_UNUSED (iter); BSON_UNUSED (key); - if (state->mode == BSON_JSON_MODE_CANONICAL || - (state->mode == BSON_JSON_MODE_RELAXED && msec_since_epoch < 0)) { + if (state->mode == BSON_JSON_MODE_CANONICAL || (state->mode == BSON_JSON_MODE_RELAXED && msec_since_epoch < 0)) { bson_string_append (state->str, "{ \"$date\" : { \"$numberLong\" : \""); bson_string_append_printf (state->str, "%" PRId64, msec_since_epoch); bson_string_append (state->str, "\" } }"); @@ -2796,11 +2562,8 @@ _bson_as_json_visit_date_time (const bson_iter_t *iter, static bool -_bson_as_json_visit_regex (const bson_iter_t *iter, - const char *key, - const char *v_regex, - const char *v_options, - void *data) +_bson_as_json_visit_regex ( + const bson_iter_t *iter, const char *key, const char *v_regex, const char *v_options, void *data) { bson_json_state_t *state = data; char *escaped; @@ -2813,10 +2576,8 @@ _bson_as_json_visit_regex (const bson_iter_t *iter, return true; } - if (state->mode == BSON_JSON_MODE_CANONICAL || - state->mode == BSON_JSON_MODE_RELAXED) { - bson_string_append (state->str, - "{ \"$regularExpression\" : { \"pattern\" : \""); + if (state->mode == BSON_JSON_MODE_CANONICAL || state->mode == BSON_JSON_MODE_RELAXED) { + bson_string_append (state->str, "{ \"$regularExpression\" : { \"pattern\" : \""); bson_string_append (state->str, escaped); bson_string_append (state->str, "\", \"options\" : \""); _bson_append_regex_options_sorted (state->str, v_options); @@ -2836,11 +2597,8 @@ _bson_as_json_visit_regex (const bson_iter_t *iter, static bool -_bson_as_json_visit_timestamp (const bson_iter_t *iter, - const char *key, - uint32_t v_timestamp, - uint32_t v_increment, - void *data) +_bson_as_json_visit_timestamp ( + const bson_iter_t *iter, const char *key, uint32_t v_timestamp, uint32_t v_increment, void *data) { bson_json_state_t *state = data; @@ -2878,8 +2636,7 @@ _bson_as_json_visit_dbpointer (const bson_iter_t *iter, return true; } - if (state->mode == BSON_JSON_MODE_CANONICAL || - state->mode == BSON_JSON_MODE_RELAXED) { + if (state->mode == BSON_JSON_MODE_CANONICAL || state->mode == BSON_JSON_MODE_RELAXED) { bson_string_append (state->str, "{ \"$dbPointer\" : { \"$ref\" : \""); bson_string_append (state->str, escaped); bson_string_append (state->str, "\""); @@ -2914,9 +2671,7 @@ _bson_as_json_visit_dbpointer (const bson_iter_t *iter, static bool -_bson_as_json_visit_minkey (const bson_iter_t *iter, - const char *key, - void *data) +_bson_as_json_visit_minkey (const bson_iter_t *iter, const char *key, void *data) { bson_json_state_t *state = data; @@ -2930,9 +2685,7 @@ _bson_as_json_visit_minkey (const bson_iter_t *iter, static bool -_bson_as_json_visit_maxkey (const bson_iter_t *iter, - const char *key, - void *data) +_bson_as_json_visit_maxkey (const bson_iter_t *iter, const char *key, void *data) { bson_json_state_t *state = data; @@ -2946,9 +2699,7 @@ _bson_as_json_visit_maxkey (const bson_iter_t *iter, static bool -_bson_as_json_visit_before (const bson_iter_t *iter, - const char *key, - void *data) +_bson_as_json_visit_before (const bson_iter_t *iter, const char *key, void *data) { bson_json_state_t *state = data; char *escaped; @@ -3017,11 +2768,7 @@ _bson_as_json_visit_corrupt (const bson_iter_t *iter, void *data) static bool -_bson_as_json_visit_code (const bson_iter_t *iter, - const char *key, - size_t v_code_len, - const char *v_code, - void *data) +_bson_as_json_visit_code (const bson_iter_t *iter, const char *key, size_t v_code_len, const char *v_code, void *data) { bson_json_state_t *state = data; char *escaped; @@ -3044,11 +2791,8 @@ _bson_as_json_visit_code (const bson_iter_t *iter, static bool -_bson_as_json_visit_symbol (const bson_iter_t *iter, - const char *key, - size_t v_symbol_len, - const char *v_symbol, - void *data) +_bson_as_json_visit_symbol ( + const bson_iter_t *iter, const char *key, size_t v_symbol_len, const char *v_symbol, void *data) { bson_json_state_t *state = data; char *escaped; @@ -3061,8 +2805,7 @@ _bson_as_json_visit_symbol (const bson_iter_t *iter, return true; } - if (state->mode == BSON_JSON_MODE_CANONICAL || - state->mode == BSON_JSON_MODE_RELAXED) { + if (state->mode == BSON_JSON_MODE_CANONICAL || state->mode == BSON_JSON_MODE_RELAXED) { bson_string_append (state->str, "{ \"$symbol\" : \""); bson_string_append (state->str, escaped); bson_string_append (state->str, "\" }"); @@ -3079,12 +2822,8 @@ _bson_as_json_visit_symbol (const bson_iter_t *iter, static bool -_bson_as_json_visit_codewscope (const bson_iter_t *iter, - const char *key, - size_t v_code_len, - const char *v_code, - const bson_t *v_scope, - void *data) +_bson_as_json_visit_codewscope ( + const bson_iter_t *iter, const char *key, size_t v_code_len, const char *v_code, const bson_t *v_scope, void *data) { bson_json_state_t *state = data; char *code_escaped; @@ -3111,8 +2850,7 @@ _bson_as_json_visit_codewscope (const bson_iter_t *iter, max_scope_len = BSON_MAX (0, state->max_len - (int32_t) state->str->len); } - scope = _bson_as_json_visit_all ( - v_scope, NULL, state->mode, max_scope_len, false); + scope = _bson_as_json_visit_all (v_scope, NULL, state->mode, max_scope_len, false); if (!scope) { return true; @@ -3128,27 +2866,20 @@ _bson_as_json_visit_codewscope (const bson_iter_t *iter, static const bson_visitor_t bson_as_json_visitors = { - _bson_as_json_visit_before, _bson_as_json_visit_after, - _bson_as_json_visit_corrupt, _bson_as_json_visit_double, - _bson_as_json_visit_utf8, _bson_as_json_visit_document, - _bson_as_json_visit_array, _bson_as_json_visit_binary, - _bson_as_json_visit_undefined, _bson_as_json_visit_oid, - _bson_as_json_visit_bool, _bson_as_json_visit_date_time, - _bson_as_json_visit_null, _bson_as_json_visit_regex, - _bson_as_json_visit_dbpointer, _bson_as_json_visit_code, - _bson_as_json_visit_symbol, _bson_as_json_visit_codewscope, - _bson_as_json_visit_int32, _bson_as_json_visit_timestamp, - _bson_as_json_visit_int64, _bson_as_json_visit_maxkey, - _bson_as_json_visit_minkey, NULL, /* visit_unsupported_type */ + _bson_as_json_visit_before, _bson_as_json_visit_after, _bson_as_json_visit_corrupt, + _bson_as_json_visit_double, _bson_as_json_visit_utf8, _bson_as_json_visit_document, + _bson_as_json_visit_array, _bson_as_json_visit_binary, _bson_as_json_visit_undefined, + _bson_as_json_visit_oid, _bson_as_json_visit_bool, _bson_as_json_visit_date_time, + _bson_as_json_visit_null, _bson_as_json_visit_regex, _bson_as_json_visit_dbpointer, + _bson_as_json_visit_code, _bson_as_json_visit_symbol, _bson_as_json_visit_codewscope, + _bson_as_json_visit_int32, _bson_as_json_visit_timestamp, _bson_as_json_visit_int64, + _bson_as_json_visit_maxkey, _bson_as_json_visit_minkey, NULL, /* visit_unsupported_type */ _bson_as_json_visit_decimal128, }; static bool -_bson_as_json_visit_document (const bson_iter_t *iter, - const char *key, - const bson_t *v_document, - void *data) +_bson_as_json_visit_document (const bson_iter_t *iter, const char *key, const bson_t *v_document, void *data) { bson_json_state_t *state = data; bson_json_state_t child_state = {0, true, state->err_offset}; @@ -3169,8 +2900,7 @@ _bson_as_json_visit_document (const bson_iter_t *iter, child_state.max_len = BSON_MAX_LEN_UNLIMITED; if (state->max_len != BSON_MAX_LEN_UNLIMITED) { BSON_ASSERT (bson_in_range_unsigned (int32_t, state->str->len)); - child_state.max_len = - BSON_MAX (0, state->max_len - (int32_t) state->str->len); + child_state.max_len = BSON_MAX (0, state->max_len - (int32_t) state->str->len); } child_state.max_len_reached = child_state.max_len == 0; @@ -3198,10 +2928,7 @@ _bson_as_json_visit_document (const bson_iter_t *iter, static bool -_bson_as_json_visit_array (const bson_iter_t *iter, - const char *key, - const bson_t *v_array, - void *data) +_bson_as_json_visit_array (const bson_iter_t *iter, const char *key, const bson_t *v_array, void *data) { bson_json_state_t *state = data; bson_json_state_t child_state = {0, false, state->err_offset}; @@ -3222,8 +2949,7 @@ _bson_as_json_visit_array (const bson_iter_t *iter, child_state.max_len = BSON_MAX_LEN_UNLIMITED; if (state->max_len != BSON_MAX_LEN_UNLIMITED) { BSON_ASSERT (bson_in_range_unsigned (int32_t, state->str->len)); - child_state.max_len = - BSON_MAX (0, state->max_len - (int32_t) state->str->len); + child_state.max_len = BSON_MAX (0, state->max_len - (int32_t) state->str->len); } child_state.max_len_reached = child_state.max_len == 0; @@ -3251,11 +2977,8 @@ _bson_as_json_visit_array (const bson_iter_t *iter, static char * -_bson_as_json_visit_all (const bson_t *bson, - size_t *length, - bson_json_mode_t mode, - int32_t max_len, - bool is_outermost_array) +_bson_as_json_visit_all ( + const bson_t *bson, size_t *length, bson_json_mode_t mode, int32_t max_len, bool is_outermost_array) { bson_json_state_t state; bson_iter_t iter; @@ -3289,9 +3012,7 @@ _bson_as_json_visit_all (const bson_t *bson, state.max_len = max_len; state.max_len_reached = false; - if ((bson_iter_visit_all (&iter, &bson_as_json_visitors, &state) || - err_offset != -1) && - !state.max_len_reached) { + if ((bson_iter_visit_all (&iter, &bson_as_json_visitors, &state) || err_offset != -1) && !state.max_len_reached) { /* * We were prematurely exited due to corruption or failed visitor. */ @@ -3320,20 +3041,16 @@ _bson_as_json_visit_all (const bson_t *bson, char * -bson_as_json_with_opts (const bson_t *bson, - size_t *length, - const bson_json_opts_t *opts) +bson_as_json_with_opts (const bson_t *bson, size_t *length, const bson_json_opts_t *opts) { - return _bson_as_json_visit_all ( - bson, length, opts->mode, opts->max_len, opts->is_outermost_array); + return _bson_as_json_visit_all (bson, length, opts->mode, opts->max_len, opts->is_outermost_array); } char * bson_as_canonical_extended_json (const bson_t *bson, size_t *length) { - const bson_json_opts_t opts = { - BSON_JSON_MODE_CANONICAL, BSON_MAX_LEN_UNLIMITED, false}; + const bson_json_opts_t opts = {BSON_JSON_MODE_CANONICAL, BSON_MAX_LEN_UNLIMITED, false}; return bson_as_json_with_opts (bson, length, &opts); } @@ -3341,8 +3058,7 @@ bson_as_canonical_extended_json (const bson_t *bson, size_t *length) char * bson_as_json (const bson_t *bson, size_t *length) { - const bson_json_opts_t opts = { - BSON_JSON_MODE_LEGACY, BSON_MAX_LEN_UNLIMITED, false}; + const bson_json_opts_t opts = {BSON_JSON_MODE_LEGACY, BSON_MAX_LEN_UNLIMITED, false}; return bson_as_json_with_opts (bson, length, &opts); } @@ -3350,8 +3066,7 @@ bson_as_json (const bson_t *bson, size_t *length) char * bson_as_relaxed_extended_json (const bson_t *bson, size_t *length) { - const bson_json_opts_t opts = { - BSON_JSON_MODE_RELAXED, BSON_MAX_LEN_UNLIMITED, false}; + const bson_json_opts_t opts = {BSON_JSON_MODE_RELAXED, BSON_MAX_LEN_UNLIMITED, false}; return bson_as_json_with_opts (bson, length, &opts); } @@ -3359,8 +3074,7 @@ bson_as_relaxed_extended_json (const bson_t *bson, size_t *length) char * bson_array_as_json (const bson_t *bson, size_t *length) { - const bson_json_opts_t opts = { - BSON_JSON_MODE_LEGACY, BSON_MAX_LEN_UNLIMITED, true}; + const bson_json_opts_t opts = {BSON_JSON_MODE_LEGACY, BSON_MAX_LEN_UNLIMITED, true}; return bson_as_json_with_opts (bson, length, &opts); } @@ -3368,8 +3082,7 @@ bson_array_as_json (const bson_t *bson, size_t *length) char * bson_array_as_relaxed_extended_json (const bson_t *bson, size_t *length) { - const bson_json_opts_t opts = { - BSON_JSON_MODE_RELAXED, BSON_MAX_LEN_UNLIMITED, true}; + const bson_json_opts_t opts = {BSON_JSON_MODE_RELAXED, BSON_MAX_LEN_UNLIMITED, true}; return bson_as_json_with_opts (bson, length, &opts); } @@ -3377,21 +3090,15 @@ bson_array_as_relaxed_extended_json (const bson_t *bson, size_t *length) char * bson_array_as_canonical_extended_json (const bson_t *bson, size_t *length) { - const bson_json_opts_t opts = { - BSON_JSON_MODE_CANONICAL, BSON_MAX_LEN_UNLIMITED, true}; + const bson_json_opts_t opts = {BSON_JSON_MODE_CANONICAL, BSON_MAX_LEN_UNLIMITED, true}; return bson_as_json_with_opts (bson, length, &opts); } -#define VALIDATION_ERR(_flag, _msg, ...) \ - bson_set_error (&state->error, BSON_ERROR_INVALID, _flag, _msg, __VA_ARGS__) +#define VALIDATION_ERR(_flag, _msg, ...) bson_set_error (&state->error, BSON_ERROR_INVALID, _flag, _msg, __VA_ARGS__) static bool -_bson_iter_validate_utf8 (const bson_iter_t *iter, - const char *key, - size_t v_utf8_len, - const char *v_utf8, - void *data) +_bson_iter_validate_utf8 (const bson_iter_t *iter, const char *key, size_t v_utf8_len, const char *v_utf8, void *data) { bson_validate_state_t *state = data; bool allow_null; @@ -3401,8 +3108,7 @@ _bson_iter_validate_utf8 (const bson_iter_t *iter, if (!bson_utf8_validate (v_utf8, v_utf8_len, allow_null)) { state->err_offset = iter->off; - VALIDATION_ERR ( - BSON_VALIDATE_UTF8, "invalid utf8 string for key \"%s\"", key); + VALIDATION_ERR (BSON_VALIDATE_UTF8, "invalid utf8 string for key \"%s\"", key); return true; } } @@ -3430,9 +3136,7 @@ _bson_iter_validate_corrupt (const bson_iter_t *iter, void *data) static bool -_bson_iter_validate_before (const bson_iter_t *iter, - const char *key, - void *data) +_bson_iter_validate_before (const bson_iter_t *iter, const char *key, void *data) { bson_validate_state_t *state = data; @@ -3446,29 +3150,21 @@ _bson_iter_validate_before (const bson_iter_t *iter, if ((state->flags & BSON_VALIDATE_DOLLAR_KEYS)) { if (key[0] == '$') { - if (state->phase == BSON_VALIDATE_PHASE_LF_REF_KEY && - strcmp (key, "$ref") == 0) { + if (state->phase == BSON_VALIDATE_PHASE_LF_REF_KEY && strcmp (key, "$ref") == 0) { state->phase = BSON_VALIDATE_PHASE_LF_REF_UTF8; - } else if (state->phase == BSON_VALIDATE_PHASE_LF_ID_KEY && - strcmp (key, "$id") == 0) { + } else if (state->phase == BSON_VALIDATE_PHASE_LF_ID_KEY && strcmp (key, "$id") == 0) { state->phase = BSON_VALIDATE_PHASE_LF_DB_KEY; - } else if (state->phase == BSON_VALIDATE_PHASE_LF_DB_KEY && - strcmp (key, "$db") == 0) { + } else if (state->phase == BSON_VALIDATE_PHASE_LF_DB_KEY && strcmp (key, "$db") == 0) { state->phase = BSON_VALIDATE_PHASE_LF_DB_UTF8; } else { state->err_offset = iter->off; - VALIDATION_ERR (BSON_VALIDATE_DOLLAR_KEYS, - "keys cannot begin with \"$\": \"%s\"", - key); + VALIDATION_ERR (BSON_VALIDATE_DOLLAR_KEYS, "keys cannot begin with \"$\": \"%s\"", key); return true; } - } else if (state->phase == BSON_VALIDATE_PHASE_LF_ID_KEY || - state->phase == BSON_VALIDATE_PHASE_LF_REF_UTF8 || + } else if (state->phase == BSON_VALIDATE_PHASE_LF_ID_KEY || state->phase == BSON_VALIDATE_PHASE_LF_REF_UTF8 || state->phase == BSON_VALIDATE_PHASE_LF_DB_UTF8) { state->err_offset = iter->off; - VALIDATION_ERR (BSON_VALIDATE_DOLLAR_KEYS, - "invalid key within DBRef subdocument: \"%s\"", - key); + VALIDATION_ERR (BSON_VALIDATE_DOLLAR_KEYS, "invalid key within DBRef subdocument: \"%s\"", key); return true; } else { state->phase = BSON_VALIDATE_PHASE_NOT_DBREF; @@ -3478,8 +3174,7 @@ _bson_iter_validate_before (const bson_iter_t *iter, if ((state->flags & BSON_VALIDATE_DOT_KEYS)) { if (strstr (key, ".")) { state->err_offset = iter->off; - VALIDATION_ERR ( - BSON_VALIDATE_DOT_KEYS, "keys cannot contain \".\": \"%s\"", key); + VALIDATION_ERR (BSON_VALIDATE_DOT_KEYS, "keys cannot contain \".\": \"%s\"", key); return true; } } @@ -3489,12 +3184,8 @@ _bson_iter_validate_before (const bson_iter_t *iter, static bool -_bson_iter_validate_codewscope (const bson_iter_t *iter, - const char *key, - size_t v_code_len, - const char *v_code, - const bson_t *v_scope, - void *data) +_bson_iter_validate_codewscope ( + const bson_iter_t *iter, const char *key, size_t v_code_len, const char *v_code, const bson_t *v_scope, void *data) { bson_validate_state_t *state = data; size_t offset = 0; @@ -3514,10 +3205,7 @@ _bson_iter_validate_codewscope (const bson_iter_t *iter, static bool -_bson_iter_validate_document (const bson_iter_t *iter, - const char *key, - const bson_t *v_document, - void *data); +_bson_iter_validate_document (const bson_iter_t *iter, const char *key, const bson_t *v_document, void *data); static const bson_visitor_t bson_validate_funcs = { @@ -3543,10 +3231,7 @@ static const bson_visitor_t bson_validate_funcs = { static bool -_bson_iter_validate_document (const bson_iter_t *iter, - const char *key, - const bson_t *v_document, - void *data) +_bson_iter_validate_document (const bson_iter_t *iter, const char *key, const bson_t *v_document, void *data) { bson_validate_state_t *state = data; bson_iter_t child; @@ -3567,8 +3252,7 @@ _bson_iter_validate_document (const bson_iter_t *iter, (void) bson_iter_visit_all (&child, &bson_validate_funcs, state); - if (state->phase == BSON_VALIDATE_PHASE_LF_ID_KEY || - state->phase == BSON_VALIDATE_PHASE_LF_REF_UTF8 || + if (state->phase == BSON_VALIDATE_PHASE_LF_ID_KEY || state->phase == BSON_VALIDATE_PHASE_LF_REF_UTF8 || state->phase == BSON_VALIDATE_PHASE_LF_DB_UTF8) { if (state->err_offset <= 0) { state->err_offset = iter->off; @@ -3618,9 +3302,7 @@ bson_validate (const bson_t *bson, bson_validate_flags_t flags, size_t *offset) bool -bson_validate_with_error (const bson_t *bson, - bson_validate_flags_t flags, - bson_error_t *error) +bson_validate_with_error (const bson_t *bson, bson_validate_flags_t flags, bson_error_t *error) { bson_validate_state_t state; @@ -3642,8 +3324,7 @@ bson_concat (bson_t *dst, const bson_t *src) BSON_ASSERT (src); if (!bson_empty (src)) { - return _bson_append ( - dst, 1, src->len - 5, src->len - 5, _bson_data (src) + 4); + return _bson_append (dst, 1, src->len - 5, src->len - 5, _bson_data (src) + 4); } return true; @@ -3664,47 +3345,44 @@ bson_array_builder_new (void) // `bson_array_builder_append_impl` generates the next key index, calls // `append_fn`, and may update the tracked next index. -#define bson_array_builder_append_impl(append_fn, ...) \ - if (1) { \ - BSON_ASSERT_PARAM (bab); \ - const char *key; \ - char buf[16]; \ - size_t key_length = \ - bson_uint32_to_string (bab->index, &key, buf, sizeof buf); \ - /* Expect enough room in `buf` for key string. UINT32_MAX is 10 digits. \ - * With the NULL terminator, 11 is expected maximum number of \ - * characters. */ \ - BSON_ASSERT (key_length < sizeof buf); \ - bool ok = append_fn (&bab->bson, key, (int) key_length, __VA_ARGS__); \ - if (ok) { \ - bab->index += 1; \ - } \ - return ok; \ - } else \ +#define bson_array_builder_append_impl(append_fn, ...) \ + if (1) { \ + BSON_ASSERT_PARAM (bab); \ + const char *key; \ + char buf[16]; \ + size_t key_length = bson_uint32_to_string (bab->index, &key, buf, sizeof buf); \ + /* Expect enough room in `buf` for key string. UINT32_MAX is 10 digits. \ + * With the NULL terminator, 11 is expected maximum number of \ + * characters. */ \ + BSON_ASSERT (key_length < sizeof buf); \ + bool ok = append_fn (&bab->bson, key, (int) key_length, __VA_ARGS__); \ + if (ok) { \ + bab->index += 1; \ + } \ + return ok; \ + } else \ (void) 0 -#define bson_array_builder_append_impl_noargs(append_fn) \ - if (1) { \ - BSON_ASSERT_PARAM (bab); \ - const char *key; \ - char buf[16]; \ - size_t key_length = \ - bson_uint32_to_string (bab->index, &key, buf, sizeof buf); \ - /* Expect enough room in `buf` for key string. UINT32_MAX is 10 digits. \ - * With the NULL terminator, 11 is expected maximum number of \ - * characters. */ \ - BSON_ASSERT (key_length < sizeof buf); \ - bool ok = append_fn (&bab->bson, key, (int) key_length); \ - if (ok) { \ - bab->index += 1; \ - } \ - return ok; \ - } else \ +#define bson_array_builder_append_impl_noargs(append_fn) \ + if (1) { \ + BSON_ASSERT_PARAM (bab); \ + const char *key; \ + char buf[16]; \ + size_t key_length = bson_uint32_to_string (bab->index, &key, buf, sizeof buf); \ + /* Expect enough room in `buf` for key string. UINT32_MAX is 10 digits. \ + * With the NULL terminator, 11 is expected maximum number of \ + * characters. */ \ + BSON_ASSERT (key_length < sizeof buf); \ + bool ok = append_fn (&bab->bson, key, (int) key_length); \ + if (ok) { \ + bab->index += 1; \ + } \ + return ok; \ + } else \ (void) 0 bool -bson_array_builder_append_value (bson_array_builder_t *bab, - const bson_value_t *value) +bson_array_builder_append_value (bson_array_builder_t *bab, const bson_value_t *value) { bson_array_builder_append_impl (bson_append_value, value); } @@ -3734,27 +3412,21 @@ bson_array_builder_append_bool (bson_array_builder_t *bab, bool value) bool -bson_array_builder_append_code (bson_array_builder_t *bab, - const char *javascript) +bson_array_builder_append_code (bson_array_builder_t *bab, const char *javascript) { bson_array_builder_append_impl (bson_append_code, javascript); } bool -bson_array_builder_append_code_with_scope (bson_array_builder_t *bab, - const char *javascript, - const bson_t *scope) +bson_array_builder_append_code_with_scope (bson_array_builder_t *bab, const char *javascript, const bson_t *scope) { - bson_array_builder_append_impl ( - bson_append_code_with_scope, javascript, scope); + bson_array_builder_append_impl (bson_append_code_with_scope, javascript, scope); } bool -bson_array_builder_append_dbpointer (bson_array_builder_t *bab, - const char *collection, - const bson_oid_t *oid) +bson_array_builder_append_dbpointer (bson_array_builder_t *bab, const char *collection, const bson_oid_t *oid) { bson_array_builder_append_impl (bson_append_dbpointer, collection, oid); } @@ -3768,24 +3440,21 @@ bson_array_builder_append_double (bson_array_builder_t *bab, double value) bool -bson_array_builder_append_document (bson_array_builder_t *bab, - const bson_t *value) +bson_array_builder_append_document (bson_array_builder_t *bab, const bson_t *value) { bson_array_builder_append_impl (bson_append_document, value); } bool -bson_array_builder_append_document_begin (bson_array_builder_t *bab, - bson_t *child) +bson_array_builder_append_document_begin (bson_array_builder_t *bab, bson_t *child) { bson_array_builder_append_impl (bson_append_document_begin, child); } bool -bson_array_builder_append_document_end (bson_array_builder_t *bab, - bson_t *child) +bson_array_builder_append_document_end (bson_array_builder_t *bab, bson_t *child) { return bson_append_document_end (&bab->bson, child); } @@ -3806,16 +3475,14 @@ bson_array_builder_append_int64 (bson_array_builder_t *bab, int64_t value) bool -bson_array_builder_append_decimal128 (bson_array_builder_t *bab, - const bson_decimal128_t *value) +bson_array_builder_append_decimal128 (bson_array_builder_t *bab, const bson_decimal128_t *value) { bson_array_builder_append_impl (bson_append_decimal128, value); } bool -bson_array_builder_append_iter (bson_array_builder_t *bab, - const bson_iter_t *iter) +bson_array_builder_append_iter (bson_array_builder_t *bab, const bson_iter_t *iter) { bson_array_builder_append_impl (bson_append_iter, iter); } @@ -3850,9 +3517,7 @@ bson_array_builder_append_oid (bson_array_builder_t *bab, const bson_oid_t *oid) bool -bson_array_builder_append_regex (bson_array_builder_t *bab, - const char *regex, - const char *options) +bson_array_builder_append_regex (bson_array_builder_t *bab, const char *regex, const char *options) { bson_array_builder_append_impl (bson_append_regex, regex, options); } @@ -3864,24 +3529,19 @@ bson_array_builder_append_regex_w_len (bson_array_builder_t *bab, int regex_length, const char *options) { - bson_array_builder_append_impl ( - bson_append_regex_w_len, regex, regex_length, options); + bson_array_builder_append_impl (bson_append_regex_w_len, regex, regex_length, options); } bool -bson_array_builder_append_utf8 (bson_array_builder_t *bab, - const char *value, - int length) +bson_array_builder_append_utf8 (bson_array_builder_t *bab, const char *value, int length) { bson_array_builder_append_impl (bson_append_utf8, value, length); } bool -bson_array_builder_append_symbol (bson_array_builder_t *bab, - const char *value, - int length) +bson_array_builder_append_symbol (bson_array_builder_t *bab, const char *value, int length) { bson_array_builder_append_impl (bson_append_symbol, value, length); } @@ -3895,8 +3555,7 @@ bson_array_builder_append_time_t (bson_array_builder_t *bab, time_t value) bool -bson_array_builder_append_timeval (bson_array_builder_t *bab, - struct timeval *value) +bson_array_builder_append_timeval (bson_array_builder_t *bab, struct timeval *value) { bson_array_builder_append_impl (bson_append_timeval, value); } @@ -3917,9 +3576,7 @@ bson_array_builder_append_now_utc (bson_array_builder_t *bab) bool -bson_array_builder_append_timestamp (bson_array_builder_t *bab, - uint32_t timestamp, - uint32_t increment) +bson_array_builder_append_timestamp (bson_array_builder_t *bab, uint32_t timestamp, uint32_t increment) { bson_array_builder_append_impl (bson_append_timestamp, timestamp, increment); } @@ -3933,15 +3590,13 @@ bson_array_builder_append_undefined (bson_array_builder_t *bab) bool -bson_array_builder_append_array_builder_begin (bson_array_builder_t *bab, - bson_array_builder_t **child) +bson_array_builder_append_array_builder_begin (bson_array_builder_t *bab, bson_array_builder_t **child) { bson_array_builder_append_impl (bson_append_array_builder_begin, child); } bool -bson_array_builder_append_array_builder_end (bson_array_builder_t *bab, - bson_array_builder_t *child) +bson_array_builder_append_array_builder_end (bson_array_builder_t *bab, bson_array_builder_t *child) { return bson_append_array_builder_end (&bab->bson, child); } @@ -3971,10 +3626,7 @@ bson_array_builder_destroy (bson_array_builder_t *bab) } bool -bson_append_array_builder_begin (bson_t *bson, - const char *key, - int key_length, - bson_array_builder_t **child) +bson_append_array_builder_begin (bson_t *bson, const char *key, int key_length, bson_array_builder_t **child) { BSON_ASSERT_PARAM (bson); BSON_ASSERT_PARAM (key); diff --git a/src/libbson/src/bson/bson.h b/src/libbson/src/bson/bson.h index 88a2f706c4..f86967bae1 100644 --- a/src/libbson/src/bson/bson.h +++ b/src/libbson/src/bson/bson.h @@ -100,82 +100,58 @@ BSON_BEGIN_DECLS #define BSON_MAX_SIZE ((size_t) ((1U << 31) - 1)) -#define BSON_APPEND_ARRAY(b, key, val) \ - bson_append_array (b, key, (int) strlen (key), val) +#define BSON_APPEND_ARRAY(b, key, val) bson_append_array (b, key, (int) strlen (key), val) -#define BSON_APPEND_ARRAY_BEGIN(b, key, child) \ - bson_append_array_begin (b, key, (int) strlen (key), child) +#define BSON_APPEND_ARRAY_BEGIN(b, key, child) bson_append_array_begin (b, key, (int) strlen (key), child) -#define BSON_APPEND_BINARY(b, key, subtype, val, len) \ - bson_append_binary (b, key, (int) strlen (key), subtype, val, len) +#define BSON_APPEND_BINARY(b, key, subtype, val, len) bson_append_binary (b, key, (int) strlen (key), subtype, val, len) -#define BSON_APPEND_BOOL(b, key, val) \ - bson_append_bool (b, key, (int) strlen (key), val) +#define BSON_APPEND_BOOL(b, key, val) bson_append_bool (b, key, (int) strlen (key), val) -#define BSON_APPEND_CODE(b, key, val) \ - bson_append_code (b, key, (int) strlen (key), val) +#define BSON_APPEND_CODE(b, key, val) bson_append_code (b, key, (int) strlen (key), val) #define BSON_APPEND_CODE_WITH_SCOPE(b, key, val, scope) \ bson_append_code_with_scope (b, key, (int) strlen (key), val, scope) -#define BSON_APPEND_DBPOINTER(b, key, coll, oid) \ - bson_append_dbpointer (b, key, (int) strlen (key), coll, oid) +#define BSON_APPEND_DBPOINTER(b, key, coll, oid) bson_append_dbpointer (b, key, (int) strlen (key), coll, oid) -#define BSON_APPEND_DOCUMENT_BEGIN(b, key, child) \ - bson_append_document_begin (b, key, (int) strlen (key), child) +#define BSON_APPEND_DOCUMENT_BEGIN(b, key, child) bson_append_document_begin (b, key, (int) strlen (key), child) -#define BSON_APPEND_DOUBLE(b, key, val) \ - bson_append_double (b, key, (int) strlen (key), val) +#define BSON_APPEND_DOUBLE(b, key, val) bson_append_double (b, key, (int) strlen (key), val) -#define BSON_APPEND_DOCUMENT(b, key, val) \ - bson_append_document (b, key, (int) strlen (key), val) +#define BSON_APPEND_DOCUMENT(b, key, val) bson_append_document (b, key, (int) strlen (key), val) -#define BSON_APPEND_INT32(b, key, val) \ - bson_append_int32 (b, key, (int) strlen (key), val) +#define BSON_APPEND_INT32(b, key, val) bson_append_int32 (b, key, (int) strlen (key), val) -#define BSON_APPEND_INT64(b, key, val) \ - bson_append_int64 (b, key, (int) strlen (key), val) +#define BSON_APPEND_INT64(b, key, val) bson_append_int64 (b, key, (int) strlen (key), val) -#define BSON_APPEND_MINKEY(b, key) \ - bson_append_minkey (b, key, (int) strlen (key)) +#define BSON_APPEND_MINKEY(b, key) bson_append_minkey (b, key, (int) strlen (key)) -#define BSON_APPEND_DECIMAL128(b, key, val) \ - bson_append_decimal128 (b, key, (int) strlen (key), val) +#define BSON_APPEND_DECIMAL128(b, key, val) bson_append_decimal128 (b, key, (int) strlen (key), val) -#define BSON_APPEND_MAXKEY(b, key) \ - bson_append_maxkey (b, key, (int) strlen (key)) +#define BSON_APPEND_MAXKEY(b, key) bson_append_maxkey (b, key, (int) strlen (key)) #define BSON_APPEND_NULL(b, key) bson_append_null (b, key, (int) strlen (key)) -#define BSON_APPEND_OID(b, key, val) \ - bson_append_oid (b, key, (int) strlen (key), val) +#define BSON_APPEND_OID(b, key, val) bson_append_oid (b, key, (int) strlen (key), val) -#define BSON_APPEND_REGEX(b, key, val, opt) \ - bson_append_regex (b, key, (int) strlen (key), val, opt) +#define BSON_APPEND_REGEX(b, key, val, opt) bson_append_regex (b, key, (int) strlen (key), val, opt) -#define BSON_APPEND_UTF8(b, key, val) \ - bson_append_utf8 (b, key, (int) strlen (key), val, (int) strlen (val)) +#define BSON_APPEND_UTF8(b, key, val) bson_append_utf8 (b, key, (int) strlen (key), val, (int) strlen (val)) -#define BSON_APPEND_SYMBOL(b, key, val) \ - bson_append_symbol (b, key, (int) strlen (key), val, (int) strlen (val)) +#define BSON_APPEND_SYMBOL(b, key, val) bson_append_symbol (b, key, (int) strlen (key), val, (int) strlen (val)) -#define BSON_APPEND_TIME_T(b, key, val) \ - bson_append_time_t (b, key, (int) strlen (key), val) +#define BSON_APPEND_TIME_T(b, key, val) bson_append_time_t (b, key, (int) strlen (key), val) -#define BSON_APPEND_TIMEVAL(b, key, val) \ - bson_append_timeval (b, key, (int) strlen (key), val) +#define BSON_APPEND_TIMEVAL(b, key, val) bson_append_timeval (b, key, (int) strlen (key), val) -#define BSON_APPEND_DATE_TIME(b, key, val) \ - bson_append_date_time (b, key, (int) strlen (key), val) +#define BSON_APPEND_DATE_TIME(b, key, val) bson_append_date_time (b, key, (int) strlen (key), val) -#define BSON_APPEND_TIMESTAMP(b, key, val, inc) \ - bson_append_timestamp (b, key, (int) strlen (key), val, inc) +#define BSON_APPEND_TIMESTAMP(b, key, val, inc) bson_append_timestamp (b, key, (int) strlen (key), val, inc) -#define BSON_APPEND_UNDEFINED(b, key) \ - bson_append_undefined (b, key, (int) strlen (key)) +#define BSON_APPEND_UNDEFINED(b, key) bson_append_undefined (b, key, (int) strlen (key)) -#define BSON_APPEND_VALUE(b, key, val) \ - bson_append_value (b, key, (int) strlen (key), (val)) +#define BSON_APPEND_VALUE(b, key, val) bson_append_value (b, key, (int) strlen (key), (val)) /** @@ -196,10 +172,7 @@ bson_new_from_json (const uint8_t *data, ssize_t len, bson_error_t *error); BSON_EXPORT (bool) -bson_init_from_json (bson_t *bson, - const char *data, - ssize_t len, - bson_error_t *error); +bson_init_from_json (bson_t *bson, const char *data, ssize_t len, bson_error_t *error); /** @@ -278,10 +251,7 @@ bson_new_from_data (const uint8_t *data, size_t length); * The underlying buffer will be used and not be freed in destroy. */ BSON_EXPORT (bson_t *) -bson_new_from_buffer (uint8_t **buf, - size_t *buf_len, - bson_realloc_func realloc_func, - void *realloc_func_ctx); +bson_new_from_buffer (uint8_t **buf, size_t *buf_len, bson_realloc_func realloc_func, void *realloc_func_ctx); /** @@ -333,10 +303,7 @@ bson_copy_to (const bson_t *src, bson_t *dst); * on dst. */ BSON_EXPORT (void) -bson_copy_to_excluding (const bson_t *src, - bson_t *dst, - const char *first_exclude, - ...) BSON_GNUC_NULL_TERMINATED +bson_copy_to_excluding (const bson_t *src, bson_t *dst, const char *first_exclude, ...) BSON_GNUC_NULL_TERMINATED BSON_GNUC_DEPRECATED_FOR (bson_copy_to_excluding_noinit); /** @@ -350,16 +317,11 @@ bson_copy_to_excluding (const bson_t *src, * old function is left for backwards compatibility. */ BSON_EXPORT (void) -bson_copy_to_excluding_noinit (const bson_t *src, - bson_t *dst, - const char *first_exclude, - ...) BSON_GNUC_NULL_TERMINATED; +bson_copy_to_excluding_noinit (const bson_t *src, bson_t *dst, const char *first_exclude, ...) + BSON_GNUC_NULL_TERMINATED; BSON_EXPORT (void) -bson_copy_to_excluding_noinit_va (const bson_t *src, - bson_t *dst, - const char *first_exclude, - va_list args); +bson_copy_to_excluding_noinit_va (const bson_t *src, bson_t *dst, const char *first_exclude, va_list args); /** @@ -489,9 +451,7 @@ bson_validate (const bson_t *bson, bson_validate_flags_t flags, size_t *offset); * Returns: true if @bson is valid; otherwise false and @error is filled out. */ BSON_EXPORT (bool) -bson_validate_with_error (const bson_t *bson, - bson_validate_flags_t flags, - bson_error_t *error); +bson_validate_with_error (const bson_t *bson, bson_validate_flags_t flags, bson_error_t *error); /** @@ -514,9 +474,7 @@ bson_validate_with_error (const bson_t *bson, * Returns: A newly allocated string that should be freed with bson_free(). */ BSON_EXPORT (char *) -bson_as_json_with_opts (const bson_t *bson, - size_t *length, - const bson_json_opts_t *opts); +bson_as_json_with_opts (const bson_t *bson, size_t *length, const bson_json_opts_t *opts); /** @@ -612,17 +570,12 @@ BSON_EXPORT (void) bson_array_builder_destroy (bson_array_builder_t *bab); BSON_EXPORT (bool) -bson_append_value (bson_t *bson, - const char *key, - int key_length, - const bson_value_t *value); +bson_append_value (bson_t *bson, const char *key, int key_length, const bson_value_t *value); -#define BSON_APPEND_VALUE(b, key, val) \ - bson_append_value (b, key, (int) strlen (key), (val)) +#define BSON_APPEND_VALUE(b, key, val) bson_append_value (b, key, (int) strlen (key), (val)) BSON_EXPORT (bool) -bson_array_builder_append_value (bson_array_builder_t *bab, - const bson_value_t *value); +bson_array_builder_append_value (bson_array_builder_t *bab, const bson_value_t *value); /** * bson_append_array: @@ -637,17 +590,12 @@ bson_array_builder_append_value (bson_array_builder_t *bab, * Returns: true if successful; false if append would overflow max size. */ BSON_EXPORT (bool) -bson_append_array (bson_t *bson, - const char *key, - int key_length, - const bson_t *array); +bson_append_array (bson_t *bson, const char *key, int key_length, const bson_t *array); -#define BSON_APPEND_ARRAY(b, key, val) \ - bson_append_array (b, key, (int) strlen (key), val) +#define BSON_APPEND_ARRAY(b, key, val) bson_append_array (b, key, (int) strlen (key), val) BSON_EXPORT (bool) -bson_array_builder_append_array (bson_array_builder_t *bab, - const bson_t *array); +bson_array_builder_append_array (bson_array_builder_t *bab, const bson_t *array); /** * bson_append_binary: @@ -662,15 +610,10 @@ bson_array_builder_append_array (bson_array_builder_t *bab, * Returns: true if successful; false if append would overflow max size. */ BSON_EXPORT (bool) -bson_append_binary (bson_t *bson, - const char *key, - int key_length, - bson_subtype_t subtype, - const uint8_t *binary, - uint32_t length); +bson_append_binary ( + bson_t *bson, const char *key, int key_length, bson_subtype_t subtype, const uint8_t *binary, uint32_t length); -#define BSON_APPEND_BINARY(b, key, subtype, val, len) \ - bson_append_binary (b, key, (int) strlen (key), subtype, val, len) +#define BSON_APPEND_BINARY(b, key, subtype, val, len) bson_append_binary (b, key, (int) strlen (key), subtype, val, len) BSON_EXPORT (bool) bson_array_builder_append_binary (bson_array_builder_t *bab, @@ -691,8 +634,7 @@ bson_array_builder_append_binary (bson_array_builder_t *bab, BSON_EXPORT (bool) bson_append_bool (bson_t *bson, const char *key, int key_length, bool value); -#define BSON_APPEND_BOOL(b, key, val) \ - bson_append_bool (b, key, (int) strlen (key), val) +#define BSON_APPEND_BOOL(b, key, val) bson_append_bool (b, key, (int) strlen (key), val) BSON_EXPORT (bool) bson_array_builder_append_bool (bson_array_builder_t *bab, bool value); @@ -709,17 +651,12 @@ bson_array_builder_append_bool (bson_array_builder_t *bab, bool value); * Returns: true if successful; false if append would overflow max size. */ BSON_EXPORT (bool) -bson_append_code (bson_t *bson, - const char *key, - int key_length, - const char *javascript); +bson_append_code (bson_t *bson, const char *key, int key_length, const char *javascript); -#define BSON_APPEND_CODE(b, key, val) \ - bson_append_code (b, key, (int) strlen (key), val) +#define BSON_APPEND_CODE(b, key, val) bson_append_code (b, key, (int) strlen (key), val) BSON_EXPORT (bool) -bson_array_builder_append_code (bson_array_builder_t *bab, - const char *javascript); +bson_array_builder_append_code (bson_array_builder_t *bab, const char *javascript); /** * bson_append_code_with_scope: @@ -734,19 +671,14 @@ bson_array_builder_append_code (bson_array_builder_t *bab, * Returns: true if successful; false if append would overflow max size. */ BSON_EXPORT (bool) -bson_append_code_with_scope (bson_t *bson, - const char *key, - int key_length, - const char *javascript, - const bson_t *scope); +bson_append_code_with_scope ( + bson_t *bson, const char *key, int key_length, const char *javascript, const bson_t *scope); #define BSON_APPEND_CODE_WITH_SCOPE(b, key, val, scope) \ bson_append_code_with_scope (b, key, (int) strlen (key), val, scope) BSON_EXPORT (bool) -bson_array_builder_append_code_with_scope (bson_array_builder_t *bab, - const char *javascript, - const bson_t *scope); +bson_array_builder_append_code_with_scope (bson_array_builder_t *bab, const char *javascript, const bson_t *scope); /** * bson_append_dbpointer: @@ -761,19 +693,12 @@ bson_array_builder_append_code_with_scope (bson_array_builder_t *bab, * Returns: true if successful; false if append would overflow max size. */ BSON_EXPORT (bool) -bson_append_dbpointer (bson_t *bson, - const char *key, - int key_length, - const char *collection, - const bson_oid_t *oid); +bson_append_dbpointer (bson_t *bson, const char *key, int key_length, const char *collection, const bson_oid_t *oid); -#define BSON_APPEND_DBPOINTER(b, key, coll, oid) \ - bson_append_dbpointer (b, key, (int) strlen (key), coll, oid) +#define BSON_APPEND_DBPOINTER(b, key, coll, oid) bson_append_dbpointer (b, key, (int) strlen (key), coll, oid) BSON_EXPORT (bool) -bson_array_builder_append_dbpointer (bson_array_builder_t *bab, - const char *collection, - const bson_oid_t *oid); +bson_array_builder_append_dbpointer (bson_array_builder_t *bab, const char *collection, const bson_oid_t *oid); /** * bson_append_double: @@ -785,13 +710,9 @@ bson_array_builder_append_dbpointer (bson_array_builder_t *bab, * Returns: true if successful; false if append would overflow max size. */ BSON_EXPORT (bool) -bson_append_double (bson_t *bson, - const char *key, - int key_length, - double value); +bson_append_double (bson_t *bson, const char *key, int key_length, double value); -#define BSON_APPEND_DOUBLE(b, key, val) \ - bson_append_double (b, key, (int) strlen (key), val) +#define BSON_APPEND_DOUBLE(b, key, val) bson_append_double (b, key, (int) strlen (key), val) BSON_EXPORT (bool) bson_array_builder_append_double (bson_array_builder_t *bab, double value); @@ -808,17 +729,12 @@ bson_array_builder_append_double (bson_array_builder_t *bab, double value); * Returns: true if successful; false if append would overflow max size. */ BSON_EXPORT (bool) -bson_append_document (bson_t *bson, - const char *key, - int key_length, - const bson_t *value); +bson_append_document (bson_t *bson, const char *key, int key_length, const bson_t *value); -#define BSON_APPEND_DOCUMENT(b, key, val) \ - bson_append_document (b, key, (int) strlen (key), val) +#define BSON_APPEND_DOCUMENT(b, key, val) bson_append_document (b, key, (int) strlen (key), val) BSON_EXPORT (bool) -bson_array_builder_append_document (bson_array_builder_t *bab, - const bson_t *value); +bson_array_builder_append_document (bson_array_builder_t *bab, const bson_t *value); /** * bson_append_document_begin: @@ -838,17 +754,12 @@ bson_array_builder_append_document (bson_array_builder_t *bab, * Returns: true if successful; false if append would overflow max size. */ BSON_EXPORT (bool) -bson_append_document_begin (bson_t *bson, - const char *key, - int key_length, - bson_t *child); +bson_append_document_begin (bson_t *bson, const char *key, int key_length, bson_t *child); -#define BSON_APPEND_DOCUMENT_BEGIN(b, key, child) \ - bson_append_document_begin (b, key, (int) strlen (key), child) +#define BSON_APPEND_DOCUMENT_BEGIN(b, key, child) bson_append_document_begin (b, key, (int) strlen (key), child) BSON_EXPORT (bool) -bson_array_builder_append_document_begin (bson_array_builder_t *bab, - bson_t *child); +bson_array_builder_append_document_begin (bson_array_builder_t *bab, bson_t *child); /** * bson_append_document_end: @@ -864,8 +775,7 @@ BSON_EXPORT (bool) bson_append_document_end (bson_t *bson, bson_t *child); BSON_EXPORT (bool) -bson_array_builder_append_document_end (bson_array_builder_t *bab, - bson_t *child); +bson_array_builder_append_document_end (bson_array_builder_t *bab, bson_t *child); /** @@ -889,13 +799,9 @@ bson_array_builder_append_document_end (bson_array_builder_t *bab, * Returns: true if successful; false if append would overflow max size. */ BSON_EXPORT (bool) -bson_append_array_begin (bson_t *bson, - const char *key, - int key_length, - bson_t *child); +bson_append_array_begin (bson_t *bson, const char *key, int key_length, bson_t *child); -#define BSON_APPEND_ARRAY_BEGIN(b, key, child) \ - bson_append_array_begin (b, key, (int) strlen (key), child) +#define BSON_APPEND_ARRAY_BEGIN(b, key, child) bson_append_array_begin (b, key, (int) strlen (key), child) /** * bson_append_array_end: @@ -922,13 +828,9 @@ bson_append_array_end (bson_t *bson, bson_t *child); * Returns: true if successful; false if append would overflow max size. */ BSON_EXPORT (bool) -bson_append_int32 (bson_t *bson, - const char *key, - int key_length, - int32_t value); +bson_append_int32 (bson_t *bson, const char *key, int key_length, int32_t value); -#define BSON_APPEND_INT32(b, key, val) \ - bson_append_int32 (b, key, (int) strlen (key), val) +#define BSON_APPEND_INT32(b, key, val) bson_append_int32 (b, key, (int) strlen (key), val) BSON_EXPORT (bool) bson_array_builder_append_int32 (bson_array_builder_t *bab, int32_t value); @@ -944,13 +846,9 @@ bson_array_builder_append_int32 (bson_array_builder_t *bab, int32_t value); * Returns: true if successful; false if append would overflow max size. */ BSON_EXPORT (bool) -bson_append_int64 (bson_t *bson, - const char *key, - int key_length, - int64_t value); +bson_append_int64 (bson_t *bson, const char *key, int key_length, int64_t value); -#define BSON_APPEND_INT64(b, key, val) \ - bson_append_int64 (b, key, (int) strlen (key), val) +#define BSON_APPEND_INT64(b, key, val) bson_append_int64 (b, key, (int) strlen (key), val) BSON_EXPORT (bool) bson_array_builder_append_int64 (bson_array_builder_t *bab, int64_t value); @@ -966,17 +864,12 @@ bson_array_builder_append_int64 (bson_array_builder_t *bab, int64_t value); * Returns: true if successful; false if append would overflow max size. */ BSON_EXPORT (bool) -bson_append_decimal128 (bson_t *bson, - const char *key, - int key_length, - const bson_decimal128_t *value); +bson_append_decimal128 (bson_t *bson, const char *key, int key_length, const bson_decimal128_t *value); -#define BSON_APPEND_DECIMAL128(b, key, val) \ - bson_append_decimal128 (b, key, (int) strlen (key), val) +#define BSON_APPEND_DECIMAL128(b, key, val) bson_append_decimal128 (b, key, (int) strlen (key), val) BSON_EXPORT (bool) -bson_array_builder_append_decimal128 (bson_array_builder_t *bab, - const bson_decimal128_t *value); +bson_array_builder_append_decimal128 (bson_array_builder_t *bab, const bson_decimal128_t *value); /** * bson_append_iter: @@ -991,17 +884,12 @@ bson_array_builder_append_decimal128 (bson_array_builder_t *bab, * Returns: true if successful; false if append would overflow max size. */ BSON_EXPORT (bool) -bson_append_iter (bson_t *bson, - const char *key, - int key_length, - const bson_iter_t *iter); +bson_append_iter (bson_t *bson, const char *key, int key_length, const bson_iter_t *iter); -#define BSON_APPEND_ITER(b, key, val) \ - bson_append_iter (b, key, (int) strlen (key), val) +#define BSON_APPEND_ITER(b, key, val) bson_append_iter (b, key, (int) strlen (key), val) BSON_EXPORT (bool) -bson_array_builder_append_iter (bson_array_builder_t *bab, - const bson_iter_t *iter); +bson_array_builder_append_iter (bson_array_builder_t *bab, const bson_iter_t *iter); /** * bson_append_minkey: @@ -1018,8 +906,7 @@ bson_array_builder_append_iter (bson_array_builder_t *bab, BSON_EXPORT (bool) bson_append_minkey (bson_t *bson, const char *key, int key_length); -#define BSON_APPEND_MINKEY(b, key) \ - bson_append_minkey (b, key, (int) strlen (key)) +#define BSON_APPEND_MINKEY(b, key) bson_append_minkey (b, key, (int) strlen (key)) BSON_EXPORT (bool) bson_array_builder_append_minkey (bson_array_builder_t *bab); @@ -1039,8 +926,7 @@ bson_array_builder_append_minkey (bson_array_builder_t *bab); BSON_EXPORT (bool) bson_append_maxkey (bson_t *bson, const char *key, int key_length); -#define BSON_APPEND_MAXKEY(b, key) \ - bson_append_maxkey (b, key, (int) strlen (key)) +#define BSON_APPEND_MAXKEY(b, key) bson_append_maxkey (b, key, (int) strlen (key)) BSON_EXPORT (bool) bson_array_builder_append_maxkey (bson_array_builder_t *bab); @@ -1074,17 +960,12 @@ bson_array_builder_append_null (bson_array_builder_t *bab); * Returns: true if successful; false if append would overflow max size. */ BSON_EXPORT (bool) -bson_append_oid (bson_t *bson, - const char *key, - int key_length, - const bson_oid_t *oid); +bson_append_oid (bson_t *bson, const char *key, int key_length, const bson_oid_t *oid); -#define BSON_APPEND_OID(b, key, val) \ - bson_append_oid (b, key, (int) strlen (key), val) +#define BSON_APPEND_OID(b, key, val) bson_append_oid (b, key, (int) strlen (key), val) BSON_EXPORT (bool) -bson_array_builder_append_oid (bson_array_builder_t *bab, - const bson_oid_t *oid); +bson_array_builder_append_oid (bson_array_builder_t *bab, const bson_oid_t *oid); /** * bson_append_regex: @@ -1110,19 +991,12 @@ bson_array_builder_append_oid (bson_array_builder_t *bab, * Returns: true if successful; false if append would overflow max size. */ BSON_EXPORT (bool) -bson_append_regex (bson_t *bson, - const char *key, - int key_length, - const char *regex, - const char *options); +bson_append_regex (bson_t *bson, const char *key, int key_length, const char *regex, const char *options); -#define BSON_APPEND_REGEX(b, key, val, opt) \ - bson_append_regex (b, key, (int) strlen (key), val, opt) +#define BSON_APPEND_REGEX(b, key, val, opt) bson_append_regex (b, key, (int) strlen (key), val, opt) BSON_EXPORT (bool) -bson_array_builder_append_regex (bson_array_builder_t *bab, - const char *regex, - const char *options); +bson_array_builder_append_regex (bson_array_builder_t *bab, const char *regex, const char *options); /** * bson_append_regex: @@ -1150,12 +1024,8 @@ bson_array_builder_append_regex (bson_array_builder_t *bab, * Returns: true if successful; false if append would overflow max size. */ BSON_EXPORT (bool) -bson_append_regex_w_len (bson_t *bson, - const char *key, - int key_length, - const char *regex, - int regex_length, - const char *options); +bson_append_regex_w_len ( + bson_t *bson, const char *key, int key_length, const char *regex, int regex_length, const char *options); BSON_EXPORT (bool) bson_array_builder_append_regex_w_len (bson_array_builder_t *bab, @@ -1179,19 +1049,12 @@ bson_array_builder_append_regex_w_len (bson_array_builder_t *bab, * Returns: true if successful; false if append would overflow max size. */ BSON_EXPORT (bool) -bson_append_utf8 (bson_t *bson, - const char *key, - int key_length, - const char *value, - int length); +bson_append_utf8 (bson_t *bson, const char *key, int key_length, const char *value, int length); -#define BSON_APPEND_UTF8(b, key, val) \ - bson_append_utf8 (b, key, (int) strlen (key), val, (int) strlen (val)) +#define BSON_APPEND_UTF8(b, key, val) bson_append_utf8 (b, key, (int) strlen (key), val, (int) strlen (val)) BSON_EXPORT (bool) -bson_array_builder_append_utf8 (bson_array_builder_t *bab, - const char *value, - int length); +bson_array_builder_append_utf8 (bson_array_builder_t *bab, const char *value, int length); /** * bson_append_symbol: @@ -1208,19 +1071,12 @@ bson_array_builder_append_utf8 (bson_array_builder_t *bab, * Returns: true if successful; false if append would overflow max size. */ BSON_EXPORT (bool) -bson_append_symbol (bson_t *bson, - const char *key, - int key_length, - const char *value, - int length); +bson_append_symbol (bson_t *bson, const char *key, int key_length, const char *value, int length); -#define BSON_APPEND_SYMBOL(b, key, val) \ - bson_append_symbol (b, key, (int) strlen (key), val, (int) strlen (val)) +#define BSON_APPEND_SYMBOL(b, key, val) bson_append_symbol (b, key, (int) strlen (key), val, (int) strlen (val)) BSON_EXPORT (bool) -bson_array_builder_append_symbol (bson_array_builder_t *bab, - const char *value, - int length); +bson_array_builder_append_symbol (bson_array_builder_t *bab, const char *value, int length); /** * bson_append_time_t: @@ -1234,13 +1090,9 @@ bson_array_builder_append_symbol (bson_array_builder_t *bab, * Returns: true if successful; false if append would overflow max size. */ BSON_EXPORT (bool) -bson_append_time_t (bson_t *bson, - const char *key, - int key_length, - time_t value); +bson_append_time_t (bson_t *bson, const char *key, int key_length, time_t value); -#define BSON_APPEND_TIME_T(b, key, val) \ - bson_append_time_t (b, key, (int) strlen (key), val) +#define BSON_APPEND_TIME_T(b, key, val) bson_append_time_t (b, key, (int) strlen (key), val) BSON_EXPORT (bool) bson_array_builder_append_time_t (bson_array_builder_t *bab, time_t value); @@ -1257,17 +1109,12 @@ bson_array_builder_append_time_t (bson_array_builder_t *bab, time_t value); * Returns: true if successful; false if append would overflow max size. */ BSON_EXPORT (bool) -bson_append_timeval (bson_t *bson, - const char *key, - int key_length, - struct timeval *value); +bson_append_timeval (bson_t *bson, const char *key, int key_length, struct timeval *value); -#define BSON_APPEND_TIMEVAL(b, key, val) \ - bson_append_timeval (b, key, (int) strlen (key), val) +#define BSON_APPEND_TIMEVAL(b, key, val) bson_append_timeval (b, key, (int) strlen (key), val) BSON_EXPORT (bool) -bson_array_builder_append_timeval (bson_array_builder_t *bab, - struct timeval *value); +bson_array_builder_append_timeval (bson_array_builder_t *bab, struct timeval *value); /** * bson_append_date_time: @@ -1281,13 +1128,9 @@ bson_array_builder_append_timeval (bson_array_builder_t *bab, * Returns: true if successful; otherwise false. */ BSON_EXPORT (bool) -bson_append_date_time (bson_t *bson, - const char *key, - int key_length, - int64_t value); +bson_append_date_time (bson_t *bson, const char *key, int key_length, int64_t value); -#define BSON_APPEND_DATE_TIME(b, key, val) \ - bson_append_date_time (b, key, (int) strlen (key), val) +#define BSON_APPEND_DATE_TIME(b, key, val) bson_append_date_time (b, key, (int) strlen (key), val) BSON_EXPORT (bool) bson_array_builder_append_date_time (bson_array_builder_t *bab, int64_t value); @@ -1306,8 +1149,7 @@ bson_array_builder_append_date_time (bson_array_builder_t *bab, int64_t value); BSON_EXPORT (bool) bson_append_now_utc (bson_t *bson, const char *key, int key_length); -#define BSON_APPEND_NOW_UTC(b, key) \ - bson_append_now_utc (b, key, (int) strlen (key)) +#define BSON_APPEND_NOW_UTC(b, key) bson_append_now_utc (b, key, (int) strlen (key)) BSON_EXPORT (bool) bson_array_builder_append_now_utc (bson_array_builder_t *bab); @@ -1329,19 +1171,12 @@ bson_array_builder_append_now_utc (bson_array_builder_t *bab); * Returns: true if successful; false if append would overflow max size. */ BSON_EXPORT (bool) -bson_append_timestamp (bson_t *bson, - const char *key, - int key_length, - uint32_t timestamp, - uint32_t increment); +bson_append_timestamp (bson_t *bson, const char *key, int key_length, uint32_t timestamp, uint32_t increment); -#define BSON_APPEND_TIMESTAMP(b, key, val, inc) \ - bson_append_timestamp (b, key, (int) strlen (key), val, inc) +#define BSON_APPEND_TIMESTAMP(b, key, val, inc) bson_append_timestamp (b, key, (int) strlen (key), val, inc) BSON_EXPORT (bool) -bson_array_builder_append_timestamp (bson_array_builder_t *bab, - uint32_t timestamp, - uint32_t increment); +bson_array_builder_append_timestamp (bson_array_builder_t *bab, uint32_t timestamp, uint32_t increment); /** * bson_append_undefined: @@ -1357,8 +1192,7 @@ bson_array_builder_append_timestamp (bson_array_builder_t *bab, BSON_EXPORT (bool) bson_append_undefined (bson_t *bson, const char *key, int key_length); -#define BSON_APPEND_UNDEFINED(b, key) \ - bson_append_undefined (b, key, (int) strlen (key)) +#define BSON_APPEND_UNDEFINED(b, key) bson_append_undefined (b, key, (int) strlen (key)) BSON_EXPORT (bool) bson_array_builder_append_undefined (bson_array_builder_t *bab); @@ -1367,24 +1201,19 @@ BSON_EXPORT (bool) bson_concat (bson_t *dst, const bson_t *src); BSON_EXPORT (bool) -bson_append_array_builder_begin (bson_t *bson, - const char *key, - int key_length, - bson_array_builder_t **child); +bson_append_array_builder_begin (bson_t *bson, const char *key, int key_length, bson_array_builder_t **child); #define BSON_APPEND_ARRAY_BUILDER_BEGIN(b, key, child) \ bson_append_array_builder_begin (b, key, (int) strlen (key), child) BSON_EXPORT (bool) -bson_array_builder_append_array_builder_begin (bson_array_builder_t *bab, - bson_array_builder_t **child); +bson_array_builder_append_array_builder_begin (bson_array_builder_t *bab, bson_array_builder_t **child); BSON_EXPORT (bool) bson_append_array_builder_end (bson_t *bson, bson_array_builder_t *child); BSON_EXPORT (bool) -bson_array_builder_append_array_builder_end (bson_array_builder_t *bab, - bson_array_builder_t *child); +bson_array_builder_append_array_builder_end (bson_array_builder_t *bab, bson_array_builder_t *child); BSON_END_DECLS diff --git a/src/libbson/tests/corpus-test.c b/src/libbson/tests/corpus-test.c index 0e34cf0946..7d814941d6 100644 --- a/src/libbson/tests/corpus-test.c +++ b/src/libbson/tests/corpus-test.c @@ -77,8 +77,7 @@ corpus_test (bson_t *scenario, BSON_ASSERT (bson_iter_init_find (&iter, scenario, "bson_type")); /* like "0x0C */ if (sscanf (bson_iter_utf8 (&iter, NULL), "%i", (int *) &bson_type) != 1) { - fprintf ( - stderr, "Couldn't parse bson_type %s\n", bson_iter_utf8 (&iter, NULL)); + fprintf (stderr, "Couldn't parse bson_type %s\n", bson_iter_utf8 (&iter, NULL)); abort (); } @@ -136,8 +135,7 @@ corpus_test (bson_t *scenario, BSON_ASSERT (bson_iter_recurse (&iter, &inner_iter)); while (bson_iter_next (&inner_iter)) { bson_iter_t test_iter; - test_bson_decode_error_type_t test = { - scenario_description, bson_type, NULL}; + test_bson_decode_error_type_t test = {scenario_description, bson_type, NULL}; BSON_ASSERT (bson_iter_recurse (&inner_iter, &test_iter)); while (bson_iter_next (&test_iter)) { @@ -163,8 +161,7 @@ corpus_test (bson_t *scenario, BSON_ASSERT (bson_iter_recurse (&iter, &inner_iter)); while (bson_iter_next (&inner_iter)) { bson_iter_t test_iter; - test_bson_parse_error_type_t test = { - scenario_description, bson_type, NULL}; + test_bson_parse_error_type_t test = {scenario_description, bson_type, NULL}; BSON_ASSERT (bson_iter_recurse (&inner_iter, &test_iter)); while (bson_iter_next (&test_iter)) { diff --git a/src/libbson/tests/test-atomic.c b/src/libbson/tests/test-atomic.c index 3f5d80332b..d8d93c3a4e 100644 --- a/src/libbson/tests/test-atomic.c +++ b/src/libbson/tests/test-atomic.c @@ -60,20 +60,14 @@ Assert (value, ==, 53); \ } while (0) -#define TEST_INTEGER_KIND(Kind, TypeName, Assert) \ - do { \ - TEST_KIND_WITH_MEMORDER ( \ - Kind, TypeName, bson_memory_order_relaxed, Assert); \ - TEST_KIND_WITH_MEMORDER ( \ - Kind, TypeName, bson_memory_order_acq_rel, Assert); \ - TEST_KIND_WITH_MEMORDER ( \ - Kind, TypeName, bson_memory_order_acquire, Assert); \ - TEST_KIND_WITH_MEMORDER ( \ - Kind, TypeName, bson_memory_order_release, Assert); \ - TEST_KIND_WITH_MEMORDER ( \ - Kind, TypeName, bson_memory_order_consume, Assert); \ - TEST_KIND_WITH_MEMORDER ( \ - Kind, TypeName, bson_memory_order_seq_cst, Assert); \ +#define TEST_INTEGER_KIND(Kind, TypeName, Assert) \ + do { \ + TEST_KIND_WITH_MEMORDER (Kind, TypeName, bson_memory_order_relaxed, Assert); \ + TEST_KIND_WITH_MEMORDER (Kind, TypeName, bson_memory_order_acq_rel, Assert); \ + TEST_KIND_WITH_MEMORDER (Kind, TypeName, bson_memory_order_acquire, Assert); \ + TEST_KIND_WITH_MEMORDER (Kind, TypeName, bson_memory_order_release, Assert); \ + TEST_KIND_WITH_MEMORDER (Kind, TypeName, bson_memory_order_consume, Assert); \ + TEST_KIND_WITH_MEMORDER (Kind, TypeName, bson_memory_order_seq_cst, Assert); \ } while (0) @@ -99,16 +93,13 @@ test_pointers (void) int *prev; other = bson_atomic_ptr_fetch ((void *) &ptr, bson_memory_order_relaxed); ASSERT_CMPVOID (other, ==, ptr); - prev = - bson_atomic_ptr_exchange ((void *) &other, &u, bson_memory_order_relaxed); + prev = bson_atomic_ptr_exchange ((void *) &other, &u, bson_memory_order_relaxed); ASSERT_CMPVOID (prev, ==, &v); ASSERT_CMPVOID (other, ==, &u); - prev = bson_atomic_ptr_compare_exchange_strong ( - (void *) &other, &v, &w, bson_memory_order_relaxed); + prev = bson_atomic_ptr_compare_exchange_strong ((void *) &other, &v, &w, bson_memory_order_relaxed); ASSERT_CMPVOID (prev, ==, &u); ASSERT_CMPVOID (other, ==, &u); - prev = bson_atomic_ptr_compare_exchange_strong ( - (void *) &other, &u, &w, bson_memory_order_relaxed); + prev = bson_atomic_ptr_compare_exchange_strong ((void *) &other, &u, &w, bson_memory_order_relaxed); ASSERT_CMPVOID (prev, ==, &u); ASSERT_CMPVOID (other, ==, &w); } diff --git a/src/libbson/tests/test-b64.c b/src/libbson/tests/test-b64.c index 4be8ecb96f..a8f9dbfb3d 100644 --- a/src/libbson/tests/test-b64.c +++ b/src/libbson/tests/test-b64.c @@ -20,10 +20,7 @@ #include "common-b64-private.h" static void -_test_encode_helper (char *input, - size_t input_len, - char *expected_output, - int expected_output_len) +_test_encode_helper (char *input, size_t input_len, char *expected_output, int expected_output_len) { char *output; size_t target_size; @@ -76,10 +73,7 @@ test_bson_b64_encode (void) } static void -_test_decode_helper (char *input, - char *expected_output, - int expected_calculated_target_size, - int expected_output_len) +_test_decode_helper (char *input, char *expected_output, int expected_calculated_target_size, int expected_output_len) { uint8_t *output; size_t target_size; diff --git a/src/libbson/tests/test-bcon-basic.c b/src/libbson/tests/test-bcon-basic.c index 7e9f3d135a..60a9deec8a 100644 --- a/src/libbson/tests/test-bcon-basic.c +++ b/src/libbson/tests/test-bcon-basic.c @@ -63,13 +63,9 @@ test_binary (void) bson_init (&bcon); bson_init (&expected); - bson_append_binary ( - &expected, "foo", -1, BSON_SUBTYPE_BINARY, (uint8_t *) "deadbeef", 8); + bson_append_binary (&expected, "foo", -1, BSON_SUBTYPE_BINARY, (uint8_t *) "deadbeef", 8); - BCON_APPEND (&bcon, - "foo", - BCON_BIN (BSON_SUBTYPE_BINARY, (const uint8_t *) "deadbeef", 8), - NULL); + BCON_APPEND (&bcon, "foo", BCON_BIN (BSON_SUBTYPE_BINARY, (const uint8_t *) "deadbeef", 8), NULL); bson_eq_bson (&bcon, &expected); @@ -484,19 +480,7 @@ test_inline_nested (void) bson_append_array (&foo, "bar", -1, &bar); bson_append_document (&expected, "foo", -1, &foo); - BCON_APPEND (&bcon, - "foo", - "{", - "bar", - "[", - BCON_INT32 (1), - BCON_INT32 (2), - "{", - "hello", - "world", - "}", - "]", - "}"); + BCON_APPEND (&bcon, "foo", "{", "bar", "[", BCON_INT32 (1), BCON_INT32 (2), "{", "hello", "world", "}", "]", "}"); bson_eq_bson (&bcon, &expected); @@ -618,8 +602,7 @@ test_append_ctx (void) bson_append_document (&expected, "a", -1, &child); - test_append_ctx_helper ( - &bcon, "a", "{", NULL, "add magic", "e", "f", "}", NULL); + test_append_ctx_helper (&bcon, "a", "{", NULL, "add magic", "e", "f", "}", NULL); bson_eq_bson (&bcon, &expected); diff --git a/src/libbson/tests/test-bcon-extract.c b/src/libbson/tests/test-bcon-extract.c index ddf111af0d..f69b541bc1 100644 --- a/src/libbson/tests/test-bcon-extract.c +++ b/src/libbson/tests/test-bcon-extract.c @@ -55,8 +55,7 @@ test_binary (void) uint32_t len; const uint8_t *binary; - bson_t *bcon = BCON_NEW ( - "foo", BCON_BIN (BSON_SUBTYPE_BINARY, (uint8_t *) "deadbeef", 8)); + bson_t *bcon = BCON_NEW ("foo", BCON_BIN (BSON_SUBTYPE_BINARY, (uint8_t *) "deadbeef", 8)); BSON_ASSERT (BCON_EXTRACT (bcon, "foo", BCONE_BIN (subtype, binary, len))); @@ -248,8 +247,7 @@ test_timestamp (void) bson_t *bcon = BCON_NEW ("foo", BCON_TIMESTAMP (100, 1000)); - BSON_ASSERT ( - BCON_EXTRACT (bcon, "foo", BCONE_TIMESTAMP (timestamp, increment))); + BSON_ASSERT (BCON_EXTRACT (bcon, "foo", BCONE_TIMESTAMP (timestamp, increment))); BSON_ASSERT (timestamp == 100); BSON_ASSERT (increment == 1000); @@ -336,8 +334,7 @@ test_inline_array (void) bson_t *bcon = BCON_NEW ("foo", "[", BCON_INT32 (1), BCON_INT32 (2), "]"); - BSON_ASSERT ( - BCON_EXTRACT (bcon, "foo", "[", BCONE_INT32 (a), BCONE_INT32 (b), "]")); + BSON_ASSERT (BCON_EXTRACT (bcon, "foo", "[", BCONE_INT32 (a), BCONE_INT32 (b), "]")); BSON_ASSERT (a == 1); BSON_ASSERT (b == 2); @@ -350,11 +347,9 @@ test_inline_doc (void) { int32_t a, b; - bson_t *bcon = - BCON_NEW ("foo", "{", "b", BCON_INT32 (2), "a", BCON_INT32 (1), "}"); + bson_t *bcon = BCON_NEW ("foo", "{", "b", BCON_INT32 (2), "a", BCON_INT32 (1), "}"); - BSON_ASSERT (BCON_EXTRACT ( - bcon, "foo", "{", "a", BCONE_INT32 (a), "b", BCONE_INT32 (b), "}")); + BSON_ASSERT (BCON_EXTRACT (bcon, "foo", "{", "a", BCONE_INT32 (a), "b", BCONE_INT32 (b), "}")); BSON_ASSERT (a == 1); BSON_ASSERT (b == 2); @@ -389,20 +384,10 @@ test_extract_ctx (void) { int32_t a, b, c; - bson_t *bson = - BCON_NEW ("a", BCON_INT32 (1), "b", BCON_INT32 (2), "c", BCON_INT32 (3)); - - test_extract_ctx_helper (bson, - 3, - "a", - BCONE_INT32 (a), - NULL, - "b", - BCONE_INT32 (b), - NULL, - "c", - BCONE_INT32 (c), - NULL); + bson_t *bson = BCON_NEW ("a", BCON_INT32 (1), "b", BCON_INT32 (2), "c", BCON_INT32 (3)); + + test_extract_ctx_helper ( + bson, 3, "a", BCONE_INT32 (a), NULL, "b", BCONE_INT32 (b), NULL, "c", BCONE_INT32 (c), NULL); BSON_ASSERT (a == 1); BSON_ASSERT (b == 2); @@ -418,17 +403,9 @@ test_nested (void) const char *utf8; int i32; - bson_t *bcon = - BCON_NEW ("hello", "world", "foo", "{", "bar", BCON_INT32 (10), "}"); + bson_t *bcon = BCON_NEW ("hello", "world", "foo", "{", "bar", BCON_INT32 (10), "}"); - BSON_ASSERT (BCON_EXTRACT (bcon, - "hello", - BCONE_UTF8 (utf8), - "foo", - "{", - "bar", - BCONE_INT32 (i32), - "}")); + BSON_ASSERT (BCON_EXTRACT (bcon, "hello", BCONE_UTF8 (utf8), "foo", "{", "bar", BCONE_INT32 (i32), "}")); BSON_ASSERT (strcmp ("world", utf8) == 0); BSON_ASSERT (i32 == 10); @@ -440,26 +417,13 @@ test_nested (void) static void test_skip (void) { - bson_t *bcon = - BCON_NEW ("hello", "world", "foo", "{", "bar", BCON_INT32 (10), "}"); - - BSON_ASSERT (BCON_EXTRACT (bcon, - "hello", - BCONE_SKIP (BSON_TYPE_UTF8), - "foo", - "{", - "bar", - BCONE_SKIP (BSON_TYPE_INT32), - "}")); - - BSON_ASSERT (!BCON_EXTRACT (bcon, - "hello", - BCONE_SKIP (BSON_TYPE_UTF8), - "foo", - "{", - "bar", - BCONE_SKIP (BSON_TYPE_INT64), - "}")); + bson_t *bcon = BCON_NEW ("hello", "world", "foo", "{", "bar", BCON_INT32 (10), "}"); + + BSON_ASSERT ( + BCON_EXTRACT (bcon, "hello", BCONE_SKIP (BSON_TYPE_UTF8), "foo", "{", "bar", BCONE_SKIP (BSON_TYPE_INT32), "}")); + + BSON_ASSERT ( + !BCON_EXTRACT (bcon, "hello", BCONE_SKIP (BSON_TYPE_UTF8), "foo", "{", "bar", BCONE_SKIP (BSON_TYPE_INT64), "}")); bson_destroy (bcon); } @@ -509,14 +473,11 @@ test_bcon_extract_install (TestSuite *suite) TestSuite_Add (suite, "/bson/bcon/extract/test_int64", test_int64); TestSuite_Add (suite, "/bson/bcon/extract/test_maxkey", test_maxkey); TestSuite_Add (suite, "/bson/bcon/extract/test_minkey", test_minkey); - TestSuite_Add ( - suite, "/bson/bcon/extract/test_bson_document", test_bson_document); + TestSuite_Add (suite, "/bson/bcon/extract/test_bson_document", test_bson_document); TestSuite_Add (suite, "/bson/bcon/extract/test_bson_array", test_bson_array); - TestSuite_Add ( - suite, "/bson/bcon/extract/test_inline_array", test_inline_array); + TestSuite_Add (suite, "/bson/bcon/extract/test_inline_array", test_inline_array); TestSuite_Add (suite, "/bson/bcon/extract/test_inline_doc", test_inline_doc); - TestSuite_Add ( - suite, "/bson/bcon/extract/test_extract_ctx", test_extract_ctx); + TestSuite_Add (suite, "/bson/bcon/extract/test_extract_ctx", test_extract_ctx); TestSuite_Add (suite, "/bson/bcon/extract/test_nested", test_nested); TestSuite_Add (suite, "/bson/bcon/extract/test_skip", test_skip); TestSuite_Add (suite, "/bson/bcon/extract/test_iter", test_iter); diff --git a/src/libbson/tests/test-bson-cmp.c b/src/libbson/tests/test-bson-cmp.c index fd922305d3..7322da5f43 100644 --- a/src/libbson/tests/test-bson-cmp.c +++ b/src/libbson/tests/test-bson-cmp.c @@ -303,7 +303,6 @@ test_bson_cmp_install (TestSuite *suite) TestSuite_Add (suite, "/bson/cmp/less", test_bson_cmp_less); TestSuite_Add (suite, "/bson/cmp/greater", test_bson_cmp_greater); TestSuite_Add (suite, "/bson/cmp/less_equal", test_bson_cmp_less_equal); - TestSuite_Add ( - suite, "/bson/cmp/greater_equal", test_bson_cmp_greater_equal); + TestSuite_Add (suite, "/bson/cmp/greater_equal", test_bson_cmp_greater_equal); TestSuite_Add (suite, "/bson/cmp/in_range", test_bson_in_range); } diff --git a/src/libbson/tests/test-bson-corpus.c b/src/libbson/tests/test-bson-corpus.c index c6d42c5961..ce94927d18 100644 --- a/src/libbson/tests/test-bson-corpus.c +++ b/src/libbson/tests/test-bson-corpus.c @@ -15,8 +15,7 @@ typedef struct { skipped_corpus_test_t SKIPPED_CORPUS_TESTS[] = { /* CDRIVER-1879, can't make Code with embedded NIL */ {"Javascript Code", "Embedded nulls"}, - {"Javascript Code with Scope", - "Unicode and embedded null in code string, empty scope"}, + {"Javascript Code with Scope", "Unicode and embedded null in code string, empty scope"}, /* CDRIVER-2223, legacy extended JSON $date syntax uses numbers */ {"Top-level document validity", "Bad $date (number, not string or hash)"}, /* CDRIVER-3500, floating point output differs */ @@ -38,10 +37,7 @@ skipped_corpus_test_t VS2013_SKIPPED_CORPUS_TESTS[] = { static void -compare_data (const uint8_t *a, - uint32_t a_len, - const uint8_t *b, - uint32_t b_len) +compare_data (const uint8_t *a, uint32_t a_len, const uint8_t *b, uint32_t b_len) { bson_string_t *a_str; bson_string_t *b_str; @@ -58,12 +54,7 @@ compare_data (const uint8_t *a, bson_string_append_printf (b_str, "%02X", (int) b[i]); } - fprintf (stderr, - "unequal data of length %d and %d:\n%s\n%s\n", - a_len, - b_len, - a_str->str, - b_str->str); + fprintf (stderr, "unequal data of length %d and %d:\n%s\n%s\n", a_len, b_len, a_str->str, b_str->str); abort (); } @@ -76,8 +67,7 @@ is_test_skipped (const char *scenario, const char *description) skipped_corpus_test_t *skip; for (skip = SKIPPED_CORPUS_TESTS; skip->scenario != NULL; skip++) { - if (!strcmp (skip->scenario, scenario) && - !strcmp (skip->test, description)) { + if (!strcmp (skip->scenario, scenario) && !strcmp (skip->test, description)) { return true; } } @@ -85,8 +75,7 @@ is_test_skipped (const char *scenario, const char *description) /* _MSC_VER 1900 is Visual Studio 2015 */ #if (defined(_MSC_VER) && _MSC_VER < 1900) for (skip = VS2013_SKIPPED_CORPUS_TESTS; skip->scenario != NULL; skip++) { - if (!strcmp (skip->scenario, scenario) && - !strcmp (skip->test, description)) { + if (!strcmp (skip->scenario, scenario) && !strcmp (skip->test, description)) { return true; } } @@ -153,8 +142,7 @@ test_bson_corpus_valid (test_bson_valid_type_t *test) ASSERT_OR_PRINT (decode_cE, error); if (!test->lossy) { - compare_data ( - bson_get_data (decode_cE), decode_cE->len, test->cB, test->cB_len); + compare_data (bson_get_data (decode_cE), decode_cE->len, test->cB, test->cB_len); } if (test->dB) { @@ -172,12 +160,10 @@ test_bson_corpus_valid (test_bson_valid_type_t *test) decode_dE = bson_new_from_json ((const uint8_t *) test->dE, -1, &error); ASSERT_OR_PRINT (decode_dE, error); - ASSERT_CMPJSON (bson_as_canonical_extended_json (decode_dE, NULL), - test->cE); + ASSERT_CMPJSON (bson_as_canonical_extended_json (decode_dE, NULL), test->cE); if (!test->lossy) { - compare_data ( - bson_get_data (decode_dE), decode_dE->len, test->cB, test->cB_len); + compare_data (bson_get_data (decode_dE), decode_dE->len, test->cB, test->cB_len); } bson_destroy (decode_dE); @@ -187,8 +173,7 @@ test_bson_corpus_valid (test_bson_valid_type_t *test) decode_rE = bson_new_from_json ((const uint8_t *) test->rE, -1, &error); ASSERT_OR_PRINT (decode_rE, error); - ASSERT_CMPJSON (bson_as_relaxed_extended_json (decode_rE, NULL), - test->rE); + ASSERT_CMPJSON (bson_as_relaxed_extended_json (decode_rE, NULL), test->rE); bson_destroy (decode_rE); } @@ -220,8 +205,7 @@ test_bson_corpus_decode_error (test_bson_decode_error_type_t *test) } ASSERT (test->bson); - ASSERT (!bson_init_static (&invalid_bson, test->bson, test->bson_len) || - bson_empty (&invalid_bson) || + ASSERT (!bson_init_static (&invalid_bson, test->bson, test->bson_len) || bson_empty (&invalid_bson) || !bson_as_canonical_extended_json (&invalid_bson, NULL)); } @@ -285,10 +269,7 @@ test_bson_corpus_parse_error (test_bson_parse_error_type_t *test) static void test_bson_corpus_cb (bson_t *scenario) { - corpus_test (scenario, - test_bson_corpus_valid, - test_bson_corpus_decode_error, - test_bson_corpus_parse_error); + corpus_test (scenario, test_bson_corpus_valid, test_bson_corpus_decode_error, test_bson_corpus_parse_error); } static void @@ -325,7 +306,6 @@ test_bson_corpus_prose_1 (void) void test_bson_corpus_install (TestSuite *suite) { - install_json_test_suite_with_check ( - suite, BSON_JSON_DIR, "bson_corpus", test_bson_corpus_cb); + install_json_test_suite_with_check (suite, BSON_JSON_DIR, "bson_corpus", test_bson_corpus_cb); TestSuite_Add (suite, "/bson_corpus/prose_1", test_bson_corpus_prose_1); } diff --git a/src/libbson/tests/test-bson-version.c b/src/libbson/tests/test-bson-version.c index 9ea90d8205..43fef600ac 100644 --- a/src/libbson/tests/test-bson-version.c +++ b/src/libbson/tests/test-bson-version.c @@ -10,11 +10,9 @@ test_bson_version (void) ASSERT_CMPINT (bson_get_micro_version (), ==, BSON_MICRO_VERSION); ASSERT_CMPSTR (bson_get_version (), BSON_VERSION_S); - ASSERT (bson_check_version ( - BSON_MAJOR_VERSION, BSON_MINOR_VERSION, BSON_MICRO_VERSION)); + ASSERT (bson_check_version (BSON_MAJOR_VERSION, BSON_MINOR_VERSION, BSON_MICRO_VERSION)); - ASSERT (!bson_check_version ( - BSON_MAJOR_VERSION, BSON_MINOR_VERSION + 1, BSON_MICRO_VERSION)); + ASSERT (!bson_check_version (BSON_MAJOR_VERSION, BSON_MINOR_VERSION + 1, BSON_MICRO_VERSION)); } void diff --git a/src/libbson/tests/test-bson.c b/src/libbson/tests/test-bson.c index 58530c02b7..832d8c4481 100644 --- a/src/libbson/tests/test-bson.c +++ b/src/libbson/tests/test-bson.c @@ -39,8 +39,7 @@ get_bson (const char *filename) char real_filename[256]; int fd; - bson_snprintf ( - real_filename, sizeof real_filename, BSON_BINARY_DIR "/%s", filename); + bson_snprintf (real_filename, sizeof real_filename, BSON_BINARY_DIR "/%s", filename); real_filename[sizeof real_filename - 1] = '\0'; @@ -135,13 +134,7 @@ BSON_ASSERT_BSON_EQUAL (const bson_t *a, const bson_t *b) abort (); } if (data1[i] != data2[i]) { - printf ("a[%u](0x%02x,%u) != b[%u](0x%02x,%u)\n", - i, - data1[i], - data1[i], - i, - data2[i], - data2[i]); + printf ("a[%u](0x%02x,%u) != b[%u](0x%02x,%u)\n", i, data1[i], data1[i], i, data2[i], data2[i]); abort (); } } @@ -295,8 +288,7 @@ test_bson_append_binary (void) bson_t *b2; b = bson_new (); - BSON_ASSERT ( - bson_append_binary (b, "binary", -1, BSON_SUBTYPE_USER, binary, 4)); + BSON_ASSERT (bson_append_binary (b, "binary", -1, BSON_SUBTYPE_USER, binary, 4)); b2 = get_bson ("test24.bson"); BSON_ASSERT_BSON_EQUAL (b, b2); bson_destroy (b); @@ -312,8 +304,7 @@ test_bson_append_binary_deprecated (void) bson_t *b2; b = bson_new (); - BSON_ASSERT (bson_append_binary ( - b, "binary", -1, BSON_SUBTYPE_BINARY_DEPRECATED, binary, 4)); + BSON_ASSERT (bson_append_binary (b, "binary", -1, BSON_SUBTYPE_BINARY_DEPRECATED, binary, 4)); b2 = get_bson ("binary_deprecated.bson"); BSON_ASSERT_BSON_EQUAL (b, b2); bson_destroy (b); @@ -409,8 +400,7 @@ test_bson_append_regex_w_len (void) bson_destroy (b2); b = bson_new (); - BSON_ASSERT ( - bson_append_regex_w_len (b, "regex", -1, "^abcd ", 5, "ilx")); + BSON_ASSERT (bson_append_regex_w_len (b, "regex", -1, "^abcd ", 5, "ilx")); b2 = get_bson ("test27.bson"); BSON_ASSERT_BSON_EQUAL (b, b2); bson_destroy (b); @@ -478,8 +468,7 @@ test_bson_append_code_with_scope (void) /* Test with NULL bson, which converts to just CODE type. */ b = bson_new (); - BSON_ASSERT ( - bson_append_code_with_scope (b, "code", -1, "var a = {};", NULL)); + BSON_ASSERT (bson_append_code_with_scope (b, "code", -1, "var a = {};", NULL)); b2 = get_bson ("test30.bson"); BSON_ASSERT_BSON_EQUAL (b, b2); r = bson_iter_init_find (&iter, b, "code"); @@ -491,8 +480,7 @@ test_bson_append_code_with_scope (void) /* Empty scope is still CODEWSCOPE. */ b = bson_new (); scope = bson_new (); - BSON_ASSERT ( - bson_append_code_with_scope (b, "code", -1, "var a = {};", scope)); + BSON_ASSERT (bson_append_code_with_scope (b, "code", -1, "var a = {};", scope)); b2 = get_bson ("code_w_empty_scope.bson"); BSON_ASSERT_BSON_EQUAL (b, b2); r = bson_iter_init_find (&iter, b, "code"); @@ -506,8 +494,7 @@ test_bson_append_code_with_scope (void) b = bson_new (); scope = bson_new (); BSON_ASSERT (bson_append_utf8 (scope, "foo", -1, "bar", -1)); - BSON_ASSERT ( - bson_append_code_with_scope (b, "code", -1, "var a = {};", scope)); + BSON_ASSERT (bson_append_code_with_scope (b, "code", -1, "var a = {};", scope)); b2 = get_bson ("test31.bson"); BSON_ASSERT_BSON_EQUAL (b, b2); r = bson_iter_init_find (&iter, b, "code"); @@ -530,8 +517,7 @@ test_bson_append_code_with_scope (void) bson_destroy (b); /* CDRIVER-2269 Test with malformed BSON from ticket */ - reader = - bson_reader_new_from_file (BSON_BINARY_DIR "/cdriver2269.bson", &err); + reader = bson_reader_new_from_file (BSON_BINARY_DIR "/cdriver2269.bson", &err); BSON_ASSERT (reader); ticket_bson = bson_reader_read (reader, &eof); @@ -1154,11 +1140,8 @@ test_bson_validate (void) bson_destroy (b); b = get_bson ("empty_key.bson"); - BSON_ASSERT (bson_validate (b, - BSON_VALIDATE_NONE | BSON_VALIDATE_UTF8 | - BSON_VALIDATE_DOLLAR_KEYS | - BSON_VALIDATE_DOT_KEYS, - &offset)); + BSON_ASSERT (bson_validate ( + b, BSON_VALIDATE_NONE | BSON_VALIDATE_UTF8 | BSON_VALIDATE_DOLLAR_KEYS | BSON_VALIDATE_DOT_KEYS, &offset)); bson_destroy (b); #define VALIDATE_TEST(_filename, _flags, _offset, _flag, _msg) \ @@ -1169,16 +1152,8 @@ test_bson_validate (void) ASSERT_ERROR_CONTAINS (error, BSON_ERROR_INVALID, _flag, _msg); \ bson_destroy (b) - VALIDATE_TEST ("overflow2.bson", - BSON_VALIDATE_NONE, - 9, - BSON_VALIDATE_NONE, - "corrupt BSON"); - VALIDATE_TEST ("trailingnull.bson", - BSON_VALIDATE_NONE, - 14, - BSON_VALIDATE_NONE, - "corrupt BSON"); + VALIDATE_TEST ("overflow2.bson", BSON_VALIDATE_NONE, 9, BSON_VALIDATE_NONE, "corrupt BSON"); + VALIDATE_TEST ("trailingnull.bson", BSON_VALIDATE_NONE, 14, BSON_VALIDATE_NONE, "corrupt BSON"); VALIDATE_TEST ("dollarquery.bson", BSON_VALIDATE_DOLLAR_KEYS | BSON_VALIDATE_DOT_KEYS, 4, @@ -1189,127 +1164,57 @@ test_bson_validate (void) 4, BSON_VALIDATE_DOT_KEYS, "keys cannot contain \".\": \"abc.def\""); - VALIDATE_TEST ("overflow3.bson", - BSON_VALIDATE_NONE, - 9, - BSON_VALIDATE_NONE, - "corrupt BSON"); + VALIDATE_TEST ("overflow3.bson", BSON_VALIDATE_NONE, 9, BSON_VALIDATE_NONE, "corrupt BSON"); /* same outcome as above, despite different flags */ - VALIDATE_TEST ("overflow3.bson", - BSON_VALIDATE_UTF8, - 9, - BSON_VALIDATE_NONE, - "corrupt BSON"); - VALIDATE_TEST ("overflow4.bson", - BSON_VALIDATE_NONE, - 9, - BSON_VALIDATE_NONE, - "corrupt BSON"); - VALIDATE_TEST ("empty_key.bson", - BSON_VALIDATE_EMPTY_KEYS, - 4, - BSON_VALIDATE_EMPTY_KEYS, - "empty key"); - VALIDATE_TEST ( - "test40.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON"); - VALIDATE_TEST ( - "test41.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON"); - VALIDATE_TEST ( - "test42.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON"); - VALIDATE_TEST ( - "test43.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON"); - VALIDATE_TEST ( - "test44.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON"); - VALIDATE_TEST ( - "test45.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON"); - VALIDATE_TEST ( - "test46.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON"); - VALIDATE_TEST ( - "test47.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON"); - VALIDATE_TEST ( - "test48.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON"); - VALIDATE_TEST ( - "test49.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON"); - VALIDATE_TEST ("test50.bson", - BSON_VALIDATE_NONE, - 10, - BSON_VALIDATE_NONE, - "corrupt code-with-scope"); - VALIDATE_TEST ("test51.bson", - BSON_VALIDATE_NONE, - 10, - BSON_VALIDATE_NONE, - "corrupt code-with-scope"); - VALIDATE_TEST ( - "test52.bson", BSON_VALIDATE_NONE, 9, BSON_VALIDATE_NONE, "corrupt BSON"); - VALIDATE_TEST ( - "test53.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON"); - VALIDATE_TEST ("test54.bson", - BSON_VALIDATE_NONE, - 12, - BSON_VALIDATE_NONE, - "corrupt BSON"); - VALIDATE_TEST ( - "test59.bson", BSON_VALIDATE_NONE, 9, BSON_VALIDATE_NONE, "corrupt BSON"); + VALIDATE_TEST ("overflow3.bson", BSON_VALIDATE_UTF8, 9, BSON_VALIDATE_NONE, "corrupt BSON"); + VALIDATE_TEST ("overflow4.bson", BSON_VALIDATE_NONE, 9, BSON_VALIDATE_NONE, "corrupt BSON"); + VALIDATE_TEST ("empty_key.bson", BSON_VALIDATE_EMPTY_KEYS, 4, BSON_VALIDATE_EMPTY_KEYS, "empty key"); + VALIDATE_TEST ("test40.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON"); + VALIDATE_TEST ("test41.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON"); + VALIDATE_TEST ("test42.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON"); + VALIDATE_TEST ("test43.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON"); + VALIDATE_TEST ("test44.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON"); + VALIDATE_TEST ("test45.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON"); + VALIDATE_TEST ("test46.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON"); + VALIDATE_TEST ("test47.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON"); + VALIDATE_TEST ("test48.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON"); + VALIDATE_TEST ("test49.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON"); + VALIDATE_TEST ("test50.bson", BSON_VALIDATE_NONE, 10, BSON_VALIDATE_NONE, "corrupt code-with-scope"); + VALIDATE_TEST ("test51.bson", BSON_VALIDATE_NONE, 10, BSON_VALIDATE_NONE, "corrupt code-with-scope"); + VALIDATE_TEST ("test52.bson", BSON_VALIDATE_NONE, 9, BSON_VALIDATE_NONE, "corrupt BSON"); + VALIDATE_TEST ("test53.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON"); + VALIDATE_TEST ("test54.bson", BSON_VALIDATE_NONE, 12, BSON_VALIDATE_NONE, "corrupt BSON"); + VALIDATE_TEST ("test59.bson", BSON_VALIDATE_NONE, 9, BSON_VALIDATE_NONE, "corrupt BSON"); /* DBRef validation */ - b = BCON_NEW ("my_dbref", - "{", - "$ref", - BCON_UTF8 ("collection"), - "$id", - BCON_INT32 (1), - "}"); + b = BCON_NEW ("my_dbref", "{", "$ref", BCON_UTF8 ("collection"), "$id", BCON_INT32 (1), "}"); BSON_ASSERT (bson_validate_with_error (b, BSON_VALIDATE_NONE, &error)); - BSON_ASSERT ( - bson_validate_with_error (b, BSON_VALIDATE_DOLLAR_KEYS, &error)); + BSON_ASSERT (bson_validate_with_error (b, BSON_VALIDATE_DOLLAR_KEYS, &error)); bson_destroy (b); /* needs "$ref" before "$id" */ b = BCON_NEW ("my_dbref", "{", "$id", BCON_INT32 (1), "}"); BSON_ASSERT (bson_validate_with_error (b, BSON_VALIDATE_NONE, &error)); - BSON_ASSERT ( - !bson_validate_with_error (b, BSON_VALIDATE_DOLLAR_KEYS, &error)); - ASSERT_ERROR_CONTAINS (error, - BSON_ERROR_INVALID, - BSON_VALIDATE_DOLLAR_KEYS, - "keys cannot begin with \"$\": \"$id\""); + BSON_ASSERT (!bson_validate_with_error (b, BSON_VALIDATE_DOLLAR_KEYS, &error)); + ASSERT_ERROR_CONTAINS ( + error, BSON_ERROR_INVALID, BSON_VALIDATE_DOLLAR_KEYS, "keys cannot begin with \"$\": \"$id\""); bson_destroy (b); /* two $refs */ - b = BCON_NEW ("my_dbref", - "{", - "$ref", - BCON_UTF8 ("collection"), - "$ref", - BCON_UTF8 ("collection"), - "}"); + b = BCON_NEW ("my_dbref", "{", "$ref", BCON_UTF8 ("collection"), "$ref", BCON_UTF8 ("collection"), "}"); BSON_ASSERT (bson_validate_with_error (b, BSON_VALIDATE_NONE, &error)); - BSON_ASSERT ( - !bson_validate_with_error (b, BSON_VALIDATE_DOLLAR_KEYS, &error)); - ASSERT_ERROR_CONTAINS (error, - BSON_ERROR_INVALID, - BSON_VALIDATE_DOLLAR_KEYS, - "keys cannot begin with \"$\": \"$ref\""); + BSON_ASSERT (!bson_validate_with_error (b, BSON_VALIDATE_DOLLAR_KEYS, &error)); + ASSERT_ERROR_CONTAINS ( + error, BSON_ERROR_INVALID, BSON_VALIDATE_DOLLAR_KEYS, "keys cannot begin with \"$\": \"$ref\""); bson_destroy (b); /* must not contain invalid key like "extra" */ - b = BCON_NEW ("my_dbref", - "{", - "$ref", - BCON_UTF8 ("collection"), - "extra", - BCON_INT32 (2), - "$id", - BCON_INT32 (1), - "}"); + b = + BCON_NEW ("my_dbref", "{", "$ref", BCON_UTF8 ("collection"), "extra", BCON_INT32 (2), "$id", BCON_INT32 (1), "}"); BSON_ASSERT (bson_validate_with_error (b, BSON_VALIDATE_NONE, &error)); - BSON_ASSERT ( - !bson_validate_with_error (b, BSON_VALIDATE_DOLLAR_KEYS, &error)); - ASSERT_ERROR_CONTAINS (error, - BSON_ERROR_INVALID, - BSON_VALIDATE_DOLLAR_KEYS, - "invalid key within DBRef subdocument: \"extra\""); + BSON_ASSERT (!bson_validate_with_error (b, BSON_VALIDATE_DOLLAR_KEYS, &error)); + ASSERT_ERROR_CONTAINS ( + error, BSON_ERROR_INVALID, BSON_VALIDATE_DOLLAR_KEYS, "invalid key within DBRef subdocument: \"extra\""); bson_destroy (b); #undef VALIDATE_TEST @@ -2149,10 +2054,7 @@ typedef struct { void -visit_unsupported_type (const bson_iter_t *iter, - const char *key, - uint32_t type_code, - void *data) +visit_unsupported_type (const bson_iter_t *iter, const char *key, uint32_t type_code, void *data) { unsupported_type_test_data_t *context; @@ -2255,16 +2157,13 @@ test_bson_subtype_2 (void) BSON_ASSERT (bson_validate (&b, BSON_VALIDATE_NONE, 0)); BSON_ASSERT (0 == bson_compare (&b, bson_ok)); - BSON_ASSERT (bson_init_static ( - &b, (uint8_t *) len_too_long, sizeof (len_too_long) - 1)); + BSON_ASSERT (bson_init_static (&b, (uint8_t *) len_too_long, sizeof (len_too_long) - 1)); BSON_ASSERT (!bson_validate (&b, BSON_VALIDATE_NONE, 0)); - BSON_ASSERT (bson_init_static ( - &b, (uint8_t *) len_too_short, sizeof (len_too_short) - 1)); + BSON_ASSERT (bson_init_static (&b, (uint8_t *) len_too_short, sizeof (len_too_short) - 1)); BSON_ASSERT (!bson_validate (&b, BSON_VALIDATE_NONE, 0)); - BSON_ASSERT (bson_init_static ( - &b, (uint8_t *) len_negative, sizeof (len_negative) - 1)); + BSON_ASSERT (bson_init_static (&b, (uint8_t *) len_negative, sizeof (len_negative) - 1)); BSON_ASSERT (!bson_validate (&b, BSON_VALIDATE_NONE, 0)); bson_destroy (bson_ok); @@ -2280,11 +2179,8 @@ test_bson_regex_lengths (void) bson_oid_init_from_string (&oid, "1234567890abcdef12345678"); bson_append_oid (&new, "0123456", -1, &oid); - bson_append_regex (&new, - "0_________1_________2_________3___4", - -1, - "0_________1_________2_________3_________4_________5___4", - "i"); + bson_append_regex ( + &new, "0_________1_________2_________3___4", -1, "0_________1_________2_________3_________4_________5___4", "i"); ASSERT (new.len == 121); ASSERT (new.flags &BSON_FLAG_STATIC); @@ -2321,8 +2217,7 @@ test_bson_iter_key_len (void) BSON_ASSERT (bson_iter_init (&iter, bson)); while (bson_iter_next (&iter)) { - ASSERT_WITH_MSG (strlen (bson_iter_key (&iter)) == - bson_iter_key_len (&iter), + ASSERT_WITH_MSG (strlen (bson_iter_key (&iter)) == bson_iter_key_len (&iter), "iter_key_len differs from real key length. got %d but " "expected %d for key %s\n", bson_iter_key_len (&iter), @@ -2347,14 +2242,11 @@ test_bson_iter_init_from_data_at_offset (void) uint32_t offset = bson_iter_offset (&iter); bson_iter_t recreated = {0}; - BSON_ASSERT (bson_iter_init_from_data_at_offset ( - &recreated, data, bson->len, offset, keylen)); - if (memcmp ((void *) &iter, (void *) &recreated, sizeof (bson_iter_t)) != - 0) { + BSON_ASSERT (bson_iter_init_from_data_at_offset (&recreated, data, bson->len, offset, keylen)); + if (memcmp ((void *) &iter, (void *) &recreated, sizeof (bson_iter_t)) != 0) { int i; bson_iter_t *iters[] = {&iter, &recreated}; - fprintf (stderr, - "recreated iterator does not match initial iterator:\n"); + fprintf (stderr, "recreated iterator does not match initial iterator:\n"); for (i = 0; i < 2; i++) { fprintf (stderr, "iter %d: ", i); fprintf (stderr, @@ -2436,11 +2328,10 @@ _binary_null_handling (bool is_legacy) _check_null_binary (bson, is_legacy); bson_destroy (bson); - bson = bson_new_from_json ( - (uint8_t *) "{\"binary\": { \"$binary\": { \"subType\": \"00\", " - "\"base64\": \"\" } } }", - -1, - &error); + bson = bson_new_from_json ((uint8_t *) "{\"binary\": { \"$binary\": { \"subType\": \"00\", " + "\"base64\": \"\" } } }", + -1, + &error); ASSERT_OR_PRINT (bson, error); _check_null_binary (bson, is_legacy); bson_destroy (bson); @@ -2475,34 +2366,30 @@ test_bson_as_json_string (void) { bson_t *all_types; char *actual; - const char *expected = - "{ \"double\" : { \"$numberDouble\" : \"1.0\" }, \"string\" : " - "\"string_example\", \"document\" : { \"x\" : \"y\" }, \"document\" : [ " - "\"x\" ], \"binary\" : { \"$binary\" : { \"base64\" : \"ZGF0YQ==\", " - "\"subType\" : \"00\" } }, \"undefined\" : { \"$undefined\" : true }, " - "\"oid\" : { \"$oid\" : \"000000000000000000000000\" }, \"bool\" : true, " - "\"datetime\" : { \"$date\" : { \"$numberLong\" : \"123\" } }, \"null\" " - ": null, \"regex\" : { \"$regularExpression\" : { \"pattern\" : \"a+\", " - "\"options\" : \"\" } }, \"dbpointer\" : { \"$dbPointer\" : { \"$ref\" : " - "\"collection\", \"$id\" : { \"$oid\" : \"000000000000000000000000\" } } " - "}, \"code\" : { \"$code\" : \"var x = 1;\" }, \"symbol\" : { " - "\"$symbol\" : \"symbol_example\" }, \"code\" : { \"$code\" : \"var x = " - "1;\" }, \"code_w_scope\" : { \"$code\" : \"var x = 1;\", \"$scope\" : { " - "} }, \"int32\" : { \"$numberInt\" : \"1\" }, \"timestamp\" : { " - "\"$timestamp\" : { \"t\" : 2, \"i\" : 3 } }, \"int64\" : { " - "\"$numberLong\" : \"4\" }, \"decimal128\" : { \"$numberDecimal\" : " - "\"1.23456789\" }, \"minkey\" : { \"$minKey\" : 1 }, \"maxkey\" : { " - "\"$maxKey\" : 1 }, \"\" : { \"$numberInt\" : \"-1\" } }"; + const char *expected = "{ \"double\" : { \"$numberDouble\" : \"1.0\" }, \"string\" : " + "\"string_example\", \"document\" : { \"x\" : \"y\" }, \"document\" : [ " + "\"x\" ], \"binary\" : { \"$binary\" : { \"base64\" : \"ZGF0YQ==\", " + "\"subType\" : \"00\" } }, \"undefined\" : { \"$undefined\" : true }, " + "\"oid\" : { \"$oid\" : \"000000000000000000000000\" }, \"bool\" : true, " + "\"datetime\" : { \"$date\" : { \"$numberLong\" : \"123\" } }, \"null\" " + ": null, \"regex\" : { \"$regularExpression\" : { \"pattern\" : \"a+\", " + "\"options\" : \"\" } }, \"dbpointer\" : { \"$dbPointer\" : { \"$ref\" : " + "\"collection\", \"$id\" : { \"$oid\" : \"000000000000000000000000\" } } " + "}, \"code\" : { \"$code\" : \"var x = 1;\" }, \"symbol\" : { " + "\"$symbol\" : \"symbol_example\" }, \"code\" : { \"$code\" : \"var x = " + "1;\" }, \"code_w_scope\" : { \"$code\" : \"var x = 1;\", \"$scope\" : { " + "} }, \"int32\" : { \"$numberInt\" : \"1\" }, \"timestamp\" : { " + "\"$timestamp\" : { \"t\" : 2, \"i\" : 3 } }, \"int64\" : { " + "\"$numberLong\" : \"4\" }, \"decimal128\" : { \"$numberDecimal\" : " + "\"1.23456789\" }, \"minkey\" : { \"$minKey\" : 1 }, \"maxkey\" : { " + "\"$maxKey\" : 1 }, \"\" : { \"$numberInt\" : \"-1\" } }"; all_types = bson_with_all_types (); actual = bson_as_canonical_extended_json (all_types, NULL); for (size_t i = 0u; i < strlen (expected); i++) { if (expected[i] != actual[i]) { - test_error ("character mismatch at %zu. Expected: %s, got %s", - i, - expected, - actual); + test_error ("character mismatch at %zu. Expected: %s, got %s", i, expected, actual); } } @@ -2544,9 +2431,7 @@ test_bson_dsl_parse (void) // We can fail to find too found = false; bool not_found = false; - bsonParse (*simple_foo_bar, - find (key ("bad"), do (found = true)), - else (do (not_found = true))); + bsonParse (*simple_foo_bar, find (key ("bad"), do (found = true)), else (do (not_found = true))); BSON_ASSERT (!found); BSON_ASSERT (not_found); @@ -2561,8 +2446,7 @@ test_bson_dsl_parse (void) // Wrong types are zeroed a = 91; found = false; - bsonParse (*TMP_BSON_FROM_JSON ({"foo" : "string"}), - find (key ("foo"), do (found = true; a = bsonAs (int32)))); + bsonParse (*TMP_BSON_FROM_JSON ({"foo" : "string"}), find (key ("foo"), do (found = true; a = bsonAs (int32)))); BSON_ASSERT (found); ASSERT_CMPINT (a, ==, 0); @@ -2627,8 +2511,7 @@ test_bson_dsl_visit (void) // Store reference to subdocs bson_t subdoc; - bsonVisitEach (*TMP_BSON_FROM_JSON ({"foo" : {"bar" : 42}}), - storeDocRef (subdoc)); + bsonVisitEach (*TMP_BSON_FROM_JSON ({"foo" : {"bar" : 42}}), storeDocRef (subdoc)); bar_val = 0; bsonVisitEach (subdoc, do (bar_val = bsonAs (int32))); ASSERT_CMPINT (bar_val, ==, 42); @@ -2636,9 +2519,8 @@ test_bson_dsl_visit (void) // Visit subdocs directly const char *baz_str = NULL; char *path = NULL; - bsonVisitEach ( - *TMP_BSON_FROM_JSON ({"foo" : {"bar" : {"baz" : "baz_string"}}}), - visitEach (visitEach (storeStrRef (baz_str), dupPath (path)))); + bsonVisitEach (*TMP_BSON_FROM_JSON ({"foo" : {"bar" : {"baz" : "baz_string"}}}), + visitEach (visitEach (storeStrRef (baz_str), dupPath (path)))); ASSERT_CMPSTR (baz_str, "baz_string"); ASSERT_CMPSTR (path, "$.foo.bar.baz"); bson_free (path); @@ -2687,34 +2569,27 @@ test_bson_dsl_predicate (void) require (key ("empty_string"), require (type (utf8))), require (key ("empty_array"), require (type (array)), require (empty)), require (key ("empty_doc"), require (type (doc)), require (empty)), - require ( - key ("with_last"), - require (type (doc)), - visitEach (if (lastElement, - then (require (key ("b")), require (type (utf8))), - else (require (key ("a")), require (type (null)))))), - require ( - key ("with_last"), - visitEach (case (when (key ("a"), require (type (null))), - when (key ("b"), require (strEqual ("lastElement"))), - else (do (abort ()))))), + require (key ("with_last"), + require (type (doc)), + visitEach (if (lastElement, + then (require (key ("b")), require (type (utf8))), + else (require (key ("a")), require (type (null)))))), + require (key ("with_last"), + visitEach (case (when (key ("a"), require (type (null))), + when (key ("b"), require (strEqual ("lastElement"))), + else (do (abort ()))))), require (key ("string"), case (when (strEqual ("goodbye"), do (abort ())), when (strEqual ("hello"), nop), // Not eached since the prior case matched: when (strEqual ("hello"), do (abort ())), else (do (abort ())))), - visitOthers (if (key ("unhandled"), - then (do (saw_other = true)), - else (do (abort ()))))); + visitOthers (if (key ("unhandled"), then (do (saw_other = true)), else (do (abort ()))))); BSON_ASSERT (saw_other); } static void -do_assert_bson_equal (const bson_t *actual, - const bson_t *expected, - const char *file, - int line) +do_assert_bson_equal (const bson_t *actual, const bson_t *expected, const char *file, int line) { char *actual_str = bson_as_canonical_extended_json (actual, NULL); ASSERT (actual_str); @@ -2733,11 +2608,9 @@ do_assert_bson_equal (const bson_t *actual, } #define ASSERT_BSON_EQUAL(Actual, ...) \ - do_assert_bson_equal ( \ - &(Actual), TMP_BSON_FROM_JSON (__VA_ARGS__), __FILE__, __LINE__) + do_assert_bson_equal (&(Actual), TMP_BSON_FROM_JSON (__VA_ARGS__), __FILE__, __LINE__) -#define ASSERT_BSON_EQUAL_BSON(Actual, Expected) \ - do_assert_bson_equal (&(Actual), &(Expected), __FILE__, __LINE__) +#define ASSERT_BSON_EQUAL_BSON(Actual, Expected) do_assert_bson_equal (&(Actual), &(Expected), __FILE__, __LINE__) static void test_bson_dsl_build (void) @@ -2761,18 +2634,15 @@ test_bson_dsl_build (void) bson_destroy (&doc); // Conditional insert - bsonBuild ( - doc, if (0, then (kv ("never", null)), else (kv ("truth", int32 (1))))); + bsonBuild (doc, if (0, then (kv ("never", null)), else (kv ("truth", int32 (1))))); ASSERT_BSON_EQUAL (doc, {"truth" : 1}); bson_destroy (&doc); // Insert a subdoc - bson_t *subdoc = - TMP_BSON_FROM_JSON ({"child" : [ 1, 2, 3 ], "other" : null}); + bson_t *subdoc = TMP_BSON_FROM_JSON ({"child" : [ 1, 2, 3 ], "other" : null}); bsonBuild (doc, kv ("subdoc", doc (insert (*subdoc, true)))); - ASSERT_BSON_EQUAL (doc, - {"subdoc" : {"child" : [ 1, 2, 3 ], "other" : null}}); + ASSERT_BSON_EQUAL (doc, {"subdoc" : {"child" : [ 1, 2, 3 ], "other" : null}}); bson_destroy (&doc); // Conditional insert @@ -2860,8 +2730,7 @@ test_bson_with_duplicate_keys (void) // Assert that bson_as_relaxed_extended_json preserves duplicate keys. { - char *json_str = - bson_as_relaxed_extended_json (&with_dups, NULL /* length */); + char *json_str = bson_as_relaxed_extended_json (&with_dups, NULL /* length */); ASSERT_CMPSTR (json_str, "{ \"duplicate\" : 1, \"duplicate\" : 2 }"); bson_free (json_str); } @@ -2870,10 +2739,7 @@ test_bson_with_duplicate_keys (void) { bson_t from_json; bson_error_t error; - ASSERT_OR_PRINT ( - bson_init_from_json ( - &from_json, "{ \"duplicate\" : 1, \"duplicate\" : 2 }", -1, &error), - error); + ASSERT_OR_PRINT (bson_init_from_json (&from_json, "{ \"duplicate\" : 1, \"duplicate\" : 2 }", -1, &error), error); BSON_ASSERT_BSON_EQUAL (&with_dups, &from_json); } @@ -2944,15 +2810,9 @@ test_bson_array_builder (void) } bson_array_builder_t *bab = bson_array_builder_new (); ASSERT (bson_array_builder_append_utf8 (bab, large_str, -1)); - ASSERT (bson_array_builder_append_utf8 ( - bab, large_str, -1)); // heap allocates. + ASSERT (bson_array_builder_append_utf8 (bab, large_str, -1)); // heap allocates. ASSERT (bson_array_builder_append_utf8 (bab, large_str, -1)); - bson_t *expect = BCON_NEW ("0", - BCON_UTF8 (large_str), - "1", - BCON_UTF8 (large_str), - "2", - BCON_UTF8 (large_str)); + bson_t *expect = BCON_NEW ("0", BCON_UTF8 (large_str), "1", BCON_UTF8 (large_str), "2", BCON_UTF8 (large_str)); bson_t b; ASSERT (bson_array_builder_build (bab, &b)); ASSERT_BSON_EQUAL_BSON (b, *expect); @@ -2998,8 +2858,7 @@ test_bson_array_builder (void) { bson_t b; bson_array_builder_t *bab = bson_array_builder_new (); - bson_value_t v = {.value_type = BSON_TYPE_INT32, - .value = {.v_int32 = 1}}; + bson_value_t v = {.value_type = BSON_TYPE_INT32, .value = {.v_int32 = 1}}; ASSERT (bson_array_builder_append_value (bab, &v)); ASSERT (bson_array_builder_build (bab, &b)); ASSERT_BSON_EQUAL (b, [1]); @@ -3010,8 +2869,7 @@ test_bson_array_builder (void) { bson_t b; bson_array_builder_t *bab = bson_array_builder_new (); - ASSERT (bson_array_builder_append_array ( - bab, TMP_BSON_FROM_JSON ([ 1, 2 ]))); + ASSERT (bson_array_builder_append_array (bab, TMP_BSON_FROM_JSON ([ 1, 2 ]))); ASSERT (bson_array_builder_build (bab, &b)); ASSERT_BSON_EQUAL (b, [[ 1, 2 ]]); bson_destroy (&b); @@ -3021,11 +2879,9 @@ test_bson_array_builder (void) { bson_t b; bson_array_builder_t *bab = bson_array_builder_new (); - ASSERT (bson_array_builder_append_binary ( - bab, BSON_SUBTYPE_BINARY, (const uint8_t *) "A", 1)); + ASSERT (bson_array_builder_append_binary (bab, BSON_SUBTYPE_BINARY, (const uint8_t *) "A", 1)); ASSERT (bson_array_builder_build (bab, &b)); - ASSERT_BSON_EQUAL ( - b, [ {"$binary" : {"base64" : "QQ==", "subType" : "00"}} ]); + ASSERT_BSON_EQUAL (b, [ {"$binary" : {"base64" : "QQ==", "subType" : "00"}} ]); bson_destroy (&b); bson_array_builder_destroy (bab); } @@ -3058,8 +2914,7 @@ test_bson_array_builder (void) { bson_t b; bson_array_builder_t *bab = bson_array_builder_new (); - ASSERT (bson_array_builder_append_code_with_scope ( - bab, "A", TMP_BSON_FROM_JSON ({"B" : 1}))); + ASSERT (bson_array_builder_append_code_with_scope (bab, "A", TMP_BSON_FROM_JSON ({"B" : 1}))); ASSERT (bson_array_builder_build (bab, &b)); // Use document string: `{ "0": ... , "1": ... }` instead of array // string: `[ ... , ... ]` for expectation. Parsing the array string @@ -3080,13 +2935,7 @@ test_bson_array_builder (void) // string: `[ ... , ... ]` for expectation. Parsing the array string // `[{ "$dbPointer": ... }]` results in incorrect BSON. See // CDRIVER-4678. - ASSERT_BSON_EQUAL (b, { - "0" : { - "$dbPointer" : - {"$ref" : "E", - "$id" : {"$oid" : "ffffffffffffffffffffffff"}} - } - }); + ASSERT_BSON_EQUAL (b, {"0" : {"$dbPointer" : {"$ref" : "E", "$id" : {"$oid" : "ffffffffffffffffffffffff"}}}}); bson_destroy (&b); bson_array_builder_destroy (bab); } @@ -3104,8 +2953,7 @@ test_bson_array_builder (void) { bson_t b; bson_array_builder_t *bab = bson_array_builder_new (); - ASSERT (bson_array_builder_append_document ( - bab, TMP_BSON_FROM_JSON ({"A" : 1}))); + ASSERT (bson_array_builder_append_document (bab, TMP_BSON_FROM_JSON ({"A" : 1}))); ASSERT (bson_array_builder_build (bab, &b)); ASSERT_BSON_EQUAL (b, [ {"A" : {"$numberInt" : "1"}} ]); bson_destroy (&b); @@ -3219,8 +3067,7 @@ test_bson_array_builder (void) bson_array_builder_t *bab = bson_array_builder_new (); ASSERT (bson_array_builder_append_regex (bab, "A", "i")); ASSERT (bson_array_builder_build (bab, &b)); - ASSERT_BSON_EQUAL ( - b, [ {"$regularExpression" : {"pattern" : "A", "options" : "i"}} ]); + ASSERT_BSON_EQUAL (b, [ {"$regularExpression" : {"pattern" : "A", "options" : "i"}} ]); bson_destroy (&b); bson_array_builder_destroy (bab); } @@ -3230,8 +3077,7 @@ test_bson_array_builder (void) bson_array_builder_t *bab = bson_array_builder_new (); ASSERT (bson_array_builder_append_regex_w_len (bab, "A", 1, "i")); ASSERT (bson_array_builder_build (bab, &b)); - ASSERT_BSON_EQUAL ( - b, [ {"$regularExpression" : {"pattern" : "A", "options" : "i"}} ]); + ASSERT_BSON_EQUAL (b, [ {"$regularExpression" : {"pattern" : "A", "options" : "i"}} ]); bson_destroy (&b); bson_array_builder_destroy (bab); } @@ -3298,8 +3144,7 @@ test_bson_array_builder (void) ASSERT_CMPUINT32 (bson_count_keys (&b), ==, 1); bson_iter_t iter; ASSERT (bson_iter_init_find (&iter, &b, "0")); - ASSERT_CMPINT ( - (int) bson_iter_type (&iter), ==, (int) BSON_TYPE_DATE_TIME); + ASSERT_CMPINT ((int) bson_iter_type (&iter), ==, (int) BSON_TYPE_DATE_TIME); bson_destroy (&b); bson_array_builder_destroy (bab); } @@ -3353,28 +3198,23 @@ test_bson_install (TestSuite *suite) TestSuite_Add (suite, "/bson/append_overflow", test_bson_append_overflow); TestSuite_Add (suite, "/bson/append_array", test_bson_append_array); TestSuite_Add (suite, "/bson/append_binary", test_bson_append_binary); - TestSuite_Add (suite, - "/bson/append_binary_deprecated", - test_bson_append_binary_deprecated); + TestSuite_Add (suite, "/bson/append_binary_deprecated", test_bson_append_binary_deprecated); TestSuite_Add (suite, "/bson/append_bool", test_bson_append_bool); TestSuite_Add (suite, "/bson/append_code", test_bson_append_code); - TestSuite_Add ( - suite, "/bson/append_code_with_scope", test_bson_append_code_with_scope); + TestSuite_Add (suite, "/bson/append_code_with_scope", test_bson_append_code_with_scope); TestSuite_Add (suite, "/bson/append_dbpointer", test_bson_append_dbpointer); TestSuite_Add (suite, "/bson/append_document", test_bson_append_document); TestSuite_Add (suite, "/bson/append_double", test_bson_append_double); TestSuite_Add (suite, "/bson/append_int32", test_bson_append_int32); TestSuite_Add (suite, "/bson/append_int64", test_bson_append_int64); - TestSuite_Add ( - suite, "/bson/append_decimal128", test_bson_append_decimal128); + TestSuite_Add (suite, "/bson/append_decimal128", test_bson_append_decimal128); TestSuite_Add (suite, "/bson/append_iter", test_bson_append_iter); TestSuite_Add (suite, "/bson/append_maxkey", test_bson_append_maxkey); TestSuite_Add (suite, "/bson/append_minkey", test_bson_append_minkey); TestSuite_Add (suite, "/bson/append_null", test_bson_append_null); TestSuite_Add (suite, "/bson/append_oid", test_bson_append_oid); TestSuite_Add (suite, "/bson/append_regex", test_bson_append_regex); - TestSuite_Add ( - suite, "/bson/append_regex_w_len", test_bson_append_regex_w_len); + TestSuite_Add (suite, "/bson/append_regex_w_len", test_bson_append_regex_w_len); TestSuite_Add (suite, "/bson/append_utf8", test_bson_append_utf8); TestSuite_Add (suite, "/bson/append_symbol", test_bson_append_symbol); TestSuite_Add (suite, "/bson/append_time_t", test_bson_append_time_t); @@ -3387,23 +3227,17 @@ test_bson_install (TestSuite *suite) TestSuite_Add (suite, "/bson/validate", test_bson_validate); TestSuite_Add (suite, "/bson/validate/dbref", test_bson_validate_dbref); TestSuite_Add (suite, "/bson/validate/bool", test_bson_validate_bool); - TestSuite_Add ( - suite, "/bson/validate/dbpointer", test_bson_validate_dbpointer); + TestSuite_Add (suite, "/bson/validate/dbpointer", test_bson_validate_dbpointer); TestSuite_Add (suite, "/bson/new_1mm", test_bson_new_1mm); TestSuite_Add (suite, "/bson/init_1mm", test_bson_init_1mm); TestSuite_Add (suite, "/bson/build_child", test_bson_build_child); TestSuite_Add (suite, "/bson/build_child_deep", test_bson_build_child_deep); - TestSuite_Add (suite, - "/bson/build_child_deep_no_begin_end", - test_bson_build_child_deep_no_begin_end); - TestSuite_Add ( - suite, "/bson/build_child_array", test_bson_build_child_array); + TestSuite_Add (suite, "/bson/build_child_deep_no_begin_end", test_bson_build_child_deep_no_begin_end); + TestSuite_Add (suite, "/bson/build_child_array", test_bson_build_child_array); TestSuite_Add (suite, "/bson/count", test_bson_count_keys); TestSuite_Add (suite, "/bson/copy", test_bson_copy); TestSuite_Add (suite, "/bson/copy_to", test_bson_copy_to); - TestSuite_Add (suite, - "/bson/copy_to_excluding_noinit", - test_bson_copy_to_excluding_noinit); + TestSuite_Add (suite, "/bson/copy_to_excluding_noinit", test_bson_copy_to_excluding_noinit); TestSuite_Add (suite, "/bson/initializer", test_bson_initializer); TestSuite_Add (suite, "/bson/concat", test_bson_concat); TestSuite_Add (suite, "/bson/reinit", test_bson_reinit); @@ -3411,42 +3245,28 @@ test_bson_install (TestSuite *suite) TestSuite_Add (suite, "/bson/clear", test_bson_clear); TestSuite_Add (suite, "/bson/steal", test_bson_steal); TestSuite_Add (suite, "/bson/reserve_buffer", test_bson_reserve_buffer); - TestSuite_Add ( - suite, "/bson/reserve_buffer/errors", test_bson_reserve_buffer_errors); - TestSuite_Add ( - suite, "/bson/destroy_with_steal", test_bson_destroy_with_steal); + TestSuite_Add (suite, "/bson/reserve_buffer/errors", test_bson_reserve_buffer_errors); + TestSuite_Add (suite, "/bson/destroy_with_steal", test_bson_destroy_with_steal); TestSuite_Add (suite, "/bson/has_field", test_bson_has_field); - TestSuite_Add ( - suite, "/bson/visit_invalid_field", test_bson_visit_invalid_field); - TestSuite_Add ( - suite, "/bson/unsupported_type", test_bson_visit_unsupported_type); - TestSuite_Add (suite, - "/bson/unsupported_type/bad_key", - test_bson_visit_unsupported_type_bad_key); - TestSuite_Add (suite, - "/bson/unsupported_type/empty_key", - test_bson_visit_unsupported_type_empty_key); + TestSuite_Add (suite, "/bson/visit_invalid_field", test_bson_visit_invalid_field); + TestSuite_Add (suite, "/bson/unsupported_type", test_bson_visit_unsupported_type); + TestSuite_Add (suite, "/bson/unsupported_type/bad_key", test_bson_visit_unsupported_type_bad_key); + TestSuite_Add (suite, "/bson/unsupported_type/empty_key", test_bson_visit_unsupported_type_empty_key); TestSuite_Add (suite, "/bson/binary_subtype_2", test_bson_subtype_2); TestSuite_Add (suite, "/bson/regex_length", test_bson_regex_lengths); TestSuite_Add (suite, "/util/next_power_of_two", test_next_power_of_two); TestSuite_Add (suite, "/bson/empty_binary", test_bson_empty_binary); TestSuite_Add (suite, "/bson/iter/key_len", test_bson_iter_key_len); - TestSuite_Add (suite, - "/bson/iter/init_from_data_at_offset", - test_bson_iter_init_from_data_at_offset); - TestSuite_Add ( - suite, "/bson/value/null_handling", test_bson_binary_null_handling); - TestSuite_Add (suite, - "/bson/append_null_from_utf8_or_symbol", - test_bson_append_null_from_utf8_or_symbol); + TestSuite_Add (suite, "/bson/iter/init_from_data_at_offset", test_bson_iter_init_from_data_at_offset); + TestSuite_Add (suite, "/bson/value/null_handling", test_bson_binary_null_handling); + TestSuite_Add (suite, "/bson/append_null_from_utf8_or_symbol", test_bson_append_null_from_utf8_or_symbol); TestSuite_Add (suite, "/bson/as_json_string", test_bson_as_json_string); TestSuite_Add (suite, "/bson/dsl/predicate", test_bson_dsl_predicate); TestSuite_Add (suite, "/bson/dsl/parse", test_bson_dsl_parse); TestSuite_Add (suite, "/bson/dsl/visit", test_bson_dsl_visit); TestSuite_Add (suite, "/bson/dsl/build", test_bson_dsl_build); - TestSuite_Add ( - suite, "/bson/with_duplicate_keys", test_bson_with_duplicate_keys); + TestSuite_Add (suite, "/bson/with_duplicate_keys", test_bson_with_duplicate_keys); TestSuite_Add (suite, "/bson/uint32_to_string", test_bson_uint32_to_string); TestSuite_Add (suite, "/bson/array_builder", test_bson_array_builder); } diff --git a/src/libbson/tests/test-clock.c b/src/libbson/tests/test-clock.c index 830d70c1df..a0a7b3accf 100644 --- a/src/libbson/tests/test-clock.c +++ b/src/libbson/tests/test-clock.c @@ -20,6 +20,5 @@ test_get_monotonic_time (void) void test_clock_install (TestSuite *suite) { - TestSuite_Add ( - suite, "/bson/clock/get_monotonic_time", test_get_monotonic_time); + TestSuite_Add (suite, "/bson/clock/get_monotonic_time", test_get_monotonic_time); } diff --git a/src/libbson/tests/test-decimal128.c b/src/libbson/tests/test-decimal128.c index 37f4ec3b3a..81bca4cd18 100644 --- a/src/libbson/tests/test-decimal128.c +++ b/src/libbson/tests/test-decimal128.c @@ -114,17 +114,13 @@ test_decimal128_to_string__regular (void) DECIMAL128_FROM_ULLS (two, 0x3040000000000000, 0x0000000000000002); DECIMAL128_FROM_ULLS (negative_one, 0xb040000000000000, 0x0000000000000001); DECIMAL128_FROM_ULLS (negative_zero, 0xb040000000000000, 0x0000000000000000); - DECIMAL128_FROM_ULLS ( - tenth, 0x303e000000000000, 0x0000000000000001); /* 0.1 */ + DECIMAL128_FROM_ULLS (tenth, 0x303e000000000000, 0x0000000000000001); /* 0.1 */ /* 0.001234 */ - DECIMAL128_FROM_ULLS ( - smallest_regular, 0x3034000000000000, 0x00000000000004d2); + DECIMAL128_FROM_ULLS (smallest_regular, 0x3034000000000000, 0x00000000000004d2); /* 12345789012 */ - DECIMAL128_FROM_ULLS ( - largest_regular, 0x3040000000000000, 0x0000001cbe991a14); + DECIMAL128_FROM_ULLS (largest_regular, 0x3040000000000000, 0x0000001cbe991a14); /* 0.00123400000 */ - DECIMAL128_FROM_ULLS ( - trailing_zeros, 0x302a000000000000, 0x00000000075aef40); + DECIMAL128_FROM_ULLS (trailing_zeros, 0x302a000000000000, 0x00000000075aef40); /* 0.1234567890123456789012345678901234 */ DECIMAL128_FROM_ULLS (all_digits, 0x2ffc3cde6fff9732, 0xde825cd07e96aff2); @@ -171,12 +167,12 @@ test_decimal128_to_string__scientific (void) { char bid_string[BSON_DECIMAL128_STRING]; - bson_decimal128_t huge; /* 1.000000000000000000000000000000000E+6144 */ - bson_decimal128_t tiny; /* 1E-6176 */ - bson_decimal128_t neg_tiny; /* -1E-6176 */ - bson_decimal128_t large; /* 9.999987654321E+112 */ - bson_decimal128_t largest; /* 9.999999999999999999999999999999999E+6144 */ - bson_decimal128_t tiniest; /* 9.999999999999999999999999999999999E-6143 */ + bson_decimal128_t huge; /* 1.000000000000000000000000000000000E+6144 */ + bson_decimal128_t tiny; /* 1E-6176 */ + bson_decimal128_t neg_tiny; /* -1E-6176 */ + bson_decimal128_t large; /* 9.999987654321E+112 */ + bson_decimal128_t largest; /* 9.999999999999999999999999999999999E+6144 */ + bson_decimal128_t tiniest; /* 9.999999999999999999999999999999999E-6143 */ bson_decimal128_t trailing_zero; /* 1.050E9 */ bson_decimal128_t one_trailing_zero; /* 1.050E4 */ bson_decimal128_t move_decimal; /* 105 */ @@ -190,17 +186,13 @@ test_decimal128_to_string__scientific (void) DECIMAL128_FROM_ULLS (largest, 0x5fffed09bead87c0, 0x378d8e63ffffffff); DECIMAL128_FROM_ULLS (tiniest, 0x0001ed09bead87c0, 0x378d8e63ffffffff); DECIMAL128_FROM_ULLS (trailing_zero, 0x304c000000000000, 0x000000000000041a); - DECIMAL128_FROM_ULLS ( - one_trailing_zero, 0x3042000000000000, 0x000000000000041a); + DECIMAL128_FROM_ULLS (one_trailing_zero, 0x3042000000000000, 0x000000000000041a); DECIMAL128_FROM_ULLS (move_decimal, 0x3040000000000000, 0x0000000000000069); - DECIMAL128_FROM_ULLS ( - move_decimal_after, 0x3042000000000000, 0x0000000000000069); - DECIMAL128_FROM_ULLS ( - trailing_zero_no_decimal, 0x3046000000000000, 0x0000000000000001); + DECIMAL128_FROM_ULLS (move_decimal_after, 0x3042000000000000, 0x0000000000000069); + DECIMAL128_FROM_ULLS (trailing_zero_no_decimal, 0x3046000000000000, 0x0000000000000001); bson_decimal128_to_string (&huge, bid_string); - BSON_ASSERT ( - !strcmp ("1.000000000000000000000000000000000E+6144", bid_string)); + BSON_ASSERT (!strcmp ("1.000000000000000000000000000000000E+6144", bid_string)); bson_decimal128_to_string (&tiny, bid_string); BSON_ASSERT (!strcmp ("1E-6176", bid_string)); @@ -215,12 +207,10 @@ test_decimal128_to_string__scientific (void) BSON_ASSERT (!strcmp ("9.999987654321E+112", bid_string)); bson_decimal128_to_string (&largest, bid_string); - BSON_ASSERT ( - !strcmp ("9.999999999999999999999999999999999E+6144", bid_string)); + BSON_ASSERT (!strcmp ("9.999999999999999999999999999999999E+6144", bid_string)); bson_decimal128_to_string (&tiniest, bid_string); - BSON_ASSERT ( - !strcmp ("9.999999999999999999999999999999999E-6143", bid_string)); + BSON_ASSERT (!strcmp ("9.999999999999999999999999999999999E-6143", bid_string)); bson_decimal128_to_string (&trailing_zero, bid_string); BSON_ASSERT (!strcmp ("1.050E+9", bid_string)); @@ -446,29 +436,18 @@ test_decimal128_from_string__simple (void) bson_decimal128_from_string ("0.12345", &fractional_number); bson_decimal128_from_string ("0.0012345", &leading_zeros); - bson_decimal128_from_string ("00012345678901234567", - &leading_insignificant_zeros); - - BSON_ASSERT ( - decimal128_equal (&one, 0x3040000000000000, 0x0000000000000001)); - BSON_ASSERT ( - decimal128_equal (&negative_one, 0xb040000000000000, 0x0000000000000001)); - BSON_ASSERT ( - decimal128_equal (&zero, 0x3040000000000000, 0x0000000000000000)); - BSON_ASSERT (decimal128_equal ( - &negative_zero, 0xb040000000000000, 0x0000000000000000)); - BSON_ASSERT ( - decimal128_equal (&number, 0x3040000000000000, 0x002bdc545d6b4b87)); - BSON_ASSERT ( - decimal128_equal (&number_two, 0x3040000000000000, 0x000000e67a93c822)); - BSON_ASSERT (decimal128_equal ( - &negative_number, 0xb040000000000000, 0x002bdc545d6b4b87)); - BSON_ASSERT (decimal128_equal ( - &fractional_number, 0x3036000000000000, 0x0000000000003039)); - BSON_ASSERT (decimal128_equal ( - &leading_zeros, 0x3032000000000000, 0x0000000000003039)); - BSON_ASSERT (decimal128_equal ( - &leading_insignificant_zeros, 0x3040000000000000, 0x002bdc545d6b4b87)); + bson_decimal128_from_string ("00012345678901234567", &leading_insignificant_zeros); + + BSON_ASSERT (decimal128_equal (&one, 0x3040000000000000, 0x0000000000000001)); + BSON_ASSERT (decimal128_equal (&negative_one, 0xb040000000000000, 0x0000000000000001)); + BSON_ASSERT (decimal128_equal (&zero, 0x3040000000000000, 0x0000000000000000)); + BSON_ASSERT (decimal128_equal (&negative_zero, 0xb040000000000000, 0x0000000000000000)); + BSON_ASSERT (decimal128_equal (&number, 0x3040000000000000, 0x002bdc545d6b4b87)); + BSON_ASSERT (decimal128_equal (&number_two, 0x3040000000000000, 0x000000e67a93c822)); + BSON_ASSERT (decimal128_equal (&negative_number, 0xb040000000000000, 0x002bdc545d6b4b87)); + BSON_ASSERT (decimal128_equal (&fractional_number, 0x3036000000000000, 0x0000000000003039)); + BSON_ASSERT (decimal128_equal (&leading_zeros, 0x3032000000000000, 0x0000000000003039)); + BSON_ASSERT (decimal128_equal (&leading_insignificant_zeros, 0x3040000000000000, 0x002bdc545d6b4b87)); bson_decimal128_from_string_w_len ("1", 1, &one); @@ -477,35 +456,23 @@ test_decimal128_from_string__simple (void) bson_decimal128_from_string_w_len ("-0", 2, &negative_zero); bson_decimal128_from_string_w_len ("12345678901234567", 17, &number); bson_decimal128_from_string_w_len ("989898983458", 12, &number_two); - bson_decimal128_from_string_w_len ( - "-12345678901234567", 18, &negative_number); + bson_decimal128_from_string_w_len ("-12345678901234567", 18, &negative_number); bson_decimal128_from_string_w_len ("0.12345", 7, &fractional_number); bson_decimal128_from_string_w_len ("0.0012345", 9, &leading_zeros); - bson_decimal128_from_string_w_len ( - "00012345678901234567", 20, &leading_insignificant_zeros); - - BSON_ASSERT ( - decimal128_equal (&one, 0x3040000000000000, 0x0000000000000001)); - BSON_ASSERT ( - decimal128_equal (&negative_one, 0xb040000000000000, 0x0000000000000001)); - BSON_ASSERT ( - decimal128_equal (&zero, 0x3040000000000000, 0x0000000000000000)); - BSON_ASSERT (decimal128_equal ( - &negative_zero, 0xb040000000000000, 0x0000000000000000)); - BSON_ASSERT ( - decimal128_equal (&number, 0x3040000000000000, 0x002bdc545d6b4b87)); - BSON_ASSERT ( - decimal128_equal (&number_two, 0x3040000000000000, 0x000000e67a93c822)); - BSON_ASSERT (decimal128_equal ( - &negative_number, 0xb040000000000000, 0x002bdc545d6b4b87)); - BSON_ASSERT (decimal128_equal ( - &fractional_number, 0x3036000000000000, 0x0000000000003039)); - BSON_ASSERT (decimal128_equal ( - &leading_zeros, 0x3032000000000000, 0x0000000000003039)); - BSON_ASSERT (decimal128_equal ( - &leading_insignificant_zeros, 0x3040000000000000, 0x002bdc545d6b4b87)); + bson_decimal128_from_string_w_len ("00012345678901234567", 20, &leading_insignificant_zeros); + + BSON_ASSERT (decimal128_equal (&one, 0x3040000000000000, 0x0000000000000001)); + BSON_ASSERT (decimal128_equal (&negative_one, 0xb040000000000000, 0x0000000000000001)); + BSON_ASSERT (decimal128_equal (&zero, 0x3040000000000000, 0x0000000000000000)); + BSON_ASSERT (decimal128_equal (&negative_zero, 0xb040000000000000, 0x0000000000000000)); + BSON_ASSERT (decimal128_equal (&number, 0x3040000000000000, 0x002bdc545d6b4b87)); + BSON_ASSERT (decimal128_equal (&number_two, 0x3040000000000000, 0x000000e67a93c822)); + BSON_ASSERT (decimal128_equal (&negative_number, 0xb040000000000000, 0x002bdc545d6b4b87)); + BSON_ASSERT (decimal128_equal (&fractional_number, 0x3036000000000000, 0x0000000000003039)); + BSON_ASSERT (decimal128_equal (&leading_zeros, 0x3032000000000000, 0x0000000000003039)); + BSON_ASSERT (decimal128_equal (&leading_insignificant_zeros, 0x3040000000000000, 0x002bdc545d6b4b87)); } @@ -524,56 +491,42 @@ test_decimal128_from_string__scientific (void) bson_decimal128_from_string ("1e1", &ten_again); bson_decimal128_from_string ("10e-1", &one); - BSON_ASSERT ( - decimal128_equal (&ten, 0x3040000000000000, 0x000000000000000a)); - BSON_ASSERT ( - decimal128_equal (&ten_again, 0x3042000000000000, 0x0000000000000001)); - BSON_ASSERT ( - decimal128_equal (&one, 0x303e000000000000, 0x000000000000000a)); + BSON_ASSERT (decimal128_equal (&ten, 0x3040000000000000, 0x000000000000000a)); + BSON_ASSERT (decimal128_equal (&ten_again, 0x3042000000000000, 0x0000000000000001)); + BSON_ASSERT (decimal128_equal (&one, 0x303e000000000000, 0x000000000000000a)); bson_decimal128_from_string ("12345678901234567e6111", &huge_exp); bson_decimal128_from_string ("1e-6176", &tiny_exp); - BSON_ASSERT ( - decimal128_equal (&huge_exp, 0x5ffe000000000000, 0x002bdc545d6b4b87)); - BSON_ASSERT ( - decimal128_equal (&tiny_exp, 0x0000000000000000, 0x0000000000000001)); + BSON_ASSERT (decimal128_equal (&huge_exp, 0x5ffe000000000000, 0x002bdc545d6b4b87)); + BSON_ASSERT (decimal128_equal (&tiny_exp, 0x0000000000000000, 0x0000000000000001)); bson_decimal128_from_string ("-100E-10", &fractional); bson_decimal128_from_string ("10.50E8", &trailing_zeros); - BSON_ASSERT ( - decimal128_equal (&fractional, 0xb02c000000000000, 0x0000000000000064)); - BSON_ASSERT (decimal128_equal ( - &trailing_zeros, 0x304c000000000000, 0x000000000000041a)); + BSON_ASSERT (decimal128_equal (&fractional, 0xb02c000000000000, 0x0000000000000064)); + BSON_ASSERT (decimal128_equal (&trailing_zeros, 0x304c000000000000, 0x000000000000041a)); bson_decimal128_from_string_w_len ("10e0", 4, &ten); bson_decimal128_from_string_w_len ("1e1", 3, &ten_again); bson_decimal128_from_string_w_len ("10e-1", 5, &one); - BSON_ASSERT ( - decimal128_equal (&ten, 0x3040000000000000, 0x000000000000000a)); - BSON_ASSERT ( - decimal128_equal (&ten_again, 0x3042000000000000, 0x0000000000000001)); - BSON_ASSERT ( - decimal128_equal (&one, 0x303e000000000000, 0x000000000000000a)); + BSON_ASSERT (decimal128_equal (&ten, 0x3040000000000000, 0x000000000000000a)); + BSON_ASSERT (decimal128_equal (&ten_again, 0x3042000000000000, 0x0000000000000001)); + BSON_ASSERT (decimal128_equal (&one, 0x303e000000000000, 0x000000000000000a)); bson_decimal128_from_string_w_len ("12345678901234567e6111", 22, &huge_exp); bson_decimal128_from_string_w_len ("1e-6176", 7, &tiny_exp); - BSON_ASSERT ( - decimal128_equal (&huge_exp, 0x5ffe000000000000, 0x002bdc545d6b4b87)); - BSON_ASSERT ( - decimal128_equal (&tiny_exp, 0x0000000000000000, 0x0000000000000001)); + BSON_ASSERT (decimal128_equal (&huge_exp, 0x5ffe000000000000, 0x002bdc545d6b4b87)); + BSON_ASSERT (decimal128_equal (&tiny_exp, 0x0000000000000000, 0x0000000000000001)); bson_decimal128_from_string_w_len ("-100E-10", 8, &fractional); bson_decimal128_from_string_w_len ("10.50E8", 7, &trailing_zeros); - BSON_ASSERT ( - decimal128_equal (&fractional, 0xb02c000000000000, 0x0000000000000064)); - BSON_ASSERT (decimal128_equal ( - &trailing_zeros, 0x304c000000000000, 0x000000000000041a)); + BSON_ASSERT (decimal128_equal (&fractional, 0xb02c000000000000, 0x0000000000000064)); + BSON_ASSERT (decimal128_equal (&trailing_zeros, 0x304c000000000000, 0x000000000000041a)); } @@ -587,47 +540,29 @@ test_decimal128_from_string__large (void) bson_decimal128_t full_house; bson_decimal128_from_string ("12345689012345789012345", &large); - bson_decimal128_from_string ("1234567890123456789012345678901234", - &all_digits); - bson_decimal128_from_string ("9.999999999999999999999999999999999E+6144", - &largest); - bson_decimal128_from_string ("9.999999999999999999999999999999999E-6143", - &tiniest); - bson_decimal128_from_string ("5.192296858534827628530496329220095E+33", - &full_house); - - BSON_ASSERT ( - decimal128_equal (&large, 0x304000000000029d, 0x42da3a76f9e0d979)); - BSON_ASSERT ( - decimal128_equal (&all_digits, 0x30403cde6fff9732, 0xde825cd07e96aff2)); - BSON_ASSERT ( - decimal128_equal (&largest, 0x5fffed09bead87c0, 0x378d8e63ffffffff)); - BSON_ASSERT ( - decimal128_equal (&tiniest, 0x0001ed09bead87c0, 0x378d8e63ffffffff)); - BSON_ASSERT ( - decimal128_equal (&full_house, 0x3040ffffffffffff, 0xffffffffffffffff)); + bson_decimal128_from_string ("1234567890123456789012345678901234", &all_digits); + bson_decimal128_from_string ("9.999999999999999999999999999999999E+6144", &largest); + bson_decimal128_from_string ("9.999999999999999999999999999999999E-6143", &tiniest); + bson_decimal128_from_string ("5.192296858534827628530496329220095E+33", &full_house); + + BSON_ASSERT (decimal128_equal (&large, 0x304000000000029d, 0x42da3a76f9e0d979)); + BSON_ASSERT (decimal128_equal (&all_digits, 0x30403cde6fff9732, 0xde825cd07e96aff2)); + BSON_ASSERT (decimal128_equal (&largest, 0x5fffed09bead87c0, 0x378d8e63ffffffff)); + BSON_ASSERT (decimal128_equal (&tiniest, 0x0001ed09bead87c0, 0x378d8e63ffffffff)); + BSON_ASSERT (decimal128_equal (&full_house, 0x3040ffffffffffff, 0xffffffffffffffff)); bson_decimal128_from_string_w_len ("12345689012345789012345", -1, &large); - bson_decimal128_from_string_w_len ( - "1234567890123456789012345678901234", -1, &all_digits); - bson_decimal128_from_string_w_len ( - "9.999999999999999999999999999999999E+6144", -1, &largest); - bson_decimal128_from_string_w_len ( - "9.999999999999999999999999999999999E-6143", -1, &tiniest); - bson_decimal128_from_string_w_len ( - "5.192296858534827628530496329220095E+33", -1, &full_house); - - BSON_ASSERT ( - decimal128_equal (&large, 0x304000000000029d, 0x42da3a76f9e0d979)); - BSON_ASSERT ( - decimal128_equal (&all_digits, 0x30403cde6fff9732, 0xde825cd07e96aff2)); - BSON_ASSERT ( - decimal128_equal (&largest, 0x5fffed09bead87c0, 0x378d8e63ffffffff)); - BSON_ASSERT ( - decimal128_equal (&tiniest, 0x0001ed09bead87c0, 0x378d8e63ffffffff)); - BSON_ASSERT ( - decimal128_equal (&full_house, 0x3040ffffffffffff, 0xffffffffffffffff)); + bson_decimal128_from_string_w_len ("1234567890123456789012345678901234", -1, &all_digits); + bson_decimal128_from_string_w_len ("9.999999999999999999999999999999999E+6144", -1, &largest); + bson_decimal128_from_string_w_len ("9.999999999999999999999999999999999E-6143", -1, &tiniest); + bson_decimal128_from_string_w_len ("5.192296858534827628530496329220095E+33", -1, &full_house); + + BSON_ASSERT (decimal128_equal (&large, 0x304000000000029d, 0x42da3a76f9e0d979)); + BSON_ASSERT (decimal128_equal (&all_digits, 0x30403cde6fff9732, 0xde825cd07e96aff2)); + BSON_ASSERT (decimal128_equal (&largest, 0x5fffed09bead87c0, 0x378d8e63ffffffff)); + BSON_ASSERT (decimal128_equal (&tiniest, 0x0001ed09bead87c0, 0x378d8e63ffffffff)); + BSON_ASSERT (decimal128_equal (&full_house, 0x3040ffffffffffff, 0xffffffffffffffff)); } @@ -639,73 +574,57 @@ test_decimal128_from_string__exponent_normalization (void) bson_decimal128_t no_normalize; bson_decimal128_t a_disaster; - bson_decimal128_from_string ("1000000000000000000000000000000000000000", - &trailing_zeros); - bson_decimal128_from_string ("10000000000000000000000000000000000", - &one_normalize); - bson_decimal128_from_string ("1000000000000000000000000000000000", - &no_normalize); - bson_decimal128_from_string ( - "100000000000000000000000000000000000000000000000000000000000000000000" - "000000000000000000000000000000000000000000000000000000000000000000000" - "000000000000000000000000000000000000000000000000000000000000000000000" - "000000000000000000000000000000000000000000000000000000000000000000000" - "000000000000000000000000000000000000000000000000000000000000000000000" - "000000000000000000000000000000000000000000000000000000000000000000000" - "000000000000000000000000000000000000000000000000000000000000000000000" - "000000000000000000000000000000000000000000000000000000000000000000000" - "000000000000000000000000000000000000000000000000000000000000000000000" - "000000000000000000000000000000000000000000000000000000000000000000000" - "000000000000000000000000000000000000000000000000000000000000000000000" - "000000000000000000000000000000000000000000000000000000000000000000000" - "000000000000000000000000000000000000000000000000000000000000000000000" - "000000000000000000000000000000000000000000000000000000000000000000000" - "0000000000000000000000000000000000", - &a_disaster); - - BSON_ASSERT (decimal128_equal ( - &trailing_zeros, 0x304c314dc6448d93, 0x38c15b0a00000000)); - BSON_ASSERT (decimal128_equal ( - &one_normalize, 0x3042314dc6448d93, 0x38c15b0a00000000)); - BSON_ASSERT ( - decimal128_equal (&no_normalize, 0x3040314dc6448d93, 0x38c15b0a00000000)); - BSON_ASSERT ( - decimal128_equal (&a_disaster, 0x37cc314dc6448d93, 0x38c15b0a00000000)); - - - bson_decimal128_from_string_w_len ( - "1000000000000000000000000000000000000000", -1, &trailing_zeros); - bson_decimal128_from_string_w_len ( - "10000000000000000000000000000000000", -1, &one_normalize); - bson_decimal128_from_string_w_len ( - "1000000000000000000000000000000000", -1, &no_normalize); - bson_decimal128_from_string_w_len ( - "100000000000000000000000000000000000000000000000000000000000000000000" - "000000000000000000000000000000000000000000000000000000000000000000000" - "000000000000000000000000000000000000000000000000000000000000000000000" - "000000000000000000000000000000000000000000000000000000000000000000000" - "000000000000000000000000000000000000000000000000000000000000000000000" - "000000000000000000000000000000000000000000000000000000000000000000000" - "000000000000000000000000000000000000000000000000000000000000000000000" - "000000000000000000000000000000000000000000000000000000000000000000000" - "000000000000000000000000000000000000000000000000000000000000000000000" - "000000000000000000000000000000000000000000000000000000000000000000000" - "000000000000000000000000000000000000000000000000000000000000000000000" - "000000000000000000000000000000000000000000000000000000000000000000000" - "000000000000000000000000000000000000000000000000000000000000000000000" - "000000000000000000000000000000000000000000000000000000000000000000000" - "0000000000000000000000000000000000", - -1, - &a_disaster); - - BSON_ASSERT (decimal128_equal ( - &trailing_zeros, 0x304c314dc6448d93, 0x38c15b0a00000000)); - BSON_ASSERT (decimal128_equal ( - &one_normalize, 0x3042314dc6448d93, 0x38c15b0a00000000)); - BSON_ASSERT ( - decimal128_equal (&no_normalize, 0x3040314dc6448d93, 0x38c15b0a00000000)); - BSON_ASSERT ( - decimal128_equal (&a_disaster, 0x37cc314dc6448d93, 0x38c15b0a00000000)); + bson_decimal128_from_string ("1000000000000000000000000000000000000000", &trailing_zeros); + bson_decimal128_from_string ("10000000000000000000000000000000000", &one_normalize); + bson_decimal128_from_string ("1000000000000000000000000000000000", &no_normalize); + bson_decimal128_from_string ("100000000000000000000000000000000000000000000000000000000000000000000" + "000000000000000000000000000000000000000000000000000000000000000000000" + "000000000000000000000000000000000000000000000000000000000000000000000" + "000000000000000000000000000000000000000000000000000000000000000000000" + "000000000000000000000000000000000000000000000000000000000000000000000" + "000000000000000000000000000000000000000000000000000000000000000000000" + "000000000000000000000000000000000000000000000000000000000000000000000" + "000000000000000000000000000000000000000000000000000000000000000000000" + "000000000000000000000000000000000000000000000000000000000000000000000" + "000000000000000000000000000000000000000000000000000000000000000000000" + "000000000000000000000000000000000000000000000000000000000000000000000" + "000000000000000000000000000000000000000000000000000000000000000000000" + "000000000000000000000000000000000000000000000000000000000000000000000" + "000000000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000", + &a_disaster); + + BSON_ASSERT (decimal128_equal (&trailing_zeros, 0x304c314dc6448d93, 0x38c15b0a00000000)); + BSON_ASSERT (decimal128_equal (&one_normalize, 0x3042314dc6448d93, 0x38c15b0a00000000)); + BSON_ASSERT (decimal128_equal (&no_normalize, 0x3040314dc6448d93, 0x38c15b0a00000000)); + BSON_ASSERT (decimal128_equal (&a_disaster, 0x37cc314dc6448d93, 0x38c15b0a00000000)); + + + bson_decimal128_from_string_w_len ("1000000000000000000000000000000000000000", -1, &trailing_zeros); + bson_decimal128_from_string_w_len ("10000000000000000000000000000000000", -1, &one_normalize); + bson_decimal128_from_string_w_len ("1000000000000000000000000000000000", -1, &no_normalize); + bson_decimal128_from_string_w_len ("100000000000000000000000000000000000000000000000000000000000000000000" + "000000000000000000000000000000000000000000000000000000000000000000000" + "000000000000000000000000000000000000000000000000000000000000000000000" + "000000000000000000000000000000000000000000000000000000000000000000000" + "000000000000000000000000000000000000000000000000000000000000000000000" + "000000000000000000000000000000000000000000000000000000000000000000000" + "000000000000000000000000000000000000000000000000000000000000000000000" + "000000000000000000000000000000000000000000000000000000000000000000000" + "000000000000000000000000000000000000000000000000000000000000000000000" + "000000000000000000000000000000000000000000000000000000000000000000000" + "000000000000000000000000000000000000000000000000000000000000000000000" + "000000000000000000000000000000000000000000000000000000000000000000000" + "000000000000000000000000000000000000000000000000000000000000000000000" + "000000000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000", + -1, + &a_disaster); + + BSON_ASSERT (decimal128_equal (&trailing_zeros, 0x304c314dc6448d93, 0x38c15b0a00000000)); + BSON_ASSERT (decimal128_equal (&one_normalize, 0x3042314dc6448d93, 0x38c15b0a00000000)); + BSON_ASSERT (decimal128_equal (&no_normalize, 0x3040314dc6448d93, 0x38c15b0a00000000)); + BSON_ASSERT (decimal128_equal (&a_disaster, 0x37cc314dc6448d93, 0x38c15b0a00000000)); } @@ -722,14 +641,10 @@ test_decimal128_from_string__zeros (void) bson_decimal128_from_string ("0e+6000", &large_exponent); bson_decimal128_from_string ("-0e-1", &negative_zero); - BSON_ASSERT ( - decimal128_equal (&zero, 0x3040000000000000, 0x0000000000000000)); - BSON_ASSERT (decimal128_equal ( - &exponent_zero, 0x2b7a000000000000, 0x0000000000000000)); - BSON_ASSERT (decimal128_equal ( - &large_exponent, 0x5f20000000000000, 0x0000000000000000)); - BSON_ASSERT (decimal128_equal ( - &negative_zero, 0xb03e000000000000, 0x0000000000000000)); + BSON_ASSERT (decimal128_equal (&zero, 0x3040000000000000, 0x0000000000000000)); + BSON_ASSERT (decimal128_equal (&exponent_zero, 0x2b7a000000000000, 0x0000000000000000)); + BSON_ASSERT (decimal128_equal (&large_exponent, 0x5f20000000000000, 0x0000000000000000)); + BSON_ASSERT (decimal128_equal (&negative_zero, 0xb03e000000000000, 0x0000000000000000)); bson_decimal128_from_string_w_len ("0", 1, &zero); @@ -737,14 +652,10 @@ test_decimal128_from_string__zeros (void) bson_decimal128_from_string_w_len ("0e+6000", 7, &large_exponent); bson_decimal128_from_string_w_len ("-0e-1", 5, &negative_zero); - BSON_ASSERT ( - decimal128_equal (&zero, 0x3040000000000000, 0x0000000000000000)); - BSON_ASSERT (decimal128_equal ( - &exponent_zero, 0x2b7a000000000000, 0x0000000000000000)); - BSON_ASSERT (decimal128_equal ( - &large_exponent, 0x5f20000000000000, 0x0000000000000000)); - BSON_ASSERT (decimal128_equal ( - &negative_zero, 0xb03e000000000000, 0x0000000000000000)); + BSON_ASSERT (decimal128_equal (&zero, 0x3040000000000000, 0x0000000000000000)); + BSON_ASSERT (decimal128_equal (&exponent_zero, 0x2b7a000000000000, 0x0000000000000000)); + BSON_ASSERT (decimal128_equal (&large_exponent, 0x5f20000000000000, 0x0000000000000000)); + BSON_ASSERT (decimal128_equal (&negative_zero, 0xb03e000000000000, 0x0000000000000000)); } static void @@ -757,59 +668,30 @@ test_decimal128_from_string_w_len__special (void) /* These strings have more bytes than the length indicates. */ bson_decimal128_from_string_w_len ("12345678901234567abcd", 17, &number); bson_decimal128_from_string_w_len ("989898983458abcd", 12, &number_two); - bson_decimal128_from_string_w_len ( - "-12345678901234567abcd", 18, &negative_number); - - BSON_ASSERT ( - decimal128_equal (&number, 0x3040000000000000, 0x002bdc545d6b4b87)); - BSON_ASSERT ( - decimal128_equal (&number_two, 0x3040000000000000, 0x000000e67a93c822)); - BSON_ASSERT (decimal128_equal ( - &negative_number, 0xb040000000000000, 0x002bdc545d6b4b87)); + bson_decimal128_from_string_w_len ("-12345678901234567abcd", 18, &negative_number); + + BSON_ASSERT (decimal128_equal (&number, 0x3040000000000000, 0x002bdc545d6b4b87)); + BSON_ASSERT (decimal128_equal (&number_two, 0x3040000000000000, 0x000000e67a93c822)); + BSON_ASSERT (decimal128_equal (&negative_number, 0xb040000000000000, 0x002bdc545d6b4b87)); } void test_decimal128_install (TestSuite *suite) { - TestSuite_Add (suite, - "/bson/decimal128/to_string/infinity", - test_decimal128_to_string__infinity); - TestSuite_Add ( - suite, "/bson/decimal128/to_string/nan", test_decimal128_to_string__nan); - TestSuite_Add (suite, - "/bson/decimal128/to_string/regular", - test_decimal128_to_string__regular); - TestSuite_Add (suite, - "/bson/decimal128/to_string/scientific", - test_decimal128_to_string__scientific); - TestSuite_Add (suite, - "/bson/decimal128/to_string/zero", - test_decimal128_to_string__zeros); - TestSuite_Add (suite, - "/bson/decimal128/from_string/invalid", - test_decimal128_from_string__invalid_inputs); - TestSuite_Add (suite, - "/bson/decimal128/from_string/nan", - test_decimal128_from_string__nan); - TestSuite_Add (suite, - "/bson/decimal128/from_string/infinity", - test_decimal128_from_string__infinity); - TestSuite_Add (suite, - "/bson/decimal128/from_string/basic", - test_decimal128_from_string__simple); - TestSuite_Add (suite, - "/bson/decimal128/from_string/scientific", - test_decimal128_from_string__scientific); - TestSuite_Add (suite, - "/bson/decimal128/from_string/large", - test_decimal128_from_string__large); + TestSuite_Add (suite, "/bson/decimal128/to_string/infinity", test_decimal128_to_string__infinity); + TestSuite_Add (suite, "/bson/decimal128/to_string/nan", test_decimal128_to_string__nan); + TestSuite_Add (suite, "/bson/decimal128/to_string/regular", test_decimal128_to_string__regular); + TestSuite_Add (suite, "/bson/decimal128/to_string/scientific", test_decimal128_to_string__scientific); + TestSuite_Add (suite, "/bson/decimal128/to_string/zero", test_decimal128_to_string__zeros); + TestSuite_Add (suite, "/bson/decimal128/from_string/invalid", test_decimal128_from_string__invalid_inputs); + TestSuite_Add (suite, "/bson/decimal128/from_string/nan", test_decimal128_from_string__nan); + TestSuite_Add (suite, "/bson/decimal128/from_string/infinity", test_decimal128_from_string__infinity); + TestSuite_Add (suite, "/bson/decimal128/from_string/basic", test_decimal128_from_string__simple); + TestSuite_Add (suite, "/bson/decimal128/from_string/scientific", test_decimal128_from_string__scientific); + TestSuite_Add (suite, "/bson/decimal128/from_string/large", test_decimal128_from_string__large); TestSuite_Add (suite, "/bson/decimal128/from_string/exponent_normalization", test_decimal128_from_string__exponent_normalization); - TestSuite_Add (suite, - "/bson/decimal128/from_string/zero", - test_decimal128_from_string__zeros); - TestSuite_Add (suite, - "/bson/decimal128/from_string/with_length", - test_decimal128_from_string_w_len__special); + TestSuite_Add (suite, "/bson/decimal128/from_string/zero", test_decimal128_from_string__zeros); + TestSuite_Add (suite, "/bson/decimal128/from_string/with_length", test_decimal128_from_string_w_len__special); } diff --git a/src/libbson/tests/test-iso8601.c b/src/libbson/tests/test-iso8601.c index 78620db87c..164ceb3d04 100644 --- a/src/libbson/tests/test-iso8601.c +++ b/src/libbson/tests/test-iso8601.c @@ -21,10 +21,7 @@ test_date (const char *str, int64_t millis) } if (v != millis) { - fprintf (stderr, - "parsed value not correct: %" PRId64 " != %" PRId64 "\n", - millis, - v); + fprintf (stderr, "parsed value not correct: %" PRId64 " != %" PRId64 "\n", millis, v); fprintf (stderr, "parsing: [%s]\n", str); abort (); @@ -81,10 +78,8 @@ test_bson_iso8601_utc (void) */ test_date_rt ("1971-02-03T04:05:06.789Z", 34401906789ULL); - test_date_io ( - "1971-02-03T04:05:06.78Z", "1971-02-03T04:05:06.780Z", 34401906780ULL); - test_date_io ( - "1971-02-03T04:05:06.7Z", "1971-02-03T04:05:06.700Z", 34401906700ULL); + test_date_io ("1971-02-03T04:05:06.78Z", "1971-02-03T04:05:06.780Z", 34401906780ULL); + test_date_io ("1971-02-03T04:05:06.7Z", "1971-02-03T04:05:06.700Z", 34401906700ULL); test_date_rt ("1971-02-03T04:05:06Z", 34401906000ULL); test_date_io ("1971-02-03T04:05Z", "1971-02-03T04:05:00Z", 34401900000ULL); test_date_io ("1970-01-01T00:00:00.000Z", "1970-01-01T00:00:00Z", 0ULL); @@ -115,40 +110,25 @@ test_bson_iso8601_local (void) * digits. */ - test_date_io ("1971-02-03T09:16:06.789+0511", - "1971-02-03T04:05:06.789Z", - 34401906789ULL); - test_date_io ("1971-02-03T09:16:06.78+0511", - "1971-02-03T04:05:06.780Z", - 34401906780ULL); - test_date_io ( - "1971-02-03T09:16:06.7+0511", "1971-02-03T04:05:06.700Z", 34401906700ULL); - test_date_io ( - "1971-02-03T09:16:06+0511", "1971-02-03T04:05:06Z", 34401906000ULL); - test_date_io ( - "1971-02-03T09:16+0511", "1971-02-03T04:05:00Z", 34401900000ULL); + test_date_io ("1971-02-03T09:16:06.789+0511", "1971-02-03T04:05:06.789Z", 34401906789ULL); + test_date_io ("1971-02-03T09:16:06.78+0511", "1971-02-03T04:05:06.780Z", 34401906780ULL); + test_date_io ("1971-02-03T09:16:06.7+0511", "1971-02-03T04:05:06.700Z", 34401906700ULL); + test_date_io ("1971-02-03T09:16:06+0511", "1971-02-03T04:05:06Z", 34401906000ULL); + test_date_io ("1971-02-03T09:16+0511", "1971-02-03T04:05:00Z", 34401900000ULL); test_date_io ("1970-01-01T00:00:00.000Z", "1970-01-01T00:00:00Z", 0ULL); test_date_rt ("1970-06-30T01:06:40.981Z", 15556000981ULL); - test_date_io ("1970-06-29T21:06:40.981-0400", - "1970-06-30T01:06:40.981Z", - 15556000981ULL); + test_date_io ("1970-06-29T21:06:40.981-0400", "1970-06-30T01:06:40.981Z", 15556000981ULL); test_date_io ("1969-12-31T16:00:00.000-0800", "1970-01-01T00:00:00Z", 0ULL); if (!is_time_t_small) { - test_date_io ("2058-02-20T13:29:11.100-0500", - "2058-02-20T18:29:11.100Z", - 2781455351100ULL); + test_date_io ("2058-02-20T13:29:11.100-0500", "2058-02-20T18:29:11.100Z", 2781455351100ULL); test_date_rt ("3000-12-31T23:59:59Z", 32535215999000ULL); } else { test_date_rt ("2038-01-19T03:14:07Z", 2147483647000ULL); } - test_date_io ("2013-02-20T13:29:11.100-0500", - "2013-02-20T18:29:11.100Z", - 1361384951100ULL); - test_date_io ("2013-02-20T13:29:11.100-0501", - "2013-02-20T18:30:11.100Z", - 1361385011100ULL); + test_date_io ("2013-02-20T13:29:11.100-0500", "2013-02-20T18:29:11.100Z", 1361384951100ULL); + test_date_io ("2013-02-20T13:29:11.100-0501", "2013-02-20T18:30:11.100Z", 1361385011100ULL); test_date ("0000-01-01T00:00:00.000Z", -62167219200000LL); test_date ("0000-01-01T00:00:00.000+2300", -62167302000000LL); test_date ("9999-01-01T00:00:00.000Z", 253370764800000ULL); @@ -389,6 +369,5 @@ test_iso8601_install (TestSuite *suite) TestSuite_Add (suite, "/bson/iso8601/utc", test_bson_iso8601_utc); TestSuite_Add (suite, "/bson/iso8601/local", test_bson_iso8601_local); TestSuite_Add (suite, "/bson/iso8601/invalid", test_bson_iso8601_invalid); - TestSuite_Add ( - suite, "/bson/iso8601/leap_year", test_bson_iso8601_leap_year); + TestSuite_Add (suite, "/bson/iso8601/leap_year", test_bson_iso8601_leap_year); } diff --git a/src/libbson/tests/test-iter.c b/src/libbson/tests/test-iter.c index 6f2c0908af..696948348a 100644 --- a/src/libbson/tests/test-iter.c +++ b/src/libbson/tests/test-iter.c @@ -395,8 +395,7 @@ static void test_bson_iter_empty_key (void) { /* create a bson document empty keys. */ - bson_t *bson = BCON_NEW ( - "", "{", "x", BCON_INT32 (1), "", "{", "y", BCON_INT32 (2), "}", "}"); + bson_t *bson = BCON_NEW ("", "{", "x", BCON_INT32 (1), "", "{", "y", BCON_INT32 (2), "}", "}"); bson_iter_t iter; bson_iter_t descendant; @@ -657,8 +656,7 @@ test_bson_iter_find_descendant (void) BSON_ASSERT (bson_iter_int32 (&desc) == 1); bson_destroy (b); - b = BCON_NEW ( - "foo", "{", "bar", "[", "{", "baz", BCON_INT32 (1), "}", "]", "}"); + b = BCON_NEW ("foo", "{", "bar", "[", "{", "baz", BCON_INT32 (1), "}", "]", "}"); BSON_ASSERT (bson_iter_init (&iter, b)); BSON_ASSERT (bson_iter_find_descendant (&iter, "foo.bar.0.baz", &desc)); BSON_ASSERT (BSON_ITER_HOLDS_INT32 (&desc)); @@ -730,48 +728,27 @@ test_iter_install (TestSuite *suite) TestSuite_Add (suite, "/bson/iter/test_mixed", test_bson_iter_mixed); TestSuite_Add (suite, "/bson/iter/test_overflow", test_bson_iter_overflow); TestSuite_Add (suite, "/bson/iter/test_timeval", test_bson_iter_timeval); - TestSuite_Add ( - suite, "/bson/iter/test_trailing_null", test_bson_iter_trailing_null); + TestSuite_Add (suite, "/bson/iter/test_trailing_null", test_bson_iter_trailing_null); TestSuite_Add (suite, "/bson/iter/test_fuzz", test_bson_iter_fuzz); TestSuite_Add (suite, "/bson/iter/test_regex", test_bson_iter_regex); - TestSuite_Add (suite, - "/bson/iter/test_next_after_finish", - test_bson_iter_next_after_finish); + TestSuite_Add (suite, "/bson/iter/test_next_after_finish", test_bson_iter_next_after_finish); TestSuite_Add (suite, "/bson/iter/test_find_case", test_bson_iter_find_case); - TestSuite_Add ( - suite, "/bson/iter/test_find_w_len", test_bson_iter_find_w_len); - TestSuite_Add ( - suite, "/bson/iter/test_init_find_w_len", test_bson_iter_init_find_w_len); - TestSuite_Add ( - suite, "/bson/iter/test_bson_iter_as_double", test_bson_iter_as_double); - TestSuite_Add ( - suite, "/bson/iter/test_overwrite_int32", test_bson_iter_overwrite_int32); - TestSuite_Add ( - suite, "/bson/iter/test_overwrite_int64", test_bson_iter_overwrite_int64); - TestSuite_Add (suite, - "/bson/iter/test_overwrite_double", - test_bson_iter_overwrite_double); - TestSuite_Add ( - suite, "/bson/iter/test_overwrite_bool", test_bson_iter_overwrite_bool); - TestSuite_Add ( - suite, "/bson/iter/test_overwrite_oid", test_bson_iter_overwrite_oid); - TestSuite_Add (suite, - "/bson/iter/test_overwrite_timestamp", - test_bson_iter_overwrite_timestamp); - TestSuite_Add (suite, - "/bson/iter/test_overwrite_date_time", - test_bson_iter_overwrite_date_time); - TestSuite_Add (suite, - "/bson/iter/test_bson_iter_overwrite_decimal128", - test_bson_iter_overwrite_decimal128); + TestSuite_Add (suite, "/bson/iter/test_find_w_len", test_bson_iter_find_w_len); + TestSuite_Add (suite, "/bson/iter/test_init_find_w_len", test_bson_iter_init_find_w_len); + TestSuite_Add (suite, "/bson/iter/test_bson_iter_as_double", test_bson_iter_as_double); + TestSuite_Add (suite, "/bson/iter/test_overwrite_int32", test_bson_iter_overwrite_int32); + TestSuite_Add (suite, "/bson/iter/test_overwrite_int64", test_bson_iter_overwrite_int64); + TestSuite_Add (suite, "/bson/iter/test_overwrite_double", test_bson_iter_overwrite_double); + TestSuite_Add (suite, "/bson/iter/test_overwrite_bool", test_bson_iter_overwrite_bool); + TestSuite_Add (suite, "/bson/iter/test_overwrite_oid", test_bson_iter_overwrite_oid); + TestSuite_Add (suite, "/bson/iter/test_overwrite_timestamp", test_bson_iter_overwrite_timestamp); + TestSuite_Add (suite, "/bson/iter/test_overwrite_date_time", test_bson_iter_overwrite_date_time); + TestSuite_Add (suite, "/bson/iter/test_bson_iter_overwrite_decimal128", test_bson_iter_overwrite_decimal128); TestSuite_Add (suite, "/bson/iter/recurse", test_bson_iter_recurse); - TestSuite_Add ( - suite, "/bson/iter/init_find_case", test_bson_iter_init_find_case); - TestSuite_Add ( - suite, "/bson/iter/find_descendant", test_bson_iter_find_descendant); + TestSuite_Add (suite, "/bson/iter/init_find_case", test_bson_iter_init_find_case); + TestSuite_Add (suite, "/bson/iter/find_descendant", test_bson_iter_find_descendant); TestSuite_Add (suite, "/bson/iter/as_bool", test_bson_iter_as_bool); - TestSuite_Add ( - suite, "/bson/iter/binary_deprecated", test_bson_iter_binary_deprecated); + TestSuite_Add (suite, "/bson/iter/binary_deprecated", test_bson_iter_binary_deprecated); TestSuite_Add (suite, "/bson/iter/from_data", test_bson_iter_from_data); TestSuite_Add (suite, "/bson/iter/empty_key", test_bson_iter_empty_key); } diff --git a/src/libbson/tests/test-json.c b/src/libbson/tests/test-json.c index 815517b192..0aeeec3615 100644 --- a/src/libbson/tests/test-json.c +++ b/src/libbson/tests/test-json.c @@ -31,20 +31,16 @@ test_bson_json_allow_multiple (void) bson_oid_t oid_expected; int i; /* nested JSON tests code that reuses parser stack frames, CDRIVER-2524 */ - char *multiple_json = - "{\"a\": 1}" - "{\"b\": {\"$dbPointer\": " - " {\"$ref\": \"c\", \"$id\": {\"$oid\": \"12341234123412abcdababcd\"}}}}" - "{\"c\": {\"x\": 1}}"; + char *multiple_json = "{\"a\": 1}" + "{\"b\": {\"$dbPointer\": " + " {\"$ref\": \"c\", \"$id\": {\"$oid\": \"12341234123412abcdababcd\"}}}}" + "{\"c\": {\"x\": 1}}"; bson_oid_init_from_string (&oid_expected, "12341234123412abcdababcd"); for (i = 0; i < 2; i++) { - reader = bson_json_reader_new (multiple_json, - &test_bson_json_read_cb_helper, - NULL, - i == 1 /* allow_multiple */, - 0); + reader = + bson_json_reader_new (multiple_json, &test_bson_json_read_cb_helper, NULL, i == 1 /* allow_multiple */, 0); BSON_ASSERT (reader); @@ -105,11 +101,9 @@ test_bson_as_json_x1000 (void) BSON_ASSERT (bson_append_bool (b, "true", -1, true)); BSON_ASSERT (bson_append_bool (b, "false", -1, false)); BSON_ASSERT (bson_append_time_t (b, "date", -1, time (NULL))); - BSON_ASSERT ( - bson_append_timestamp (b, "timestamp", -1, (uint32_t) time (NULL), 1234)); + BSON_ASSERT (bson_append_timestamp (b, "timestamp", -1, (uint32_t) time (NULL), 1234)); BSON_ASSERT (bson_append_regex (b, "regex", -1, "^abcd", "xi")); - BSON_ASSERT ( - bson_append_dbpointer (b, "dbpointer", -1, "mycollection", &oid)); + BSON_ASSERT (bson_append_dbpointer (b, "dbpointer", -1, "mycollection", &oid)); BSON_ASSERT (bson_append_minkey (b, "minkey", -1)); BSON_ASSERT (bson_append_maxkey (b, "maxkey", -1)); BSON_ASSERT (bson_append_symbol (b, "symbol", -1, "var a = {};", -1)); @@ -122,8 +116,7 @@ test_bson_as_json_x1000 (void) { const uint8_t binary[] = {0, 1, 2, 3, 4}; - BSON_ASSERT (bson_append_binary ( - b, "binary", -1, BSON_SUBTYPE_BINARY, binary, sizeof binary)); + BSON_ASSERT (bson_append_binary (b, "binary", -1, BSON_SUBTYPE_BINARY, binary, sizeof binary)); } for (i = 0; i < 1000; i++) { @@ -158,38 +151,21 @@ test_bson_as_json_multi (void) BSON_ASSERT (bson_append_double (b, "Double", -1, -1.0)); { - const uint8_t binary[] = {0xa3, - 0x4c, - 0x38, - 0xf7, - 0xc3, - 0xab, - 0xed, - 0xc8, - 0xa3, - 0x78, - 0x14, - 0xa9, - 0x92, - 0xab, - 0x8d, - 0xb6}; - BSON_ASSERT (bson_append_binary ( - b, "Binary", -1, BSON_SUBTYPE_UUID_DEPRECATED, binary, sizeof binary)); + const uint8_t binary[] = { + 0xa3, 0x4c, 0x38, 0xf7, 0xc3, 0xab, 0xed, 0xc8, 0xa3, 0x78, 0x14, 0xa9, 0x92, 0xab, 0x8d, 0xb6}; + BSON_ASSERT (bson_append_binary (b, "Binary", -1, BSON_SUBTYPE_UUID_DEPRECATED, binary, sizeof binary)); } { const uint8_t binary[] = {1, 2, 3, 4, 5}; - BSON_ASSERT (bson_append_binary ( - b, "BinaryUserDefined", -1, BSON_SUBTYPE_USER, binary, sizeof binary)); + BSON_ASSERT (bson_append_binary (b, "BinaryUserDefined", -1, BSON_SUBTYPE_USER, binary, sizeof binary)); } BSON_ASSERT (bson_append_code (b, "Code", -1, "function() {}")); { bson_t *scope = bson_new (); - BSON_ASSERT (bson_append_code_with_scope ( - b, "CodeWithScope", -1, "function() {}", scope)); + BSON_ASSERT (bson_append_code_with_scope (b, "CodeWithScope", -1, "function() {}", scope)); bson_destroy (scope); } @@ -214,18 +190,15 @@ test_bson_as_json_multi (void) BSON_ASSERT (bson_append_timestamp (b, "Timestamp", -1, 42, 1)); BSON_ASSERT (bson_append_regex (b, "Regex", -1, "pattern", "")); BSON_ASSERT (bson_append_date_time (b, "DatetimeEpoch", -1, 0)); - BSON_ASSERT (bson_append_date_time ( - b, "DatetimePositive", -1, (int64_t) 2147483647LL)); - BSON_ASSERT (bson_append_date_time ( - b, "DatetimeNegative", -1, (int64_t) -2147483648LL)); + BSON_ASSERT (bson_append_date_time (b, "DatetimePositive", -1, (int64_t) 2147483647LL)); + BSON_ASSERT (bson_append_date_time (b, "DatetimeNegative", -1, (int64_t) -2147483648LL)); BSON_ASSERT (bson_append_bool (b, "True", -1, true)); BSON_ASSERT (bson_append_bool (b, "False", -1, false)); { bson_oid_t oid; bson_oid_init_from_string (&oid, "57e193d7a9cc81b4027498b1"); - BSON_ASSERT ( - bson_append_dbpointer (b, "DBPointer", -1, "collection", &oid)); + BSON_ASSERT (bson_append_dbpointer (b, "DBPointer", -1, "collection", &oid)); } { @@ -254,40 +227,39 @@ test_bson_as_json_multi (void) str = bson_as_json (b, &len); /* Based on multi-type-deprecated.json from BSON Corpus Tests. */ - ASSERT_CMPSTR ( - str, - "{" - " \"_id\" : { \"$oid\" : \"57e193d7a9cc81b4027498b5\" }," - " \"Symbol\" : \"symbol\"," - " \"String\" : \"string\"," - " \"Int32\" : 42," - " \"Int64\" : 42," - " \"Double\" : -1.0," - " \"Binary\" : { \"$binary\" : \"o0w498Or7cijeBSpkquNtg==\", \"$type\" : " - "\"03\" }," - " \"BinaryUserDefined\" : { \"$binary\" : \"AQIDBAU=\", \"$type\" : " - "\"80\" }," - " \"Code\" : { \"$code\" : \"function() {}\" }," - " \"CodeWithScope\" : { \"$code\" : \"function() {}\", \"$scope\" : { } " - "}," - " \"Subdocument\" : { \"foo\" : \"bar\" }," - " \"Array\" : [ 1, 2, 3, 4, 5 ]," - " \"Timestamp\" : { \"$timestamp\" : { \"t\" : 42, \"i\" : 1 } }," - " \"Regex\" : { \"$regex\" : \"pattern\", \"$options\" : \"\" }," - " \"DatetimeEpoch\" : { \"$date\" : 0 }," - " \"DatetimePositive\" : { \"$date\" : 2147483647 }," - " \"DatetimeNegative\" : { \"$date\" : -2147483648 }," - " \"True\" : true," - " \"False\" : false," - " \"DBPointer\" : { \"$ref\" : \"collection\", \"$id\" : " - "\"57e193d7a9cc81b4027498b1\" }," - " \"DBRef\" : { \"$ref\" : \"collection\", \"$id\" : { \"$oid\" : " - "\"57fd71e96e32ab4225b723fb\" }, \"$db\" : \"database\" }," - " \"Minkey\" : { \"$minKey\" : 1 }," - " \"Maxkey\" : { \"$maxKey\" : 1 }," - " \"Null\" : null," - " \"Undefined\" : { \"$undefined\" : true }," - " \"Decimal128\" : { \"$numberDecimal\" : \"11\" } }"); + ASSERT_CMPSTR (str, + "{" + " \"_id\" : { \"$oid\" : \"57e193d7a9cc81b4027498b5\" }," + " \"Symbol\" : \"symbol\"," + " \"String\" : \"string\"," + " \"Int32\" : 42," + " \"Int64\" : 42," + " \"Double\" : -1.0," + " \"Binary\" : { \"$binary\" : \"o0w498Or7cijeBSpkquNtg==\", \"$type\" : " + "\"03\" }," + " \"BinaryUserDefined\" : { \"$binary\" : \"AQIDBAU=\", \"$type\" : " + "\"80\" }," + " \"Code\" : { \"$code\" : \"function() {}\" }," + " \"CodeWithScope\" : { \"$code\" : \"function() {}\", \"$scope\" : { } " + "}," + " \"Subdocument\" : { \"foo\" : \"bar\" }," + " \"Array\" : [ 1, 2, 3, 4, 5 ]," + " \"Timestamp\" : { \"$timestamp\" : { \"t\" : 42, \"i\" : 1 } }," + " \"Regex\" : { \"$regex\" : \"pattern\", \"$options\" : \"\" }," + " \"DatetimeEpoch\" : { \"$date\" : 0 }," + " \"DatetimePositive\" : { \"$date\" : 2147483647 }," + " \"DatetimeNegative\" : { \"$date\" : -2147483648 }," + " \"True\" : true," + " \"False\" : false," + " \"DBPointer\" : { \"$ref\" : \"collection\", \"$id\" : " + "\"57e193d7a9cc81b4027498b1\" }," + " \"DBRef\" : { \"$ref\" : \"collection\", \"$id\" : { \"$oid\" : " + "\"57fd71e96e32ab4225b723fb\" }, \"$db\" : \"database\" }," + " \"Minkey\" : { \"$minKey\" : 1 }," + " \"Maxkey\" : { \"$maxKey\" : 1 }," + " \"Null\" : null," + " \"Undefined\" : { \"$undefined\" : true }," + " \"Decimal128\" : { \"$numberDecimal\" : \"11\" } }"); bson_free (str); bson_destroy (b); @@ -448,18 +420,15 @@ test_bson_as_json_code (void) bson_reinit (&code); /* empty scope */ - BSON_ASSERT ( - BSON_APPEND_CODE_WITH_SCOPE (&code, "c", "function () {}", &scope)); + BSON_ASSERT (BSON_APPEND_CODE_WITH_SCOPE (&code, "c", "function () {}", &scope)); str = bson_as_json (&code, NULL); - ASSERT_CMPSTR ( - str, "{ \"c\" : { \"$code\" : \"function () {}\", \"$scope\" : { } } }"); + ASSERT_CMPSTR (str, "{ \"c\" : { \"$code\" : \"function () {}\", \"$scope\" : { } } }"); bson_free (str); bson_reinit (&code); BSON_APPEND_INT32 (&scope, "x", 1); - BSON_ASSERT ( - BSON_APPEND_CODE_WITH_SCOPE (&code, "c", "function () {}", &scope)); + BSON_ASSERT (BSON_APPEND_CODE_WITH_SCOPE (&code, "c", "function () {}", &scope)); str = bson_as_json (&code, NULL); ASSERT_CMPSTR (str, "{ \"c\" : { \"$code\" : \"function () {}\", \"$scope\" " @@ -763,9 +732,7 @@ rand_r (unsigned int *seed) #endif static char * -rand_str (size_t maxlen, - unsigned int *seed /* IN / OUT */, - char *buf /* IN / OUT */) +rand_str (size_t maxlen, unsigned int *seed /* IN / OUT */, char *buf /* IN / OUT */) { size_t len = RAND_R (seed) % (maxlen - 1); size_t i; @@ -809,16 +776,10 @@ test_bson_json_read_buffering (void) bsons[docs_idx] = bson_new (); n_elems = RAND_R (&seed) % 5; for (elem_idx = 0; elem_idx < n_elems; elem_idx++) { - bson_append_utf8 (bsons[docs_idx], - rand_str (sizeof key, &seed, key), - -1, - rand_str (sizeof val, &seed, val), - -1); - - bson_append_int32 (bsons[docs_idx], - rand_str (sizeof key, &seed, key), - -1, - RAND_R (&seed) % INT32_MAX); + bson_append_utf8 ( + bsons[docs_idx], rand_str (sizeof key, &seed, key), -1, rand_str (sizeof val, &seed, val), -1); + + bson_append_int32 (bsons[docs_idx], rand_str (sizeof key, &seed, key), -1, RAND_R (&seed) % INT32_MAX); } /* append the BSON document's JSON representation to "json" */ @@ -828,12 +789,10 @@ test_bson_json_read_buffering (void) bson_free (json_tmp); } - reader = bson_json_data_reader_new ( - true /* "allow_multiple" is unused */, - (size_t) RAND_R (&seed) % 100 /* bufsize*/); + reader = bson_json_data_reader_new (true /* "allow_multiple" is unused */, + (size_t) RAND_R (&seed) % 100 /* bufsize*/); - bson_json_data_reader_ingest ( - reader, (uint8_t *) json->str, json->len); + bson_json_data_reader_ingest (reader, (uint8_t *) json->str, json->len); for (docs_idx = 0; docs_idx < n_docs; docs_idx++) { bson_reinit (&bson_out); @@ -848,8 +807,7 @@ test_bson_json_read_buffering (void) } /* finished parsing */ - ASSERT_CMPINT ( - 0, ==, bson_json_reader_read (reader, &bson_out, &error)); + ASSERT_CMPINT (0, ==, bson_json_reader_read (reader, &bson_out, &error)); bson_json_reader_destroy (reader); bson_string_truncate (json, 0); @@ -907,8 +865,7 @@ _test_bson_json_read_compare (const char *json, int size, ...) static void test_bson_json_read (void) { - char *json = bson_strdup_printf ( - "%s { \"after\": \"b\" } { \"twice\" : true }", json_with_all_types ()); + char *json = bson_strdup_printf ("%s { \"after\": \"b\" } { \"twice\" : true }", json_with_all_types ()); bson_oid_t oid; bson_t *first, *second, *third; @@ -931,12 +888,11 @@ test_bson_json_read_invalid_base64 (void) bson_error_t error = {0}; BSON_ASSERT (!bson_new_from_json ((uint8_t *) bad_json, -1, &error)); - ASSERT_ERROR_CONTAINS ( - error, - BSON_ERROR_JSON, - BSON_JSON_ERROR_READ_INVALID_PARAM, - "Invalid input string \"\x30\x30\x30\x30\xcd\x8d\x79\", looking for " - "base64-encoded binary"); + ASSERT_ERROR_CONTAINS (error, + BSON_ERROR_JSON, + BSON_JSON_ERROR_READ_INVALID_PARAM, + "Invalid input string \"\x30\x30\x30\x30\xcd\x8d\x79\", looking for " + "base64-encoded binary"); } static void @@ -945,8 +901,7 @@ test_bson_json_read_raw_utf8 (void) bson_t *bson; bson_iter_t iter; - bson = bson_new_from_json ( - (const uint8_t *) "{\"" EU "\": \"" EU "\"}", -1, NULL); + bson = bson_new_from_json ((const uint8_t *) "{\"" EU "\": \"" EU "\"}", -1, NULL); ASSERT (bson); ASSERT (bson_iter_init_find (&iter, bson, EU)); ASSERT_CMPSTR (bson_iter_key (&iter), EU); @@ -964,18 +919,12 @@ test_bson_json_read_corrupt_utf8 (void) bson_error_t error = {0}; BSON_ASSERT (!bson_new_from_json ((uint8_t *) bad_key, -1, &error)); - ASSERT_ERROR_CONTAINS (error, - BSON_ERROR_JSON, - BSON_JSON_ERROR_READ_CORRUPT_JS, - "invalid bytes in UTF8 string"); + ASSERT_ERROR_CONTAINS (error, BSON_ERROR_JSON, BSON_JSON_ERROR_READ_CORRUPT_JS, "invalid bytes in UTF8 string"); memset (&error, 0, sizeof error); BSON_ASSERT (!bson_new_from_json ((uint8_t *) bad_value, -1, &error)); - ASSERT_ERROR_CONTAINS (error, - BSON_ERROR_JSON, - BSON_JSON_ERROR_READ_CORRUPT_JS, - "invalid bytes in UTF8 string"); + ASSERT_ERROR_CONTAINS (error, BSON_ERROR_JSON, BSON_JSON_ERROR_READ_CORRUPT_JS, "invalid bytes in UTF8 string"); } @@ -984,26 +933,24 @@ static void test_bson_json_read_corrupt_document (void) { /* like {a: {a: "\x80"}}, the value is invalid UTF-8 */ - const char bad_doc[] = "\x16\x00\x00\x00" /* length */ - "\x03\x61\x00" /* subdoc field with key "a" */ - "\x0e\x00\x00\x00" /* length of subdoc in bytes */ + const char bad_doc[] = "\x16\x00\x00\x00" /* length */ + "\x03\x61\x00" /* subdoc field with key "a" */ + "\x0e\x00\x00\x00" /* length of subdoc in bytes */ "\x02\x61\x00\x02\x00\x00\x00\x80\x00" /* a: "\x80" */ - "\x00"; /* terminator */ + "\x00"; /* terminator */ /* like {a: ["\x80"]}, the inner value is invalid UTF-8 */ - const char bad_array[] = "\x16\x00\x00\x00" /* length */ - "\x04\x61\x00" /* array field with key "a" */ - "\x0e\x00\x00\x00" /* length of array in bytes */ - "\x02\x30\x00" /* key "0" */ + const char bad_array[] = "\x16\x00\x00\x00" /* length */ + "\x04\x61\x00" /* array field with key "a" */ + "\x0e\x00\x00\x00" /* length of array in bytes */ + "\x02\x30\x00" /* key "0" */ "\x02\x00\x00\x00\x80\x00" /* string "\x80" */ "\x00"; /* terminator */ bson_t bson; - BSON_ASSERT ( - bson_init_static (&bson, (uint8_t *) bad_doc, sizeof (bad_doc))); + BSON_ASSERT (bson_init_static (&bson, (uint8_t *) bad_doc, sizeof (bad_doc))); BSON_ASSERT (!bson_as_json (&bson, NULL)); - BSON_ASSERT ( - bson_init_static (&bson, (uint8_t *) bad_array, sizeof (bad_array))); + BSON_ASSERT (bson_init_static (&bson, (uint8_t *) bad_array, sizeof (bad_array))); BSON_ASSERT (!bson_as_json (&bson, NULL)); } @@ -1030,29 +977,27 @@ test_bson_json_read_dbpointer (void) bool r; /* must have both $ref and $id, $id must be ObjectId */ - const char *invalid[] = { - "{\"p\": {\"$dbPointer\": {\"$ref\": \"db.collection\"}}", - "$dbPointer requires both $id and $ref", + const char *invalid[] = {"{\"p\": {\"$dbPointer\": {\"$ref\": \"db.collection\"}}", + "$dbPointer requires both $id and $ref", - "{\"p\": {\"$dbPointer\": {\"$ref\": \"db.collection\", \"$id\": 1}}", - "$dbPointer.$id must be like {\"$oid\": ...\"}", + "{\"p\": {\"$dbPointer\": {\"$ref\": \"db.collection\", \"$id\": 1}}", + "$dbPointer.$id must be like {\"$oid\": ...\"}", - "{\"p\": {\"$dbPointer\": {\"$id\": {" - "\"$oid\": \"57e193d7a9cc81b4027498b1\"}}}}", - "$dbPointer requires both $id and $ref", + "{\"p\": {\"$dbPointer\": {\"$id\": {" + "\"$oid\": \"57e193d7a9cc81b4027498b1\"}}}}", + "$dbPointer requires both $id and $ref", - "{\"p\": {\"$dbPointer\": {}}}", - "Empty $dbPointer", + "{\"p\": {\"$dbPointer\": {}}}", + "Empty $dbPointer", - NULL}; + NULL}; const char **p; for (p = invalid; *p; p += 2) { r = bson_init_from_json (&b, *p, -1, &error); BSON_ASSERT (!r); - ASSERT_ERROR_CONTAINS ( - error, BSON_ERROR_JSON, BSON_JSON_ERROR_READ_INVALID_PARAM, *(p + 1)); + ASSERT_ERROR_CONTAINS (error, BSON_ERROR_JSON, BSON_JSON_ERROR_READ_INVALID_PARAM, *(p + 1)); } } @@ -1066,8 +1011,7 @@ test_bson_json_read_legacy_regex (void) const char *pattern; const char *flags; - r = bson_init_from_json ( - &b, "{\"a\": {\"$regex\": \"abc\", \"$options\": \"ix\"}}", -1, &error); + r = bson_init_from_json (&b, "{\"a\": {\"$regex\": \"abc\", \"$options\": \"ix\"}}", -1, &error); ASSERT_OR_PRINT (r, error); BCON_EXTRACT (&b, "a", BCONE_REGEX (pattern, flags)); ASSERT_CMPSTR (pattern, "abc"); @@ -1085,10 +1029,8 @@ test_bson_json_read_legacy_regex (void) r = bson_init_from_json (&b, "{\"a\": {\"$options\": \"ix\"}}", -1, &error); BSON_ASSERT (!r); - ASSERT_ERROR_CONTAINS (error, - BSON_ERROR_JSON, - BSON_JSON_ERROR_READ_INVALID_PARAM, - "Missing \"$regex\" after \"$options\""); + ASSERT_ERROR_CONTAINS ( + error, BSON_ERROR_JSON, BSON_JSON_ERROR_READ_INVALID_PARAM, "Missing \"$regex\" after \"$options\""); } @@ -1101,16 +1043,14 @@ test_bson_json_read_regex_options_order (void) const char *pattern; const char *flags; - r = bson_init_from_json ( - &b, "{\"a\": {\"$regex\": \"\", \"$options\": \"ism\"}}", -1, &error); + r = bson_init_from_json (&b, "{\"a\": {\"$regex\": \"\", \"$options\": \"ism\"}}", -1, &error); ASSERT_OR_PRINT (r, error); BCON_EXTRACT (&b, "a", BCONE_REGEX (pattern, flags)); ASSERT_CMPSTR (flags, "ims"); bson_destroy (&b); - r = bson_init_from_json ( - &b, "{\"a\": {\"$regex\": \"\", \"$options\": \"misl\"}}", -1, &error); + r = bson_init_from_json (&b, "{\"a\": {\"$regex\": \"\", \"$options\": \"misl\"}}", -1, &error); ASSERT_OR_PRINT (r, error); BCON_EXTRACT (&b, "a", BCONE_REGEX (pattern, flags)); ASSERT_CMPSTR (flags, "ilms"); @@ -1129,11 +1069,7 @@ test_bson_json_read_binary (void) uint32_t len; const uint8_t *binary; - r = bson_init_from_json ( - &b, - "{\"b\": {\"$binary\": {\"base64\": \"Zm9v\", \"subType\": \"05\"}}}", - -1, - &error); + r = bson_init_from_json (&b, "{\"b\": {\"$binary\": {\"base64\": \"Zm9v\", \"subType\": \"05\"}}}", -1, &error); ASSERT_OR_PRINT (r, error); BCON_EXTRACT (&b, "b", BCONE_BIN (subtype, binary, len)); @@ -1143,11 +1079,7 @@ test_bson_json_read_binary (void) bson_destroy (&b); - r = bson_init_from_json ( - &b, - "{\"b\": {\"$binary\": {\"subType\": \"05\", \"base64\": \"Zm9v\"}}}", - -1, - &error); + r = bson_init_from_json (&b, "{\"b\": {\"$binary\": {\"subType\": \"05\", \"base64\": \"Zm9v\"}}}", -1, &error); ASSERT_OR_PRINT (r, error); BCON_EXTRACT (&b, "b", BCONE_BIN (subtype, binary, len)); ASSERT_CMPINT ((int) subtype, ==, 5); @@ -1157,24 +1089,18 @@ test_bson_json_read_binary (void) bson_destroy (&b); /* no base64 */ - r = bson_init_from_json ( - &b, "{\"b\": {\"$binary\": {\"subType\": \"5\"}}}", -1, &error); + r = bson_init_from_json (&b, "{\"b\": {\"$binary\": {\"subType\": \"5\"}}}", -1, &error); BSON_ASSERT (!r); - ASSERT_ERROR_CONTAINS (error, - BSON_ERROR_JSON, - BSON_JSON_ERROR_READ_INVALID_PARAM, - "Missing \"base64\" after \"subType\""); + ASSERT_ERROR_CONTAINS ( + error, BSON_ERROR_JSON, BSON_JSON_ERROR_READ_INVALID_PARAM, "Missing \"base64\" after \"subType\""); memset (&error, 0, sizeof error); /* no subType */ - r = bson_init_from_json ( - &b, "{\"b\": {\"$binary\": {\"base64\": \"Zm9v\"}}}", -1, &error); + r = bson_init_from_json (&b, "{\"b\": {\"$binary\": {\"base64\": \"Zm9v\"}}}", -1, &error); BSON_ASSERT (!r); - ASSERT_ERROR_CONTAINS (error, - BSON_ERROR_JSON, - BSON_JSON_ERROR_READ_INVALID_PARAM, - "Missing \"subType\" after \"base64\""); + ASSERT_ERROR_CONTAINS ( + error, BSON_ERROR_JSON, BSON_JSON_ERROR_READ_INVALID_PARAM, "Missing \"subType\" after \"base64\""); } @@ -1275,17 +1201,11 @@ test_bson_json_read_empty (void) bson_ptr = bson_new_from_json ((uint8_t *) "", 0, &error); BSON_ASSERT (!bson_ptr); - ASSERT_ERROR_CONTAINS (error, - BSON_ERROR_JSON, - BSON_JSON_ERROR_READ_INVALID_PARAM, - "Empty JSON string"); + ASSERT_ERROR_CONTAINS (error, BSON_ERROR_JSON, BSON_JSON_ERROR_READ_INVALID_PARAM, "Empty JSON string"); memset (&error, 0, sizeof error); bson_init_from_json (&bson, "", 0, &error); - ASSERT_ERROR_CONTAINS (error, - BSON_ERROR_JSON, - BSON_JSON_ERROR_READ_INVALID_PARAM, - "Empty JSON string"); + ASSERT_ERROR_CONTAINS (error, BSON_ERROR_JSON, BSON_JSON_ERROR_READ_INVALID_PARAM, "Empty JSON string"); } static void @@ -1297,17 +1217,15 @@ test_bson_json_read_missing_complex (void) }\n\ }"; - test_bson_json_error ( - json, BSON_ERROR_JSON, BSON_JSON_ERROR_READ_INVALID_PARAM); + test_bson_json_error (json, BSON_ERROR_JSON, BSON_JSON_ERROR_READ_INVALID_PARAM); } static void test_bson_json_read_invalid_binary (void) { bson_error_t error; - const char *json = - "{ " - " \"bin\" : { \"$binary\" : \"invalid\", \"$type\" : \"80\" } }"; + const char *json = "{ " + " \"bin\" : { \"$binary\" : \"invalid\", \"$type\" : \"80\" } }"; bson_t b; bool r; @@ -1323,8 +1241,7 @@ test_bson_json_read_invalid_json (void) }"; bson_t *b; - test_bson_json_error ( - json, BSON_ERROR_JSON, BSON_JSON_ERROR_READ_CORRUPT_JS); + test_bson_json_error (json, BSON_ERROR_JSON, BSON_JSON_ERROR_READ_CORRUPT_JS); b = bson_new_from_json ((uint8_t *) "1", 1, NULL); BSON_ASSERT (!b); @@ -1360,8 +1277,7 @@ test_bson_json_read_bad_cb (void) int r; bson_t bson = BSON_INITIALIZER; - reader = bson_json_reader_new ( - NULL, &test_bson_json_read_bad_cb_helper, NULL, false, 0); + reader = bson_json_reader_new (NULL, &test_bson_json_read_bad_cb_helper, NULL, false, 0); r = bson_json_reader_read (reader, &bson, &error); @@ -1390,8 +1306,7 @@ test_bson_json_read_invalid (void) int r; bson_t bson = BSON_INITIALIZER; - reader = bson_json_reader_new ( - NULL, test_bson_json_read_invalid_helper, NULL, false, 0); + reader = bson_json_reader_new (NULL, test_bson_json_read_invalid_helper, NULL, false, 0); r = bson_json_reader_read (reader, &bson, &error); @@ -1411,8 +1326,7 @@ test_bson_json_number_long (void) bson_t b; bool r; - r = bson_init_from_json ( - &b, "{\"key\": {\"$numberLong\": \"4611686018427387904\"}}", -1, &error); + r = bson_init_from_json (&b, "{\"key\": {\"$numberLong\": \"4611686018427387904\"}}", -1, &error); if (!r) fprintf (stderr, "%s\n", error.message); BSON_ASSERT (r); @@ -1422,14 +1336,11 @@ test_bson_json_number_long (void) BSON_ASSERT (bson_iter_int64 (&iter) == 4611686018427387904LL); bson_destroy (&b); - BSON_ASSERT (!bson_init_from_json ( - &b, "{\"key\": {\"$numberLong\": \"461168601abcd\"}}", -1, &error)); - BSON_ASSERT (!bson_init_from_json ( - &b, "{\"key\": {\"$numberLong\": \"461168601abcd\"}}", -1, &error)); + BSON_ASSERT (!bson_init_from_json (&b, "{\"key\": {\"$numberLong\": \"461168601abcd\"}}", -1, &error)); + BSON_ASSERT (!bson_init_from_json (&b, "{\"key\": {\"$numberLong\": \"461168601abcd\"}}", -1, &error)); /* INT64_MAX */ - r = bson_init_from_json ( - &b, "{\"x\": {\"$numberLong\": \"9223372036854775807\"}}", -1, &error); + r = bson_init_from_json (&b, "{\"x\": {\"$numberLong\": \"9223372036854775807\"}}", -1, &error); ASSERT_OR_PRINT (r, error); BSON_ASSERT (bson_iter_init_find (&iter, &b, "x")); BSON_ASSERT (BSON_ITER_HOLDS_INT64 (&iter)); @@ -1437,8 +1348,7 @@ test_bson_json_number_long (void) bson_destroy (&b); /* INT64_MIN */ - r = bson_init_from_json ( - &b, "{\"x\": {\"$numberLong\": \"-9223372036854775808\"}}", -1, &error); + r = bson_init_from_json (&b, "{\"x\": {\"$numberLong\": \"-9223372036854775808\"}}", -1, &error); ASSERT_OR_PRINT (r, error); BSON_ASSERT (bson_iter_init_find (&iter, &b, "x")); @@ -1447,37 +1357,28 @@ test_bson_json_number_long (void) bson_destroy (&b); /* INT64_MAX + 1 */ - r = bson_init_from_json ( - &b, "{\"x\": {\"$numberLong\": \"9223372036854775808\"}}", -1, &error); + r = bson_init_from_json (&b, "{\"x\": {\"$numberLong\": \"9223372036854775808\"}}", -1, &error); BSON_ASSERT (!r); - ASSERT_ERROR_CONTAINS (error, - BSON_ERROR_JSON, - BSON_JSON_ERROR_READ_INVALID_PARAM, - "Number \"9223372036854775808\" is out of range"); + ASSERT_ERROR_CONTAINS ( + error, BSON_ERROR_JSON, BSON_JSON_ERROR_READ_INVALID_PARAM, "Number \"9223372036854775808\" is out of range"); memset (&error, 0, sizeof error); /* INT64_MIN - 1 */ - r = bson_init_from_json ( - &b, "{\"x\": {\"$numberLong\": \"-9223372036854775809\"}}", -1, &error); + r = bson_init_from_json (&b, "{\"x\": {\"$numberLong\": \"-9223372036854775809\"}}", -1, &error); BSON_ASSERT (!r); - ASSERT_ERROR_CONTAINS (error, - BSON_ERROR_JSON, - BSON_JSON_ERROR_READ_INVALID_PARAM, - "Number \"-9223372036854775809\" is out of range"); + ASSERT_ERROR_CONTAINS ( + error, BSON_ERROR_JSON, BSON_JSON_ERROR_READ_INVALID_PARAM, "Number \"-9223372036854775809\" is out of range"); memset (&error, 0, sizeof error); - r = bson_init_from_json ( - &b, "{\"x\": {\"$numberLong\": \"10000000000000000000\"}}", -1, &error); + r = bson_init_from_json (&b, "{\"x\": {\"$numberLong\": \"10000000000000000000\"}}", -1, &error); BSON_ASSERT (!r); - ASSERT_ERROR_CONTAINS (error, - BSON_ERROR_JSON, - BSON_JSON_ERROR_READ_INVALID_PARAM, - "Number \"10000000000000000000\" is out of range"); + ASSERT_ERROR_CONTAINS ( + error, BSON_ERROR_JSON, BSON_JSON_ERROR_READ_INVALID_PARAM, "Number \"10000000000000000000\" is out of range"); memset (&error, 0, sizeof error); @@ -1485,10 +1386,8 @@ test_bson_json_number_long (void) r = bson_init_from_json (&b, "{\"x\": -10000000000000000000}", -1, &error); BSON_ASSERT (!r); - ASSERT_ERROR_CONTAINS (error, - BSON_ERROR_JSON, - BSON_JSON_ERROR_READ_INVALID_PARAM, - "Number \"-10000000000000000000\" is out of range"); + ASSERT_ERROR_CONTAINS ( + error, BSON_ERROR_JSON, BSON_JSON_ERROR_READ_INVALID_PARAM, "Number \"-10000000000000000000\" is out of range"); } static void @@ -1525,26 +1424,21 @@ test_bson_json_code (void) bson_t *scope1 = BCON_NEW ("var", BCON_INT32 (1)); bson_t *bson_code_w_scope = BCON_NEW ("a", BCON_CODEWSCOPE ("b", scope1)); - const char *json_code_w_scope_special = - "{\"a\": {\"$code\": \"b\", " - " \"$scope\": {\"var2\": {\"$numberLong\": \"2\"}}}}"; + const char *json_code_w_scope_special = "{\"a\": {\"$code\": \"b\", " + " \"$scope\": {\"var2\": {\"$numberLong\": \"2\"}}}}"; bson_t *scope2 = BCON_NEW ("var2", BCON_INT64 (2)); - bson_t *bson_code_w_scope_special = - BCON_NEW ("a", BCON_CODEWSCOPE ("b", scope2)); - - const char *json_2_codes_w_scope = - "{\"a\": {\"$code\": \"b\", " - " \"$scope\": {\"var\": 1}}," - " \"c\": {\"$code\": \"d\", " - " \"$scope\": {\"var2\": {\"$numberLong\": \"2\"}}}}"; - bson_t *bson_2_codes_w_scope = BCON_NEW ( - "a", BCON_CODEWSCOPE ("b", scope1), "c", BCON_CODEWSCOPE ("d", scope2)); - - const char *json_code_then_regular = - "{\"a\": {\"$code\": \"b\", " - " \"$scope\": {\"var\": 1}}," - " \"c\": {\"key1\": \"value\", " - " \"subdoc\": {\"key2\": \"value2\"}}}"; + bson_t *bson_code_w_scope_special = BCON_NEW ("a", BCON_CODEWSCOPE ("b", scope2)); + + const char *json_2_codes_w_scope = "{\"a\": {\"$code\": \"b\", " + " \"$scope\": {\"var\": 1}}," + " \"c\": {\"$code\": \"d\", " + " \"$scope\": {\"var2\": {\"$numberLong\": \"2\"}}}}"; + bson_t *bson_2_codes_w_scope = BCON_NEW ("a", BCON_CODEWSCOPE ("b", scope1), "c", BCON_CODEWSCOPE ("d", scope2)); + + const char *json_code_then_regular = "{\"a\": {\"$code\": \"b\", " + " \"$scope\": {\"var\": 1}}," + " \"c\": {\"key1\": \"value\", " + " \"subdoc\": {\"key2\": \"value2\"}}}"; bson_t *bson_code_then_regular = BCON_NEW ("a", BCON_CODEWSCOPE ("b", scope1), @@ -1561,20 +1455,17 @@ test_bson_json_code (void) const char *json_code_w_scope_reverse = "{\"a\": {\"$scope\": {\"var\": 1}, " " \"$code\": \"b\"}}"; - bson_t *bson_code_w_scope_reverse = - BCON_NEW ("a", BCON_CODEWSCOPE ("b", scope1)); + bson_t *bson_code_w_scope_reverse = BCON_NEW ("a", BCON_CODEWSCOPE ("b", scope1)); const char *json_code_w_scope_nest = "{\"a\": {\"$code\": \"b\", " " \"$scope\": {\"var\": {}}}}"; bson_t *scope3 = BCON_NEW ("var", "{", "}"); - bson_t *bson_code_w_scope_nest = - BCON_NEW ("a", BCON_CODEWSCOPE ("b", scope3)); + bson_t *bson_code_w_scope_nest = BCON_NEW ("a", BCON_CODEWSCOPE ("b", scope3)); - const char *json_code_w_scope_nest_deep = - "{\"a\": {\"$code\": \"b\", " - " \"$scope\": {\"arr\": [1, 2], \"d\": {}," - " \"n\": {\"$numberLong\": \"1\"}," - " \"d2\": {\"x\": 1, \"d3\": {\"z\": 3}}}}}"; + const char *json_code_w_scope_nest_deep = "{\"a\": {\"$code\": \"b\", " + " \"$scope\": {\"arr\": [1, 2], \"d\": {}," + " \"n\": {\"$numberLong\": \"1\"}," + " \"d2\": {\"x\": 1, \"d3\": {\"z\": 3}}}}}"; bson_t *scope_deep = BCON_NEW ("arr", "[", @@ -1597,22 +1488,18 @@ test_bson_json_code (void) "}", "}"); - bson_t *bson_code_w_scope_nest_deep = - BCON_NEW ("a", BCON_CODEWSCOPE ("b", scope_deep)); + bson_t *bson_code_w_scope_nest_deep = BCON_NEW ("a", BCON_CODEWSCOPE ("b", scope_deep)); const char *json_code_w_empty_scope = "{\"a\": {\"$code\": \"b\", " " \"$scope\": {}}}"; bson_t *empty = bson_new (); - bson_t *bson_code_w_empty_scope = - BCON_NEW ("a", BCON_CODEWSCOPE ("b", empty)); + bson_t *bson_code_w_empty_scope = BCON_NEW ("a", BCON_CODEWSCOPE ("b", empty)); - const char *json_code_in_scope = - "{\"a\": {\"$code\": \"b\", " - " \"$scope\": {\"x\": {\"$code\": \"c\"}}}}"; + const char *json_code_in_scope = "{\"a\": {\"$code\": \"b\", " + " \"$scope\": {\"x\": {\"$code\": \"c\"}}}}"; bson_t *code_in_scope = BCON_NEW ("x", "{", "$code", BCON_UTF8 ("c"), "}"); - bson_t *bson_code_in_scope = - BCON_NEW ("a", BCON_CODEWSCOPE ("b", code_in_scope)); + bson_t *bson_code_in_scope = BCON_NEW ("a", BCON_CODEWSCOPE ("b", code_in_scope)); typedef struct { const char *json; @@ -1679,25 +1566,18 @@ test_bson_json_code_errors (void) {"{\"a\": {\"$scope\": {}}", "Missing $code after $scope"}, {"{\"a\": {\"$scope\": {}, \"$x\": 1}", "Invalid key \"$x\""}, {"{\"a\": {\"$scope\": {\"a\": 1}}", "Missing $code after $scope"}, - {"{\"a\": {\"$code\": \"\", \"$scope\": \"a\"}}", - "Invalid read of \"a\""}, - {"{\"a\": {\"$code\": \"\", \"$scope\": 1}}", - "Unexpected integer 1 in state \"IN_BSON_TYPE_SCOPE_STARTMAP\""}, + {"{\"a\": {\"$code\": \"\", \"$scope\": \"a\"}}", "Invalid read of \"a\""}, + {"{\"a\": {\"$code\": \"\", \"$scope\": 1}}", "Unexpected integer 1 in state \"IN_BSON_TYPE_SCOPE_STARTMAP\""}, {"{\"a\": {\"$code\": \"\", \"$scope\": []}}", "Invalid read of \"[\""}, - {"{\"a\": {\"$code\": \"\", \"x\": 1}}", - "Invalid key \"x\". Looking for values for type \"code\""}, + {"{\"a\": {\"$code\": \"\", \"x\": 1}}", "Invalid key \"x\". Looking for values for type \"code\""}, {"{\"a\": {\"$code\": \"\", \"$x\": 1}}", "Invalid key \"$x\""}, - {"{\"a\": {\"$code\": \"\", \"$numberLong\": \"1\"}}", - "Invalid key \"$numberLong\""}, + {"{\"a\": {\"$code\": \"\", \"$numberLong\": \"1\"}}", "Invalid key \"$numberLong\""}, }; for (i = 0; i < sizeof (tests) / (sizeof (code_error_test_t)); i++) { r = bson_init_from_json (&b, tests[i].json, -1, &error); BSON_ASSERT (!r); - ASSERT_ERROR_CONTAINS (error, - BSON_ERROR_JSON, - BSON_JSON_ERROR_READ_INVALID_PARAM, - tests[i].error_message); + ASSERT_ERROR_CONTAINS (error, BSON_ERROR_JSON, BSON_JSON_ERROR_READ_INVALID_PARAM, tests[i].error_message); } } @@ -1720,102 +1600,63 @@ test_bson_json_dbref (void) { bson_error_t error; - const char *json_with_objectid_id = - "{ \"key\": {" - "\"$ref\": \"collection\"," - "\"$id\": {\"$oid\": \"000000000000000000000000\"}}}"; + const char *json_with_objectid_id = "{ \"key\": {" + "\"$ref\": \"collection\"," + "\"$id\": {\"$oid\": \"000000000000000000000000\"}}}"; - bson_t *bson_with_objectid_id = BCON_NEW ("key", - "{", - "$ref", - BCON_UTF8 ("collection"), - "$id", - BCON_OID (oid_zero ()), - "}"); + bson_t *bson_with_objectid_id = + BCON_NEW ("key", "{", "$ref", BCON_UTF8 ("collection"), "$id", BCON_OID (oid_zero ()), "}"); const char *json_with_int_id = "{ \"key\": {" "\"$ref\": \"collection\"," "\"$id\": 1}}"; - bson_t *bson_with_int_id = BCON_NEW ( - "key", "{", "$ref", BCON_UTF8 ("collection"), "$id", BCON_INT32 (1), "}"); + bson_t *bson_with_int_id = BCON_NEW ("key", "{", "$ref", BCON_UTF8 ("collection"), "$id", BCON_INT32 (1), "}"); const char *json_with_subdoc_id = "{ \"key\": {" "\"$ref\": \"collection\"," "\"$id\": {\"a\": 1}}}"; - bson_t *bson_with_subdoc_id = BCON_NEW ("key", - "{", - "$ref", - BCON_UTF8 ("collection"), - "$id", - "{", - "a", - BCON_INT32 (1), - "}", - "}"); + bson_t *bson_with_subdoc_id = + BCON_NEW ("key", "{", "$ref", BCON_UTF8 ("collection"), "$id", "{", "a", BCON_INT32 (1), "}", "}"); const char *json_with_metadata = "{ \"key\": {" "\"$ref\": \"collection\"," "\"$id\": 1," "\"meta\": true}}"; - bson_t *bson_with_metadata = BCON_NEW ("key", - "{", - "$ref", - BCON_UTF8 ("collection"), - "$id", - BCON_INT32 (1), - "meta", - BCON_BOOL (true), - "}"); + bson_t *bson_with_metadata = + BCON_NEW ("key", "{", "$ref", BCON_UTF8 ("collection"), "$id", BCON_INT32 (1), "meta", BCON_BOOL (true), "}"); const char *json_with_db = "{ \"key\": {" "\"$ref\": \"collection\"," "\"$id\": 1," "\"$db\": \"database\"}}"; - bson_t *bson_with_db = BCON_NEW ("key", - "{", - "$ref", - BCON_UTF8 ("collection"), - "$id", - BCON_INT32 (1), - "$db", - BCON_UTF8 ("database"), - "}"); + bson_t *bson_with_db = BCON_NEW ( + "key", "{", "$ref", BCON_UTF8 ("collection"), "$id", BCON_INT32 (1), "$db", BCON_UTF8 ("database"), "}"); /* Note: the following examples are not valid DBRefs but are intended to test * that the Extended JSON parser leaves such documents as-is. */ const char *json_with_missing_ref = "{\"key\": {\"$id\": 1}}"; - bson_t *bson_with_missing_ref = - BCON_NEW ("key", "{", "$id", BCON_INT32 (1), "}"); + bson_t *bson_with_missing_ref = BCON_NEW ("key", "{", "$id", BCON_INT32 (1), "}"); const char *json_with_missing_id = "{\"key\": {\"$ref\": \"collection\"}}"; - bson_t *bson_with_missing_id = - BCON_NEW ("key", "{", "$ref", BCON_UTF8 ("collection"), "}"); + bson_t *bson_with_missing_id = BCON_NEW ("key", "{", "$ref", BCON_UTF8 ("collection"), "}"); const char *json_with_int_ref = "{\"key\": {\"$ref\": 1, \"$id\": 1}}"; - bson_t *bson_with_int_ref = - BCON_NEW ("key", "{", "$ref", BCON_INT32 (1), "$id", BCON_INT32 (1), "}"); + bson_t *bson_with_int_ref = BCON_NEW ("key", "{", "$ref", BCON_INT32 (1), "$id", BCON_INT32 (1), "}"); const char *json_with_int_db = "{ \"key\": {" "\"$ref\": \"collection\"," "\"$id\": 1," "\"$db\": 1}}"; - bson_t *bson_with_int_db = BCON_NEW ("key", - "{", - "$ref", - BCON_UTF8 ("collection"), - "$id", - BCON_INT32 (1), - "$db", - BCON_INT32 (1), - "}"); + bson_t *bson_with_int_db = + BCON_NEW ("key", "{", "$ref", BCON_UTF8 ("collection"), "$id", BCON_INT32 (1), "$db", BCON_INT32 (1), "}"); bson_t b; bool r; @@ -1947,10 +1788,7 @@ test_bson_json_uescape_bad (void) r = bson_init_from_json (&b, "{ \"bad\": \"\\u1\"}", -1, &error); BSON_ASSERT (!r); - ASSERT_ERROR_CONTAINS (error, - BSON_ERROR_JSON, - BSON_JSON_ERROR_READ_CORRUPT_JS, - "UESCAPE_TOOSHORT"); + ASSERT_ERROR_CONTAINS (error, BSON_ERROR_JSON, BSON_JSON_ERROR_READ_CORRUPT_JS, "UESCAPE_TOOSHORT"); } @@ -1962,8 +1800,7 @@ test_bson_json_int32 (void) bson_error_t error; /* INT32_MAX */ - ASSERT_OR_PRINT ( - bson_init_from_json (&b, "{ \"x\": 2147483647 }", -1, &error), error); + ASSERT_OR_PRINT (bson_init_from_json (&b, "{ \"x\": 2147483647 }", -1, &error), error); BSON_ASSERT (bson_iter_init_find (&iter, &b, "x")); BSON_ASSERT (BSON_ITER_HOLDS_INT32 (&iter)); @@ -1971,8 +1808,7 @@ test_bson_json_int32 (void) bson_destroy (&b); /* INT32_MIN */ - ASSERT_OR_PRINT ( - bson_init_from_json (&b, "{ \"x\": -2147483648 }", -1, &error), error); + ASSERT_OR_PRINT (bson_init_from_json (&b, "{ \"x\": -2147483648 }", -1, &error), error); BSON_ASSERT (bson_iter_init_find (&iter, &b, "x")); BSON_ASSERT (BSON_ITER_HOLDS_INT32 (&iter)); @@ -1980,8 +1816,7 @@ test_bson_json_int32 (void) bson_destroy (&b); /* INT32_MAX + 1 */ - ASSERT_OR_PRINT ( - bson_init_from_json (&b, "{ \"x\": 2147483648 }", -1, &error), error); + ASSERT_OR_PRINT (bson_init_from_json (&b, "{ \"x\": 2147483648 }", -1, &error), error); BSON_ASSERT (bson_iter_init_find (&iter, &b, "x")); BSON_ASSERT (BSON_ITER_HOLDS_INT64 (&iter)); @@ -1989,8 +1824,7 @@ test_bson_json_int32 (void) bson_destroy (&b); /* INT32_MIN - 1 */ - ASSERT_OR_PRINT ( - bson_init_from_json (&b, "{ \"x\": -2147483649 }", -1, &error), error); + ASSERT_OR_PRINT (bson_init_from_json (&b, "{ \"x\": -2147483649 }", -1, &error), error); BSON_ASSERT (bson_iter_init_find (&iter, &b, "x")); BSON_ASSERT (BSON_ITER_HOLDS_INT64 (&iter)); @@ -2007,20 +1841,15 @@ test_bson_json_int64 (void) bson_error_t error; /* INT64_MAX */ - ASSERT_OR_PRINT ( - bson_init_from_json (&b, "{ \"x\": 9223372036854775807 }", -1, &error), - error); + ASSERT_OR_PRINT (bson_init_from_json (&b, "{ \"x\": 9223372036854775807 }", -1, &error), error); BSON_ASSERT (bson_iter_init_find (&iter, &b, "x")); BSON_ASSERT (BSON_ITER_HOLDS_INT64 (&iter)); - ASSERT_CMPINT64 ( - bson_iter_int64 (&iter), ==, (int64_t) 9223372036854775807LL); + ASSERT_CMPINT64 (bson_iter_int64 (&iter), ==, (int64_t) 9223372036854775807LL); bson_destroy (&b); /* INT64_MIN */ - ASSERT_OR_PRINT ( - bson_init_from_json (&b, "{ \"x\": -9223372036854775808 }", -1, &error), - error); + ASSERT_OR_PRINT (bson_init_from_json (&b, "{ \"x\": -9223372036854775808 }", -1, &error), error); BSON_ASSERT (bson_iter_init_find (&iter, &b, "x")); BSON_ASSERT (BSON_ITER_HOLDS_INT64 (&iter)); @@ -2028,42 +1857,30 @@ test_bson_json_int64 (void) bson_destroy (&b); /* INT64_MAX + 1 */ - BSON_ASSERT ( - !bson_init_from_json (&b, "{ \"x\": 9223372036854775808 }", -1, &error)); - ASSERT_ERROR_CONTAINS (error, - BSON_ERROR_JSON, - BSON_JSON_ERROR_READ_INVALID_PARAM, - "Number \"9223372036854775808\" is out of range"); + BSON_ASSERT (!bson_init_from_json (&b, "{ \"x\": 9223372036854775808 }", -1, &error)); + ASSERT_ERROR_CONTAINS ( + error, BSON_ERROR_JSON, BSON_JSON_ERROR_READ_INVALID_PARAM, "Number \"9223372036854775808\" is out of range"); memset (&error, 0, sizeof error); /* INT64_MIN - 1 */ - BSON_ASSERT ( - !bson_init_from_json (&b, "{ \"x\": -9223372036854775809 }", -1, &error)); - ASSERT_ERROR_CONTAINS (error, - BSON_ERROR_JSON, - BSON_JSON_ERROR_READ_INVALID_PARAM, - "Number \"-9223372036854775809\" is out of range"); + BSON_ASSERT (!bson_init_from_json (&b, "{ \"x\": -9223372036854775809 }", -1, &error)); + ASSERT_ERROR_CONTAINS ( + error, BSON_ERROR_JSON, BSON_JSON_ERROR_READ_INVALID_PARAM, "Number \"-9223372036854775809\" is out of range"); memset (&error, 0, sizeof error); - BSON_ASSERT ( - !bson_init_from_json (&b, "{ \"x\": 10000000000000000000 }", -1, &error)); - ASSERT_ERROR_CONTAINS (error, - BSON_ERROR_JSON, - BSON_JSON_ERROR_READ_INVALID_PARAM, - "Number \"10000000000000000000\" is out of range"); + BSON_ASSERT (!bson_init_from_json (&b, "{ \"x\": 10000000000000000000 }", -1, &error)); + ASSERT_ERROR_CONTAINS ( + error, BSON_ERROR_JSON, BSON_JSON_ERROR_READ_INVALID_PARAM, "Number \"10000000000000000000\" is out of range"); memset (&error, 0, sizeof error); /* INT64_MIN - 2 */ - BSON_ASSERT (!bson_init_from_json ( - &b, "{ \"x\": -10000000000000000000 }", -1, &error)); + BSON_ASSERT (!bson_init_from_json (&b, "{ \"x\": -10000000000000000000 }", -1, &error)); - ASSERT_ERROR_CONTAINS (error, - BSON_ERROR_JSON, - BSON_JSON_ERROR_READ_INVALID_PARAM, - "Number \"-10000000000000000000\" is out of range"); + ASSERT_ERROR_CONTAINS ( + error, BSON_ERROR_JSON, BSON_JSON_ERROR_READ_INVALID_PARAM, "Number \"-10000000000000000000\" is out of range"); } @@ -2074,40 +1891,35 @@ test_bson_json_double (void) bson_error_t error; bson_iter_t iter; - ASSERT_OR_PRINT (bson_init_from_json (&b, "{ \"x\": 1 }", -1, &error), - error); + ASSERT_OR_PRINT (bson_init_from_json (&b, "{ \"x\": 1 }", -1, &error), error); BSON_ASSERT (bson_iter_init_find (&iter, &b, "x")); BSON_ASSERT (BSON_ITER_HOLDS_INT32 (&iter)); ASSERT_CMPINT32 (bson_iter_int32 (&iter), ==, (int32_t) 1); bson_destroy (&b); - ASSERT_OR_PRINT ( - bson_init_from_json (&b, "{ \"x\": 4294967296 }", -1, &error), error); + ASSERT_OR_PRINT (bson_init_from_json (&b, "{ \"x\": 4294967296 }", -1, &error), error); BSON_ASSERT (bson_iter_init_find (&iter, &b, "x")); BSON_ASSERT (BSON_ITER_HOLDS_INT64 (&iter)); ASSERT_CMPINT64 (bson_iter_int64 (&iter), ==, (int64_t) 4294967296); bson_destroy (&b); - ASSERT_OR_PRINT (bson_init_from_json (&b, "{ \"x\": 1.0 }", -1, &error), - error); + ASSERT_OR_PRINT (bson_init_from_json (&b, "{ \"x\": 1.0 }", -1, &error), error); BSON_ASSERT (bson_iter_init_find (&iter, &b, "x")); BSON_ASSERT (BSON_ITER_HOLDS_DOUBLE (&iter)); ASSERT_CMPDOUBLE (bson_iter_double (&iter), ==, 1.0); bson_destroy (&b); - ASSERT_OR_PRINT (bson_init_from_json (&b, "{ \"x\": 0.0 }", -1, &error), - error); + ASSERT_OR_PRINT (bson_init_from_json (&b, "{ \"x\": 0.0 }", -1, &error), error); BSON_ASSERT (bson_iter_init_find (&iter, &b, "x")); BSON_ASSERT (BSON_ITER_HOLDS_DOUBLE (&iter)); ASSERT_CMPDOUBLE (bson_iter_double (&iter), ==, 0.0); bson_destroy (&b); - ASSERT_OR_PRINT (bson_init_from_json (&b, "{ \"x\": -0.0 }", -1, &error), - error); + ASSERT_OR_PRINT (bson_init_from_json (&b, "{ \"x\": -0.0 }", -1, &error), error); BSON_ASSERT (bson_iter_init_find (&iter, &b, "x")); BSON_ASSERT (BSON_ITER_HOLDS_DOUBLE (&iter)); @@ -2115,8 +1927,7 @@ test_bson_json_double (void) /* check that "x" is -0.0. signbit not available on Solaris, FreeBSD, or VS 2010 */ -#if !defined(__sun) && !defined(__FreeBSD__) && \ - (!defined(_MSC_VER) || (_MSC_VER >= 1800)) +#if !defined(__sun) && !defined(__FreeBSD__) && (!defined(_MSC_VER) || (_MSC_VER >= 1800)) BSON_ASSERT (signbit (bson_iter_double (&iter))); #endif @@ -2136,10 +1947,7 @@ test_bson_json_double_overflow (void) for (p = nums; *p; p++) { j = bson_strdup_printf ("{ \"d\" : %s }", *p); BSON_ASSERT (!bson_init_from_json (&b, j, -1, &error)); - ASSERT_ERROR_CONTAINS (error, - BSON_ERROR_JSON, - BSON_JSON_ERROR_READ_INVALID_PARAM, - "out of range"); + ASSERT_ERROR_CONTAINS (error, BSON_ERROR_JSON, BSON_JSON_ERROR_READ_INVALID_PARAM, "out of range"); bson_free (j); memset (&error, 0, sizeof error); @@ -2147,10 +1955,7 @@ test_bson_json_double_overflow (void) /* same test with canonical Extended JSON */ j = bson_strdup_printf ("{ \"d\" : { \"$numberDouble\" : \"%s\" } }", *p); BSON_ASSERT (!bson_init_from_json (&b, j, -1, &error)); - ASSERT_ERROR_CONTAINS (error, - BSON_ERROR_JSON, - BSON_JSON_ERROR_READ_INVALID_PARAM, - "out of range"); + ASSERT_ERROR_CONTAINS (error, BSON_ERROR_JSON, BSON_JSON_ERROR_READ_INVALID_PARAM, "out of range"); bson_free (j); } @@ -2193,19 +1998,13 @@ test_bson_json_nan (void) for (j = bad; *j; j++) { BSON_ASSERT (!bson_init_from_json (&b, *j, -1, &error)); - ASSERT_ERROR_CONTAINS (error, - BSON_ERROR_JSON, - BSON_JSON_ERROR_READ_CORRUPT_JS, - "Got parse error at"); + ASSERT_ERROR_CONTAINS (error, BSON_ERROR_JSON, BSON_JSON_ERROR_READ_CORRUPT_JS, "Got parse error at"); memset (&error, 0, sizeof error); } for (j = partial; *j; j++) { BSON_ASSERT (!bson_init_from_json (&b, *j, -1, &error)); - ASSERT_ERROR_CONTAINS (error, - BSON_ERROR_JSON, - BSON_JSON_ERROR_READ_CORRUPT_JS, - "Incomplete JSON"); + ASSERT_ERROR_CONTAINS (error, BSON_ERROR_JSON, BSON_JSON_ERROR_READ_CORRUPT_JS, "Incomplete JSON"); memset (&error, 0, sizeof error); } } @@ -2218,15 +2017,9 @@ test_bson_json_infinity (void) double d; /* should parse any capitalization of Infinity */ - const char *infs[] = {"{ \"d\": Infinity }", - "{ \"d\": infinity }", - "{ \"d\": inFINIty }", - NULL}; + const char *infs[] = {"{ \"d\": Infinity }", "{ \"d\": infinity }", "{ \"d\": inFINIty }", NULL}; - const char *negs[] = {"{ \"d\": -Infinity }", - "{ \"d\": -infinity }", - "{ \"d\": -inFINIty }", - NULL}; + const char *negs[] = {"{ \"d\": -Infinity }", "{ \"d\": -infinity }", "{ \"d\": -inFINIty }", NULL}; const char *bad[] = {"{ \"d\": Infinityy }", "{ \"d\": Infinit }", @@ -2260,19 +2053,13 @@ test_bson_json_infinity (void) for (j = bad; *j; j++) { BSON_ASSERT (!bson_init_from_json (&b, *j, -1, &error)); - ASSERT_ERROR_CONTAINS (error, - BSON_ERROR_JSON, - BSON_JSON_ERROR_READ_CORRUPT_JS, - "Got parse error at"); + ASSERT_ERROR_CONTAINS (error, BSON_ERROR_JSON, BSON_JSON_ERROR_READ_CORRUPT_JS, "Got parse error at"); memset (&error, 0, sizeof error); } for (j = partial; *j; j++) { BSON_ASSERT (!bson_init_from_json (&b, *j, -1, &error)); - ASSERT_ERROR_CONTAINS (error, - BSON_ERROR_JSON, - BSON_JSON_ERROR_READ_CORRUPT_JS, - "Incomplete JSON"); + ASSERT_ERROR_CONTAINS (error, BSON_ERROR_JSON, BSON_JSON_ERROR_READ_CORRUPT_JS, "Incomplete JSON"); memset (&error, 0, sizeof error); } } @@ -2451,12 +2238,10 @@ static void test_bson_json_merge_multiple (void) { bson_error_t error; - bson_t *b = bson_new_from_json ( - (const uint8_t *) "{\"a\" : 1}, {\"b\" : 2}", -1, &error); + bson_t *b = bson_new_from_json ((const uint8_t *) "{\"a\" : 1}, {\"b\" : 2}", -1, &error); ASSERT_OR_PRINT (b, error); - bson_t *compare = bson_new_from_json ( - (const uint8_t *) BSON_STR ({"a" : 1, "b" : 2}), -1, &error); + bson_t *compare = bson_new_from_json ((const uint8_t *) BSON_STR ({"a" : 1, "b" : 2}), -1, &error); bson_eq_bson (b, compare); bson_destroy (b); @@ -2468,22 +2253,16 @@ test_bson_json_extra_chars (void) { bson_error_t error; { - bson_t *b = - bson_new_from_json ((const uint8_t *) "{\"a\": 1}abc", -1, &error); + bson_t *b = bson_new_from_json ((const uint8_t *) "{\"a\": 1}abc", -1, &error); ASSERT (b == NULL); - ASSERT_ERROR_CONTAINS (error, - BSON_ERROR_JSON, - BSON_JSON_ERROR_READ_CORRUPT_JS, - "Got parse error at \"a\""); + ASSERT_ERROR_CONTAINS (error, BSON_ERROR_JSON, BSON_JSON_ERROR_READ_CORRUPT_JS, "Got parse error at \"a\""); } { - bson_t *b = bson_new_from_json ( - (const uint8_t *) "{\"a\" : 1}{abc,[],{},123", -1, &error); + bson_t *b = bson_new_from_json ((const uint8_t *) "{\"a\" : 1}{abc,[],{},123", -1, &error); ASSERT_OR_PRINT (b, error); - bson_t *compare = - bson_new_from_json ((const uint8_t *) "{\"a\" : 1}", -1, &error); + bson_t *compare = bson_new_from_json ((const uint8_t *) "{\"a\" : 1}", -1, &error); bson_eq_bson (b, compare); bson_destroy (b); @@ -2527,8 +2306,7 @@ test_bson_json_date_error (const char *json, const char *msg) fprintf (stderr, "parsing %s should fail\n", json); } BSON_ASSERT (!r); - ASSERT_ERROR_CONTAINS ( - error, BSON_ERROR_JSON, BSON_JSON_ERROR_READ_INVALID_PARAM, msg); + ASSERT_ERROR_CONTAINS (error, BSON_ERROR_JSON, BSON_JSON_ERROR_READ_INVALID_PARAM, msg); } static void @@ -2537,71 +2315,39 @@ test_bson_json_date (void) /* to make a timestamp, "python3 -m pip install iso8601" and in Python 3: * iso8601.parse_date("2016-12-13T12:34:56.123Z").timestamp() * 1000 */ - test_bson_json_date_check ( - "{ \"dt\" : { \"$date\" : \"2016-12-13T12:34:56.123Z\" } }", - 1481632496123); - test_bson_json_date_check ( - "{ \"dt\" : { \"$date\" : \"1970-01-01T00:00:00.000Z\" } }", 0); - test_bson_json_date_check ( - "{ \"dt\" : { \"$date\" : \"1969-12-31T16:00:00.000-0800\" } }", 0); - - test_bson_json_date_error ( - "{ \"dt\" : { \"$date\" : \"1970-01-01T01:00:00.000+01:00\" } }", - "Could not parse"); - test_bson_json_date_error ( - "{ \"dt\" : { \"$date\" : \"1970-01-01T01:30:\" } }", - "reached end of date while looking for seconds"); - test_bson_json_date_error ( - "{ \"dt\" : { \"$date\" : \"1970-01-01T01:00:+01:00\" } }", - "seconds is required"); - test_bson_json_date_error ( - "{ \"dt\" : { \"$date\" : \"1970-01-01T01:30:00.\" } }", - "reached end of date while looking for milliseconds"); - test_bson_json_date_error ( - "{ \"dt\" : { \"$date\" : \"1970-01-01T01:00:00.+01:00\" } }", - "milliseconds is required"); - test_bson_json_date_error ( - "{ \"dt\" : { \"$date\" : \"foo-01-01T00:00:00.000Z\" } }", - "year must be an integer"); - test_bson_json_date_error ( - "{ \"dt\" : { \"$date\" : \"1970-foo-01T00:00:00.000Z\" } }", - "month must be an integer"); - test_bson_json_date_error ( - "{ \"dt\" : { \"$date\" : \"1970-01-fooT00:00:00.000Z\" } }", - "day must be an integer"); - test_bson_json_date_error ( - "{ \"dt\" : { \"$date\" : \"1970-01-01Tfoo:00:00.000Z\" } }", - "hour must be an integer"); - test_bson_json_date_error ( - "{ \"dt\" : { \"$date\" : \"1970-01-01T00:foo:00.000Z\" } }", - "minute must be an integer"); - test_bson_json_date_error ( - "{ \"dt\" : { \"$date\" : \"1970-01-01T00:00:foo.000Z\" } }", - "seconds must be an integer"); - test_bson_json_date_error ( - "{ \"dt\" : { \"$date\" : \"1970-01-01T01:00:00.000\" } }", - "timezone is required"); - test_bson_json_date_error ( - "{ \"dt\" : { \"$date\" : \"1970-01-01T01:00:00.000X\" } }", - "timezone is required"); - test_bson_json_date_error ( - "{ \"dt\" : { \"$date\" : \"1970-01-01T01:00:00.000+1\" } }", - "could not parse timezone"); - test_bson_json_date_error ( - "{ \"dt\" : { \"$date\" : \"1970-01-01T01:00:00.000+xx00\" } }", - "could not parse timezone"); - test_bson_json_date_error ( - "{ \"dt\" : { \"$date\" : \"1970-01-01T01:00:00.000+2400\" } }", - "timezone hour must be at most 23"); - test_bson_json_date_error ( - "{ \"dt\" : { \"$date\" : \"1970-01-01T01:00:00.000-2400\" } }", - "timezone hour must be at most 23"); - test_bson_json_date_error ( - "{ \"dt\" : { \"$date\" : \"1970-01-01T01:00:00.000+0060\" } }", - "timezone minute must be at most 59"); - test_bson_json_date_error ( - "{ \"dt\" : { \"$date\" : \"1970-01-01T01:00:00.000-0060\" } }", - "timezone minute must be at most 59"); + test_bson_json_date_check ("{ \"dt\" : { \"$date\" : \"2016-12-13T12:34:56.123Z\" } }", 1481632496123); + test_bson_json_date_check ("{ \"dt\" : { \"$date\" : \"1970-01-01T00:00:00.000Z\" } }", 0); + test_bson_json_date_check ("{ \"dt\" : { \"$date\" : \"1969-12-31T16:00:00.000-0800\" } }", 0); + + test_bson_json_date_error ("{ \"dt\" : { \"$date\" : \"1970-01-01T01:00:00.000+01:00\" } }", "Could not parse"); + test_bson_json_date_error ("{ \"dt\" : { \"$date\" : \"1970-01-01T01:30:\" } }", + "reached end of date while looking for seconds"); + test_bson_json_date_error ("{ \"dt\" : { \"$date\" : \"1970-01-01T01:00:+01:00\" } }", "seconds is required"); + test_bson_json_date_error ("{ \"dt\" : { \"$date\" : \"1970-01-01T01:30:00.\" } }", + "reached end of date while looking for milliseconds"); + test_bson_json_date_error ("{ \"dt\" : { \"$date\" : \"1970-01-01T01:00:00.+01:00\" } }", + "milliseconds is required"); + test_bson_json_date_error ("{ \"dt\" : { \"$date\" : \"foo-01-01T00:00:00.000Z\" } }", "year must be an integer"); + test_bson_json_date_error ("{ \"dt\" : { \"$date\" : \"1970-foo-01T00:00:00.000Z\" } }", "month must be an integer"); + test_bson_json_date_error ("{ \"dt\" : { \"$date\" : \"1970-01-fooT00:00:00.000Z\" } }", "day must be an integer"); + test_bson_json_date_error ("{ \"dt\" : { \"$date\" : \"1970-01-01Tfoo:00:00.000Z\" } }", "hour must be an integer"); + test_bson_json_date_error ("{ \"dt\" : { \"$date\" : \"1970-01-01T00:foo:00.000Z\" } }", + "minute must be an integer"); + test_bson_json_date_error ("{ \"dt\" : { \"$date\" : \"1970-01-01T00:00:foo.000Z\" } }", + "seconds must be an integer"); + test_bson_json_date_error ("{ \"dt\" : { \"$date\" : \"1970-01-01T01:00:00.000\" } }", "timezone is required"); + test_bson_json_date_error ("{ \"dt\" : { \"$date\" : \"1970-01-01T01:00:00.000X\" } }", "timezone is required"); + test_bson_json_date_error ("{ \"dt\" : { \"$date\" : \"1970-01-01T01:00:00.000+1\" } }", "could not parse timezone"); + test_bson_json_date_error ("{ \"dt\" : { \"$date\" : \"1970-01-01T01:00:00.000+xx00\" } }", + "could not parse timezone"); + test_bson_json_date_error ("{ \"dt\" : { \"$date\" : \"1970-01-01T01:00:00.000+2400\" } }", + "timezone hour must be at most 23"); + test_bson_json_date_error ("{ \"dt\" : { \"$date\" : \"1970-01-01T01:00:00.000-2400\" } }", + "timezone hour must be at most 23"); + test_bson_json_date_error ("{ \"dt\" : { \"$date\" : \"1970-01-01T01:00:00.000+0060\" } }", + "timezone minute must be at most 59"); + test_bson_json_date_error ("{ \"dt\" : { \"$date\" : \"1970-01-01T01:00:00.000-0060\" } }", + "timezone minute must be at most 59"); } @@ -2609,50 +2355,38 @@ static void test_bson_json_date_legacy (void) { test_bson_json_date_check ("{ \"dt\" : { \"$date\" : 0 } }", 0); - test_bson_json_date_check ("{ \"dt\" : { \"$date\" : 1356351330500 } }", - 1356351330500); - test_bson_json_date_check ("{ \"dt\" : { \"$date\" : -62135593139000 } }", - -62135593139000); + test_bson_json_date_check ("{ \"dt\" : { \"$date\" : 1356351330500 } }", 1356351330500); + test_bson_json_date_check ("{ \"dt\" : { \"$date\" : -62135593139000 } }", -62135593139000); /* INT64_MAX */ - test_bson_json_date_check ( - "{ \"dt\" : { \"$date\" : 9223372036854775807 } }", INT64_MAX); + test_bson_json_date_check ("{ \"dt\" : { \"$date\" : 9223372036854775807 } }", INT64_MAX); /* INT64_MIN */ - test_bson_json_date_check ( - "{ \"dt\" : { \"$date\" : -9223372036854775808 } }", INT64_MIN); + test_bson_json_date_check ("{ \"dt\" : { \"$date\" : -9223372036854775808 } }", INT64_MIN); /* INT64_MAX + 1 */ - test_bson_json_date_error ( - "{ \"dt\" : { \"$date\" : 9223372036854775808 } }", - "Number \"9223372036854775808\" is out of range"); + test_bson_json_date_error ("{ \"dt\" : { \"$date\" : 9223372036854775808 } }", + "Number \"9223372036854775808\" is out of range"); /* INT64_MIN - 1 */ - test_bson_json_date_error ( - "{ \"dt\" : { \"$date\" : -9223372036854775809 } }", - "Number \"-9223372036854775809\" is out of range"); + test_bson_json_date_error ("{ \"dt\" : { \"$date\" : -9223372036854775809 } }", + "Number \"-9223372036854775809\" is out of range"); - test_bson_json_date_error ( - "{ \"dt\" : { \"$date\" : 10000000000000000000 } }", - "Number \"10000000000000000000\" is out of range"); + test_bson_json_date_error ("{ \"dt\" : { \"$date\" : 10000000000000000000 } }", + "Number \"10000000000000000000\" is out of range"); - test_bson_json_date_error ( - "{ \"dt\" : { \"$date\" : -10000000000000000000 } }", - "Number \"-10000000000000000000\" is out of range"); + test_bson_json_date_error ("{ \"dt\" : { \"$date\" : -10000000000000000000 } }", + "Number \"-10000000000000000000\" is out of range"); } static void test_bson_json_date_numberlong (void) { - test_bson_json_date_check ( - "{ \"dt\" : { \"$date\" : {\"$numberLong\": \"0\" } } }", 0); - test_bson_json_date_check ( - "{ \"dt\" : { \"$date\" : {\"$numberLong\": \"1356351330500\" } } }", - 1356351330500); - test_bson_json_date_check ( - "{ \"dt\" : { \"$date\" : { \"$numberLong\" : \"-62135593139000\" } } }", - -62135593139000); + test_bson_json_date_check ("{ \"dt\" : { \"$date\" : {\"$numberLong\": \"0\" } } }", 0); + test_bson_json_date_check ("{ \"dt\" : { \"$date\" : {\"$numberLong\": \"1356351330500\" } } }", 1356351330500); + test_bson_json_date_check ("{ \"dt\" : { \"$date\" : { \"$numberLong\" : \"-62135593139000\" } } }", + -62135593139000); /* INT64_MAX */ test_bson_json_date_check ("{ \"dt\" : { \"$date\" : { \"$numberLong\" " @@ -2670,20 +2404,17 @@ test_bson_json_date_numberlong (void) "Number \"9223372036854775808\" is out of range"); /* INT64_MIN - 1 */ - test_bson_json_date_error ( - "{ \"dt\" : { \"$date\" : { \"$numberLong\" " - ": \"-9223372036854775809\" } } }", - "Number \"-9223372036854775809\" is out of range"); + test_bson_json_date_error ("{ \"dt\" : { \"$date\" : { \"$numberLong\" " + ": \"-9223372036854775809\" } } }", + "Number \"-9223372036854775809\" is out of range"); - test_bson_json_date_error ( - "{ \"dt\" : { \"$date\" : { \"$numberLong\" " - ": \"10000000000000000000\" } } }", - "Number \"10000000000000000000\" is out of range"); + test_bson_json_date_error ("{ \"dt\" : { \"$date\" : { \"$numberLong\" " + ": \"10000000000000000000\" } } }", + "Number \"10000000000000000000\" is out of range"); - test_bson_json_date_error ( - "{ \"dt\" : { \"$date\" : { \"$numberLong\" " - ": \"-10000000000000000000\" } } }", - "Number \"-10000000000000000000\" is out of range"); + test_bson_json_date_error ("{ \"dt\" : { \"$date\" : { \"$numberLong\" " + ": \"-10000000000000000000\" } } }", + "Number \"-10000000000000000000\" is out of range"); } @@ -2696,14 +2427,9 @@ test_bson_json_timestamp (void) bson_init (&compare); - BSON_APPEND_TIMESTAMP ( - &compare, "ts", (uint32_t) 1486785977, (uint32_t) 1234); + BSON_APPEND_TIMESTAMP (&compare, "ts", (uint32_t) 1486785977, (uint32_t) 1234); - r = bson_init_from_json ( - &b, - "{\"ts\": {\"$timestamp\": {\"t\": 1486785977, \"i\": 1234}}}", - -1, - &error); + r = bson_init_from_json (&b, "{\"ts\": {\"$timestamp\": {\"t\": 1486785977, \"i\": 1234}}}", -1, &error); if (!r) { fprintf (stderr, "%s\n", error.message); @@ -2825,16 +2551,12 @@ test_bson_json_errors (void) { typedef const char *test_bson_json_error_t[2]; test_bson_json_error_t tests[] = { - {"{\"x\": {\"$numberLong\": 1}}", - "Invalid state for integer read: INT64"}, + {"{\"x\": {\"$numberLong\": 1}}", "Invalid state for integer read: INT64"}, {"{\"x\": {\"$binary\": 1}}", "Unexpected integer 1 in type \"binary\""}, - {"{\"x\": {\"$numberInt\": true}}", - "Invalid read of boolean in state IN_BSON_TYPE"}, - {"{\"x\": {\"$dbPointer\": true}}", - "Invalid read of boolean in state IN_BSON_TYPE_DBPOINTER_STARTMAP"}, + {"{\"x\": {\"$numberInt\": true}}", "Invalid read of boolean in state IN_BSON_TYPE"}, + {"{\"x\": {\"$dbPointer\": true}}", "Invalid read of boolean in state IN_BSON_TYPE_DBPOINTER_STARTMAP"}, {"[{\"$code\": {}}]", "Unexpected nested object value for \"$code\" key"}, - {"{\"x\": {\"$numberInt\": \"8589934592\"}}", - "Invalid input string \"8589934592\", looking for INT32"}, + {"{\"x\": {\"$numberInt\": \"8589934592\"}}", "Invalid input string \"8589934592\", looking for INT32"}, {0}, }; @@ -2843,8 +2565,7 @@ test_bson_json_errors (void) for (p = tests; *(p[0]); p++) { BSON_ASSERT (!bson_new_from_json ((const uint8_t *) (*p)[0], -1, &error)); - ASSERT_ERROR_CONTAINS ( - error, BSON_ERROR_JSON, BSON_JSON_ERROR_READ_INVALID_PARAM, (*p)[1]); + ASSERT_ERROR_CONTAINS (error, BSON_ERROR_JSON, BSON_JSON_ERROR_READ_INVALID_PARAM, (*p)[1]); } } @@ -2871,15 +2592,11 @@ test_bson_json_null_in_str (void) const char bad_json[] = "{\"a\":\"\0\"}"; const char cdriver2305[] = "{\"\0"; bson_error_t err; - ASSERT (!bson_new_from_json ( - (const uint8_t *) bad_json, sizeof (bad_json) - 1, &err)); - ASSERT_ERROR_CONTAINS ( - err, BSON_ERROR_JSON, BSON_JSON_ERROR_READ_CORRUPT_JS, "Got parse error"); + ASSERT (!bson_new_from_json ((const uint8_t *) bad_json, sizeof (bad_json) - 1, &err)); + ASSERT_ERROR_CONTAINS (err, BSON_ERROR_JSON, BSON_JSON_ERROR_READ_CORRUPT_JS, "Got parse error"); memset (&err, 0, sizeof err); - ASSERT (!bson_new_from_json ( - (const uint8_t *) cdriver2305, sizeof (cdriver2305) - 1, &err)); - ASSERT_ERROR_CONTAINS ( - err, BSON_ERROR_JSON, BSON_JSON_ERROR_READ_CORRUPT_JS, "Got parse error"); + ASSERT (!bson_new_from_json ((const uint8_t *) cdriver2305, sizeof (cdriver2305) - 1, &err)); + ASSERT_ERROR_CONTAINS (err, BSON_ERROR_JSON, BSON_JSON_ERROR_READ_CORRUPT_JS, "Got parse error"); } static char * @@ -2907,8 +2624,7 @@ _test_json_produces_multiple (const char *json_in, int err_expected, ...) int ret; va_list ap; char *json = _single_to_double (json_in); - bson_json_reader_t *reader = - bson_json_data_reader_new (false /* ignored */, 512 /* buffer size */); + bson_json_reader_t *reader = bson_json_data_reader_new (false /* ignored */, 512 /* buffer size */); va_start (ap, err_expected); @@ -2922,8 +2638,7 @@ _test_json_produces_multiple (const char *json_in, int err_expected, ...) if (bson_compare (&bson_in, bson_expected) != 0) { char *expect = bson_as_json (bson_expected, NULL); char *in = bson_as_json (&bson_in, NULL); - fprintf ( - stderr, "Got %s, but expected %s for input %s\n", expect, in, json); + fprintf (stderr, "Got %s, but expected %s for input %s\n", expect, in, json); bson_free (expect); bson_free (in); abort (); @@ -2963,46 +2678,32 @@ test_bson_as_json_multi_object (void) /* Test the desired multiple document behavior */ - TEST_JSON_PRODUCES_MULTIPLE ("{'a': 1} {'b': 1}", - 0, - BCON_NEW ("a", BCON_INT32 (1)), - BCON_NEW ("b", BCON_INT32 (1))); + TEST_JSON_PRODUCES_MULTIPLE ("{'a': 1} {'b': 1}", 0, BCON_NEW ("a", BCON_INT32 (1)), BCON_NEW ("b", BCON_INT32 (1))); - TEST_JSON_PRODUCES_MULTIPLE ( - "{}{}{}", 0, bson_new (), bson_new (), bson_new ()); + TEST_JSON_PRODUCES_MULTIPLE ("{}{}{}", 0, bson_new (), bson_new (), bson_new ()); /* Test strange behavior we may consider changing */ /* Combines both documents into one? */ - TEST_JSON_PRODUCES_MULTIPLE ( - "{'a': 1}, {'b': 1}", - 0, - BCON_NEW ("a", BCON_INT32 (1), "b", BCON_INT32 (1))); + TEST_JSON_PRODUCES_MULTIPLE ("{'a': 1}, {'b': 1}", 0, BCON_NEW ("a", BCON_INT32 (1), "b", BCON_INT32 (1))); - TEST_JSON_PRODUCES_MULTIPLE ( - "{},{'a': 1}", 0, BCON_NEW ("a", BCON_INT32 (1))); + TEST_JSON_PRODUCES_MULTIPLE ("{},{'a': 1}", 0, BCON_NEW ("a", BCON_INT32 (1))); - TEST_JSON_PRODUCES_MULTIPLE ( - "{},{},{'a': 1}", 0, BCON_NEW ("a", BCON_INT32 (1))); + TEST_JSON_PRODUCES_MULTIPLE ("{},{},{'a': 1}", 0, BCON_NEW ("a", BCON_INT32 (1))); - TEST_JSON_PRODUCES_MULTIPLE ( - "[],{'a': 1}", 0, BCON_NEW ("a", BCON_INT32 (1))); + TEST_JSON_PRODUCES_MULTIPLE ("[],{'a': 1}", 0, BCON_NEW ("a", BCON_INT32 (1))); /* We support a root level array */ TEST_JSON_PRODUCES_MULTIPLE ("[]", 0, bson_new ()); - TEST_JSON_PRODUCES_MULTIPLE ( - "[{'x': 0}]", 0, BCON_NEW ("0", "{", "x", BCON_INT32 (0), "}")); + TEST_JSON_PRODUCES_MULTIPLE ("[{'x': 0}]", 0, BCON_NEW ("0", "{", "x", BCON_INT32 (0), "}")); /* Yet this fails */ TEST_JSON_PRODUCES_MULTIPLE ("[],[{'a': 1}]", 1, NULL); } static void -test_bson_as_json_with_opts (bson_t *bson, - bson_json_mode_t mode, - int max_len, - const char *expected) +test_bson_as_json_with_opts (bson_t *bson, bson_json_mode_t mode, int max_len, const char *expected) { bson_json_opts_t *opts = bson_json_opts_new (mode, max_len); size_t json_len; @@ -3033,9 +2734,7 @@ truncate_string (const char *str, size_t len) } static void -run_bson_as_json_with_opts_tests (bson_t *bson, - bson_json_mode_t mode, - const char *expected) +run_bson_as_json_with_opts_tests (bson_t *bson, bson_json_mode_t mode, const char *expected) { const size_t ulen = strlen (expected); char *truncated; @@ -3070,12 +2769,8 @@ test_bson_as_json_with_opts_double (void) b = bson_new (); BSON_ASSERT (BSON_APPEND_DOUBLE (b, "v", 1.0)); - run_bson_as_json_with_opts_tests ( - b, - BSON_JSON_MODE_CANONICAL, - "{ \"v\" : { \"$numberDouble\" : \"1.0\" } }"); - run_bson_as_json_with_opts_tests ( - b, BSON_JSON_MODE_RELAXED, "{ \"v\" : 1.0 }"); + run_bson_as_json_with_opts_tests (b, BSON_JSON_MODE_CANONICAL, "{ \"v\" : { \"$numberDouble\" : \"1.0\" } }"); + run_bson_as_json_with_opts_tests (b, BSON_JSON_MODE_RELAXED, "{ \"v\" : 1.0 }"); bson_destroy (b); } @@ -3088,10 +2783,8 @@ test_bson_as_json_with_opts_utf8 (void) b = bson_new (); BSON_ASSERT (BSON_APPEND_UTF8 (b, "v", "abcdef")); - run_bson_as_json_with_opts_tests ( - b, BSON_JSON_MODE_CANONICAL, "{ \"v\" : \"abcdef\" }"); - run_bson_as_json_with_opts_tests ( - b, BSON_JSON_MODE_RELAXED, "{ \"v\" : \"abcdef\" }"); + run_bson_as_json_with_opts_tests (b, BSON_JSON_MODE_CANONICAL, "{ \"v\" : \"abcdef\" }"); + run_bson_as_json_with_opts_tests (b, BSON_JSON_MODE_RELAXED, "{ \"v\" : \"abcdef\" }"); bson_destroy (b); } @@ -3109,13 +2802,9 @@ test_bson_as_json_with_opts_document (void) BSON_ASSERT (BSON_APPEND_UTF8 (b, "w", "abcdef")); run_bson_as_json_with_opts_tests ( - b, - BSON_JSON_MODE_CANONICAL, - "{ \"v\" : { \"v\" : \"abcdef\" }, \"w\" : \"abcdef\" }"); + b, BSON_JSON_MODE_CANONICAL, "{ \"v\" : { \"v\" : \"abcdef\" }, \"w\" : \"abcdef\" }"); run_bson_as_json_with_opts_tests ( - b, - BSON_JSON_MODE_RELAXED, - "{ \"v\" : { \"v\" : \"abcdef\" }, \"w\" : \"abcdef\" }"); + b, BSON_JSON_MODE_RELAXED, "{ \"v\" : { \"v\" : \"abcdef\" }, \"w\" : \"abcdef\" }"); bson_destroy (b); bson_destroy (&nested); @@ -3133,14 +2822,8 @@ test_bson_as_json_with_opts_array (void) BSON_ASSERT (bson_append_array_end (b, &nested)); BSON_ASSERT (BSON_APPEND_UTF8 (b, "w", "abcdef")); - run_bson_as_json_with_opts_tests ( - b, - BSON_JSON_MODE_CANONICAL, - "{ \"v\" : [ \"abcdef\" ], \"w\" : \"abcdef\" }"); - run_bson_as_json_with_opts_tests ( - b, - BSON_JSON_MODE_RELAXED, - "{ \"v\" : [ \"abcdef\" ], \"w\" : \"abcdef\" }"); + run_bson_as_json_with_opts_tests (b, BSON_JSON_MODE_CANONICAL, "{ \"v\" : [ \"abcdef\" ], \"w\" : \"abcdef\" }"); + run_bson_as_json_with_opts_tests (b, BSON_JSON_MODE_RELAXED, "{ \"v\" : [ \"abcdef\" ], \"w\" : \"abcdef\" }"); bson_destroy (b); bson_destroy (&nested); @@ -3155,17 +2838,15 @@ test_bson_as_json_with_opts_binary (void) b = bson_new (); BSON_ASSERT (BSON_APPEND_BINARY (b, "v", 0, data, sizeof data)); - run_bson_as_json_with_opts_tests ( - b, - BSON_JSON_MODE_CANONICAL, - "{ \"v\" : { \"$binary\" : { \"base64\" : " - "\"AQIDBA==\", \"subType\" : \"00\" } } }"); + run_bson_as_json_with_opts_tests (b, + BSON_JSON_MODE_CANONICAL, + "{ \"v\" : { \"$binary\" : { \"base64\" : " + "\"AQIDBA==\", \"subType\" : \"00\" } } }"); - run_bson_as_json_with_opts_tests ( - b, - BSON_JSON_MODE_RELAXED, - "{ \"v\" : { \"$binary\" : { \"base64\" : " - "\"AQIDBA==\", \"subType\" : \"00\" } } }"); + run_bson_as_json_with_opts_tests (b, + BSON_JSON_MODE_RELAXED, + "{ \"v\" : { \"$binary\" : { \"base64\" : " + "\"AQIDBA==\", \"subType\" : \"00\" } } }"); bson_destroy (b); } @@ -3178,11 +2859,9 @@ test_bson_as_json_with_opts_undefined (void) b = bson_new (); BSON_ASSERT (BSON_APPEND_UNDEFINED (b, "v")); - run_bson_as_json_with_opts_tests ( - b, BSON_JSON_MODE_RELAXED, "{ \"v\" : { \"$undefined\" : true } }"); + run_bson_as_json_with_opts_tests (b, BSON_JSON_MODE_RELAXED, "{ \"v\" : { \"$undefined\" : true } }"); - run_bson_as_json_with_opts_tests ( - b, BSON_JSON_MODE_CANONICAL, "{ \"v\" : { \"$undefined\" : true } }"); + run_bson_as_json_with_opts_tests (b, BSON_JSON_MODE_CANONICAL, "{ \"v\" : { \"$undefined\" : true } }"); bson_destroy (b); } @@ -3198,14 +2877,10 @@ test_bson_as_json_with_opts_oid (void) BSON_ASSERT (BSON_APPEND_OID (b, "v", &oid)); run_bson_as_json_with_opts_tests ( - b, - BSON_JSON_MODE_RELAXED, - "{ \"v\" : { \"$oid\" : \"12341234123412abcdababcd\" } }"); + b, BSON_JSON_MODE_RELAXED, "{ \"v\" : { \"$oid\" : \"12341234123412abcdababcd\" } }"); run_bson_as_json_with_opts_tests ( - b, - BSON_JSON_MODE_CANONICAL, - "{ \"v\" : { \"$oid\" : \"12341234123412abcdababcd\" } }"); + b, BSON_JSON_MODE_CANONICAL, "{ \"v\" : { \"$oid\" : \"12341234123412abcdababcd\" } }"); bson_destroy (b); } @@ -3218,11 +2893,9 @@ test_bson_as_json_with_opts_bool (void) b = bson_new (); BSON_ASSERT (BSON_APPEND_BOOL (b, "v", false)); - run_bson_as_json_with_opts_tests ( - b, BSON_JSON_MODE_RELAXED, "{ \"v\" : false }"); + run_bson_as_json_with_opts_tests (b, BSON_JSON_MODE_RELAXED, "{ \"v\" : false }"); - run_bson_as_json_with_opts_tests ( - b, BSON_JSON_MODE_CANONICAL, "{ \"v\" : false }"); + run_bson_as_json_with_opts_tests (b, BSON_JSON_MODE_CANONICAL, "{ \"v\" : false }"); bson_destroy (b); } @@ -3236,14 +2909,10 @@ test_bson_as_json_with_opts_date_time (void) BSON_ASSERT (BSON_APPEND_DATE_TIME (b, "v", 1602572588123)); run_bson_as_json_with_opts_tests ( - b, - BSON_JSON_MODE_RELAXED, - "{ \"v\" : { \"$date\" : \"2020-10-13T07:03:08.123Z\" } }"); + b, BSON_JSON_MODE_RELAXED, "{ \"v\" : { \"$date\" : \"2020-10-13T07:03:08.123Z\" } }"); run_bson_as_json_with_opts_tests ( - b, - BSON_JSON_MODE_CANONICAL, - "{ \"v\" : { \"$date\" : { \"$numberLong\" : \"1602572588123\" } } }"); + b, BSON_JSON_MODE_CANONICAL, "{ \"v\" : { \"$date\" : { \"$numberLong\" : \"1602572588123\" } } }"); bson_destroy (b); } @@ -3256,11 +2925,9 @@ test_bson_as_json_with_opts_null (void) b = bson_new (); BSON_ASSERT (BSON_APPEND_NULL (b, "v")); - run_bson_as_json_with_opts_tests ( - b, BSON_JSON_MODE_RELAXED, "{ \"v\" : null }"); + run_bson_as_json_with_opts_tests (b, BSON_JSON_MODE_RELAXED, "{ \"v\" : null }"); - run_bson_as_json_with_opts_tests ( - b, BSON_JSON_MODE_CANONICAL, "{ \"v\" : null }"); + run_bson_as_json_with_opts_tests (b, BSON_JSON_MODE_CANONICAL, "{ \"v\" : null }"); bson_destroy (b); } @@ -3273,17 +2940,15 @@ test_bson_as_json_with_opts_regex (void) b = bson_new (); BSON_ASSERT (BSON_APPEND_REGEX (b, "v", "^abc", "i")); - run_bson_as_json_with_opts_tests ( - b, - BSON_JSON_MODE_RELAXED, - "{ \"v\" : { \"$regularExpression\" : { \"pattern\" : \"^abc\", " - "\"options\" : \"i\" } } }"); + run_bson_as_json_with_opts_tests (b, + BSON_JSON_MODE_RELAXED, + "{ \"v\" : { \"$regularExpression\" : { \"pattern\" : \"^abc\", " + "\"options\" : \"i\" } } }"); - run_bson_as_json_with_opts_tests ( - b, - BSON_JSON_MODE_CANONICAL, - "{ \"v\" : { \"$regularExpression\" : { \"pattern\" : \"^abc\", " - "\"options\" : \"i\" } } }"); + run_bson_as_json_with_opts_tests (b, + BSON_JSON_MODE_CANONICAL, + "{ \"v\" : { \"$regularExpression\" : { \"pattern\" : \"^abc\", " + "\"options\" : \"i\" } } }"); bson_destroy (b); } @@ -3298,17 +2963,15 @@ test_bson_as_json_with_opts_dbpointer (void) b = bson_new (); BSON_ASSERT (BSON_APPEND_DBPOINTER (b, "v", "coll", &oid)); - run_bson_as_json_with_opts_tests ( - b, - BSON_JSON_MODE_RELAXED, - "{ \"v\" : { \"$dbPointer\" : { \"$ref\" : \"coll\", \"$id\" : { " - "\"$oid\" : \"12341234123412abcdababcd\" } } } }"); + run_bson_as_json_with_opts_tests (b, + BSON_JSON_MODE_RELAXED, + "{ \"v\" : { \"$dbPointer\" : { \"$ref\" : \"coll\", \"$id\" : { " + "\"$oid\" : \"12341234123412abcdababcd\" } } } }"); - run_bson_as_json_with_opts_tests ( - b, - BSON_JSON_MODE_CANONICAL, - "{ \"v\" : { \"$dbPointer\" : { \"$ref\" : \"coll\", \"$id\" : { " - "\"$oid\" : \"12341234123412abcdababcd\" } } } }"); + run_bson_as_json_with_opts_tests (b, + BSON_JSON_MODE_CANONICAL, + "{ \"v\" : { \"$dbPointer\" : { \"$ref\" : \"coll\", \"$id\" : { " + "\"$oid\" : \"12341234123412abcdababcd\" } } } }"); bson_destroy (b); } @@ -3321,15 +2984,9 @@ test_bson_as_json_with_opts_code (void) b = bson_new (); BSON_ASSERT (BSON_APPEND_CODE (b, "v", "function(){}")); - run_bson_as_json_with_opts_tests ( - b, - BSON_JSON_MODE_RELAXED, - "{ \"v\" : { \"$code\" : \"function(){}\" } }"); + run_bson_as_json_with_opts_tests (b, BSON_JSON_MODE_RELAXED, "{ \"v\" : { \"$code\" : \"function(){}\" } }"); - run_bson_as_json_with_opts_tests ( - b, - BSON_JSON_MODE_CANONICAL, - "{ \"v\" : { \"$code\" : \"function(){}\" } }"); + run_bson_as_json_with_opts_tests (b, BSON_JSON_MODE_CANONICAL, "{ \"v\" : { \"$code\" : \"function(){}\" } }"); bson_destroy (b); } @@ -3342,11 +2999,9 @@ test_bson_as_json_with_opts_symbol (void) b = bson_new (); BSON_ASSERT (BSON_APPEND_SYMBOL (b, "v", "symbol")); - run_bson_as_json_with_opts_tests ( - b, BSON_JSON_MODE_RELAXED, "{ \"v\" : { \"$symbol\" : \"symbol\" } }"); + run_bson_as_json_with_opts_tests (b, BSON_JSON_MODE_RELAXED, "{ \"v\" : { \"$symbol\" : \"symbol\" } }"); - run_bson_as_json_with_opts_tests ( - b, BSON_JSON_MODE_CANONICAL, "{ \"v\" : { \"$symbol\" : \"symbol\" } }"); + run_bson_as_json_with_opts_tests (b, BSON_JSON_MODE_CANONICAL, "{ \"v\" : { \"$symbol\" : \"symbol\" } }"); bson_destroy (b); } @@ -3363,17 +3018,15 @@ test_bson_as_json_with_opts_codewscope (void) b = bson_new (); BSON_ASSERT (BSON_APPEND_CODE_WITH_SCOPE (b, "v", "function(){}", scope)); - run_bson_as_json_with_opts_tests ( - b, - BSON_JSON_MODE_RELAXED, - "{ \"v\" : { \"$code\" : \"function(){}\", " - "\"$scope\" : { \"v\" : \"abcdef\" } } }"); + run_bson_as_json_with_opts_tests (b, + BSON_JSON_MODE_RELAXED, + "{ \"v\" : { \"$code\" : \"function(){}\", " + "\"$scope\" : { \"v\" : \"abcdef\" } } }"); - run_bson_as_json_with_opts_tests ( - b, - BSON_JSON_MODE_CANONICAL, - "{ \"v\" : { \"$code\" : \"function(){}\", " - "\"$scope\" : { \"v\" : \"abcdef\" } } }"); + run_bson_as_json_with_opts_tests (b, + BSON_JSON_MODE_CANONICAL, + "{ \"v\" : { \"$code\" : \"function(){}\", " + "\"$scope\" : { \"v\" : \"abcdef\" } } }"); bson_destroy (b); bson_destroy (scope); @@ -3387,13 +3040,9 @@ test_bson_as_json_with_opts_int32 (void) b = bson_new (); BSON_ASSERT (BSON_APPEND_INT32 (b, "v", 461394000)); - run_bson_as_json_with_opts_tests ( - b, BSON_JSON_MODE_RELAXED, "{ \"v\" : 461394000 }"); + run_bson_as_json_with_opts_tests (b, BSON_JSON_MODE_RELAXED, "{ \"v\" : 461394000 }"); - run_bson_as_json_with_opts_tests ( - b, - BSON_JSON_MODE_CANONICAL, - "{ \"v\" : { \"$numberInt\" : \"461394000\" } }"); + run_bson_as_json_with_opts_tests (b, BSON_JSON_MODE_CANONICAL, "{ \"v\" : { \"$numberInt\" : \"461394000\" } }"); bson_destroy (b); } @@ -3406,13 +3055,9 @@ test_bson_as_json_with_opts_int64 (void) b = bson_new (); BSON_ASSERT (BSON_APPEND_INT64 (b, "v", 461394000)); - run_bson_as_json_with_opts_tests ( - b, BSON_JSON_MODE_RELAXED, "{ \"v\" : 461394000 }"); + run_bson_as_json_with_opts_tests (b, BSON_JSON_MODE_RELAXED, "{ \"v\" : 461394000 }"); - run_bson_as_json_with_opts_tests ( - b, - BSON_JSON_MODE_CANONICAL, - "{ \"v\" : { \"$numberLong\" : \"461394000\" } }"); + run_bson_as_json_with_opts_tests (b, BSON_JSON_MODE_CANONICAL, "{ \"v\" : { \"$numberLong\" : \"461394000\" } }"); bson_destroy (b); } @@ -3426,14 +3071,10 @@ test_bson_as_json_with_opts_timestamp (void) BSON_ASSERT (BSON_APPEND_TIMESTAMP (b, "v", 461394000, 2)); run_bson_as_json_with_opts_tests ( - b, - BSON_JSON_MODE_RELAXED, - "{ \"v\" : { \"$timestamp\" : { \"t\" : 461394000, \"i\" : 2 } } }"); + b, BSON_JSON_MODE_RELAXED, "{ \"v\" : { \"$timestamp\" : { \"t\" : 461394000, \"i\" : 2 } } }"); run_bson_as_json_with_opts_tests ( - b, - BSON_JSON_MODE_CANONICAL, - "{ \"v\" : { \"$timestamp\" : { \"t\" : 461394000, \"i\" : 2 } } }"); + b, BSON_JSON_MODE_CANONICAL, "{ \"v\" : { \"$timestamp\" : { \"t\" : 461394000, \"i\" : 2 } } }"); bson_destroy (b); } @@ -3446,11 +3087,9 @@ test_bson_as_json_with_opts_minkey (void) b = bson_new (); BSON_ASSERT (BSON_APPEND_MINKEY (b, "v")); - run_bson_as_json_with_opts_tests ( - b, BSON_JSON_MODE_RELAXED, "{ \"v\" : { \"$minKey\" : 1 } }"); + run_bson_as_json_with_opts_tests (b, BSON_JSON_MODE_RELAXED, "{ \"v\" : { \"$minKey\" : 1 } }"); - run_bson_as_json_with_opts_tests ( - b, BSON_JSON_MODE_CANONICAL, "{ \"v\" : { \"$minKey\" : 1 } }"); + run_bson_as_json_with_opts_tests (b, BSON_JSON_MODE_CANONICAL, "{ \"v\" : { \"$minKey\" : 1 } }"); bson_destroy (b); } @@ -3463,11 +3102,9 @@ test_bson_as_json_with_opts_maxkey (void) b = bson_new (); BSON_ASSERT (BSON_APPEND_MAXKEY (b, "v")); - run_bson_as_json_with_opts_tests ( - b, BSON_JSON_MODE_RELAXED, "{ \"v\" : { \"$maxKey\" : 1 } }"); + run_bson_as_json_with_opts_tests (b, BSON_JSON_MODE_RELAXED, "{ \"v\" : { \"$maxKey\" : 1 } }"); - run_bson_as_json_with_opts_tests ( - b, BSON_JSON_MODE_CANONICAL, "{ \"v\" : { \"$maxKey\" : 1 } }"); + run_bson_as_json_with_opts_tests (b, BSON_JSON_MODE_CANONICAL, "{ \"v\" : { \"$maxKey\" : 1 } }"); bson_destroy (b); } @@ -3484,17 +3121,15 @@ test_bson_as_json_with_opts_decimal128 (void) b = bson_new (); BSON_ASSERT (BSON_APPEND_DECIMAL128 (b, "v", &dec)); - run_bson_as_json_with_opts_tests ( - b, - BSON_JSON_MODE_RELAXED, - "{ \"v\" : { \"$numberDecimal\" : " - "\"5192296858534827628530496329220095\" } }"); + run_bson_as_json_with_opts_tests (b, + BSON_JSON_MODE_RELAXED, + "{ \"v\" : { \"$numberDecimal\" : " + "\"5192296858534827628530496329220095\" } }"); - run_bson_as_json_with_opts_tests ( - b, - BSON_JSON_MODE_CANONICAL, - "{ \"v\" : { \"$numberDecimal\" : " - "\"5192296858534827628530496329220095\" } }"); + run_bson_as_json_with_opts_tests (b, + BSON_JSON_MODE_CANONICAL, + "{ \"v\" : { \"$numberDecimal\" : " + "\"5192296858534827628530496329220095\" } }"); bson_destroy (b); } @@ -3521,8 +3156,7 @@ test_bson_as_json_with_opts_all_types (void) BCON_APPEND (&b, "utf8", "bar"); BCON_APPEND (&b, "document", "{", "x", BCON_INT32 (1), "}"); BCON_APPEND (&b, "array", "[", BCON_INT32 (1), "]"); - BCON_APPEND ( - &b, "binary", BCON_BIN (BSON_SUBTYPE_BINARY, (uint8_t *) "abc", 3)); + BCON_APPEND (&b, "binary", BCON_BIN (BSON_SUBTYPE_BINARY, (uint8_t *) "abc", 3)); BCON_APPEND (&b, "undefined", BCON_UNDEFINED); BCON_APPEND (&b, "oid", BCON_OID (&oid)); BCON_APPEND (&b, "false", BCON_BOOL (false)); @@ -3545,8 +3179,7 @@ test_bson_as_json_with_opts_all_types (void) full_relaxed = bson_as_relaxed_extended_json (&b, NULL); run_bson_as_json_with_opts_tests (&b, BSON_JSON_MODE_RELAXED, full_relaxed); - run_bson_as_json_with_opts_tests ( - &b, BSON_JSON_MODE_CANONICAL, full_canonical); + run_bson_as_json_with_opts_tests (&b, BSON_JSON_MODE_CANONICAL, full_canonical); bson_free (full_canonical); bson_free (full_relaxed); @@ -3570,79 +3203,63 @@ test_decimal128_overflowing_exponent (void) { bson_decimal128_t decimal128; - BSON_ASSERT ( - !bson_decimal128_from_string ("-0E+2147483648", &decimal128)); + BSON_ASSERT (!bson_decimal128_from_string ("-0E+2147483648", &decimal128)); } { bson_decimal128_t decimal128; - BSON_ASSERT ( - !bson_decimal128_from_string ("-0E-2147483649", &decimal128)); + BSON_ASSERT (!bson_decimal128_from_string ("-0E-2147483649", &decimal128)); } { bson_error_t error; - const char *degenerate_extjson = - "{\"d\" : {\"$numberDecimal\" : \"0E+2147483648\"}}"; - - BSON_ASSERT (!bson_new_from_json ( - (const uint8_t *) degenerate_extjson, -1, &error)); - ASSERT_ERROR_CONTAINS ( - error, - BSON_ERROR_JSON, - BSON_JSON_ERROR_READ_INVALID_PARAM, - "Invalid input string \"0E+2147483648\", looking for DECIMAL128"); + const char *degenerate_extjson = "{\"d\" : {\"$numberDecimal\" : \"0E+2147483648\"}}"; + + BSON_ASSERT (!bson_new_from_json ((const uint8_t *) degenerate_extjson, -1, &error)); + ASSERT_ERROR_CONTAINS (error, + BSON_ERROR_JSON, + BSON_JSON_ERROR_READ_INVALID_PARAM, + "Invalid input string \"0E+2147483648\", looking for DECIMAL128"); } { bson_error_t error; - const char *degenerate_extjson = - "{\"d\" : {\"$numberDecimal\" : \"0E-2147483649\"}}"; - - BSON_ASSERT (!bson_new_from_json ( - (const uint8_t *) degenerate_extjson, -1, &error)); - ASSERT_ERROR_CONTAINS ( - error, - BSON_ERROR_JSON, - BSON_JSON_ERROR_READ_INVALID_PARAM, - "Invalid input string \"0E-2147483649\", looking for DECIMAL128"); + const char *degenerate_extjson = "{\"d\" : {\"$numberDecimal\" : \"0E-2147483649\"}}"; + + BSON_ASSERT (!bson_new_from_json ((const uint8_t *) degenerate_extjson, -1, &error)); + ASSERT_ERROR_CONTAINS (error, + BSON_ERROR_JSON, + BSON_JSON_ERROR_READ_INVALID_PARAM, + "Invalid input string \"0E-2147483649\", looking for DECIMAL128"); } { bson_error_t error; - const char *degenerate_extjson = - "{\"d\" : {\"$numberDecimal\" : \"-0E+2147483648\"}}"; - - BSON_ASSERT (!bson_new_from_json ( - (const uint8_t *) degenerate_extjson, -1, &error)); - ASSERT_ERROR_CONTAINS ( - error, - BSON_ERROR_JSON, - BSON_JSON_ERROR_READ_INVALID_PARAM, - "Invalid input string \"-0E+2147483648\", looking for DECIMAL128"); + const char *degenerate_extjson = "{\"d\" : {\"$numberDecimal\" : \"-0E+2147483648\"}}"; + + BSON_ASSERT (!bson_new_from_json ((const uint8_t *) degenerate_extjson, -1, &error)); + ASSERT_ERROR_CONTAINS (error, + BSON_ERROR_JSON, + BSON_JSON_ERROR_READ_INVALID_PARAM, + "Invalid input string \"-0E+2147483648\", looking for DECIMAL128"); } { bson_error_t error; - const char *degenerate_extjson = - "{\"d\" : {\"$numberDecimal\" : \"-0E-2147483649\"}}"; - - BSON_ASSERT (!bson_new_from_json ( - (const uint8_t *) degenerate_extjson, -1, &error)); - ASSERT_ERROR_CONTAINS ( - error, - BSON_ERROR_JSON, - BSON_JSON_ERROR_READ_INVALID_PARAM, - "Invalid input string \"-0E-2147483649\", looking for DECIMAL128"); + const char *degenerate_extjson = "{\"d\" : {\"$numberDecimal\" : \"-0E-2147483649\"}}"; + + BSON_ASSERT (!bson_new_from_json ((const uint8_t *) degenerate_extjson, -1, &error)); + ASSERT_ERROR_CONTAINS (error, + BSON_ERROR_JSON, + BSON_JSON_ERROR_READ_INVALID_PARAM, + "Invalid input string \"-0E-2147483649\", looking for DECIMAL128"); } { bson_decimal128_t decimal128; - BSON_ASSERT ( - !bson_decimal128_from_string ("0E+99999999999999999999", &decimal128)); + BSON_ASSERT (!bson_decimal128_from_string ("0E+99999999999999999999", &decimal128)); } { bson_decimal128_t decimal128; - BSON_ASSERT ( - !bson_decimal128_from_string ("0E-99999999999999999999", &decimal128)); + BSON_ASSERT (!bson_decimal128_from_string ("0E-99999999999999999999", &decimal128)); } } @@ -3682,8 +3299,7 @@ test_parse_array (void) bson_t *b2; { - const char *json = - BSON_STR ({"0" : {"$code" : "A"}}, {"1" : {"$code" : "B"}}); + const char *json = BSON_STR ({"0" : {"$code" : "A"}}, {"1" : {"$code" : "B"}}); bson_error_t error; b2 = bson_new_from_json ((const uint8_t *) json, -1, &error); ASSERT_OR_PRINT (b2, error); @@ -3697,11 +3313,8 @@ test_parse_array (void) { bson_t *b1; { - const char *json = BSON_STR ([ { - "$dbPointer" : - {"$ref" : "foo", - "$id" : {"$oid" : "01234567890abcdef0123456"}} - } ]); + const char *json = + BSON_STR ([ {"$dbPointer" : {"$ref" : "foo", "$id" : {"$oid" : "01234567890abcdef0123456"}}} ]); bson_error_t error; b1 = bson_new_from_json ((const uint8_t *) json, -1, &error); ASSERT_OR_PRINT (b1, error); @@ -3709,14 +3322,8 @@ test_parse_array (void) bson_t *b2; { - const char *json = BSON_STR ({ - "0" : { - "$dbPointer" : { - "$ref" : "foo", - "$id" : {"$oid" : "01234567890abcdef0123456"} - } - } - }); + const char *json = + BSON_STR ({"0" : {"$dbPointer" : {"$ref" : "foo", "$id" : {"$oid" : "01234567890abcdef0123456"}}}}); bson_error_t error; b2 = bson_new_from_json ((const uint8_t *) json, -1, &error); ASSERT_OR_PRINT (b2, error); @@ -3731,18 +3338,8 @@ test_parse_array (void) bson_t *b1; { const char *json = BSON_STR ([ - { - "$dbPointer" : { - "$ref" : "foo", - "$id" : {"$oid" : "01234567890abcdef0123456"} - } - }, - { - "$dbPointer" : { - "$ref" : "foo", - "$id" : {"$oid" : "01234567890abcdef0123456"} - } - } + {"$dbPointer" : {"$ref" : "foo", "$id" : {"$oid" : "01234567890abcdef0123456"}}}, + {"$dbPointer" : {"$ref" : "foo", "$id" : {"$oid" : "01234567890abcdef0123456"}}} ]); bson_error_t error; b1 = bson_new_from_json ((const uint8_t *) json, -1, &error); @@ -3751,23 +3348,9 @@ test_parse_array (void) bson_t *b2; { - const char *json = BSON_STR ( - { - "0" : { - "$dbPointer" : { - "$ref" : "foo", - "$id" : {"$oid" : "01234567890abcdef0123456"} - } - } - }, - { - "1" : { - "$dbPointer" : { - "$ref" : "foo", - "$id" : {"$oid" : "01234567890abcdef0123456"} - } - } - }); + const char *json = + BSON_STR ({"0" : {"$dbPointer" : {"$ref" : "foo", "$id" : {"$oid" : "01234567890abcdef0123456"}}}}, + {"1" : {"$dbPointer" : {"$ref" : "foo", "$id" : {"$oid" : "01234567890abcdef0123456"}}}}); bson_error_t error; b2 = bson_new_from_json ((const uint8_t *) json, -1, &error); @@ -3789,192 +3372,98 @@ test_json_install (TestSuite *suite) TestSuite_Add (suite, "/bson/as_json/int32", test_bson_as_json_int32); TestSuite_Add (suite, "/bson/as_json/int64", test_bson_as_json_int64); TestSuite_Add (suite, "/bson/as_json/double", test_bson_as_json_double); - TestSuite_Add (suite, - "/bson/as_json/double/nonfinite", - test_bson_as_json_double_nonfinite); + TestSuite_Add (suite, "/bson/as_json/double/nonfinite", test_bson_as_json_double_nonfinite); TestSuite_Add (suite, "/bson/as_json/code", test_bson_as_json_code); - TestSuite_Add ( - suite, "/bson/as_json/date_time", test_bson_as_json_date_time); + TestSuite_Add (suite, "/bson/as_json/date_time", test_bson_as_json_date_time); TestSuite_Add (suite, "/bson/as_json/regex", test_bson_as_json_regex); TestSuite_Add (suite, "/bson/as_json/symbol", test_bson_as_json_symbol); TestSuite_Add (suite, "/bson/as_json/utf8", test_bson_as_json_utf8); - TestSuite_Add ( - suite, "/bson/as_json/dbpointer", test_bson_as_json_dbpointer); - TestSuite_Add (suite, - "/bson/as_canonical_extended_json/dbpointer", - test_bson_as_canonical_extended_json_dbpointer); - TestSuite_Add ( - suite, "/bson/as_json/stack_overflow", test_bson_as_json_stack_overflow); + TestSuite_Add (suite, "/bson/as_json/dbpointer", test_bson_as_json_dbpointer); + TestSuite_Add (suite, "/bson/as_canonical_extended_json/dbpointer", test_bson_as_canonical_extended_json_dbpointer); + TestSuite_Add (suite, "/bson/as_json/stack_overflow", test_bson_as_json_stack_overflow); TestSuite_Add (suite, "/bson/as_json/corrupt", test_bson_corrupt); TestSuite_Add (suite, "/bson/as_json/corrupt_utf8", test_bson_corrupt_utf8); - TestSuite_Add ( - suite, "/bson/as_json/corrupt_binary", test_bson_corrupt_binary); + TestSuite_Add (suite, "/bson/as_json/corrupt_binary", test_bson_corrupt_binary); TestSuite_Add (suite, "/bson/as_json_spacing", test_bson_as_json_spacing); - TestSuite_Add ( - suite, "/bson/array_as_legacy_json", test_bson_array_as_legacy_json); - TestSuite_Add ( - suite, "/bson/array_as_relaxed_json", test_bson_array_as_relaxed_json); - TestSuite_Add (suite, - "/bson/array_as_canonical_json", - test_bson_array_as_canonical_json); - TestSuite_Add ( - suite, "/bson/json/allow_multiple", test_bson_json_allow_multiple); - TestSuite_Add ( - suite, "/bson/json/read/buffering", test_bson_json_read_buffering); + TestSuite_Add (suite, "/bson/array_as_legacy_json", test_bson_array_as_legacy_json); + TestSuite_Add (suite, "/bson/array_as_relaxed_json", test_bson_array_as_relaxed_json); + TestSuite_Add (suite, "/bson/array_as_canonical_json", test_bson_array_as_canonical_json); + TestSuite_Add (suite, "/bson/json/allow_multiple", test_bson_json_allow_multiple); + TestSuite_Add (suite, "/bson/json/read/buffering", test_bson_json_read_buffering); TestSuite_Add (suite, "/bson/json/read", test_bson_json_read); TestSuite_Add (suite, "/bson/json/inc", test_bson_json_inc); TestSuite_Add (suite, "/bson/json/array", test_bson_json_array); - TestSuite_Add ( - suite, "/bson/json/array/single", test_bson_json_array_single); + TestSuite_Add (suite, "/bson/json/array/single", test_bson_json_array_single); TestSuite_Add (suite, "/bson/json/array/int64", test_bson_json_array_int64); - TestSuite_Add ( - suite, "/bson/json/array/subdoc", test_bson_json_array_subdoc); + TestSuite_Add (suite, "/bson/json/array/subdoc", test_bson_json_array_subdoc); TestSuite_Add (suite, "/bson/json/date", test_bson_json_date); TestSuite_Add (suite, "/bson/json/date/legacy", test_bson_json_date_legacy); - TestSuite_Add ( - suite, "/bson/json/date/long", test_bson_json_date_numberlong); + TestSuite_Add (suite, "/bson/json/date/long", test_bson_json_date_numberlong); TestSuite_Add (suite, "/bson/json/timestamp", test_bson_json_timestamp); TestSuite_Add (suite, "/bson/json/read/empty", test_bson_json_read_empty); - TestSuite_Add (suite, - "/bson/json/read/missing_complex", - test_bson_json_read_missing_complex); - TestSuite_Add (suite, - "/bson/json/read/invalid_binary", - test_bson_json_read_invalid_binary); - TestSuite_Add ( - suite, "/bson/json/read/invalid_json", test_bson_json_read_invalid_json); + TestSuite_Add (suite, "/bson/json/read/missing_complex", test_bson_json_read_missing_complex); + TestSuite_Add (suite, "/bson/json/read/invalid_binary", test_bson_json_read_invalid_binary); + TestSuite_Add (suite, "/bson/json/read/invalid_json", test_bson_json_read_invalid_json); TestSuite_Add (suite, "/bson/json/read/bad_cb", test_bson_json_read_bad_cb); - TestSuite_Add ( - suite, "/bson/json/read/invalid", test_bson_json_read_invalid); - TestSuite_Add (suite, - "/bson/json/read/invalid_base64", - test_bson_json_read_invalid_base64); - TestSuite_Add ( - suite, "/bson/json/read/raw_utf8", test_bson_json_read_raw_utf8); - TestSuite_Add ( - suite, "/bson/json/read/corrupt_utf8", test_bson_json_read_corrupt_utf8); - TestSuite_Add (suite, - "/bson/json/read/corrupt_document", - test_bson_json_read_corrupt_document); - TestSuite_Add ( - suite, "/bson/json/read/decimal128", test_bson_json_read_decimal128); - TestSuite_Add ( - suite, "/bson/json/read/dbpointer", test_bson_json_read_dbpointer); - TestSuite_Add ( - suite, "/bson/json/read/legacy_regex", test_bson_json_read_legacy_regex); - TestSuite_Add (suite, - "/bson/json/read/regex_options_order", - test_bson_json_read_regex_options_order); + TestSuite_Add (suite, "/bson/json/read/invalid", test_bson_json_read_invalid); + TestSuite_Add (suite, "/bson/json/read/invalid_base64", test_bson_json_read_invalid_base64); + TestSuite_Add (suite, "/bson/json/read/raw_utf8", test_bson_json_read_raw_utf8); + TestSuite_Add (suite, "/bson/json/read/corrupt_utf8", test_bson_json_read_corrupt_utf8); + TestSuite_Add (suite, "/bson/json/read/corrupt_document", test_bson_json_read_corrupt_document); + TestSuite_Add (suite, "/bson/json/read/decimal128", test_bson_json_read_decimal128); + TestSuite_Add (suite, "/bson/json/read/dbpointer", test_bson_json_read_dbpointer); + TestSuite_Add (suite, "/bson/json/read/legacy_regex", test_bson_json_read_legacy_regex); + TestSuite_Add (suite, "/bson/json/read/regex_options_order", test_bson_json_read_regex_options_order); TestSuite_Add (suite, "/bson/json/read/binary", test_bson_json_read_binary); - TestSuite_Add (suite, - "/bson/json/read/legacy_binary", - test_bson_json_read_legacy_binary); - TestSuite_Add ( - suite, "/bson/json/read/file", test_json_reader_new_from_file); - TestSuite_Add ( - suite, "/bson/json/read/bad_path", test_json_reader_new_from_bad_path); - TestSuite_Add ( - suite, "/bson/json/read/$numberLong", test_bson_json_number_long); - TestSuite_Add (suite, - "/bson/json/read/$numberLong/zero", - test_bson_json_number_long_zero); + TestSuite_Add (suite, "/bson/json/read/legacy_binary", test_bson_json_read_legacy_binary); + TestSuite_Add (suite, "/bson/json/read/file", test_json_reader_new_from_file); + TestSuite_Add (suite, "/bson/json/read/bad_path", test_json_reader_new_from_bad_path); + TestSuite_Add (suite, "/bson/json/read/$numberLong", test_bson_json_number_long); + TestSuite_Add (suite, "/bson/json/read/$numberLong/zero", test_bson_json_number_long_zero); TestSuite_Add (suite, "/bson/json/read/code", test_bson_json_code); - TestSuite_Add ( - suite, "/bson/json/read/code/errors", test_bson_json_code_errors); + TestSuite_Add (suite, "/bson/json/read/code/errors", test_bson_json_code_errors); TestSuite_Add (suite, "/bson/json/read/dbref", test_bson_json_dbref); TestSuite_Add (suite, "/bson/json/read/uescape", test_bson_json_uescape); - TestSuite_Add ( - suite, "/bson/json/read/uescape/key", test_bson_json_uescape_key); - TestSuite_Add ( - suite, "/bson/json/read/uescape/bad", test_bson_json_uescape_bad); + TestSuite_Add (suite, "/bson/json/read/uescape/key", test_bson_json_uescape_key); + TestSuite_Add (suite, "/bson/json/read/uescape/bad", test_bson_json_uescape_bad); TestSuite_Add (suite, "/bson/json/read/int32", test_bson_json_int32); TestSuite_Add (suite, "/bson/json/read/int64", test_bson_json_int64); TestSuite_Add (suite, "/bson/json/read/double", test_bson_json_double); - TestSuite_Add ( - suite, "/bson/json/read/double/overflow", test_bson_json_double_overflow); + TestSuite_Add (suite, "/bson/json/read/double/overflow", test_bson_json_double_overflow); TestSuite_Add (suite, "/bson/json/read/double/nan", test_bson_json_nan); - TestSuite_Add ( - suite, "/bson/json/read/double/infinity", test_bson_json_infinity); + TestSuite_Add (suite, "/bson/json/read/double/infinity", test_bson_json_infinity); TestSuite_Add (suite, "/bson/json/read/null", test_bson_json_null); - TestSuite_Add ( - suite, "/bson/json/read/empty_final", test_bson_json_empty_final_object); - TestSuite_Add ( - suite, "/bson/as_json/decimal128", test_bson_as_json_decimal128); - TestSuite_Add ( - suite, "/bson/json/read/$numberDecimal", test_bson_json_number_decimal); + TestSuite_Add (suite, "/bson/json/read/empty_final", test_bson_json_empty_final_object); + TestSuite_Add (suite, "/bson/as_json/decimal128", test_bson_as_json_decimal128); + TestSuite_Add (suite, "/bson/json/read/$numberDecimal", test_bson_json_number_decimal); TestSuite_Add (suite, "/bson/json/errors", test_bson_json_errors); TestSuite_Add (suite, "/bson/integer/width", test_bson_integer_width); - TestSuite_Add ( - suite, "/bson/json/read/null_in_str", test_bson_json_null_in_str); - TestSuite_Add ( - suite, "/bson/json/read/merge_multiple", test_bson_json_merge_multiple); - TestSuite_Add ( - suite, "/bson/json/read/extra_chars", test_bson_json_extra_chars); - TestSuite_Add ( - suite, "/bson/as_json/multi_object", test_bson_as_json_multi_object); - TestSuite_Add (suite, - "/bson/as_json_with_opts/double", - test_bson_as_json_with_opts_double); - TestSuite_Add ( - suite, "/bson/as_json_with_opts/utf8", test_bson_as_json_with_opts_utf8); - TestSuite_Add (suite, - "/bson/as_json_with_opts/document", - test_bson_as_json_with_opts_document); - TestSuite_Add (suite, - "/bson/as_json_with_opts/array", - test_bson_as_json_with_opts_array); - TestSuite_Add (suite, - "/bson/as_json_with_opts/binary", - test_bson_as_json_with_opts_binary); - TestSuite_Add (suite, - "/bson/as_json_with_opts/undefined", - test_bson_as_json_with_opts_undefined); - TestSuite_Add ( - suite, "/bson/as_json_with_opts/oid", test_bson_as_json_with_opts_oid); - TestSuite_Add ( - suite, "/bson/as_json_with_opts/bool", test_bson_as_json_with_opts_bool); - TestSuite_Add (suite, - "/bson/as_json_with_opts/date_time", - test_bson_as_json_with_opts_date_time); - TestSuite_Add ( - suite, "/bson/as_json_with_opts/null", test_bson_as_json_with_opts_null); - TestSuite_Add (suite, - "/bson/as_json_with_opts/regex", - test_bson_as_json_with_opts_regex); - TestSuite_Add (suite, - "/bson/as_json_with_opts/dbpointer", - test_bson_as_json_with_opts_dbpointer); - TestSuite_Add ( - suite, "/bson/as_json_with_opts/code", test_bson_as_json_with_opts_code); - TestSuite_Add (suite, - "/bson/as_json_with_opts/symbol", - test_bson_as_json_with_opts_symbol); - TestSuite_Add (suite, - "/bson/as_json_with_opts/codewscope", - test_bson_as_json_with_opts_codewscope); - TestSuite_Add (suite, - "/bson/as_json_with_opts/int32", - test_bson_as_json_with_opts_int32); - TestSuite_Add (suite, - "/bson/as_json_with_opts/int64", - test_bson_as_json_with_opts_int64); - TestSuite_Add (suite, - "/bson/as_json_with_opts/timestamp", - test_bson_as_json_with_opts_timestamp); - TestSuite_Add (suite, - "/bson/as_json_with_opts/minkey", - test_bson_as_json_with_opts_minkey); - TestSuite_Add (suite, - "/bson/as_json_with_opts/maxkey", - test_bson_as_json_with_opts_maxkey); - TestSuite_Add (suite, - "/bson/as_json_with_opts/decimal128", - test_bson_as_json_with_opts_decimal128); - TestSuite_Add (suite, - "/bson/as_json_with_opts/all_types", - test_bson_as_json_with_opts_all_types); + TestSuite_Add (suite, "/bson/json/read/null_in_str", test_bson_json_null_in_str); + TestSuite_Add (suite, "/bson/json/read/merge_multiple", test_bson_json_merge_multiple); + TestSuite_Add (suite, "/bson/json/read/extra_chars", test_bson_json_extra_chars); + TestSuite_Add (suite, "/bson/as_json/multi_object", test_bson_as_json_multi_object); + TestSuite_Add (suite, "/bson/as_json_with_opts/double", test_bson_as_json_with_opts_double); + TestSuite_Add (suite, "/bson/as_json_with_opts/utf8", test_bson_as_json_with_opts_utf8); + TestSuite_Add (suite, "/bson/as_json_with_opts/document", test_bson_as_json_with_opts_document); + TestSuite_Add (suite, "/bson/as_json_with_opts/array", test_bson_as_json_with_opts_array); + TestSuite_Add (suite, "/bson/as_json_with_opts/binary", test_bson_as_json_with_opts_binary); + TestSuite_Add (suite, "/bson/as_json_with_opts/undefined", test_bson_as_json_with_opts_undefined); + TestSuite_Add (suite, "/bson/as_json_with_opts/oid", test_bson_as_json_with_opts_oid); + TestSuite_Add (suite, "/bson/as_json_with_opts/bool", test_bson_as_json_with_opts_bool); + TestSuite_Add (suite, "/bson/as_json_with_opts/date_time", test_bson_as_json_with_opts_date_time); + TestSuite_Add (suite, "/bson/as_json_with_opts/null", test_bson_as_json_with_opts_null); + TestSuite_Add (suite, "/bson/as_json_with_opts/regex", test_bson_as_json_with_opts_regex); + TestSuite_Add (suite, "/bson/as_json_with_opts/dbpointer", test_bson_as_json_with_opts_dbpointer); + TestSuite_Add (suite, "/bson/as_json_with_opts/code", test_bson_as_json_with_opts_code); + TestSuite_Add (suite, "/bson/as_json_with_opts/symbol", test_bson_as_json_with_opts_symbol); + TestSuite_Add (suite, "/bson/as_json_with_opts/codewscope", test_bson_as_json_with_opts_codewscope); + TestSuite_Add (suite, "/bson/as_json_with_opts/int32", test_bson_as_json_with_opts_int32); + TestSuite_Add (suite, "/bson/as_json_with_opts/int64", test_bson_as_json_with_opts_int64); + TestSuite_Add (suite, "/bson/as_json_with_opts/timestamp", test_bson_as_json_with_opts_timestamp); + TestSuite_Add (suite, "/bson/as_json_with_opts/minkey", test_bson_as_json_with_opts_minkey); + TestSuite_Add (suite, "/bson/as_json_with_opts/maxkey", test_bson_as_json_with_opts_maxkey); + TestSuite_Add (suite, "/bson/as_json_with_opts/decimal128", test_bson_as_json_with_opts_decimal128); + TestSuite_Add (suite, "/bson/as_json_with_opts/all_types", test_bson_as_json_with_opts_all_types); TestSuite_Add (suite, "/bson/parse_array", test_parse_array); - TestSuite_Add (suite, - "/bson/decimal128_overflowing_exponent", - test_decimal128_overflowing_exponent); + TestSuite_Add (suite, "/bson/decimal128_overflowing_exponent", test_decimal128_overflowing_exponent); } diff --git a/src/libbson/tests/test-oid.c b/src/libbson/tests/test-oid.c index 2af2e1b7be..e7cb77d164 100644 --- a/src/libbson/tests/test-oid.c +++ b/src/libbson/tests/test-oid.c @@ -247,8 +247,7 @@ test_bson_oid_get_time_t (void) context = bson_context_new (BSON_CONTEXT_NONE); bson_oid_init (&oid, context); ASSERT_CMPUINT32 ((uint32_t) bson_oid_get_time_t (&oid), >=, start); - ASSERT_CMPUINT32 ( - (uint32_t) bson_oid_get_time_t (&oid), <=, (uint32_t) time (NULL)); + ASSERT_CMPUINT32 ((uint32_t) bson_oid_get_time_t (&oid), <=, (uint32_t) time (NULL)); bson_oid_init_from_string (&oid, "000000000000000000000000"); str = get_time_as_string (&oid); @@ -473,18 +472,14 @@ void test_oid_install (TestSuite *suite) { TestSuite_Add (suite, "/bson/oid/init", test_bson_oid_init); - TestSuite_Add ( - suite, "/bson/oid/init_from_string", test_bson_oid_init_from_string); - TestSuite_Add ( - suite, "/bson/oid/init_sequence", test_bson_oid_init_sequence); - TestSuite_Add ( - suite, "/bson/oid/init_with_threads", test_bson_oid_init_with_threads); + TestSuite_Add (suite, "/bson/oid/init_from_string", test_bson_oid_init_from_string); + TestSuite_Add (suite, "/bson/oid/init_sequence", test_bson_oid_init_sequence); + TestSuite_Add (suite, "/bson/oid/init_with_threads", test_bson_oid_init_with_threads); TestSuite_Add (suite, "/bson/oid/hash", test_bson_oid_hash); TestSuite_Add (suite, "/bson/oid/compare", test_bson_oid_compare); TestSuite_Add (suite, "/bson/oid/copy", test_bson_oid_copy); TestSuite_Add (suite, "/bson/oid/get_time_t", test_bson_oid_get_time_t); - TestSuite_Add ( - suite, "/bson/oid/counter_overflow", test_bson_oid_counter_overflow); + TestSuite_Add (suite, "/bson/oid/counter_overflow", test_bson_oid_counter_overflow); #ifndef _WIN32 if (!TestSuite_NoFork (suite)) { TestSuite_Add (suite, "/bson/oid/after_fork", test_bson_oid_after_fork); diff --git a/src/libbson/tests/test-reader.c b/src/libbson/tests/test-reader.c index 9c6b6e3b2a..730e7de1c2 100644 --- a/src/libbson/tests/test-reader.c +++ b/src/libbson/tests/test-reader.c @@ -160,9 +160,7 @@ test_reader_from_handle (void) fd = bson_open (BSON_BINARY_DIR "/stream.bson", O_RDONLY); BSON_ASSERT (-1 != fd); - reader = bson_reader_new_from_handle ((void *) &fd, - &test_reader_from_handle_read, - &test_reader_from_handle_destroy); + reader = bson_reader_new_from_handle ((void *) &fd, &test_reader_from_handle_read, &test_reader_from_handle_destroy); for (i = 0; i < 1000; i++) { eof = false; @@ -193,9 +191,7 @@ test_reader_tell (void) fd = bson_open (BSON_BINARY_DIR "/stream.bson", O_RDONLY); BSON_ASSERT (-1 != fd); - reader = bson_reader_new_from_handle ((void *) &fd, - &test_reader_from_handle_read, - &test_reader_from_handle_destroy); + reader = bson_reader_new_from_handle ((void *) &fd, &test_reader_from_handle_read, &test_reader_from_handle_destroy); for (i = 0; i < 1000; i++) { if (i) { @@ -232,9 +228,7 @@ test_reader_from_handle_corrupt (void) fd = bson_open (BSON_BINARY_DIR "/stream_corrupt.bson", O_RDONLY); BSON_ASSERT (-1 != fd); - reader = bson_reader_new_from_handle ((void *) &fd, - &test_reader_from_handle_read, - &test_reader_from_handle_destroy); + reader = bson_reader_new_from_handle ((void *) &fd, &test_reader_from_handle_read, &test_reader_from_handle_destroy); for (i = 0; i < 1000; i++) { b = bson_reader_read (reader, &eof); @@ -260,9 +254,7 @@ test_reader_grow_buffer (void) fd = bson_open (BSON_BINARY_DIR "/readergrow.bson", O_RDONLY); BSON_ASSERT (-1 != fd); - reader = bson_reader_new_from_handle ((void *) &fd, - &test_reader_from_handle_read, - &test_reader_from_handle_destroy); + reader = bson_reader_new_from_handle ((void *) &fd, &test_reader_from_handle_read, &test_reader_from_handle_destroy); b = bson_reader_read (reader, &eof); BSON_ASSERT (b); @@ -311,21 +303,14 @@ void test_reader_install (TestSuite *suite) { TestSuite_Add (suite, "/bson/reader/new_from_data", test_reader_from_data); - TestSuite_Add (suite, - "/bson/reader/new_from_data_overflow", - test_reader_from_data_overflow); - TestSuite_Add (suite, - "/bson/reader/new_from_data_document_length_too_large", - test_reader_from_data_document_length_too_large); - TestSuite_Add (suite, - "/bson/reader/new_from_data_document_length_too_small", - test_reader_from_data_document_length_too_small); + TestSuite_Add (suite, "/bson/reader/new_from_data_overflow", test_reader_from_data_overflow); TestSuite_Add ( - suite, "/bson/reader/new_from_handle", test_reader_from_handle); + suite, "/bson/reader/new_from_data_document_length_too_large", test_reader_from_data_document_length_too_large); + TestSuite_Add ( + suite, "/bson/reader/new_from_data_document_length_too_small", test_reader_from_data_document_length_too_small); + TestSuite_Add (suite, "/bson/reader/new_from_handle", test_reader_from_handle); TestSuite_Add (suite, "/bson/reader/tell", test_reader_tell); - TestSuite_Add (suite, - "/bson/reader/new_from_handle_corrupt", - test_reader_from_handle_corrupt); + TestSuite_Add (suite, "/bson/reader/new_from_handle_corrupt", test_reader_from_handle_corrupt); TestSuite_Add (suite, "/bson/reader/grow_buffer", test_reader_grow_buffer); TestSuite_Add (suite, "/bson/reader/reset", test_reader_reset); } diff --git a/src/libbson/tests/test-string.c b/src/libbson/tests/test-string.c index 8efd004b35..58791b156f 100644 --- a/src/libbson/tests/test-string.c +++ b/src/libbson/tests/test-string.c @@ -202,61 +202,60 @@ test_bson_ascii_strtoll (void) int64_t rv; int i; char *endptr; - strtoll_test tests[] = { - /* input, base, expected output, # of chars parsed, expected errno */ - {"1", 10, 1, END, 0}, - {"+1", 10, 1, END, 0}, - {"-1", 10, -1, END, 0}, - {"0", 10, 0, END, 0}, - {"0 ", 10, 0, " ", 0}, - {" 0 ", 10, 0, " ", 0}, - {" 0", 10, 0, END, 0}, - {" 0\"", 10, 0, "\"", 0}, - {"0l", 10, 0, "l", 0}, - {"0l ", 10, 0, "l ", 0}, - {"0u", 10, 0, "u", 0}, - {"0u ", 10, 0, "u ", 0}, - {"0L", 10, 0, "L", 0}, - {"0L ", 10, 0, "L ", 0}, - {"0U", 10, 0, "U", 0}, - {"0U ", 10, 0, "U ", 0}, - {"-0", 10, 0, END, 0}, - {"+0", 10, 0, END, 0}, - {"010", 8, 8, END, 0}, - /* stroll "takes as many characters as possible to form a valid base-n - * integer", so it ignores "8" and returns 0 */ - {"08", 0, 0, "8", 0}, - {"010", 10, 10, END, 0}, - {"010", 8, 8, END, 0}, - {"010", 0, 8, END, 0}, - {"68719476736", 10, 68719476736, END, 0}, - {"-68719476736", 10, -68719476736, END, 0}, - {"+68719476736", 10, 68719476736, END, 0}, - {" 68719476736 ", 10, 68719476736, " ", 0}, - {" 68719476736 ", 0, 68719476736, " ", 0}, - {" -68719476736 ", 10, -68719476736, " ", 0}, - {" -68719476736 ", 0, -68719476736, " ", 0}, - {" 4611686018427387904LL", 10, 4611686018427387904LL, "LL", 0}, - {" -4611686018427387904LL ", 10, -4611686018427387904LL, "LL ", 0}, - {"0x1000000000", 16, 68719476736, END, 0}, - {"0x1000000000", 0, 68719476736, END, 0}, - {"-0x1000000000", 16, -68719476736, END, 0}, - {"-0x1000000000", 0, -68719476736, END, 0}, - {"+0x1000000000", 16, 68719476736, END, 0}, - {"+0x1000000000", 0, 68719476736, END, 0}, - {"01234", 8, 668, END, 0}, - {"01234", 0, 668, END, 0}, - {"-01234", 8, -668, END, 0}, - {"-01234", 0, -668, END, 0}, - {"+01234", 8, 668, END, 0}, - {"+01234", 0, 668, END, 0}, - {"9223372036854775807", 10, INT64_MAX, END, 0}, - {"-9223372036854775808", 10, INT64_MIN, END, 0}, - {"9223372036854775808", 10, INT64_MAX, "8", ERANGE}, /* LLONG_MAX+1 */ - {"-9223372036854775809", 10, INT64_MIN, "9", ERANGE}, /* LLONG_MIN-1 */ - {"18446744073709551615", 10, INT64_MAX, "5", ERANGE}, /* 2*LLONG_MAX+1 */ - {"-18446744073709551618", 10, INT64_MIN, "8", ERANGE}, /* 2*LLONG_MIN-1 */ - {NULL}}; + strtoll_test tests[] = {/* input, base, expected output, # of chars parsed, expected errno */ + {"1", 10, 1, END, 0}, + {"+1", 10, 1, END, 0}, + {"-1", 10, -1, END, 0}, + {"0", 10, 0, END, 0}, + {"0 ", 10, 0, " ", 0}, + {" 0 ", 10, 0, " ", 0}, + {" 0", 10, 0, END, 0}, + {" 0\"", 10, 0, "\"", 0}, + {"0l", 10, 0, "l", 0}, + {"0l ", 10, 0, "l ", 0}, + {"0u", 10, 0, "u", 0}, + {"0u ", 10, 0, "u ", 0}, + {"0L", 10, 0, "L", 0}, + {"0L ", 10, 0, "L ", 0}, + {"0U", 10, 0, "U", 0}, + {"0U ", 10, 0, "U ", 0}, + {"-0", 10, 0, END, 0}, + {"+0", 10, 0, END, 0}, + {"010", 8, 8, END, 0}, + /* stroll "takes as many characters as possible to form a valid base-n + * integer", so it ignores "8" and returns 0 */ + {"08", 0, 0, "8", 0}, + {"010", 10, 10, END, 0}, + {"010", 8, 8, END, 0}, + {"010", 0, 8, END, 0}, + {"68719476736", 10, 68719476736, END, 0}, + {"-68719476736", 10, -68719476736, END, 0}, + {"+68719476736", 10, 68719476736, END, 0}, + {" 68719476736 ", 10, 68719476736, " ", 0}, + {" 68719476736 ", 0, 68719476736, " ", 0}, + {" -68719476736 ", 10, -68719476736, " ", 0}, + {" -68719476736 ", 0, -68719476736, " ", 0}, + {" 4611686018427387904LL", 10, 4611686018427387904LL, "LL", 0}, + {" -4611686018427387904LL ", 10, -4611686018427387904LL, "LL ", 0}, + {"0x1000000000", 16, 68719476736, END, 0}, + {"0x1000000000", 0, 68719476736, END, 0}, + {"-0x1000000000", 16, -68719476736, END, 0}, + {"-0x1000000000", 0, -68719476736, END, 0}, + {"+0x1000000000", 16, 68719476736, END, 0}, + {"+0x1000000000", 0, 68719476736, END, 0}, + {"01234", 8, 668, END, 0}, + {"01234", 0, 668, END, 0}, + {"-01234", 8, -668, END, 0}, + {"-01234", 0, -668, END, 0}, + {"+01234", 8, 668, END, 0}, + {"+01234", 0, 668, END, 0}, + {"9223372036854775807", 10, INT64_MAX, END, 0}, + {"-9223372036854775808", 10, INT64_MIN, END, 0}, + {"9223372036854775808", 10, INT64_MAX, "8", ERANGE}, /* LLONG_MAX+1 */ + {"-9223372036854775809", 10, INT64_MIN, "9", ERANGE}, /* LLONG_MIN-1 */ + {"18446744073709551615", 10, INT64_MAX, "5", ERANGE}, /* 2*LLONG_MAX+1 */ + {"-18446744073709551618", 10, INT64_MIN, "8", ERANGE}, /* 2*LLONG_MIN-1 */ + {NULL}}; for (i = 0; tests[i].str; i++) { errno = 0; @@ -311,10 +310,8 @@ test_string_install (TestSuite *suite) TestSuite_Add (suite, "/bson/string/new", test_bson_string_new); TestSuite_Add (suite, "/bson/string/append", test_bson_string_append); TestSuite_Add (suite, "/bson/string/append_c", test_bson_string_append_c); - TestSuite_Add ( - suite, "/bson/string/append_printf", test_bson_string_append_printf); - TestSuite_Add ( - suite, "/bson/string/append_unichar", test_bson_string_append_unichar); + TestSuite_Add (suite, "/bson/string/append_printf", test_bson_string_append_printf); + TestSuite_Add (suite, "/bson/string/append_unichar", test_bson_string_append_unichar); TestSuite_Add (suite, "/bson/string/strdup", test_bson_strdup); TestSuite_Add (suite, "/bson/string/strdup_printf", test_bson_strdup_printf); TestSuite_Add (suite, "/bson/string/strndup", test_bson_strndup); diff --git a/src/libbson/tests/test-utf8.c b/src/libbson/tests/test-utf8.c index 14fe08d188..e08269a902 100644 --- a/src/libbson/tests/test-utf8.c +++ b/src/libbson/tests/test-utf8.c @@ -22,11 +22,9 @@ static void test_bson_utf8_validate (void) { - static const unsigned char test1[] = { - 0xe2, 0x82, 0xac, ' ', 0xe2, 0x82, 0xac, ' ', 0xe2, 0x82, 0xac, 0}; + static const unsigned char test1[] = {0xe2, 0x82, 0xac, ' ', 0xe2, 0x82, 0xac, ' ', 0xe2, 0x82, 0xac, 0}; static const unsigned char test2[] = {0xc0, 0x80, 0}; - static const unsigned char out_of_bound[] = { - 0xfd, 0x9f, 0xb0, 0x80, 0x80, 0x80, 0}; + static const unsigned char out_of_bound[] = {0xfd, 0x9f, 0xb0, 0x80, 0x80, 0x80, 0}; static const unsigned char bad[] = {0xed, 0xa0, 0xa5, 0}; BSON_ASSERT (bson_utf8_validate ("asdf", 4, false)); @@ -122,8 +120,7 @@ static void test_bson_utf8_get_char (void) { static const char *test1 = "asdf"; - static const unsigned char test2[] = { - 0xe2, 0x82, 0xac, ' ', 0xe2, 0x82, 0xac, ' ', 0xe2, 0x82, 0xac, 0}; + static const unsigned char test2[] = {0xe2, 0x82, 0xac, ' ', 0xe2, 0x82, 0xac, ' ', 0xe2, 0x82, 0xac, 0}; const char *c; c = test1; @@ -217,22 +214,20 @@ test_bson_utf8_from_unichar (void) static void test_bson_utf8_non_shortest (void) { - static const char *tests[] = { - "\xE0\x80\x80", /* Non-shortest form representation of U+0000 */ - "\xF0\x80\x80\x80", /* Non-shortest form representation of U+0000 */ + static const char *tests[] = {"\xE0\x80\x80", /* Non-shortest form representation of U+0000 */ + "\xF0\x80\x80\x80", /* Non-shortest form representation of U+0000 */ - "\xE0\x83\xBF", /* Non-shortest form representation of U+00FF */ - "\xF0\x80\x83\xBF", /* Non-shortest form representation of U+00FF */ + "\xE0\x83\xBF", /* Non-shortest form representation of U+00FF */ + "\xF0\x80\x83\xBF", /* Non-shortest form representation of U+00FF */ - "\xF0\x80\xA3\x80", /* Non-shortest form representation of U+08C0 */ + "\xF0\x80\xA3\x80", /* Non-shortest form representation of U+08C0 */ - NULL}; - static const char *valid_tests[] = { - "\xC0\x80", /* Non-shortest form representation of U+0000. - * This is how \0 should be encoded. Special casing - * to allow for use in things like strlen(). */ + NULL}; + static const char *valid_tests[] = {"\xC0\x80", /* Non-shortest form representation of U+0000. + * This is how \0 should be encoded. Special casing + * to allow for use in things like strlen(). */ - NULL}; + NULL}; int i; for (i = 0; tests[i]; i++) { @@ -257,12 +252,8 @@ test_utf8_install (TestSuite *suite) TestSuite_Add (suite, "/bson/utf8/validate", test_bson_utf8_validate); TestSuite_Add (suite, "/bson/utf8/invalid", test_bson_utf8_invalid); TestSuite_Add (suite, "/bson/utf8/nil", test_bson_utf8_nil); - TestSuite_Add ( - suite, "/bson/utf8/escape_for_json", test_bson_utf8_escape_for_json); - TestSuite_Add ( - suite, "/bson/utf8/get_char_next_char", test_bson_utf8_get_char); - TestSuite_Add ( - suite, "/bson/utf8/from_unichar", test_bson_utf8_from_unichar); - TestSuite_Add ( - suite, "/bson/utf8/non_shortest", test_bson_utf8_non_shortest); + TestSuite_Add (suite, "/bson/utf8/escape_for_json", test_bson_utf8_escape_for_json); + TestSuite_Add (suite, "/bson/utf8/get_char_next_char", test_bson_utf8_get_char); + TestSuite_Add (suite, "/bson/utf8/from_unichar", test_bson_utf8_from_unichar); + TestSuite_Add (suite, "/bson/utf8/non_shortest", test_bson_utf8_non_shortest); } diff --git a/src/libbson/tests/test-writer.c b/src/libbson/tests/test-writer.c index f786049e82..36c5d8f2b2 100644 --- a/src/libbson/tests/test-writer.c +++ b/src/libbson/tests/test-writer.c @@ -38,8 +38,7 @@ test_bson_writer_custom_realloc (void) bson_t *b; int x = 0; - writer = bson_writer_new ( - &buf, &buflen, 0, test_bson_writer_custom_realloc_helper, &x); + writer = bson_writer_new (&buf, &buflen, 0, test_bson_writer_custom_realloc_helper, &x); BSON_ASSERT (bson_writer_begin (writer, &b)); @@ -103,8 +102,7 @@ test_bson_writer_shared_buffer (void) static void test_bson_writer_empty_sequence (void) { - const uint8_t testdata[] = {5, 0, 0, 0, 0, 5, 0, 0, 0, 0, 5, 0, 0, - 0, 0, 5, 0, 0, 0, 0, 5, 0, 0, 0, 0}; + const uint8_t testdata[] = {5, 0, 0, 0, 0, 5, 0, 0, 0, 0, 5, 0, 0, 0, 0, 5, 0, 0, 0, 0, 5, 0, 0, 0, 0}; bson_writer_t *writer; uint8_t *buf = NULL; bson_t *b; @@ -183,14 +181,9 @@ test_bson_writer_null_realloc_2 (void) void test_writer_install (TestSuite *suite) { - TestSuite_Add ( - suite, "/bson/writer/custom_realloc", test_bson_writer_custom_realloc); - TestSuite_Add ( - suite, "/bson/writer/shared_buffer", test_bson_writer_shared_buffer); - TestSuite_Add ( - suite, "/bson/writer/empty_sequence", test_bson_writer_empty_sequence); - TestSuite_Add ( - suite, "/bson/writer/null_realloc", test_bson_writer_null_realloc); - TestSuite_Add ( - suite, "/bson/writer/null_realloc_2", test_bson_writer_null_realloc_2); + TestSuite_Add (suite, "/bson/writer/custom_realloc", test_bson_writer_custom_realloc); + TestSuite_Add (suite, "/bson/writer/shared_buffer", test_bson_writer_shared_buffer); + TestSuite_Add (suite, "/bson/writer/empty_sequence", test_bson_writer_empty_sequence); + TestSuite_Add (suite, "/bson/writer/null_realloc", test_bson_writer_null_realloc); + TestSuite_Add (suite, "/bson/writer/null_realloc_2", test_bson_writer_null_realloc_2); } diff --git a/src/libmongoc/examples/aggregation/aggregation1.c b/src/libmongoc/examples/aggregation/aggregation1.c index fe641a1bab..9ca29fdd9f 100644 --- a/src/libmongoc/examples/aggregation/aggregation1.c +++ b/src/libmongoc/examples/aggregation/aggregation1.c @@ -36,8 +36,7 @@ print_pipeline (mongoc_collection_t *collection) "}", "]"); - cursor = mongoc_collection_aggregate ( - collection, MONGOC_QUERY_NONE, pipeline, NULL, NULL); + cursor = mongoc_collection_aggregate (collection, MONGOC_QUERY_NONE, pipeline, NULL, NULL); while (mongoc_cursor_next (cursor, &doc)) { str = bson_as_canonical_extended_json (doc, NULL); @@ -58,8 +57,7 @@ main (void) { mongoc_client_t *client; mongoc_collection_t *collection; - const char *uri_string = - "mongodb://localhost:27017/?appname=aggregation-example"; + const char *uri_string = "mongodb://localhost:27017/?appname=aggregation-example"; mongoc_uri_t *uri; bson_error_t error; diff --git a/src/libmongoc/examples/basic_aggregation/basic-aggregation.c b/src/libmongoc/examples/basic_aggregation/basic-aggregation.c index d801757d9f..512ed755d0 100644 --- a/src/libmongoc/examples/basic_aggregation/basic-aggregation.c +++ b/src/libmongoc/examples/basic_aggregation/basic-aggregation.c @@ -40,8 +40,7 @@ main (int argc, char *argv[]) if (argc != 2) { fprintf (stderr, "usage: %s CONNECTION-STRING\n", argv[0]); - fprintf (stderr, - "the connection string can be of the following forms:\n"); + fprintf (stderr, "the 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, diff --git a/src/libmongoc/examples/basic_aggregation/distinct.c b/src/libmongoc/examples/basic_aggregation/distinct.c index 663a7733cb..14951cc561 100644 --- a/src/libmongoc/examples/basic_aggregation/distinct.c +++ b/src/libmongoc/examples/basic_aggregation/distinct.c @@ -21,16 +21,14 @@ distinct (mongoc_database_t *database) BCON_DOUBLE (1.0), "}", "}"); - res = - mongoc_database_command_simple (database, command, NULL, &reply, &error); + res = mongoc_database_command_simple (database, command, NULL, &reply, &error); if (!res) { fprintf (stderr, "Error with distinct: %s\n", error.message); goto cleanup; } /* Do something with reply (in this case iterate through the values) */ - if (!(bson_iter_init_find (&iter, &reply, "values") && - BSON_ITER_HOLDS_ARRAY (&iter) && + if (!(bson_iter_init_find (&iter, &reply, "values") && BSON_ITER_HOLDS_ARRAY (&iter) && bson_iter_recurse (&iter, &array_iter))) { fprintf (stderr, "Couldn't extract \"values\" field from response\n"); goto cleanup; diff --git a/src/libmongoc/examples/basic_aggregation/map-reduce-advanced.c b/src/libmongoc/examples/basic_aggregation/map-reduce-advanced.c index 145fb7a4d3..ebc0989d0e 100644 --- a/src/libmongoc/examples/basic_aggregation/map-reduce-advanced.c +++ b/src/libmongoc/examples/basic_aggregation/map-reduce-advanced.c @@ -26,8 +26,7 @@ map_reduce_advanced (mongoc_database_t *database) "}"); read_pref = mongoc_read_prefs_new (MONGOC_READ_SECONDARY); - cursor = mongoc_database_command ( - database, MONGOC_QUERY_NONE, 0, 0, 0, command, NULL, read_pref); + cursor = mongoc_database_command (database, MONGOC_QUERY_NONE, 0, 0, 0, command, NULL, read_pref); /* Do something with the results */ while (mongoc_cursor_next (cursor, &doc)) { diff --git a/src/libmongoc/examples/basic_aggregation/map-reduce-basic.c b/src/libmongoc/examples/basic_aggregation/map-reduce-basic.c index 5ecebe0dad..72e3d8c85a 100644 --- a/src/libmongoc/examples/basic_aggregation/map-reduce-basic.c +++ b/src/libmongoc/examples/basic_aggregation/map-reduce-basic.c @@ -26,8 +26,7 @@ map_reduce_basic (mongoc_database_t *database) BCON_CODE (REDUCER), "out", BCON_UTF8 (out_collection_name)); - res = - mongoc_database_command_simple (database, command, NULL, &reply, &error); + res = mongoc_database_command_simple (database, command, NULL, &reply, &error); if (!res) { fprintf (stderr, "MapReduce failed: %s\n", error.message); @@ -38,10 +37,8 @@ map_reduce_basic (mongoc_database_t *database) print_res (&reply); /* Now we'll query outCollection to see what the results are */ - out_collection = - mongoc_database_get_collection (database, out_collection_name); - cursor = mongoc_collection_find_with_opts ( - out_collection, &find_query, NULL, NULL); + out_collection = mongoc_database_get_collection (database, out_collection_name); + cursor = mongoc_collection_find_with_opts (out_collection, &find_query, NULL, NULL); query_done = true; /* Do something with the results */ diff --git a/src/libmongoc/examples/bulk/bulk-collation.c b/src/libmongoc/examples/bulk/bulk-collation.c index 645b740ff7..2b0f6248f7 100644 --- a/src/libmongoc/examples/bulk/bulk-collation.c +++ b/src/libmongoc/examples/bulk/bulk-collation.c @@ -25,19 +25,12 @@ bulk_collation (mongoc_collection_t *collection) bson_destroy (doc); /* "One" normally sorts before "one"; make "one" come first */ - opts = BCON_NEW ("collation", - "{", - "locale", - BCON_UTF8 ("en_US"), - "caseFirst", - BCON_UTF8 ("lower"), - "}"); + opts = BCON_NEW ("collation", "{", "locale", BCON_UTF8 ("en_US"), "caseFirst", BCON_UTF8 ("lower"), "}"); /* set x=1 on the document with _id "One", which now sorts after "one" */ update = BCON_NEW ("$set", "{", "x", BCON_INT64 (1), "}"); selector = BCON_NEW ("_id", "{", "$gt", BCON_UTF8 ("one"), "}"); - mongoc_bulk_operation_update_one_with_opts ( - bulk, selector, update, opts, &error); + mongoc_bulk_operation_update_one_with_opts (bulk, selector, update, opts, &error); ret = mongoc_bulk_operation_execute (bulk, &reply, &error); diff --git a/src/libmongoc/examples/bulk/bulk5.c b/src/libmongoc/examples/bulk/bulk5.c index cf4020dc2a..9fad7a3c32 100644 --- a/src/libmongoc/examples/bulk/bulk5.c +++ b/src/libmongoc/examples/bulk/bulk5.c @@ -111,10 +111,8 @@ main (void) database = mongoc_client_get_database (client, "testasdf"); /* Create schema validator */ - options = BCON_NEW ( - "validator", "{", "number", "{", "$gte", BCON_INT32 (5), "}", "}"); - collection = - mongoc_database_create_collection (database, "collname", options, &error); + options = BCON_NEW ("validator", "{", "number", "{", "$gte", BCON_INT32 (5), "}", "}"); + collection = mongoc_database_create_collection (database, "collname", options, &error); if (collection) { bulk5_fail (collection); diff --git a/src/libmongoc/examples/client-side-encryption-auto-decryption.c b/src/libmongoc/examples/client-side-encryption-auto-decryption.c index 4e696c3558..016cdca655 100644 --- a/src/libmongoc/examples/client-side-encryption-auto-decryption.c +++ b/src/libmongoc/examples/client-side-encryption-auto-decryption.c @@ -50,8 +50,7 @@ main (void) /* Configure the master key. This must be the same master key that was used * to create the encryption key. */ - local_masterkey = - hex_to_bin (getenv ("LOCAL_MASTERKEY"), &local_masterkey_len); + local_masterkey = hex_to_bin (getenv ("LOCAL_MASTERKEY"), &local_masterkey_len); if (!local_masterkey || local_masterkey_len != 96) { fprintf (stderr, "Specify LOCAL_MASTERKEY environment variable as a " @@ -59,31 +58,22 @@ main (void) goto fail; } - kms_providers = BCON_NEW ("local", - "{", - "key", - BCON_BIN (0, local_masterkey, local_masterkey_len), - "}"); + kms_providers = BCON_NEW ("local", "{", "key", BCON_BIN (0, local_masterkey, local_masterkey_len), "}"); - client = - mongoc_client_new ("mongodb://localhost/?appname=client-side-encryption"); + client = mongoc_client_new ("mongodb://localhost/?appname=client-side-encryption"); auto_encryption_opts = mongoc_auto_encryption_opts_new (); - mongoc_auto_encryption_opts_set_keyvault_namespace ( - auto_encryption_opts, KEYVAULT_DB, KEYVAULT_COLL); - mongoc_auto_encryption_opts_set_kms_providers (auto_encryption_opts, - kms_providers); + mongoc_auto_encryption_opts_set_keyvault_namespace (auto_encryption_opts, KEYVAULT_DB, KEYVAULT_COLL); + mongoc_auto_encryption_opts_set_kms_providers (auto_encryption_opts, kms_providers); /* Setting bypass_auto_encryption to true disables automatic encryption but * keeps the automatic decryption behavior. bypass_auto_encryption will also * disable spawning mongocryptd */ - mongoc_auto_encryption_opts_set_bypass_auto_encryption (auto_encryption_opts, - true); + mongoc_auto_encryption_opts_set_bypass_auto_encryption (auto_encryption_opts, true); /* Once bypass_auto_encryption is set, community users can enable auto * encryption on the client. This will, in fact, only perform automatic * decryption. */ - ret = mongoc_client_enable_auto_encryption ( - client, auto_encryption_opts, &error); + ret = mongoc_client_enable_auto_encryption (client, auto_encryption_opts, &error); if (!ret) { goto fail; } @@ -98,8 +88,7 @@ main (void) mongoc_collection_drop (coll, NULL); /* Set up the key vault for this example. */ - keyvault_coll = - mongoc_client_get_collection (client, KEYVAULT_DB, KEYVAULT_COLL); + keyvault_coll = mongoc_client_get_collection (client, KEYVAULT_DB, KEYVAULT_COLL); mongoc_collection_drop (keyvault_coll, NULL); /* Create a unique index to ensure that two data keys cannot share the same @@ -116,29 +105,21 @@ main (void) "}", "}"); index_model = mongoc_index_model_new (index_keys, index_opts); - ret = mongoc_collection_create_indexes_with_opts (keyvault_coll, - &index_model, - 1, - NULL /* opts */, - NULL /* reply */, - &error); + ret = mongoc_collection_create_indexes_with_opts ( + keyvault_coll, &index_model, 1, NULL /* opts */, NULL /* reply */, &error); if (!ret) { goto fail; } client_encryption_opts = mongoc_client_encryption_opts_new (); - mongoc_client_encryption_opts_set_kms_providers (client_encryption_opts, - kms_providers); - mongoc_client_encryption_opts_set_keyvault_namespace ( - client_encryption_opts, KEYVAULT_DB, KEYVAULT_COLL); + mongoc_client_encryption_opts_set_kms_providers (client_encryption_opts, kms_providers); + mongoc_client_encryption_opts_set_keyvault_namespace (client_encryption_opts, KEYVAULT_DB, KEYVAULT_COLL); /* The key vault client is used for reading to/from the key vault. This can * be the same mongoc_client_t used by the application. */ - mongoc_client_encryption_opts_set_keyvault_client (client_encryption_opts, - client); - client_encryption = - mongoc_client_encryption_new (client_encryption_opts, &error); + mongoc_client_encryption_opts_set_keyvault_client (client_encryption_opts, client); + client_encryption = mongoc_client_encryption_new (client_encryption_opts, &error); if (!client_encryption) { goto fail; } @@ -147,36 +128,31 @@ main (void) * https://dochub.mongodb.org/core/client-side-field-level-encryption-automatic-encryption-rules */ datakey_opts = mongoc_client_encryption_datakey_opts_new (); - mongoc_client_encryption_datakey_opts_set_keyaltnames ( - datakey_opts, keyaltnames, 1); - ret = mongoc_client_encryption_create_datakey ( - client_encryption, "local", datakey_opts, &datakey_id, &error); + mongoc_client_encryption_datakey_opts_set_keyaltnames (datakey_opts, keyaltnames, 1); + ret = mongoc_client_encryption_create_datakey (client_encryption, "local", datakey_opts, &datakey_id, &error); if (!ret) { goto fail; } /* Explicitly encrypt a field. */ encrypt_opts = mongoc_client_encryption_encrypt_opts_new (); - mongoc_client_encryption_encrypt_opts_set_algorithm ( - encrypt_opts, MONGOC_AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC); - mongoc_client_encryption_encrypt_opts_set_keyaltname ( - encrypt_opts, "mongoc_encryption_example_4"); + mongoc_client_encryption_encrypt_opts_set_algorithm (encrypt_opts, + MONGOC_AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC); + mongoc_client_encryption_encrypt_opts_set_keyaltname (encrypt_opts, "mongoc_encryption_example_4"); to_encrypt.value_type = BSON_TYPE_UTF8; to_encrypt.value.v_utf8.str = "123456789"; const size_t len = strlen (to_encrypt.value.v_utf8.str); BSON_ASSERT (bson_in_range_unsigned (uint32_t, len)); to_encrypt.value.v_utf8.len = (uint32_t) len; - ret = mongoc_client_encryption_encrypt ( - client_encryption, &to_encrypt, encrypt_opts, &encrypted_field, &error); + ret = mongoc_client_encryption_encrypt (client_encryption, &to_encrypt, encrypt_opts, &encrypted_field, &error); if (!ret) { goto fail; } to_insert = bson_new (); BSON_APPEND_VALUE (to_insert, "encryptedField", &encrypted_field); - ret = mongoc_collection_insert_one ( - coll, to_insert, NULL /* opts */, NULL /* reply */, &error); + ret = mongoc_collection_insert_one (coll, to_insert, NULL /* opts */, NULL /* reply */, &error); if (!ret) { goto fail; } @@ -189,10 +165,8 @@ main (void) } printf ("\n"); - unencrypted_client = - mongoc_client_new ("mongodb://localhost/?appname=client-side-encryption"); - unencrypted_coll = mongoc_client_get_collection ( - unencrypted_client, ENCRYPTED_DB, ENCRYPTED_COLL); + unencrypted_client = mongoc_client_new ("mongodb://localhost/?appname=client-side-encryption"); + unencrypted_coll = mongoc_client_get_collection (unencrypted_client, ENCRYPTED_DB, ENCRYPTED_COLL); printf ("encrypted document: "); if (!print_one_document (unencrypted_coll, &error)) { diff --git a/src/libmongoc/examples/client-side-encryption-doc-snippets.c b/src/libmongoc/examples/client-side-encryption-doc-snippets.c index 9ca38ac398..f4d08aab8a 100644 --- a/src/libmongoc/examples/client-side-encryption-doc-snippets.c +++ b/src/libmongoc/examples/client-side-encryption-doc-snippets.c @@ -10,8 +10,7 @@ main (void) { /* BEGIN:mongoc_auto_encryption_opts_set_tls_opts. */ - mongoc_auto_encryption_opts_t *ae_opts = - mongoc_auto_encryption_opts_new (); + mongoc_auto_encryption_opts_t *ae_opts = mongoc_auto_encryption_opts_new (); bson_t *tls_opts = bson_new (); BCON_APPEND (tls_opts, "kmip", "{", MONGOC_URI_TLSCAFILE, "ca1.pem", "}"); @@ -25,8 +24,7 @@ main (void) { /* BEGIN:mongoc_client_encryption_opts_set_tls_opts. */ - mongoc_client_encryption_opts_t *ce_opts = - mongoc_client_encryption_opts_new (); + mongoc_client_encryption_opts_t *ce_opts = mongoc_client_encryption_opts_new (); bson_t *tls_opts = bson_new (); BCON_APPEND (tls_opts, "kmip", "{", MONGOC_URI_TLSCAFILE, "ca1.pem", "}"); diff --git a/src/libmongoc/examples/client-side-encryption-explicit.c b/src/libmongoc/examples/client-side-encryption-explicit.c index 58ca141c83..4bf235888e 100644 --- a/src/libmongoc/examples/client-side-encryption-explicit.c +++ b/src/libmongoc/examples/client-side-encryption-explicit.c @@ -47,8 +47,7 @@ main (void) /* Configure the master key. This must be the same master key that was used * to create the encryption key. */ - local_masterkey = - hex_to_bin (getenv ("LOCAL_MASTERKEY"), &local_masterkey_len); + local_masterkey = hex_to_bin (getenv ("LOCAL_MASTERKEY"), &local_masterkey_len); if (!local_masterkey || local_masterkey_len != 96) { fprintf (stderr, "Specify LOCAL_MASTERKEY environment variable as a " @@ -56,23 +55,17 @@ main (void) goto fail; } - kms_providers = BCON_NEW ("local", - "{", - "key", - BCON_BIN (0, local_masterkey, local_masterkey_len), - "}"); + kms_providers = BCON_NEW ("local", "{", "key", BCON_BIN (0, local_masterkey, local_masterkey_len), "}"); /* The mongoc_client_t used to read/write application data. */ - client = - mongoc_client_new ("mongodb://localhost/?appname=client-side-encryption"); + client = mongoc_client_new ("mongodb://localhost/?appname=client-side-encryption"); coll = mongoc_client_get_collection (client, ENCRYPTED_DB, ENCRYPTED_COLL); /* Clear old data */ mongoc_collection_drop (coll, NULL); /* Set up the key vault for this example. */ - keyvault_coll = - mongoc_client_get_collection (client, KEYVAULT_DB, KEYVAULT_COLL); + keyvault_coll = mongoc_client_get_collection (client, KEYVAULT_DB, KEYVAULT_COLL); mongoc_collection_drop (keyvault_coll, NULL); /* Create a unique index to ensure that two data keys cannot share the same @@ -89,29 +82,21 @@ main (void) "}", "}"); index_model = mongoc_index_model_new (index_keys, index_opts); - ret = mongoc_collection_create_indexes_with_opts (keyvault_coll, - &index_model, - 1, - NULL /* opts */, - NULL /* reply */, - &error); + ret = mongoc_collection_create_indexes_with_opts ( + keyvault_coll, &index_model, 1, NULL /* opts */, NULL /* reply */, &error); if (!ret) { goto fail; } client_encryption_opts = mongoc_client_encryption_opts_new (); - mongoc_client_encryption_opts_set_kms_providers (client_encryption_opts, - kms_providers); - mongoc_client_encryption_opts_set_keyvault_namespace ( - client_encryption_opts, KEYVAULT_DB, KEYVAULT_COLL); + mongoc_client_encryption_opts_set_kms_providers (client_encryption_opts, kms_providers); + mongoc_client_encryption_opts_set_keyvault_namespace (client_encryption_opts, KEYVAULT_DB, KEYVAULT_COLL); /* Set a mongoc_client_t to use for reading/writing to the key vault. This * can be the same mongoc_client_t used by the main application. */ - mongoc_client_encryption_opts_set_keyvault_client (client_encryption_opts, - client); - client_encryption = - mongoc_client_encryption_new (client_encryption_opts, &error); + mongoc_client_encryption_opts_set_keyvault_client (client_encryption_opts, client); + client_encryption = mongoc_client_encryption_new (client_encryption_opts, &error); if (!client_encryption) { goto fail; } @@ -120,17 +105,15 @@ main (void) * https://dochub.mongodb.org/core/client-side-field-level-encryption-automatic-encryption-rules */ datakey_opts = mongoc_client_encryption_datakey_opts_new (); - mongoc_client_encryption_datakey_opts_set_keyaltnames ( - datakey_opts, keyaltnames, 1); - if (!mongoc_client_encryption_create_datakey ( - client_encryption, "local", datakey_opts, &datakey_id, &error)) { + mongoc_client_encryption_datakey_opts_set_keyaltnames (datakey_opts, keyaltnames, 1); + if (!mongoc_client_encryption_create_datakey (client_encryption, "local", datakey_opts, &datakey_id, &error)) { goto fail; } /* Explicitly encrypt a field */ encrypt_opts = mongoc_client_encryption_encrypt_opts_new (); - mongoc_client_encryption_encrypt_opts_set_algorithm ( - encrypt_opts, MONGOC_AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC); + mongoc_client_encryption_encrypt_opts_set_algorithm (encrypt_opts, + MONGOC_AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC); mongoc_client_encryption_encrypt_opts_set_keyid (encrypt_opts, &datakey_id); to_encrypt.value_type = BSON_TYPE_UTF8; to_encrypt.value.v_utf8.str = "123456789"; @@ -138,16 +121,14 @@ main (void) BSON_ASSERT (bson_in_range_unsigned (uint32_t, len)); to_encrypt.value.v_utf8.len = (uint32_t) len; - ret = mongoc_client_encryption_encrypt ( - client_encryption, &to_encrypt, encrypt_opts, &encrypted_field, &error); + ret = mongoc_client_encryption_encrypt (client_encryption, &to_encrypt, encrypt_opts, &encrypted_field, &error); if (!ret) { goto fail; } to_insert = bson_new (); BSON_APPEND_VALUE (to_insert, "encryptedField", &encrypted_field); - ret = mongoc_collection_insert_one ( - coll, to_insert, NULL /* opts */, NULL /* reply */, &error); + ret = mongoc_collection_insert_one (coll, to_insert, NULL /* opts */, NULL /* reply */, &error); if (!ret) { goto fail; } @@ -159,8 +140,7 @@ main (void) printf ("\n"); /* Explicitly decrypt a field */ - ret = mongoc_client_encryption_decrypt ( - client_encryption, &encrypted_field, &decrypted, &error); + ret = mongoc_client_encryption_decrypt (client_encryption, &encrypted_field, &decrypted, &error); if (!ret) { goto fail; } diff --git a/src/libmongoc/examples/client-side-encryption-helpers.c b/src/libmongoc/examples/client-side-encryption-helpers.c index 77a4c254bb..3e917c1961 100644 --- a/src/libmongoc/examples/client-side-encryption-helpers.c +++ b/src/libmongoc/examples/client-side-encryption-helpers.c @@ -43,8 +43,7 @@ print_one_document (mongoc_collection_t *coll, bson_error_t *error) char *as_string = NULL; filter = bson_new (); - cursor = mongoc_collection_find_with_opts ( - coll, filter, NULL /* opts */, NULL /* read prefs */); + cursor = mongoc_collection_find_with_opts (coll, filter, NULL /* opts */, NULL /* read prefs */); if (!mongoc_cursor_next (cursor, &found)) { fprintf (stderr, "error: did not find inserted document\n"); goto fail; diff --git a/src/libmongoc/examples/client-side-encryption-schema-map.c b/src/libmongoc/examples/client-side-encryption-schema-map.c index 5304cc18a1..cdee3a6a89 100644 --- a/src/libmongoc/examples/client-side-encryption-schema-map.c +++ b/src/libmongoc/examples/client-side-encryption-schema-map.c @@ -25,15 +25,11 @@ create_schema_file (bson_t *kms_providers, bool ret = false; client_encryption_opts = mongoc_client_encryption_opts_new (); - mongoc_client_encryption_opts_set_kms_providers (client_encryption_opts, - kms_providers); - mongoc_client_encryption_opts_set_keyvault_namespace ( - client_encryption_opts, keyvault_db, keyvault_coll); - mongoc_client_encryption_opts_set_keyvault_client (client_encryption_opts, - keyvault_client); - - client_encryption = - mongoc_client_encryption_new (client_encryption_opts, error); + mongoc_client_encryption_opts_set_kms_providers (client_encryption_opts, kms_providers); + mongoc_client_encryption_opts_set_keyvault_namespace (client_encryption_opts, keyvault_db, keyvault_coll); + mongoc_client_encryption_opts_set_keyvault_client (client_encryption_opts, keyvault_client); + + client_encryption = mongoc_client_encryption_new (client_encryption_opts, error); if (!client_encryption) { goto fail; } @@ -42,36 +38,33 @@ create_schema_file (bson_t *kms_providers, * https://dochub.mongodb.org/core/client-side-field-level-encryption-automatic-encryption-rules */ datakey_opts = mongoc_client_encryption_datakey_opts_new (); - mongoc_client_encryption_datakey_opts_set_keyaltnames ( - datakey_opts, keyaltnames, 1); - if (!mongoc_client_encryption_create_datakey ( - client_encryption, "local", datakey_opts, &datakey_id, error)) { + mongoc_client_encryption_datakey_opts_set_keyaltnames (datakey_opts, keyaltnames, 1); + if (!mongoc_client_encryption_create_datakey (client_encryption, "local", datakey_opts, &datakey_id, error)) { goto fail; } /* Create a schema describing that "encryptedField" is a string encrypted * with the newly created data key using deterministic encryption. */ - schema = BCON_NEW ("properties", - "{", - "encryptedField", - "{", - "encrypt", - "{", - "keyId", - "[", - BCON_BIN (datakey_id.value.v_binary.subtype, - datakey_id.value.v_binary.data, - datakey_id.value.v_binary.data_len), - "]", - "bsonType", - "string", - "algorithm", - MONGOC_AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC, - "}", - "}", - "}", - "bsonType", - "object"); + schema = BCON_NEW ( + "properties", + "{", + "encryptedField", + "{", + "encrypt", + "{", + "keyId", + "[", + BCON_BIN (datakey_id.value.v_binary.subtype, datakey_id.value.v_binary.data, datakey_id.value.v_binary.data_len), + "]", + "bsonType", + "string", + "algorithm", + MONGOC_AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC, + "}", + "}", + "}", + "bsonType", + "object"); /* Use canonical JSON so that other drivers and tools will be * able to parse the MongoDB extended JSON file. */ @@ -135,8 +128,7 @@ main (void) /* Configure the master key. This must be the same master key that was used * to create the encryption key. */ - local_masterkey = - hex_to_bin (getenv ("LOCAL_MASTERKEY"), &local_masterkey_len); + local_masterkey = hex_to_bin (getenv ("LOCAL_MASTERKEY"), &local_masterkey_len); if (!local_masterkey || local_masterkey_len != 96) { fprintf (stderr, "Specify LOCAL_MASTERKEY environment variable as a " @@ -144,19 +136,13 @@ main (void) goto fail; } - kms_providers = BCON_NEW ("local", - "{", - "key", - BCON_BIN (0, local_masterkey, local_masterkey_len), - "}"); + kms_providers = BCON_NEW ("local", "{", "key", BCON_BIN (0, local_masterkey, local_masterkey_len), "}"); /* Set up the key vault for this example. */ - keyvault_client = mongoc_client_new ( - "mongodb://localhost/?appname=client-side-encryption-keyvault"); + keyvault_client = mongoc_client_new ("mongodb://localhost/?appname=client-side-encryption-keyvault"); BSON_ASSERT (keyvault_client); - keyvault_coll = mongoc_client_get_collection ( - keyvault_client, KEYVAULT_DB, KEYVAULT_COLL); + keyvault_coll = mongoc_client_get_collection (keyvault_client, KEYVAULT_DB, KEYVAULT_COLL); mongoc_collection_drop (keyvault_coll, NULL); /* Create a unique index to ensure that two data keys cannot share the same @@ -173,12 +159,8 @@ main (void) "}", "}"); index_model = mongoc_index_model_new (index_keys, index_opts); - ret = mongoc_collection_create_indexes_with_opts (keyvault_coll, - &index_model, - 1, - NULL /* opts */, - NULL /* reply */, - &error); + ret = mongoc_collection_create_indexes_with_opts ( + keyvault_coll, &index_model, 1, NULL /* opts */, NULL /* reply */, &error); if (!ret) { goto fail; @@ -186,8 +168,7 @@ main (void) /* Create a new data key and a schema using it for encryption. Save the * schema to the file jsonSchema.json */ - ret = create_schema_file ( - kms_providers, KEYVAULT_DB, KEYVAULT_COLL, keyvault_client, &error); + ret = create_schema_file (kms_providers, KEYVAULT_DB, KEYVAULT_COLL, keyvault_client, &error); if (!ret) { goto fail; @@ -203,28 +184,21 @@ main (void) /* Construct the schema map, mapping the namespace of the collection to the * schema describing encryption. */ - schema_map = - BCON_NEW (ENCRYPTED_DB "." ENCRYPTED_COLL, BCON_DOCUMENT (&schema)); + schema_map = BCON_NEW (ENCRYPTED_DB "." ENCRYPTED_COLL, BCON_DOCUMENT (&schema)); auto_encryption_opts = mongoc_auto_encryption_opts_new (); - mongoc_auto_encryption_opts_set_keyvault_client (auto_encryption_opts, - keyvault_client); - mongoc_auto_encryption_opts_set_keyvault_namespace ( - auto_encryption_opts, KEYVAULT_DB, KEYVAULT_COLL); - mongoc_auto_encryption_opts_set_kms_providers (auto_encryption_opts, - kms_providers); - mongoc_auto_encryption_opts_set_schema_map (auto_encryption_opts, - schema_map); - - client = - mongoc_client_new ("mongodb://localhost/?appname=client-side-encryption"); + mongoc_auto_encryption_opts_set_keyvault_client (auto_encryption_opts, keyvault_client); + mongoc_auto_encryption_opts_set_keyvault_namespace (auto_encryption_opts, KEYVAULT_DB, KEYVAULT_COLL); + mongoc_auto_encryption_opts_set_kms_providers (auto_encryption_opts, kms_providers); + mongoc_auto_encryption_opts_set_schema_map (auto_encryption_opts, schema_map); + + client = mongoc_client_new ("mongodb://localhost/?appname=client-side-encryption"); BSON_ASSERT (client); /* Enable automatic encryption. It will determine that encryption is * necessary from the schema map instead of relying on the server to provide * a schema. */ - ret = mongoc_client_enable_auto_encryption ( - client, auto_encryption_opts, &error); + ret = mongoc_client_enable_auto_encryption (client, auto_encryption_opts, &error); if (!ret) { goto fail; } @@ -235,8 +209,7 @@ main (void) mongoc_collection_drop (coll, NULL); to_insert = BCON_NEW ("encryptedField", "123456789"); - ret = mongoc_collection_insert_one ( - coll, to_insert, NULL /* opts */, NULL /* reply */, &error); + ret = mongoc_collection_insert_one (coll, to_insert, NULL /* opts */, NULL /* reply */, &error); if (!ret) { goto fail; } @@ -246,12 +219,10 @@ main (void) } printf ("\n"); - unencrypted_client = mongoc_client_new ( - "mongodb://localhost/?appname=client-side-encryption-unencrypted"); + unencrypted_client = mongoc_client_new ("mongodb://localhost/?appname=client-side-encryption-unencrypted"); BSON_ASSERT (unencrypted_client); - unencrypted_coll = mongoc_client_get_collection ( - unencrypted_client, ENCRYPTED_DB, ENCRYPTED_COLL); + unencrypted_coll = mongoc_client_get_collection (unencrypted_client, ENCRYPTED_DB, ENCRYPTED_COLL); printf ("encrypted document: "); if (!print_one_document (unencrypted_coll, &error)) { goto fail; diff --git a/src/libmongoc/examples/client-side-encryption-server-schema.c b/src/libmongoc/examples/client-side-encryption-server-schema.c index 59e22e8f21..0595a5c927 100644 --- a/src/libmongoc/examples/client-side-encryption-server-schema.c +++ b/src/libmongoc/examples/client-side-encryption-server-schema.c @@ -22,15 +22,11 @@ create_schema (bson_t *kms_providers, bson_t *schema = NULL; client_encryption_opts = mongoc_client_encryption_opts_new (); - mongoc_client_encryption_opts_set_kms_providers (client_encryption_opts, - kms_providers); - mongoc_client_encryption_opts_set_keyvault_namespace ( - client_encryption_opts, keyvault_db, keyvault_coll); - mongoc_client_encryption_opts_set_keyvault_client (client_encryption_opts, - keyvault_client); + mongoc_client_encryption_opts_set_kms_providers (client_encryption_opts, kms_providers); + mongoc_client_encryption_opts_set_keyvault_namespace (client_encryption_opts, keyvault_db, keyvault_coll); + mongoc_client_encryption_opts_set_keyvault_client (client_encryption_opts, keyvault_client); - client_encryption = - mongoc_client_encryption_new (client_encryption_opts, error); + client_encryption = mongoc_client_encryption_new (client_encryption_opts, error); if (!client_encryption) { goto fail; } @@ -39,36 +35,33 @@ create_schema (bson_t *kms_providers, * https://dochub.mongodb.org/core/client-side-field-level-encryption-automatic-encryption-rules */ datakey_opts = mongoc_client_encryption_datakey_opts_new (); - mongoc_client_encryption_datakey_opts_set_keyaltnames ( - datakey_opts, keyaltnames, 1); - if (!mongoc_client_encryption_create_datakey ( - client_encryption, "local", datakey_opts, &datakey_id, error)) { + mongoc_client_encryption_datakey_opts_set_keyaltnames (datakey_opts, keyaltnames, 1); + if (!mongoc_client_encryption_create_datakey (client_encryption, "local", datakey_opts, &datakey_id, error)) { goto fail; } /* Create a schema describing that "encryptedField" is a string encrypted * with the newly created data key using deterministic encryption. */ - schema = BCON_NEW ("properties", - "{", - "encryptedField", - "{", - "encrypt", - "{", - "keyId", - "[", - BCON_BIN (datakey_id.value.v_binary.subtype, - datakey_id.value.v_binary.data, - datakey_id.value.v_binary.data_len), - "]", - "bsonType", - "string", - "algorithm", - MONGOC_AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC, - "}", - "}", - "}", - "bsonType", - "object"); + schema = BCON_NEW ( + "properties", + "{", + "encryptedField", + "{", + "encrypt", + "{", + "keyId", + "[", + BCON_BIN (datakey_id.value.v_binary.subtype, datakey_id.value.v_binary.data, datakey_id.value.v_binary.data_len), + "]", + "bsonType", + "string", + "algorithm", + MONGOC_AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC, + "}", + "}", + "}", + "bsonType", + "object"); fail: mongoc_client_encryption_destroy (client_encryption); @@ -120,8 +113,7 @@ main (void) /* Configure the master key. This must be the same master key that was used * to create * the encryption key. */ - local_masterkey = - hex_to_bin (getenv ("LOCAL_MASTERKEY"), &local_masterkey_len); + local_masterkey = hex_to_bin (getenv ("LOCAL_MASTERKEY"), &local_masterkey_len); if (!local_masterkey || local_masterkey_len != 96) { fprintf (stderr, "Specify LOCAL_MASTERKEY environment variable as a " @@ -129,19 +121,13 @@ main (void) goto fail; } - kms_providers = BCON_NEW ("local", - "{", - "key", - BCON_BIN (0, local_masterkey, local_masterkey_len), - "}"); + kms_providers = BCON_NEW ("local", "{", "key", BCON_BIN (0, local_masterkey, local_masterkey_len), "}"); /* Set up the key vault for this example. */ - keyvault_client = mongoc_client_new ( - "mongodb://localhost/?appname=client-side-encryption-keyvault"); + keyvault_client = mongoc_client_new ("mongodb://localhost/?appname=client-side-encryption-keyvault"); BSON_ASSERT (keyvault_client); - keyvault_coll = mongoc_client_get_collection ( - keyvault_client, KEYVAULT_DB, KEYVAULT_COLL); + keyvault_coll = mongoc_client_get_collection (keyvault_client, KEYVAULT_DB, KEYVAULT_COLL); mongoc_collection_drop (keyvault_coll, NULL); /* Create a unique index to ensure that two data keys cannot share the same @@ -158,37 +144,27 @@ main (void) "}", "}"); index_model = mongoc_index_model_new (index_keys, index_opts); - ret = mongoc_collection_create_indexes_with_opts (keyvault_coll, - &index_model, - 1, - NULL /* opts */, - NULL /* reply */, - &error); + ret = mongoc_collection_create_indexes_with_opts ( + keyvault_coll, &index_model, 1, NULL /* opts */, NULL /* reply */, &error); if (!ret) { goto fail; } auto_encryption_opts = mongoc_auto_encryption_opts_new (); - mongoc_auto_encryption_opts_set_keyvault_client (auto_encryption_opts, - keyvault_client); - mongoc_auto_encryption_opts_set_keyvault_namespace ( - auto_encryption_opts, KEYVAULT_DB, KEYVAULT_COLL); - mongoc_auto_encryption_opts_set_kms_providers (auto_encryption_opts, - kms_providers); - schema = create_schema ( - kms_providers, KEYVAULT_DB, KEYVAULT_COLL, keyvault_client, &error); + mongoc_auto_encryption_opts_set_keyvault_client (auto_encryption_opts, keyvault_client); + mongoc_auto_encryption_opts_set_keyvault_namespace (auto_encryption_opts, KEYVAULT_DB, KEYVAULT_COLL); + mongoc_auto_encryption_opts_set_kms_providers (auto_encryption_opts, kms_providers); + schema = create_schema (kms_providers, KEYVAULT_DB, KEYVAULT_COLL, keyvault_client, &error); if (!schema) { goto fail; } - client = - mongoc_client_new ("mongodb://localhost/?appname=client-side-encryption"); + client = mongoc_client_new ("mongodb://localhost/?appname=client-side-encryption"); BSON_ASSERT (client); - ret = mongoc_client_enable_auto_encryption ( - client, auto_encryption_opts, &error); + ret = mongoc_client_enable_auto_encryption (client, auto_encryption_opts, &error); if (!ret) { goto fail; } @@ -199,31 +175,19 @@ main (void) mongoc_collection_drop (coll, NULL); /* Create the collection with the encryption JSON Schema. */ - create_cmd = BCON_NEW ("create", - ENCRYPTED_COLL, - "validator", - "{", - "$jsonSchema", - BCON_DOCUMENT (schema), - "}"); + create_cmd = BCON_NEW ("create", ENCRYPTED_COLL, "validator", "{", "$jsonSchema", BCON_DOCUMENT (schema), "}"); wc = mongoc_write_concern_new (); mongoc_write_concern_set_wmajority (wc, 0); create_cmd_opts = bson_new (); mongoc_write_concern_append (wc, create_cmd_opts); - ret = mongoc_client_command_with_opts (client, - ENCRYPTED_DB, - create_cmd, - NULL /* read prefs */, - create_cmd_opts, - NULL /* reply */, - &error); + ret = mongoc_client_command_with_opts ( + client, ENCRYPTED_DB, create_cmd, NULL /* read prefs */, create_cmd_opts, NULL /* reply */, &error); if (!ret) { goto fail; } to_insert = BCON_NEW ("encryptedField", "123456789"); - ret = mongoc_collection_insert_one ( - coll, to_insert, NULL /* opts */, NULL /* reply */, &error); + ret = mongoc_collection_insert_one (coll, to_insert, NULL /* opts */, NULL /* reply */, &error); if (!ret) { goto fail; } @@ -233,12 +197,10 @@ main (void) } printf ("\n"); - unencrypted_client = mongoc_client_new ( - "mongodb://localhost/?appname=client-side-encryption-unencrypted"); + unencrypted_client = mongoc_client_new ("mongodb://localhost/?appname=client-side-encryption-unencrypted"); BSON_ASSERT (unencrypted_client); - unencrypted_coll = mongoc_client_get_collection ( - unencrypted_client, ENCRYPTED_DB, ENCRYPTED_COLL); + unencrypted_coll = mongoc_client_get_collection (unencrypted_client, ENCRYPTED_DB, ENCRYPTED_COLL); printf ("encrypted document: "); if (!print_one_document (unencrypted_coll, &error)) { goto fail; @@ -247,8 +209,7 @@ main (void) /* Expect a server-side error if inserting with the unencrypted collection. */ - ret = mongoc_collection_insert_one ( - unencrypted_coll, to_insert, NULL /* opts */, NULL /* reply */, &error); + ret = mongoc_collection_insert_one (unencrypted_coll, to_insert, NULL /* opts */, NULL /* reply */, &error); if (!ret) { printf ("insert with unencrypted collection failed: %s\n", error.message); memset (&error, 0, sizeof (error)); diff --git a/src/libmongoc/examples/common_operations/explain.c b/src/libmongoc/examples/common_operations/explain.c index 7ef77ae905..8c823c79e5 100644 --- a/src/libmongoc/examples/common_operations/explain.c +++ b/src/libmongoc/examples/common_operations/explain.c @@ -6,18 +6,9 @@ explain (mongoc_collection_t *collection) bson_error_t error; bool res; - command = BCON_NEW ("explain", - "{", - "find", - BCON_UTF8 (COLLECTION_NAME), - "filter", - "{", - "x", - BCON_INT32 (1), - "}", - "}"); - res = mongoc_collection_command_simple ( - collection, command, NULL, &reply, &error); + command = + BCON_NEW ("explain", "{", "find", BCON_UTF8 (COLLECTION_NAME), "filter", "{", "x", BCON_INT32 (1), "}", "}"); + res = mongoc_collection_command_simple (collection, command, NULL, &reply, &error); if (!res) { fprintf (stderr, "Error with explain: %s\n", error.message); goto cleanup; diff --git a/src/libmongoc/examples/doc-common-insert.c b/src/libmongoc/examples/doc-common-insert.c index b8dd286099..21edb4d589 100644 --- a/src/libmongoc/examples/doc-common-insert.c +++ b/src/libmongoc/examples/doc-common-insert.c @@ -16,8 +16,7 @@ insert_data (mongoc_collection_t *collection) docs[0] = BCON_NEW ("x", BCON_DOUBLE (1.0), "tags", "[", "dog", "cat", "]"); docs[1] = BCON_NEW ("x", BCON_DOUBLE (2.0), "tags", "[", "cat", "]"); - docs[2] = BCON_NEW ( - "x", BCON_DOUBLE (2.0), "tags", "[", "mouse", "cat", "dog", "]"); + docs[2] = BCON_NEW ("x", BCON_DOUBLE (2.0), "tags", "[", "mouse", "cat", "dog", "]"); docs[3] = BCON_NEW ("x", BCON_DOUBLE (3.0), "tags", "[", "]"); for (i = 0; i < ndocs; i++) { diff --git a/src/libmongoc/examples/example-client.c b/src/libmongoc/examples/example-client.c index c74b46c110..5f3eb5f449 100644 --- a/src/libmongoc/examples/example-client.c +++ b/src/libmongoc/examples/example-client.c @@ -49,11 +49,10 @@ main (int argc, char *argv[]) bson_init (&query); collection = mongoc_client_get_collection (client, "test", collection_name); - cursor = mongoc_collection_find_with_opts ( - collection, - &query, - NULL, /* additional options */ - NULL); /* read prefs, NULL for default */ + cursor = mongoc_collection_find_with_opts (collection, + &query, + NULL, /* additional options */ + NULL); /* read prefs, NULL for default */ while (mongoc_cursor_next (cursor, &doc)) { str = bson_as_canonical_extended_json (doc, NULL); diff --git a/src/libmongoc/examples/example-collection-command.c b/src/libmongoc/examples/example-collection-command.c index d6a6a6c700..50e171ffa8 100644 --- a/src/libmongoc/examples/example-collection-command.c +++ b/src/libmongoc/examples/example-collection-command.c @@ -13,8 +13,7 @@ do_ping (mongoc_collection_t *collection) cmd = BCON_NEW ("ping", BCON_INT32 (1)); - if (mongoc_collection_command_simple ( - collection, cmd, NULL, &reply, &error)) { + if (mongoc_collection_command_simple (collection, cmd, NULL, &reply, &error)) { str = bson_as_canonical_extended_json (&reply, NULL); printf ("Got reply: %s\n", str); bson_free (str); @@ -49,8 +48,7 @@ main (int argc, char **argv) uri_string = argv[1]; uri = mongoc_uri_new_with_error (uri_string, &error); if (!uri) { - MONGOC_ERROR ( - "failed to parse URI: %s\nError: %s", uri_string, error.message); + MONGOC_ERROR ("failed to parse URI: %s\nError: %s", uri_string, error.message); return EXIT_FAILURE; } diff --git a/src/libmongoc/examples/example-collection-watch.c b/src/libmongoc/examples/example-collection-watch.c index c5d683ff54..b03b01cc86 100644 --- a/src/libmongoc/examples/example-collection-watch.c +++ b/src/libmongoc/examples/example-collection-watch.c @@ -57,9 +57,7 @@ main (void) 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)); + fprintf (stderr, "Server Error: %s\n", bson_as_relaxed_extended_json (err_doc, NULL)); } else { fprintf (stderr, "Client Error: %s\n", error.message); } diff --git a/src/libmongoc/examples/example-command-monitoring.c b/src/libmongoc/examples/example-command-monitoring.c index fe154dce8b..5dc34ca75a 100644 --- a/src/libmongoc/examples/example-command-monitoring.c +++ b/src/libmongoc/examples/example-command-monitoring.c @@ -19,8 +19,7 @@ command_started (const mongoc_apm_command_started_t *event) { char *s; - s = bson_as_relaxed_extended_json ( - mongoc_apm_command_started_get_command (event), NULL); + s = bson_as_relaxed_extended_json (mongoc_apm_command_started_get_command (event), NULL); printf ("Command %s started on %s:\n%s\n\n", mongoc_apm_command_started_get_command_name (event), mongoc_apm_command_started_get_host (event)->host, @@ -37,11 +36,8 @@ command_succeeded (const mongoc_apm_command_succeeded_t *event) { char *s; - s = bson_as_relaxed_extended_json ( - mongoc_apm_command_succeeded_get_reply (event), NULL); - printf ("Command %s succeeded:\n%s\n\n", - mongoc_apm_command_succeeded_get_command_name (event), - s); + s = bson_as_relaxed_extended_json (mongoc_apm_command_succeeded_get_reply (event), NULL); + printf ("Command %s succeeded:\n%s\n\n", mongoc_apm_command_succeeded_get_command_name (event), s); ((stats_t *) mongoc_apm_command_succeeded_get_context (event))->succeeded++; @@ -55,9 +51,7 @@ command_failed (const mongoc_apm_command_failed_t *event) bson_error_t error; mongoc_apm_command_failed_get_error (event, &error); - printf ("Command %s failed:\n\"%s\"\n\n", - mongoc_apm_command_failed_get_command_name (event), - error.message); + printf ("Command %s failed:\n\"%s\"\n\n", mongoc_apm_command_failed_get_command_name (event), error.message); ((stats_t *) mongoc_apm_command_failed_get_context (event))->failed++; } @@ -71,8 +65,7 @@ main (int argc, char *argv[]) stats_t stats = {0}; mongoc_collection_t *collection; bson_error_t error; - const char *uri_string = - "mongodb://127.0.0.1/?appname=cmd-monitoring-example"; + const char *uri_string = "mongodb://127.0.0.1/?appname=cmd-monitoring-example"; mongoc_uri_t *uri; const char *collection_name = "test"; bson_t *docs[2]; @@ -103,16 +96,14 @@ main (int argc, char *argv[]) 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 */); + mongoc_client_set_apm_callbacks (client, callbacks, (void *) &stats /* context pointer */); collection = mongoc_client_get_collection (client, "test", collection_name); mongoc_collection_drop (collection, NULL); docs[0] = BCON_NEW ("_id", BCON_INT32 (0)); docs[1] = BCON_NEW ("_id", BCON_INT32 (1)); - mongoc_collection_insert_many ( - collection, (const bson_t **) docs, 2, NULL, NULL, NULL); + mongoc_collection_insert_many (collection, (const bson_t **) docs, 2, NULL, NULL, NULL); /* duplicate key error on the second insert */ mongoc_collection_insert_one (collection, docs[0], NULL, NULL, NULL); @@ -122,10 +113,7 @@ main (int argc, char *argv[]) mongoc_uri_destroy (uri); mongoc_client_destroy (client); - printf ("started: %d\nsucceeded: %d\nfailed: %d\n", - stats.started, - stats.succeeded, - stats.failed); + printf ("started: %d\nsucceeded: %d\nfailed: %d\n", stats.started, stats.succeeded, stats.failed); bson_destroy (docs[0]); bson_destroy (docs[1]); diff --git a/src/libmongoc/examples/example-command-with-opts.c b/src/libmongoc/examples/example-command-with-opts.c index fbbc3481f0..e1e6ab918a 100644 --- a/src/libmongoc/examples/example-command-with-opts.c +++ b/src/libmongoc/examples/example-command-with-opts.c @@ -79,8 +79,7 @@ main (int argc, char *argv[]) opts = bson_new (); mongoc_write_concern_append (write_concern, opts); - if (mongoc_client_write_command_with_opts ( - client, "test", cmd, opts, &reply, &error)) { + if (mongoc_client_write_command_with_opts (client, "test", cmd, opts, &reply, &error)) { json = bson_as_canonical_extended_json (&reply, NULL); printf ("cloneCollectionAsCapped: %s\n", json); bson_free (json); @@ -108,23 +107,15 @@ main (int argc, char *argv[]) read_prefs = mongoc_read_prefs_new (MONGOC_READ_SECONDARY); /* "One" normally sorts before "one"; make "One" sort after "one" */ - opts = BCON_NEW ("collation", - "{", - "locale", - BCON_UTF8 ("en_US"), - "caseFirst", - BCON_UTF8 ("lower"), - "}"); + opts = BCON_NEW ("collation", "{", "locale", BCON_UTF8 ("en_US"), "caseFirst", BCON_UTF8 ("lower"), "}"); /* add a read concern to "opts" */ read_concern = mongoc_read_concern_new (); - mongoc_read_concern_set_level (read_concern, - MONGOC_READ_CONCERN_LEVEL_MAJORITY); + mongoc_read_concern_set_level (read_concern, MONGOC_READ_CONCERN_LEVEL_MAJORITY); mongoc_read_concern_append (read_concern, opts); - if (mongoc_client_read_command_with_opts ( - client, "test", cmd, read_prefs, opts, &reply, &error)) { + if (mongoc_client_read_command_with_opts (client, "test", cmd, read_prefs, opts, &reply, &error)) { json = bson_as_canonical_extended_json (&reply, NULL); printf ("distinct: %s\n", json); bson_free (json); diff --git a/src/libmongoc/examples/example-gridfs-bucket.c b/src/libmongoc/examples/example-gridfs-bucket.c index 56e29e067d..431943d0ec 100644 --- a/src/libmongoc/examples/example-gridfs-bucket.c +++ b/src/libmongoc/examples/example-gridfs-bucket.c @@ -6,8 +6,7 @@ int main (int argc, char *argv[]) { - const char *uri_string = - "mongodb://localhost:27017/?appname=new-gridfs-example"; + const char *uri_string = "mongodb://localhost:27017/?appname=new-gridfs-example"; mongoc_client_t *client; mongoc_database_t *db; mongoc_stream_t *file_stream; @@ -37,8 +36,7 @@ main (int argc, char *argv[]) /* 2. Insert a file. */ file_stream = mongoc_stream_file_new_for_path (argv[1], O_RDONLY, 0); - res = mongoc_gridfs_bucket_upload_from_stream ( - bucket, "my-file", file_stream, NULL, &file_id, &error); + res = mongoc_gridfs_bucket_upload_from_stream (bucket, "my-file", file_stream, NULL, &file_id, &error); if (!res) { printf ("Error uploading file: %s\n", error.message); return EXIT_FAILURE; @@ -54,8 +52,7 @@ main (int argc, char *argv[]) return EXIT_FAILURE; } - res = mongoc_gridfs_bucket_download_to_stream ( - bucket, &file_id, file_stream, &error); + res = mongoc_gridfs_bucket_download_to_stream (bucket, &file_id, file_stream, &error); if (!res) { printf ("Error downloading file to stream: %s\n", error.message); return EXIT_FAILURE; diff --git a/src/libmongoc/examples/example-manage-collection-indexes.c b/src/libmongoc/examples/example-manage-collection-indexes.c index e14a3728c4..d387910203 100644 --- a/src/libmongoc/examples/example-manage-collection-indexes.c +++ b/src/libmongoc/examples/example-manage-collection-indexes.c @@ -17,8 +17,7 @@ int main (int argc, char *argv[]) { mongoc_client_t *client = NULL; - const char *uri_string = - "mongodb://127.0.0.1/?appname=create-indexes-example"; + const char *uri_string = "mongodb://127.0.0.1/?appname=create-indexes-example"; mongoc_uri_t *uri = NULL; mongoc_collection_t *coll = NULL; bson_error_t error; @@ -27,9 +26,7 @@ main (int argc, char *argv[]) mongoc_init (); if (argc > 2) { - HANDLE_ERROR ( - "Unexpected arguments. Expected usage: %s [CONNECTION_STRING]", - argv[0]); + HANDLE_ERROR ("Unexpected arguments. Expected usage: %s [CONNECTION_STRING]", argv[0]); } if (argc > 1) { @@ -52,8 +49,7 @@ main (int argc, char *argv[]) // `keys` represents an ascending index on field `x`. bson_t *keys = BCON_NEW ("x", BCON_INT32 (1)); mongoc_index_model_t *im = mongoc_index_model_new (keys, NULL /* opts */); - if (mongoc_collection_create_indexes_with_opts ( - coll, &im, 1, NULL /* opts */, NULL /* reply */, &error)) { + if (mongoc_collection_create_indexes_with_opts (coll, &im, 1, NULL /* opts */, NULL /* reply */, &error)) { printf ("Successfully created index\n"); } else { bson_destroy (keys); @@ -65,8 +61,7 @@ main (int argc, char *argv[]) { // List indexes ... begin - mongoc_cursor_t *cursor = - mongoc_collection_find_indexes_with_opts (coll, NULL /* opts */); + mongoc_cursor_t *cursor = mongoc_collection_find_indexes_with_opts (coll, NULL /* opts */); printf ("Listing indexes:\n"); const bson_t *got; while (mongoc_cursor_next (cursor, &got)) { @@ -86,8 +81,7 @@ main (int argc, char *argv[]) // Drop an index ... begin bson_t *keys = BCON_NEW ("x", BCON_INT32 (1)); char *index_name = mongoc_collection_keys_to_index_string (keys); - if (mongoc_collection_drop_index_with_opts ( - coll, index_name, NULL /* opts */, &error)) { + if (mongoc_collection_drop_index_with_opts (coll, index_name, NULL /* opts */, &error)) { printf ("Successfully dropped index\n"); } else { bson_free (index_name); diff --git a/src/libmongoc/examples/example-manage-search-indexes.c b/src/libmongoc/examples/example-manage-search-indexes.c index dac5c5bb59..c16cc2dafb 100644 --- a/src/libmongoc/examples/example-manage-search-indexes.c +++ b/src/libmongoc/examples/example-manage-search-indexes.c @@ -13,22 +13,18 @@ } else \ (void) 0 -#define ASSERT(stmt) \ - if (!stmt) { \ - fprintf (stderr, \ - "assertion failed on line: %d, statement: %s\n", \ - __LINE__, \ - #stmt); \ - abort (); \ - } else \ +#define ASSERT(stmt) \ + if (!stmt) { \ + fprintf (stderr, "assertion failed on line: %d, statement: %s\n", __LINE__, #stmt); \ + abort (); \ + } else \ (void) 0 int main (int argc, char *argv[]) { mongoc_client_t *client = NULL; - const char *uri_string = - "mongodb://127.0.0.1/?appname=create-search-indexes-example"; + const char *uri_string = "mongodb://127.0.0.1/?appname=create-search-indexes-example"; mongoc_uri_t *uri = NULL; mongoc_collection_t *coll = NULL; bson_error_t error; @@ -37,9 +33,7 @@ main (int argc, char *argv[]) mongoc_init (); if (argc > 2) { - HANDLE_ERROR ( - "Unexpected arguments. Expected usage: %s [CONNECTION_STRING]", - argv[0]); + HANDLE_ERROR ("Unexpected arguments. Expected usage: %s [CONNECTION_STRING]", argv[0]); } if (argc > 1) { @@ -73,8 +67,7 @@ main (int argc, char *argv[]) // Create the collection server-side to avoid the server error: // "Collection 'test.' does not exist." mongoc_database_t *db = mongoc_client_get_database (client, "test"); - coll = mongoc_database_create_collection ( - db, collname, NULL /* options */, &error); + coll = mongoc_database_create_collection (db, collname, NULL /* options */, &error); if (!coll) { mongoc_database_destroy (db); HANDLE_ERROR ("Failed to create collection: %s", error.message); @@ -85,16 +78,11 @@ main (int argc, char *argv[]) // Check that $listSearchIndexes pipeline stage is supported. // This is intended to check that a MongoDB Atlas cluster is used. { - const char *pipeline_str = - BSON_STR ({"pipeline" : [ {"$listSearchIndexes" : {}} ]}); + const char *pipeline_str = BSON_STR ({"pipeline" : [ {"$listSearchIndexes" : {}} ]}); bson_t pipeline; ASSERT (bson_init_from_json (&pipeline, pipeline_str, -1, &error)); mongoc_cursor_t *cursor = - mongoc_collection_aggregate (coll, - MONGOC_QUERY_NONE, - &pipeline, - NULL /* opts */, - NULL /* read_prefs */); + mongoc_collection_aggregate (coll, MONGOC_QUERY_NONE, &pipeline, NULL /* opts */, NULL /* read_prefs */); const bson_t *got; while (mongoc_cursor_next (cursor, &got)) ; @@ -118,17 +106,13 @@ main (int argc, char *argv[]) char *cmd_str = bson_strdup_printf ( BSON_STR ({ "createSearchIndexes" : "%s", - "indexes" : [ { - "definition" : {"mappings" : {"dynamic" : false}}, - "name" : "test-index" - } ] + "indexes" : [ {"definition" : {"mappings" : {"dynamic" : false}}, "name" : "test-index"} ] }), collname); ASSERT (bson_init_from_json (&cmd, cmd_str, -1, &error)); bson_free (cmd_str); } - if (!mongoc_collection_command_simple ( - coll, &cmd, NULL /* read_prefs */, NULL /* reply */, &error)) { + if (!mongoc_collection_command_simple (coll, &cmd, NULL /* read_prefs */, NULL /* reply */, &error)) { bson_destroy (&cmd); HANDLE_ERROR ("Failed to run createSearchIndexes: %s", error.message); } @@ -139,16 +123,11 @@ main (int argc, char *argv[]) { // List Atlas Search Indexes ... begin - const char *pipeline_str = - BSON_STR ({"pipeline" : [ {"$listSearchIndexes" : {}} ]}); + const char *pipeline_str = BSON_STR ({"pipeline" : [ {"$listSearchIndexes" : {}} ]}); bson_t pipeline; ASSERT (bson_init_from_json (&pipeline, pipeline_str, -1, &error)); mongoc_cursor_t *cursor = - mongoc_collection_aggregate (coll, - MONGOC_QUERY_NONE, - &pipeline, - NULL /* opts */, - NULL /* read_prefs */); + mongoc_collection_aggregate (coll, MONGOC_QUERY_NONE, &pipeline, NULL /* opts */, NULL /* read_prefs */); printf ("Listing indexes:\n"); const bson_t *got; while (mongoc_cursor_next (cursor, &got)) { @@ -172,17 +151,13 @@ main (int argc, char *argv[]) // Create command. { char *cmd_str = bson_strdup_printf ( - BSON_STR ({ - "updateSearchIndex" : "%s", - "definition" : {"mappings" : {"dynamic" : true}}, - "name" : "test-index" - }), + BSON_STR ( + {"updateSearchIndex" : "%s", "definition" : {"mappings" : {"dynamic" : true}}, "name" : "test-index"}), collname); ASSERT (bson_init_from_json (&cmd, cmd_str, -1, &error)); bson_free (cmd_str); } - if (!mongoc_collection_command_simple ( - coll, &cmd, NULL /* read_prefs */, NULL /* reply */, &error)) { + if (!mongoc_collection_command_simple (coll, &cmd, NULL /* read_prefs */, NULL /* reply */, &error)) { bson_destroy (&cmd); HANDLE_ERROR ("Failed to run updateSearchIndex: %s", error.message); } @@ -196,14 +171,11 @@ main (int argc, char *argv[]) bson_t cmd; // Create command. { - char *cmd_str = bson_strdup_printf ( - BSON_STR ({"dropSearchIndex" : "%s", "name" : "test-index"}), - collname); + char *cmd_str = bson_strdup_printf (BSON_STR ({"dropSearchIndex" : "%s", "name" : "test-index"}), collname); ASSERT (bson_init_from_json (&cmd, cmd_str, -1, &error)); bson_free (cmd_str); } - if (!mongoc_collection_command_simple ( - coll, &cmd, NULL /* read_prefs */, NULL /* reply */, &error)) { + if (!mongoc_collection_command_simple (coll, &cmd, NULL /* read_prefs */, NULL /* reply */, &error)) { bson_destroy (&cmd); HANDLE_ERROR ("Failed to run dropSearchIndex: %s", error.message); } @@ -215,8 +187,7 @@ main (int argc, char *argv[]) // Drop created collection. { if (!mongoc_collection_drop (coll, &error)) { - HANDLE_ERROR ( - "Failed to drop collection '%s': %s", collname, error.message); + HANDLE_ERROR ("Failed to drop collection '%s': %s", collname, error.message); } } diff --git a/src/libmongoc/examples/example-pool.c b/src/libmongoc/examples/example-pool.c index 8b80b01dfc..7271bbc8b9 100644 --- a/src/libmongoc/examples/example-pool.c +++ b/src/libmongoc/examples/example-pool.c @@ -27,8 +27,7 @@ worker (void *data) * probably only want to hold onto the client for the portion of the * request performing database queries. */ - r = mongoc_client_command_simple ( - client, "admin", &ping, NULL, NULL, &error); + r = mongoc_client_command_simple (client, "admin", &ping, NULL, NULL, &error); if (!r) { fprintf (stderr, "%s\n", error.message); diff --git a/src/libmongoc/examples/example-resume.c b/src/libmongoc/examples/example-resume.c index d1d6b60654..72d00b87d5 100644 --- a/src/libmongoc/examples/example-resume.c +++ b/src/libmongoc/examples/example-resume.c @@ -41,10 +41,7 @@ _save_resume_token (const bson_t *doc) bson_destroy (&resume_token_doc); n_written = 0; while (n_written < as_json_len) { - r = fwrite ((void *) (as_json + n_written), - sizeof (char), - as_json_len - n_written, - file_stream); + r = fwrite ((void *) (as_json + n_written), sizeof (char), as_json_len - n_written, file_stream); if (r == -1) { fprintf (stderr, "failed to write to %s\n", RESUME_TOKEN_PATH); bson_free (as_json); @@ -72,10 +69,7 @@ _load_resume_token (bson_t *opts) } reader = bson_json_reader_new_from_file (RESUME_TOKEN_PATH, &error); if (!reader) { - fprintf (stderr, - "failed to open %s for reading: %s\n", - RESUME_TOKEN_PATH, - error.message); + fprintf (stderr, "failed to open %s for reading: %s\n", RESUME_TOKEN_PATH, error.message); return false; } @@ -87,8 +81,7 @@ _load_resume_token (bson_t *opts) return false; } - printf ("found cached resume token in %s, resuming change stream.\n", - RESUME_TOKEN_PATH); + printf ("found cached resume token in %s, resuming change stream.\n", RESUME_TOKEN_PATH); bson_concat (opts, &doc); bson_destroy (&doc); diff --git a/src/libmongoc/examples/example-sdam-monitoring.c b/src/libmongoc/examples/example-sdam-monitoring.c index 879e163856..de617c87fb 100644 --- a/src/libmongoc/examples/example-sdam-monitoring.c +++ b/src/libmongoc/examples/example-sdam-monitoring.c @@ -47,8 +47,7 @@ server_opening (const mongoc_apm_server_opening_t *event) context = (stats_t *) mongoc_apm_server_opening_get_context (event); context->server_opening_events++; - printf ("server opening: %s\n", - mongoc_apm_server_opening_get_host (event)->host_and_port); + printf ("server opening: %s\n", mongoc_apm_server_opening_get_host (event)->host_and_port); } @@ -60,8 +59,7 @@ server_closed (const mongoc_apm_server_closed_t *event) context = (stats_t *) mongoc_apm_server_closed_get_context (event); context->server_closed_events++; - printf ("server closed: %s\n", - mongoc_apm_server_closed_get_host (event)->host_and_port); + printf ("server closed: %s\n", mongoc_apm_server_closed_get_host (event)->host_and_port); } @@ -111,15 +109,13 @@ topology_changed (const mongoc_apm_topology_changed_t *event) prefs = mongoc_read_prefs_new (MONGOC_READ_SECONDARY); /* it is safe, and unfortunately necessary, to cast away const here */ - if (mongoc_topology_description_has_readable_server ( - (mongoc_topology_description_t *) new_td, prefs)) { + if (mongoc_topology_description_has_readable_server ((mongoc_topology_description_t *) new_td, prefs)) { printf (" secondary AVAILABLE\n"); } else { printf (" secondary UNAVAILABLE\n"); } - if (mongoc_topology_description_has_writable_server ( - (mongoc_topology_description_t *) new_td)) { + if (mongoc_topology_description_has_writable_server ((mongoc_topology_description_t *) new_td)) { printf (" primary AVAILABLE\n"); } else { printf (" primary UNAVAILABLE\n"); @@ -160,33 +156,26 @@ server_heartbeat_started (const mongoc_apm_server_heartbeat_started_t *event) { stats_t *context; - context = - (stats_t *) mongoc_apm_server_heartbeat_started_get_context (event); + context = (stats_t *) mongoc_apm_server_heartbeat_started_get_context (event); context->heartbeat_started_events++; - printf ("%s heartbeat started\n", - mongoc_apm_server_heartbeat_started_get_host (event)->host_and_port); + printf ("%s heartbeat started\n", mongoc_apm_server_heartbeat_started_get_host (event)->host_and_port); } static void -server_heartbeat_succeeded ( - const mongoc_apm_server_heartbeat_succeeded_t *event) +server_heartbeat_succeeded (const mongoc_apm_server_heartbeat_succeeded_t *event) { stats_t *context; char *reply; - context = - (stats_t *) mongoc_apm_server_heartbeat_succeeded_get_context (event); + context = (stats_t *) mongoc_apm_server_heartbeat_succeeded_get_context (event); context->heartbeat_succeeded_events++; - reply = bson_as_canonical_extended_json ( - mongoc_apm_server_heartbeat_succeeded_get_reply (event), NULL); + reply = bson_as_canonical_extended_json (mongoc_apm_server_heartbeat_succeeded_get_reply (event), NULL); printf ( - "%s heartbeat succeeded: %s\n", - mongoc_apm_server_heartbeat_succeeded_get_host (event)->host_and_port, - reply); + "%s heartbeat succeeded: %s\n", mongoc_apm_server_heartbeat_succeeded_get_host (event)->host_and_port, reply); bson_free (reply); } @@ -202,9 +191,8 @@ server_heartbeat_failed (const mongoc_apm_server_heartbeat_failed_t *event) context->heartbeat_failed_events++; mongoc_apm_server_heartbeat_failed_get_error (event, &error); - printf ("%s heartbeat failed: %s\n", - mongoc_apm_server_heartbeat_failed_get_host (event)->host_and_port, - error.message); + printf ( + "%s heartbeat failed: %s\n", mongoc_apm_server_heartbeat_failed_get_host (event)->host_and_port, error.message); } @@ -214,8 +202,7 @@ main (int argc, char *argv[]) mongoc_client_t *client; mongoc_apm_callbacks_t *cbs; stats_t stats = {0}; - const char *uri_string = - "mongodb://127.0.0.1/?appname=sdam-monitoring-example"; + const char *uri_string = "mongodb://127.0.0.1/?appname=sdam-monitoring-example"; mongoc_uri_t *uri; bson_t cmd = BSON_INITIALIZER; bson_t reply; @@ -251,11 +238,9 @@ main (int argc, char *argv[]) mongoc_apm_set_topology_opening_cb (cbs, topology_opening); mongoc_apm_set_topology_closed_cb (cbs, topology_closed); mongoc_apm_set_server_heartbeat_started_cb (cbs, server_heartbeat_started); - mongoc_apm_set_server_heartbeat_succeeded_cb (cbs, - server_heartbeat_succeeded); + mongoc_apm_set_server_heartbeat_succeeded_cb (cbs, server_heartbeat_succeeded); mongoc_apm_set_server_heartbeat_failed_cb (cbs, server_heartbeat_failed); - mongoc_client_set_apm_callbacks ( - client, cbs, (void *) &stats /* context pointer */); + mongoc_client_set_apm_callbacks (client, cbs, (void *) &stats /* context pointer */); /* the driver connects on demand to perform first operation */ BSON_APPEND_INT32 (&cmd, "buildinfo", 1); diff --git a/src/libmongoc/examples/example-session.c b/src/libmongoc/examples/example-session.c index e62aa04ea0..589c9c5101 100644 --- a/src/libmongoc/examples/example-session.c +++ b/src/libmongoc/examples/example-session.c @@ -67,8 +67,7 @@ main (int argc, char *argv[]) goto done; } - r = mongoc_collection_update_one ( - collection, selector, update, update_opts, NULL /* reply */, &error); + r = mongoc_collection_update_one (collection, selector, update, update_opts, NULL /* reply */, &error); if (!r) { fprintf (stderr, "Update failed: %s\n", error.message); @@ -90,8 +89,7 @@ main (int argc, char *argv[]) * blocks waiting for the secondary to catch up, if necessary, or times out * and fails after 2000 ms. */ - cursor = mongoc_collection_find_with_opts ( - collection, selector, find_opts, secondary); + cursor = mongoc_collection_find_with_opts (collection, selector, find_opts, secondary); while (mongoc_cursor_next (cursor, &doc)) { str = bson_as_json (doc, NULL); diff --git a/src/libmongoc/examples/example-start-at-optime.c b/src/libmongoc/examples/example-start-at-optime.c index d9a03ed57d..0b7f4069b3 100644 --- a/src/libmongoc/examples/example-start-at-optime.c +++ b/src/libmongoc/examples/example-start-at-optime.c @@ -40,18 +40,9 @@ main (void) coll = mongoc_client_get_collection (client, "db", "coll"); for (i = 0; i < 5; i++) { bson_t reply; - bson_t *insert_cmd = BCON_NEW ("insert", - "coll", - "documents", - "[", - "{", - "x", - BCON_INT64 (i), - "}", - "]"); + bson_t *insert_cmd = BCON_NEW ("insert", "coll", "documents", "[", "{", "x", BCON_INT64 (i), "}", "]"); - r = mongoc_collection_write_command_with_opts ( - coll, insert_cmd, NULL, &reply, &error); + r = mongoc_collection_write_command_with_opts (coll, insert_cmd, NULL, &reply, &error); bson_destroy (insert_cmd); if (!r) { bson_destroy (&reply); diff --git a/src/libmongoc/examples/example-transaction.c b/src/libmongoc/examples/example-transaction.c index 3977b4840d..f7aa48bd07 100644 --- a/src/libmongoc/examples/example-transaction.c +++ b/src/libmongoc/examples/example-transaction.c @@ -57,8 +57,7 @@ main (int argc, char *argv[]) /* inserting into a nonexistent collection normally creates it, but a * collection can't be created in a transaction; create it now */ - collection = - mongoc_database_create_collection (database, "collection", NULL, &error); + collection = mongoc_database_create_collection (database, "collection", NULL, &error); if (!collection) { /* code 48 is NamespaceExists, see error_codes.err in mongodb source */ @@ -79,8 +78,7 @@ main (int argc, char *argv[]) mongoc_read_concern_set_level (read_concern, "snapshot"); mongoc_transaction_opts_set_read_concern (default_txn_opts, read_concern); session_opts = mongoc_session_opts_new (); - mongoc_session_opts_set_default_transaction_opts (session_opts, - default_txn_opts); + mongoc_session_opts_set_default_transaction_opts (session_opts, default_txn_opts); session = mongoc_client_start_session (client, session_opts, &error); if (!session) { @@ -111,8 +109,7 @@ main (int argc, char *argv[]) for (i = 0; i < 2; i++) { doc = BCON_NEW ("_id", BCON_INT32 (i)); bson_destroy (&reply); - r = mongoc_collection_insert_one ( - collection, doc, insert_opts, &reply, &error); + r = mongoc_collection_insert_one (collection, doc, insert_opts, &reply, &error); bson_destroy (doc); @@ -148,8 +145,7 @@ main (int argc, char *argv[]) MONGOC_ERROR ("Warning: commit failed: %s", error.message); if (mongoc_error_has_label (&reply, "TransientTransactionError")) { goto retry_transaction; - } else if (mongoc_error_has_label (&reply, - "UnknownTransactionCommitResult")) { + } else if (mongoc_error_has_label (&reply, "UnknownTransactionCommitResult")) { /* try again to commit */ continue; } diff --git a/src/libmongoc/examples/example-update.c b/src/libmongoc/examples/example-update.c index 5fd3e76a5f..2443eee705 100644 --- a/src/libmongoc/examples/example-update.c +++ b/src/libmongoc/examples/example-update.c @@ -38,8 +38,7 @@ main (void) return EXIT_FAILURE; } - if (!mongoc_collection_update_one ( - coll, selector, update, NULL, NULL, &error)) { + if (!mongoc_collection_update_one (coll, selector, update, NULL, NULL, &error)) { fprintf (stderr, "update failed: %s\n", error.message); return EXIT_FAILURE; } diff --git a/src/libmongoc/examples/example-with-transaction-cb.c b/src/libmongoc/examples/example-with-transaction-cb.c index 2efcb7049e..66f171d834 100644 --- a/src/libmongoc/examples/example-with-transaction-cb.c +++ b/src/libmongoc/examples/example-with-transaction-cb.c @@ -42,11 +42,9 @@ create_and_insert_doc (mongoc_client_session_t *session, */ doc = BCON_NEW ("_id", BCON_INT32 (1)); - printf ( - "Running the user-defined callback in a newly created transaction...\n"); + printf ("Running the user-defined callback in a newly created transaction...\n"); data = (ctx_t *) ctx; - retval = mongoc_collection_insert_one ( - data->collection, doc, data->insert_opts, &local_reply, error); + retval = mongoc_collection_insert_one (data->collection, doc, data->insert_opts, &local_reply, error); /* * To return to the mongoc_client_session_with_transaction() method, set @@ -119,8 +117,7 @@ main (int argc, char *argv[]) * Inserting into a nonexistent collection normally creates it, but a * collection can't be created in a transaction; create it now */ - collection = - mongoc_database_create_collection (database, "collection", NULL, &error); + collection = mongoc_database_create_collection (database, "collection", NULL, &error); if (!collection) { /* code 48 is NamespaceExists, see error_codes.err in mongodb source */ if (error.code == 48) { @@ -157,8 +154,7 @@ main (int argc, char *argv[]) * function, i.e., &create_and_insert_doc, passing &ctx as an argument and * commit the transaction. */ - if (!mongoc_client_session_with_transaction ( - session, &create_and_insert_doc, NULL, &ctx, &reply, &error)) { + if (!mongoc_client_session_with_transaction (session, &create_and_insert_doc, NULL, &ctx, &reply, &error)) { MONGOC_ERROR ("Insert failed: %s", error.message); goto done; } diff --git a/src/libmongoc/examples/find-and-modify.c b/src/libmongoc/examples/find-and-modify.c index 3297fc581f..b2dbb02c3b 100644 --- a/src/libmongoc/examples/find-and-modify.c +++ b/src/libmongoc/examples/find-and-modify.c @@ -7,8 +7,7 @@ main (void) { mongoc_collection_t *collection; mongoc_client_t *client; - const char *uri_string = - "mongodb://127.0.0.1:27017/?appname=find-and-modify-example"; + const char *uri_string = "mongodb://127.0.0.1:27017/?appname=find-and-modify-example"; mongoc_uri_t *uri; bson_error_t error; bson_t *query; @@ -49,16 +48,7 @@ main (void) /* * Submit the findAndModify. */ - if (!mongoc_collection_find_and_modify (collection, - query, - NULL, - update, - NULL, - false, - false, - true, - &reply, - &error)) { + if (!mongoc_collection_find_and_modify (collection, query, NULL, update, NULL, false, false, true, &reply, &error)) { fprintf (stderr, "find_and_modify() failure: %s\n", error.message); return EXIT_FAILURE; } diff --git a/src/libmongoc/examples/find_and_modify_with_opts/fam.c b/src/libmongoc/examples/find_and_modify_with_opts/fam.c index 711a05d2b7..3fd91b50cb 100644 --- a/src/libmongoc/examples/find_and_modify_with_opts/fam.c +++ b/src/libmongoc/examples/find_and_modify_with_opts/fam.c @@ -26,8 +26,7 @@ fam_bypass (mongoc_collection_t *collection) /* He can still play, even though he is pretty old. */ mongoc_find_and_modify_opts_set_bypass_document_validation (opts, true); - success = mongoc_collection_find_and_modify_with_opts ( - collection, &query, opts, &reply, &error); + success = mongoc_collection_find_and_modify_with_opts (collection, &query, opts, &reply, &error); if (success) { char *str; @@ -36,8 +35,7 @@ fam_bypass (mongoc_collection_t *collection) printf ("%s\n", str); bson_free (str); } else { - fprintf ( - stderr, "Got error: \"%s\" on line %d\n", error.message, __LINE__); + fprintf (stderr, "Got error: \"%s\" on line %d\n", error.message, __LINE__); } bson_destroy (&reply); @@ -64,8 +62,7 @@ fam_flags (mongoc_collection_t *collection) 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)); + 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"), "}"); @@ -75,11 +72,9 @@ fam_flags (mongoc_collection_t *collection) 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); + 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); + success = mongoc_collection_find_and_modify_with_opts (collection, &query, opts, &reply, &error); if (success) { char *str; @@ -88,8 +83,7 @@ fam_flags (mongoc_collection_t *collection) printf ("%s\n", str); bson_free (str); } else { - fprintf ( - stderr, "Got error: \"%s\" on line %d\n", error.message, __LINE__); + fprintf (stderr, "Got error: \"%s\" on line %d\n", error.message, __LINE__); } bson_destroy (&reply); @@ -126,8 +120,7 @@ fam_update (mongoc_collection_t *collection) */ mongoc_find_and_modify_opts_set_update (opts, update); - success = mongoc_collection_find_and_modify_with_opts ( - collection, &query, opts, &reply, &error); + success = mongoc_collection_find_and_modify_with_opts (collection, &query, opts, &reply, &error); if (success) { char *str; @@ -136,8 +129,7 @@ fam_update (mongoc_collection_t *collection) printf ("%s\n", str); bson_free (str); } else { - fprintf ( - stderr, "Got error: \"%s\" on line %d\n", error.message, __LINE__); + fprintf (stderr, "Got error: \"%s\" on line %d\n", error.message, __LINE__); } bson_destroy (&reply); @@ -174,11 +166,9 @@ fam_fields (mongoc_collection_t *collection) mongoc_find_and_modify_opts_set_update (opts, update); mongoc_find_and_modify_opts_set_fields (opts, &fields); /* Return the new tally */ - mongoc_find_and_modify_opts_set_flags (opts, - MONGOC_FIND_AND_MODIFY_RETURN_NEW); + mongoc_find_and_modify_opts_set_flags (opts, MONGOC_FIND_AND_MODIFY_RETURN_NEW); - success = mongoc_collection_find_and_modify_with_opts ( - collection, &query, opts, &reply, &error); + success = mongoc_collection_find_and_modify_with_opts (collection, &query, opts, &reply, &error); if (success) { char *str; @@ -187,8 +177,7 @@ fam_fields (mongoc_collection_t *collection) printf ("%s\n", str); bson_free (str); } else { - fprintf ( - stderr, "Got error: \"%s\" on line %d\n", error.message, __LINE__); + fprintf (stderr, "Got error: \"%s\" on line %d\n", error.message, __LINE__); } bson_destroy (&reply); @@ -237,8 +226,7 @@ fam_opts (mongoc_collection_t *collection) BSON_APPEND_INT32 (&extra, "futureOption", 42); mongoc_find_and_modify_opts_append (opts, &extra); - success = mongoc_collection_find_and_modify_with_opts ( - collection, &query, opts, &reply, &error); + success = mongoc_collection_find_and_modify_with_opts (collection, &query, opts, &reply, &error); if (success) { char *str; @@ -247,8 +235,7 @@ fam_opts (mongoc_collection_t *collection) printf ("%s\n", str); bson_free (str); } else { - fprintf ( - stderr, "Got error: \"%s\" on line %d\n", error.message, __LINE__); + fprintf (stderr, "Got error: \"%s\" on line %d\n", error.message, __LINE__); } bson_destroy (&reply); @@ -286,8 +273,7 @@ fam_sort (mongoc_collection_t *collection) mongoc_find_and_modify_opts_set_update (opts, update); mongoc_find_and_modify_opts_set_sort (opts, &sort); - success = mongoc_collection_find_and_modify_with_opts ( - collection, &query, opts, &reply, &error); + success = mongoc_collection_find_and_modify_with_opts (collection, &query, opts, &reply, &error); if (success) { char *str; @@ -296,8 +282,7 @@ fam_sort (mongoc_collection_t *collection) printf ("%s\n", str); bson_free (str); } else { - fprintf ( - stderr, "Got error: \"%s\" on line %d\n", error.message, __LINE__); + fprintf (stderr, "Got error: \"%s\" on line %d\n", error.message, __LINE__); } bson_destroy (&reply); @@ -315,8 +300,7 @@ main (void) mongoc_collection_t *collection; mongoc_database_t *database; mongoc_client_t *client; - const char *uri_string = - "mongodb://localhost:27017/admin?appname=find-and-modify-opts-example"; + const char *uri_string = "mongodb://localhost:27017/admin?appname=find-and-modify-opts-example"; mongoc_uri_t *uri; bson_error_t error; bson_t *options; @@ -354,11 +338,9 @@ main (void) "validationLevel", BCON_UTF8 ("moderate")); - collection = mongoc_database_create_collection ( - database, "collectionName", options, &error); + collection = mongoc_database_create_collection (database, "collectionName", options, &error); if (!collection) { - fprintf ( - stderr, "Got error: \"%s\" on line %d\n", error.message, __LINE__); + fprintf (stderr, "Got error: \"%s\" on line %d\n", error.message, __LINE__); return EXIT_FAILURE; } diff --git a/src/libmongoc/examples/hello_mongoc.c b/src/libmongoc/examples/hello_mongoc.c index d6ede67cac..f4ad8faed3 100644 --- a/src/libmongoc/examples/hello_mongoc.c +++ b/src/libmongoc/examples/hello_mongoc.c @@ -81,8 +81,7 @@ main (int argc, char *argv[]) */ command = BCON_NEW ("ping", BCON_INT32 (1)); - retval = mongoc_client_command_simple ( - client, "admin", command, NULL, &reply, &error); + retval = mongoc_client_command_simple (client, "admin", command, NULL, &reply, &error); if (!retval) { fprintf (stderr, "%s\n", error.message); diff --git a/src/libmongoc/examples/mongoc-dump.c b/src/libmongoc/examples/mongoc-dump.c index 37d30a4615..2323cde911 100644 --- a/src/libmongoc/examples/mongoc-dump.c +++ b/src/libmongoc/examples/mongoc-dump.c @@ -36,9 +36,7 @@ mongoc_dump_mkdir_p (const char *path, int mode) static int -mongoc_dump_collection (mongoc_client_t *client, - const char *database, - const char *collection) +mongoc_dump_collection (mongoc_client_t *client, const char *database, const char *collection) { mongoc_collection_t *col; mongoc_cursor_t *cursor; @@ -66,8 +64,7 @@ mongoc_dump_collection (mongoc_client_t *client, cursor = mongoc_collection_find_with_opts (col, &query, NULL, NULL); while (mongoc_cursor_next (cursor, &doc)) { - if (BSON_UNLIKELY (doc->len != - fwrite (bson_get_data (doc), 1, doc->len, stream))) { + if (BSON_UNLIKELY (doc->len != fwrite (bson_get_data (doc), 1, doc->len, stream))) { fprintf (stderr, "Failed to write %u bytes to %s\n", doc->len, path); ret = EXIT_FAILURE; goto cleanup; @@ -90,9 +87,7 @@ mongoc_dump_collection (mongoc_client_t *client, static int -mongoc_dump_database (mongoc_client_t *client, - const char *database, - const char *collection) +mongoc_dump_database (mongoc_client_t *client, const char *database, const char *collection) { mongoc_database_t *db; bson_error_t error; @@ -135,9 +130,7 @@ mongoc_dump_database (mongoc_client_t *client, static int -mongoc_dump (mongoc_client_t *client, - const char *database, - const char *collection) +mongoc_dump (mongoc_client_t *client, const char *database, const char *collection) { bson_error_t error; char **str; @@ -154,8 +147,7 @@ mongoc_dump (mongoc_client_t *client, return mongoc_dump_database (client, database, collection); } - if (!(str = mongoc_client_get_database_names_with_opts ( - client, NULL, &error))) { + if (!(str = mongoc_client_get_database_names_with_opts (client, NULL, &error))) { fprintf (stderr, "Failed to fetch database names: %s\n", error.message); return EXIT_FAILURE; } @@ -231,12 +223,8 @@ main (int argc, char *argv[]) } } - uri_string = - bson_strdup_printf ("mongodb://%s:%hu/%s?appname=dump-example&ssl=%s", - host, - port, - database ? database : "", - ssl ? "true" : "false"); + uri_string = bson_strdup_printf ( + "mongodb://%s:%hu/%s?appname=dump-example&ssl=%s", host, port, database ? database : "", ssl ? "true" : "false"); uri = mongoc_uri_new_with_error (uri_string, &error); if (!uri) { diff --git a/src/libmongoc/examples/mongoc-ping.c b/src/libmongoc/examples/mongoc-ping.c index 9901d54ac2..f4539e5fd6 100644 --- a/src/libmongoc/examples/mongoc-ping.c +++ b/src/libmongoc/examples/mongoc-ping.c @@ -42,8 +42,7 @@ main (int argc, char *argv[]) port = (argc == 3) ? atoi (argv[2]) : 27017; - if (!strncmp (argv[1], "mongodb://", 10) || - !strncmp (argv[1], "mongodb+srv://", 14)) { + if (!strncmp (argv[1], "mongodb://", 10) || !strncmp (argv[1], "mongodb+srv://", 14)) { host_and_port = bson_strdup (argv[1]); } else { host_and_port = bson_strdup_printf ("mongodb://%s:%hu", argv[1], port); @@ -70,8 +69,7 @@ main (int argc, char *argv[]) bson_init (&ping); bson_append_int32 (&ping, "ping", 4, 1); database = mongoc_client_get_database (client, "test"); - r = mongoc_database_command_with_opts ( - database, &ping, NULL, NULL, &reply, &error); + r = mongoc_database_command_with_opts (database, &ping, NULL, NULL, &reply, &error); if (r) { str = bson_as_canonical_extended_json (&reply, NULL); diff --git a/src/libmongoc/examples/mongoc-tail.c b/src/libmongoc/examples/mongoc-tail.c index 02f31000ac..40f2f6c4c4 100644 --- a/src/libmongoc/examples/mongoc-tail.c +++ b/src/libmongoc/examples/mongoc-tail.c @@ -62,11 +62,9 @@ tail_collection (mongoc_collection_t *collection) while (true) { cursor = query_collection (collection, last_time); - while (!mongoc_cursor_error (cursor, &error) && - mongoc_cursor_more (cursor)) { + while (!mongoc_cursor_error (cursor, &error) && mongoc_cursor_more (cursor)) { if (mongoc_cursor_next (cursor, &doc)) { - if (bson_iter_init_find (&iter, doc, "ts") && - BSON_ITER_HOLDS_TIMESTAMP (&iter)) { + if (bson_iter_init_find (&iter, doc, "ts") && BSON_ITER_HOLDS_TIMESTAMP (&iter)) { bson_iter_timestamp (&iter, &last_time, NULL); } print_bson (doc); diff --git a/src/libmongoc/examples/tutorial/executing.c b/src/libmongoc/examples/tutorial/executing.c index d89600a9db..164a25ef1b 100644 --- a/src/libmongoc/examples/tutorial/executing.c +++ b/src/libmongoc/examples/tutorial/executing.c @@ -13,12 +13,10 @@ main (void) mongoc_init (); - client = mongoc_client_new ( - "mongodb://localhost:27017/?appname=executing-example"); + client = mongoc_client_new ("mongodb://localhost:27017/?appname=executing-example"); command = BCON_NEW ("ping", BCON_INT32 (1)); - if (mongoc_client_command_simple ( - client, "mydb", command, NULL, &reply, &error)) { + if (mongoc_client_command_simple (client, "mydb", command, NULL, &reply, &error)) { str = bson_as_canonical_extended_json (&reply, NULL); printf ("%s\n", str); bson_free (str); diff --git a/src/libmongoc/src/mongoc/mcd-azure.c b/src/libmongoc/src/mongoc/mcd-azure.c index 8f51351f85..1896b202ee 100644 --- a/src/libmongoc/src/mongoc/mcd-azure.c +++ b/src/libmongoc/src/mongoc/mcd-azure.c @@ -22,8 +22,7 @@ static const char *const DEFAULT_METADATA_PATH = "/metadata/identity/oauth2/" - "token?api-version=" AZURE_API_VERSION - "&resource=https%3A%2F%2Fvault.azure.net"; + "token?api-version=" AZURE_API_VERSION "&resource=https%3A%2F%2Fvault.azure.net"; void mcd_azure_imds_request_init (mcd_azure_imds_request *req, @@ -34,8 +33,7 @@ mcd_azure_imds_request_init (mcd_azure_imds_request *req, BSON_ASSERT_PARAM (req); _mongoc_http_request_init (&req->req); // The HTTP host of the IMDS server - req->req.host = req->_owned_host = - bson_strdup (opt_imds_host ? opt_imds_host : "169.254.169.254"); + req->req.host = req->_owned_host = bson_strdup (opt_imds_host ? opt_imds_host : "169.254.169.254"); if (opt_port) { req->req.port = opt_port; } else { @@ -46,10 +44,9 @@ mcd_azure_imds_request_init (mcd_azure_imds_request *req, // We GET req->req.method = "GET"; // 'Metadata: true' is required - req->req.extra_headers = req->_owned_headers = - bson_strdup_printf ("Metadata: true\r\n" - "Accept: application/json\r\n%s", - opt_extra_headers ? opt_extra_headers : ""); + req->req.extra_headers = req->_owned_headers = bson_strdup_printf ("Metadata: true\r\n" + "Accept: application/json\r\n%s", + opt_extra_headers ? opt_extra_headers : ""); // The default path is suitable. In the future, we may want to add query // parameters to disambiguate a managed identity. req->req.path = req->_owned_path = bson_strdup (DEFAULT_METADATA_PATH); @@ -92,8 +89,7 @@ mcd_azure_access_token_try_init_from_json_str (mcd_azure_access_token *out, bson_iter_t iter; // access_token bool found = bson_iter_init_find (&iter, &bson, "access_token"); - const char *const access_token = - !found ? NULL : bson_iter_utf8 (&iter, NULL); + const char *const access_token = !found ? NULL : bson_iter_utf8 (&iter, NULL); // resource found = bson_iter_init_find (&iter, &bson, "resource"); const char *const resource = !found ? NULL : bson_iter_utf8 (&iter, NULL); @@ -103,17 +99,15 @@ mcd_azure_access_token_try_init_from_json_str (mcd_azure_access_token *out, // expires_in found = bson_iter_init_find (&iter, &bson, "expires_in"); uint32_t expires_in_len = 0; - const char *const expires_in_str = - !found ? NULL : bson_iter_utf8 (&iter, &expires_in_len); + const char *const expires_in_str = !found ? NULL : bson_iter_utf8 (&iter, &expires_in_len); if (!(access_token && resource && token_type && expires_in_str)) { - bson_set_error ( - error, - MONGOC_ERROR_AZURE, - MONGOC_ERROR_KMS_SERVER_BAD_JSON, - "One or more required JSON properties are missing/invalid: data: %.*s", - len, - json); + bson_set_error (error, + MONGOC_ERROR_AZURE, + MONGOC_ERROR_KMS_SERVER_BAD_JSON, + "One or more required JSON properties are missing/invalid: data: %.*s", + len, + json); } else { // Set the output, duplicate each string *out = (mcd_azure_access_token){ @@ -128,13 +122,12 @@ mcd_azure_access_token_try_init_from_json_str (mcd_azure_access_token *out, long long s = strtoll (expires_in_str, &parse_end, 0); if (parse_end != expires_in_str + expires_in_len) { // Did not parse the entire string. Bad - bson_set_error ( - error, - MONGOC_ERROR_AZURE, - MONGOC_ERROR_KMS_SERVER_BAD_JSON, - "Invalid 'expires_in' string \"%.*s\" from IMDS server", - expires_in_len, - expires_in_str); + bson_set_error (error, + MONGOC_ERROR_AZURE, + MONGOC_ERROR_KMS_SERVER_BAD_JSON, + "Invalid 'expires_in' string \"%.*s\" from IMDS server", + expires_in_len, + expires_in_str); } else { out->expires_in = mcd_seconds (s); okay = true; @@ -176,8 +169,7 @@ mcd_azure_access_token_from_imds (mcd_azure_access_token *const out, _mongoc_http_response_init (&resp); mcd_azure_imds_request req = MCD_AZURE_IMDS_REQUEST_INIT; - mcd_azure_imds_request_init ( - &req, opt_imds_host, opt_port, opt_extra_headers); + mcd_azure_imds_request_init (&req, opt_imds_host, opt_port, opt_extra_headers); if (!_mongoc_http_send (&req.req, 3 * 1000, false, NULL, &resp, error)) { goto fail; @@ -196,8 +188,7 @@ mcd_azure_access_token_from_imds (mcd_azure_access_token *const out, } // Parse the token from the response JSON - if (!mcd_azure_access_token_try_init_from_json_str ( - out, resp.body, resp.body_len, error)) { + if (!mcd_azure_access_token_try_init_from_json_str (out, resp.body, resp.body_len, error)) { goto fail; } diff --git a/src/libmongoc/src/mongoc/mcd-azure.h b/src/libmongoc/src/mongoc/mcd-azure.h index 54120ddc9d..8a9780b93d 100644 --- a/src/libmongoc/src/mongoc/mcd-azure.h +++ b/src/libmongoc/src/mongoc/mcd-azure.h @@ -58,8 +58,7 @@ bool mcd_azure_access_token_try_init_from_json_str (mcd_azure_access_token *out, const char *json, int len, - bson_error_t *error) - BSON_GNUC_WARN_UNUSED_RESULT; + bson_error_t *error) BSON_GNUC_WARN_UNUSED_RESULT; /** * @brief Destroy and zero-fill an access token object @@ -80,11 +79,10 @@ typedef struct mcd_azure_imds_request { char *_owned_headers; } mcd_azure_imds_request; -#define MCD_AZURE_IMDS_REQUEST_INIT \ - (mcd_azure_imds_request) \ - { \ - .req = {0}, ._owned_path = NULL, ._owned_host = NULL, \ - ._owned_headers = NULL, \ +#define MCD_AZURE_IMDS_REQUEST_INIT \ + (mcd_azure_imds_request) \ + { \ + .req = {0}, ._owned_path = NULL, ._owned_host = NULL, ._owned_headers = NULL, \ } /** diff --git a/src/libmongoc/src/mongoc/mcd-rpc.c b/src/libmongoc/src/mongoc/mcd-rpc.c index 446e4ef812..863832db99 100644 --- a/src/libmongoc/src/mongoc/mcd-rpc.c +++ b/src/libmongoc/src/mongoc/mcd-rpc.c @@ -185,28 +185,27 @@ _int32_from_le (const void *data) // In addition to validating expected size against remaining bytes, ensure // proper conversion from little endian format. -#define MONGOC_RPC_CONSUME(type, raw_type, from_le) \ - static bool _consume_##type ( \ - type *target, const uint8_t **ptr, size_t *remaining_bytes) \ - { \ - BSON_ASSERT_PARAM (target); \ - BSON_ASSERT_PARAM (ptr); \ - BSON_ASSERT_PARAM (remaining_bytes); \ - \ - if (*remaining_bytes < sizeof (type)) { \ - return false; \ - } \ - \ - raw_type raw; \ - memcpy (&raw, *ptr, sizeof (type)); \ - \ - const raw_type native = from_le (raw); \ - memcpy (target, &native, sizeof (type)); \ - \ - *ptr += sizeof (type); \ - *remaining_bytes -= sizeof (type); \ - \ - return true; \ +#define MONGOC_RPC_CONSUME(type, raw_type, from_le) \ + static bool _consume_##type (type *target, const uint8_t **ptr, size_t *remaining_bytes) \ + { \ + BSON_ASSERT_PARAM (target); \ + BSON_ASSERT_PARAM (ptr); \ + BSON_ASSERT_PARAM (remaining_bytes); \ + \ + if (*remaining_bytes < sizeof (type)) { \ + return false; \ + } \ + \ + raw_type raw; \ + memcpy (&raw, *ptr, sizeof (type)); \ + \ + const raw_type native = from_le (raw); \ + memcpy (target, &native, sizeof (type)); \ + \ + *ptr += sizeof (type); \ + *remaining_bytes -= sizeof (type); \ + \ + return true; \ } MONGOC_RPC_CONSUME (uint8_t, uint8_t, (uint8_t)) @@ -215,10 +214,7 @@ MONGOC_RPC_CONSUME (uint32_t, uint32_t, BSON_UINT32_FROM_LE) MONGOC_RPC_CONSUME (int64_t, uint64_t, BSON_UINT64_FROM_LE) static bool -_consume_utf8 (const char **target, - size_t *length, - const uint8_t **ptr, - size_t *remaining_bytes) +_consume_utf8 (const char **target, size_t *length, const uint8_t **ptr, size_t *remaining_bytes) { BSON_ASSERT_PARAM (target); BSON_ASSERT_PARAM (length); @@ -270,10 +266,7 @@ _consume_reserved_zero (const uint8_t **ptr, size_t *remaining_bytes) static bool -_consume_bson_objects (const uint8_t **ptr, - size_t *remaining_bytes, - int32_t *num_parsed, - int32_t limit) +_consume_bson_objects (const uint8_t **ptr, size_t *remaining_bytes, int32_t *num_parsed, int32_t limit) { BSON_ASSERT_PARAM (ptr); BSON_ASSERT_PARAM (remaining_bytes); @@ -311,9 +304,7 @@ _consume_bson_objects (const uint8_t **ptr, static bool -_consume_op_compressed (mcd_rpc_message *rpc, - const uint8_t **ptr, - size_t *remaining_bytes) +_consume_op_compressed (mcd_rpc_message *rpc, const uint8_t **ptr, size_t *remaining_bytes) { BSON_ASSERT_PARAM (rpc); BSON_ASSERT_PARAM (ptr); @@ -321,18 +312,15 @@ _consume_op_compressed (mcd_rpc_message *rpc, mcd_rpc_op_compressed *const op_compressed = &rpc->op_compressed; - if (!_consume_int32_t ( - &op_compressed->original_opcode, ptr, remaining_bytes)) { + if (!_consume_int32_t (&op_compressed->original_opcode, ptr, remaining_bytes)) { return false; } - if (!_consume_int32_t ( - &op_compressed->uncompressed_size, ptr, remaining_bytes)) { + if (!_consume_int32_t (&op_compressed->uncompressed_size, ptr, remaining_bytes)) { return false; } - if (!_consume_uint8_t ( - &op_compressed->compressor_id, ptr, remaining_bytes)) { + if (!_consume_uint8_t (&op_compressed->compressor_id, ptr, remaining_bytes)) { return false; } @@ -347,11 +335,8 @@ _consume_op_compressed (mcd_rpc_message *rpc, static bool -_consume_op_msg_section (mcd_rpc_op_msg *op_msg, - const uint8_t **ptr, - size_t *remaining_bytes, - size_t *capacity, - bool *found_kind_0) +_consume_op_msg_section ( + mcd_rpc_op_msg *op_msg, const uint8_t **ptr, size_t *remaining_bytes, size_t *capacity, bool *found_kind_0) { BSON_ASSERT_PARAM (op_msg); BSON_ASSERT_PARAM (ptr); @@ -383,8 +368,7 @@ _consume_op_msg_section (mcd_rpc_op_msg *op_msg, section.payload.body.bson = *ptr; int32_t num_parsed = 0; - if (!_consume_bson_objects (ptr, remaining_bytes, &num_parsed, 1) || - num_parsed != 1) { + if (!_consume_bson_objects (ptr, remaining_bytes, &num_parsed, 1) || num_parsed != 1) { return false; } @@ -392,9 +376,7 @@ _consume_op_msg_section (mcd_rpc_op_msg *op_msg, } case 1: { // Document Sequence - if (!_consume_int32_t (§ion.payload.document_sequence.section_len, - ptr, - remaining_bytes)) { + if (!_consume_int32_t (§ion.payload.document_sequence.section_len, ptr, remaining_bytes)) { return false; } @@ -403,16 +385,13 @@ _consume_op_msg_section (mcd_rpc_op_msg *op_msg, // identifier field, but 4 bytes is sufficient to avoid unsigned integer // overflow when computing `remaining_section_bytes` and to encourage as // much progress is made parsing input data as able. - if (bson_cmp_less_su (section.payload.document_sequence.section_len, - sizeof (int32_t))) { + if (bson_cmp_less_su (section.payload.document_sequence.section_len, sizeof (int32_t))) { *ptr -= sizeof (int32_t); // Revert so *data_end points to start of // document sequence as invalid input. return false; } - size_t remaining_section_bytes = - (size_t) section.payload.document_sequence.section_len - - sizeof (int32_t); + size_t remaining_section_bytes = (size_t) section.payload.document_sequence.section_len - sizeof (int32_t); // Section length exceeds remaining data. if (remaining_section_bytes > *remaining_bytes) { @@ -434,8 +413,7 @@ _consume_op_msg_section (mcd_rpc_op_msg *op_msg, } section.payload.document_sequence.bson_objects = *ptr; - section.payload.document_sequence.bson_objects_len = - remaining_section_bytes; + section.payload.document_sequence.bson_objects_len = remaining_section_bytes; _consume_bson_objects (ptr, &remaining_section_bytes, NULL, INT32_MAX); @@ -444,9 +422,7 @@ _consume_op_msg_section (mcd_rpc_op_msg *op_msg, return false; } - *remaining_bytes -= - (size_t) (*ptr - (const uint8_t *) - section.payload.document_sequence.bson_objects); + *remaining_bytes -= (size_t) (*ptr - (const uint8_t *) section.payload.document_sequence.bson_objects); break; } @@ -460,8 +436,7 @@ _consume_op_msg_section (mcd_rpc_op_msg *op_msg, // Expand sections capacity if required. if (op_msg->sections_count >= *capacity) { *capacity *= 2u; - op_msg->sections = bson_realloc ( - op_msg->sections, *capacity * sizeof (mcd_rpc_op_msg_section)); + op_msg->sections = bson_realloc (op_msg->sections, *capacity * sizeof (mcd_rpc_op_msg_section)); } // Append the valid section. @@ -471,9 +446,7 @@ _consume_op_msg_section (mcd_rpc_op_msg *op_msg, } static bool -_consume_op_msg (mcd_rpc_message *rpc, - const uint8_t **ptr, - size_t *remaining_bytes) +_consume_op_msg (mcd_rpc_message *rpc, const uint8_t **ptr, size_t *remaining_bytes) { BSON_ASSERT_PARAM (rpc); BSON_ASSERT_PARAM (ptr); @@ -486,9 +459,8 @@ _consume_op_msg (mcd_rpc_message *rpc, } { - const uint32_t defined_bits = MONGOC_OP_MSG_FLAG_CHECKSUM_PRESENT | - MONGOC_OP_MSG_FLAG_MORE_TO_COME | - MONGOC_OP_MSG_FLAG_EXHAUST_ALLOWED; + const uint32_t defined_bits = + MONGOC_OP_MSG_FLAG_CHECKSUM_PRESENT | MONGOC_OP_MSG_FLAG_MORE_TO_COME | MONGOC_OP_MSG_FLAG_EXHAUST_ALLOWED; // Clients MUST error if any unsupported or undefined required bits are // set to 1 and MUST ignore all undefined optional bits. @@ -513,8 +485,7 @@ _consume_op_msg (mcd_rpc_message *rpc, // A section requires at least 5 bytes for kind (1) + length (4). while (*remaining_bytes > 4u) { - if (!_consume_op_msg_section ( - op_msg, ptr, remaining_bytes, &capacity, &found_kind_0)) { + if (!_consume_op_msg_section (op_msg, ptr, remaining_bytes, &capacity, &found_kind_0)) { return false; } } @@ -537,9 +508,7 @@ _consume_op_msg (mcd_rpc_message *rpc, static bool -_consume_op_reply (mcd_rpc_message *rpc, - const uint8_t **ptr, - size_t *remaining_bytes) +_consume_op_reply (mcd_rpc_message *rpc, const uint8_t **ptr, size_t *remaining_bytes) { BSON_ASSERT_PARAM (rpc); BSON_ASSERT_PARAM (ptr); @@ -578,8 +547,7 @@ _consume_op_reply (mcd_rpc_message *rpc, } int32_t num_parsed = 0; - if (!_consume_bson_objects ( - ptr, remaining_bytes, &num_parsed, op_reply->number_returned) || + if (!_consume_bson_objects (ptr, remaining_bytes, &num_parsed, op_reply->number_returned) || num_parsed != op_reply->number_returned) { return false; } @@ -589,9 +557,7 @@ _consume_op_reply (mcd_rpc_message *rpc, static bool -_consume_op_update (mcd_rpc_message *rpc, - const uint8_t **ptr, - size_t *remaining_bytes) +_consume_op_update (mcd_rpc_message *rpc, const uint8_t **ptr, size_t *remaining_bytes) { BSON_ASSERT_PARAM (rpc); BSON_ASSERT_PARAM (ptr); @@ -603,10 +569,7 @@ _consume_op_update (mcd_rpc_message *rpc, return false; } - if (!_consume_utf8 (&op_update->full_collection_name, - &op_update->full_collection_name_len, - ptr, - remaining_bytes)) { + if (!_consume_utf8 (&op_update->full_collection_name, &op_update->full_collection_name_len, ptr, remaining_bytes)) { return false; } @@ -624,14 +587,12 @@ _consume_op_update (mcd_rpc_message *rpc, int32_t num_parsed = 0; op_update->selector = *ptr; - if (!_consume_bson_objects (ptr, remaining_bytes, &num_parsed, 1) || - num_parsed != 1) { + if (!_consume_bson_objects (ptr, remaining_bytes, &num_parsed, 1) || num_parsed != 1) { return false; } op_update->update = *ptr; - if (!_consume_bson_objects (ptr, remaining_bytes, &num_parsed, 1) || - num_parsed != 1) { + if (!_consume_bson_objects (ptr, remaining_bytes, &num_parsed, 1) || num_parsed != 1) { return false; } @@ -640,9 +601,7 @@ _consume_op_update (mcd_rpc_message *rpc, static bool -_consume_op_insert (mcd_rpc_message *rpc, - const uint8_t **ptr, - size_t *remaining_bytes) +_consume_op_insert (mcd_rpc_message *rpc, const uint8_t **ptr, size_t *remaining_bytes) { BSON_ASSERT_PARAM (rpc); BSON_ASSERT_PARAM (ptr); @@ -661,10 +620,7 @@ _consume_op_insert (mcd_rpc_message *rpc, return false; } - if (!_consume_utf8 (&op_insert->full_collection_name, - &op_insert->full_collection_name_len, - ptr, - remaining_bytes)) { + if (!_consume_utf8 (&op_insert->full_collection_name, &op_insert->full_collection_name_len, ptr, remaining_bytes)) { return false; } @@ -672,8 +628,7 @@ _consume_op_insert (mcd_rpc_message *rpc, op_insert->documents_len = *remaining_bytes; int32_t num_parsed = 0; - if (!_consume_bson_objects (ptr, remaining_bytes, &num_parsed, INT32_MAX) || - num_parsed == 0) { + if (!_consume_bson_objects (ptr, remaining_bytes, &num_parsed, INT32_MAX) || num_parsed == 0) { return false; } @@ -682,9 +637,7 @@ _consume_op_insert (mcd_rpc_message *rpc, static bool -_consume_op_query (mcd_rpc_message *rpc, - const uint8_t **ptr, - size_t *remaining_bytes) +_consume_op_query (mcd_rpc_message *rpc, const uint8_t **ptr, size_t *remaining_bytes) { BSON_ASSERT_PARAM (rpc); BSON_ASSERT_PARAM (ptr); @@ -710,10 +663,7 @@ _consume_op_query (mcd_rpc_message *rpc, return false; } - if (!_consume_utf8 (&op_query->full_collection_name, - &op_query->full_collection_name_len, - ptr, - remaining_bytes)) { + if (!_consume_utf8 (&op_query->full_collection_name, &op_query->full_collection_name_len, ptr, remaining_bytes)) { return false; } @@ -728,8 +678,7 @@ _consume_op_query (mcd_rpc_message *rpc, int32_t num_parsed = 0; op_query->query = *ptr; - if (!_consume_bson_objects (ptr, remaining_bytes, &num_parsed, 1) || - num_parsed != 1) { + if (!_consume_bson_objects (ptr, remaining_bytes, &num_parsed, 1) || num_parsed != 1) { return false; } @@ -748,9 +697,7 @@ _consume_op_query (mcd_rpc_message *rpc, static bool -_consume_op_get_more (mcd_rpc_message *rpc, - const uint8_t **ptr, - size_t *remaining_bytes) +_consume_op_get_more (mcd_rpc_message *rpc, const uint8_t **ptr, size_t *remaining_bytes) { BSON_ASSERT_PARAM (rpc); BSON_ASSERT_PARAM (ptr); @@ -762,15 +709,12 @@ _consume_op_get_more (mcd_rpc_message *rpc, return false; } - if (!_consume_utf8 (&op_get_more->full_collection_name, - &op_get_more->full_collection_name_len, - ptr, - remaining_bytes)) { + if (!_consume_utf8 ( + &op_get_more->full_collection_name, &op_get_more->full_collection_name_len, ptr, remaining_bytes)) { return false; } - if (!_consume_int32_t ( - &op_get_more->number_to_return, ptr, remaining_bytes)) { + if (!_consume_int32_t (&op_get_more->number_to_return, ptr, remaining_bytes)) { return false; } @@ -783,9 +727,7 @@ _consume_op_get_more (mcd_rpc_message *rpc, static bool -_consume_op_delete (mcd_rpc_message *rpc, - const uint8_t **ptr, - size_t *remaining_bytes) +_consume_op_delete (mcd_rpc_message *rpc, const uint8_t **ptr, size_t *remaining_bytes) { BSON_ASSERT_PARAM (rpc); BSON_ASSERT_PARAM (ptr); @@ -797,10 +739,7 @@ _consume_op_delete (mcd_rpc_message *rpc, return false; } - if (!_consume_utf8 (&op_delete->full_collection_name, - &op_delete->full_collection_name_len, - ptr, - remaining_bytes)) { + if (!_consume_utf8 (&op_delete->full_collection_name, &op_delete->full_collection_name_len, ptr, remaining_bytes)) { return false; } @@ -818,8 +757,7 @@ _consume_op_delete (mcd_rpc_message *rpc, op_delete->selector = *ptr; int32_t num_parsed = 0; - if (!_consume_bson_objects (ptr, remaining_bytes, &num_parsed, 1) || - num_parsed != 1) { + if (!_consume_bson_objects (ptr, remaining_bytes, &num_parsed, 1) || num_parsed != 1) { return false; } @@ -828,9 +766,7 @@ _consume_op_delete (mcd_rpc_message *rpc, static bool -_consume_op_kill_cursors (mcd_rpc_message *rpc, - const uint8_t **ptr, - size_t *remaining_bytes) +_consume_op_kill_cursors (mcd_rpc_message *rpc, const uint8_t **ptr, size_t *remaining_bytes) { BSON_ASSERT_PARAM (rpc); BSON_ASSERT_PARAM (ptr); @@ -842,31 +778,27 @@ _consume_op_kill_cursors (mcd_rpc_message *rpc, return false; } - if (!_consume_int32_t ( - &op_kill_cursors->number_of_cursor_ids, ptr, remaining_bytes)) { + if (!_consume_int32_t (&op_kill_cursors->number_of_cursor_ids, ptr, remaining_bytes)) { return false; } if (op_kill_cursors->number_of_cursor_ids < 0 || // Truncation may (deliberately) leave unparsed bytes that will later // trigger validation failure due to unexpected remaining bytes. - bson_cmp_greater_su (op_kill_cursors->number_of_cursor_ids, - *remaining_bytes / sizeof (int64_t))) { + bson_cmp_greater_su (op_kill_cursors->number_of_cursor_ids, *remaining_bytes / sizeof (int64_t))) { *ptr -= sizeof (int32_t); // Revert so *data_len points to start of // numberOfCursorIds as invalid input. return false; } - const size_t cursor_ids_length = - (size_t) op_kill_cursors->number_of_cursor_ids * sizeof (int64_t); + const size_t cursor_ids_length = (size_t) op_kill_cursors->number_of_cursor_ids * sizeof (int64_t); bson_free (op_kill_cursors->cursor_ids); if (op_kill_cursors->number_of_cursor_ids > 0) { op_kill_cursors->cursor_ids = bson_malloc (cursor_ids_length); for (int32_t i = 0; i < op_kill_cursors->number_of_cursor_ids; ++i) { - if (!_consume_int64_t ( - op_kill_cursors->cursor_ids + i, ptr, remaining_bytes)) { + if (!_consume_int64_t (op_kill_cursors->cursor_ids + i, ptr, remaining_bytes)) { return false; } } @@ -879,9 +811,7 @@ _consume_op_kill_cursors (mcd_rpc_message *rpc, mcd_rpc_message * -mcd_rpc_message_from_data (const void *data, - size_t length, - const void **data_end) +mcd_rpc_message_from_data (const void *data, size_t length, const void **data_end) { BSON_ASSERT_PARAM (data); BSON_ASSERT (data_end || true); @@ -904,10 +834,7 @@ mcd_rpc_message_from_data (const void *data, } bool -mcd_rpc_message_from_data_in_place (mcd_rpc_message *rpc, - const void *data, - size_t length, - const void **data_end) +mcd_rpc_message_from_data_in_place (mcd_rpc_message *rpc, const void *data, size_t length, const void **data_end) { ASSERT_MCD_RPC_ACCESSOR_PRECONDITIONS; BSON_ASSERT_PARAM (data); @@ -919,14 +846,12 @@ mcd_rpc_message_from_data_in_place (mcd_rpc_message *rpc, const uint8_t *ptr = data; - if (!_consume_int32_t ( - &rpc->msg_header.message_length, &ptr, &remaining_bytes)) { + if (!_consume_int32_t (&rpc->msg_header.message_length, &ptr, &remaining_bytes)) { goto fail; } if (rpc->msg_header.message_length < MONGOC_RPC_MINIMUM_MESSAGE_LENGTH || - bson_cmp_greater_su (rpc->msg_header.message_length, - remaining_bytes + sizeof (int32_t))) { + bson_cmp_greater_su (rpc->msg_header.message_length, remaining_bytes + sizeof (int32_t))) { ptr -= sizeof (int32_t); // Revert so *data_end points to start of // messageLength as invalid input. goto fail; @@ -935,13 +860,11 @@ mcd_rpc_message_from_data_in_place (mcd_rpc_message *rpc, // Use reported message length as upper bound. remaining_bytes = (size_t) rpc->msg_header.message_length - sizeof (int32_t); - if (!_consume_int32_t ( - &rpc->msg_header.request_id, &ptr, &remaining_bytes)) { + if (!_consume_int32_t (&rpc->msg_header.request_id, &ptr, &remaining_bytes)) { goto fail; } - if (!_consume_int32_t ( - &rpc->msg_header.response_to, &ptr, &remaining_bytes)) { + if (!_consume_int32_t (&rpc->msg_header.response_to, &ptr, &remaining_bytes)) { goto fail; } @@ -1045,10 +968,7 @@ _append_iovec_reserve_space_for (mongoc_iovec_t **iovecs, } static bool -_append_iovec (mongoc_iovec_t *iovecs, - size_t *capacity, - size_t *count, - mongoc_iovec_t iovec) +_append_iovec (mongoc_iovec_t *iovecs, size_t *capacity, size_t *count, mongoc_iovec_t iovec) { BSON_ASSERT_PARAM (iovecs); BSON_ASSERT_PARAM (capacity); @@ -1069,21 +989,20 @@ _append_iovec (mongoc_iovec_t *iovecs, return true; } -#define MONGOC_RPC_APPEND_IOVEC(type, raw_type, to_le) \ - static bool _append_iovec_##type ( \ - mongoc_iovec_t *iovecs, size_t *capacity, size_t *count, type *value) \ - { \ - raw_type storage; \ - memcpy (&storage, value, sizeof (raw_type)); \ - storage = to_le (storage); \ - memcpy (value, &storage, sizeof (raw_type)); \ - return _append_iovec (iovecs, \ - capacity, \ - count, \ - (mongoc_iovec_t){ \ - .iov_base = (void *) value, \ - .iov_len = sizeof (type), \ - }); \ +#define MONGOC_RPC_APPEND_IOVEC(type, raw_type, to_le) \ + static bool _append_iovec_##type (mongoc_iovec_t *iovecs, size_t *capacity, size_t *count, type *value) \ + { \ + raw_type storage; \ + memcpy (&storage, value, sizeof (raw_type)); \ + storage = to_le (storage); \ + memcpy (value, &storage, sizeof (raw_type)); \ + return _append_iovec (iovecs, \ + capacity, \ + count, \ + (mongoc_iovec_t){ \ + .iov_base = (void *) value, \ + .iov_len = sizeof (type), \ + }); \ } MONGOC_RPC_APPEND_IOVEC (uint8_t, uint8_t, (uint8_t)) @@ -1092,11 +1011,7 @@ MONGOC_RPC_APPEND_IOVEC (uint32_t, uint32_t, BSON_UINT32_TO_LE) MONGOC_RPC_APPEND_IOVEC (int64_t, uint64_t, BSON_UINT64_TO_LE) static bool -_append_iovec_data (mongoc_iovec_t *iovecs, - size_t *capacity, - size_t *count, - const void *data, - size_t length) +_append_iovec_data (mongoc_iovec_t *iovecs, size_t *capacity, size_t *count, const void *data, size_t length) { return _append_iovec (iovecs, capacity, @@ -1108,9 +1023,7 @@ _append_iovec_data (mongoc_iovec_t *iovecs, } static bool -_append_iovec_reserved_zero (mongoc_iovec_t *iovecs, - size_t *capacity, - size_t *count) +_append_iovec_reserved_zero (mongoc_iovec_t *iovecs, size_t *capacity, size_t *count) { static int32_t zero = 0u; @@ -1138,26 +1051,20 @@ _append_iovec_op_compressed (mongoc_iovec_t **iovecs, _append_iovec_reserve_space_for (iovecs, capacity, header_iovecs, 4u); - if (!_append_iovec_int32_t ( - *iovecs, capacity, count, &op_compressed->original_opcode)) { + if (!_append_iovec_int32_t (*iovecs, capacity, count, &op_compressed->original_opcode)) { return false; } - if (!_append_iovec_int32_t ( - *iovecs, capacity, count, &op_compressed->uncompressed_size)) { + if (!_append_iovec_int32_t (*iovecs, capacity, count, &op_compressed->uncompressed_size)) { return false; } - if (!_append_iovec_uint8_t ( - *iovecs, capacity, count, &op_compressed->compressor_id)) { + if (!_append_iovec_uint8_t (*iovecs, capacity, count, &op_compressed->compressor_id)) { return false; } - if (!_append_iovec_data (*iovecs, - capacity, - count, - op_compressed->compressed_message, - op_compressed->compressed_message_len)) { + if (!_append_iovec_data ( + *iovecs, capacity, count, op_compressed->compressed_message, op_compressed->compressed_message_len)) { return false; } @@ -1208,8 +1115,7 @@ _append_iovec_op_msg (mongoc_iovec_t **iovecs, return false; } - _append_iovec_reserve_space_for ( - iovecs, capacity, header_iovecs, 2u + section_iovecs); + _append_iovec_reserve_space_for (iovecs, capacity, header_iovecs, 2u + section_iovecs); if (!_append_iovec_uint32_t (*iovecs, capacity, count, &op_msg->flag_bits)) { return false; @@ -1228,39 +1134,30 @@ _append_iovec_op_msg (mongoc_iovec_t **iovecs, switch (section->kind) { case 0: // Body - if (!_append_iovec_data (*iovecs, - capacity, - count, - section->payload.body.bson, - (size_t) section->payload.body.section_len)) { + if (!_append_iovec_data ( + *iovecs, capacity, count, section->payload.body.bson, (size_t) section->payload.body.section_len)) { return false; } break; case 1: // Document Sequence - if (!_append_iovec_int32_t ( - *iovecs, - capacity, - count, - §ion->payload.document_sequence.section_len)) { + if (!_append_iovec_int32_t (*iovecs, capacity, count, §ion->payload.document_sequence.section_len)) { return false; } - if (!_append_iovec_data ( - *iovecs, - capacity, - count, - section->payload.document_sequence.identifier, - section->payload.document_sequence.identifier_len)) { + if (!_append_iovec_data (*iovecs, + capacity, + count, + section->payload.document_sequence.identifier, + section->payload.document_sequence.identifier_len)) { return false; } - if (!_append_iovec_data ( - *iovecs, - capacity, - count, - section->payload.document_sequence.bson_objects, - section->payload.document_sequence.bson_objects_len)) { + if (!_append_iovec_data (*iovecs, + capacity, + count, + section->payload.document_sequence.bson_objects, + section->payload.document_sequence.bson_objects_len)) { return false; } @@ -1272,8 +1169,7 @@ _append_iovec_op_msg (mongoc_iovec_t **iovecs, } if (op_msg->checksum_set) { - if (!_append_iovec_uint32_t ( - *iovecs, capacity, count, &op_msg->checksum)) { + if (!_append_iovec_uint32_t (*iovecs, capacity, count, &op_msg->checksum)) { return false; } } @@ -1296,32 +1192,24 @@ _append_iovec_op_reply (mongoc_iovec_t **iovecs, _append_iovec_reserve_space_for (iovecs, capacity, header_iovecs, 5u); - if (!_append_iovec_int32_t ( - *iovecs, capacity, count, &op_reply->response_flags)) { + if (!_append_iovec_int32_t (*iovecs, capacity, count, &op_reply->response_flags)) { return false; } - if (!_append_iovec_int64_t ( - *iovecs, capacity, count, &op_reply->cursor_id)) { + if (!_append_iovec_int64_t (*iovecs, capacity, count, &op_reply->cursor_id)) { return false; } - if (!_append_iovec_int32_t ( - *iovecs, capacity, count, &op_reply->starting_from)) { + if (!_append_iovec_int32_t (*iovecs, capacity, count, &op_reply->starting_from)) { return false; } - if (!_append_iovec_int32_t ( - *iovecs, capacity, count, &op_reply->number_returned)) { + if (!_append_iovec_int32_t (*iovecs, capacity, count, &op_reply->number_returned)) { return false; } if (op_reply->number_returned > 0 && - !_append_iovec_data (*iovecs, - capacity, - count, - op_reply->documents, - op_reply->documents_len)) { + !_append_iovec_data (*iovecs, capacity, count, op_reply->documents, op_reply->documents_len)) { return false; } @@ -1347,11 +1235,8 @@ _append_iovec_op_update (mongoc_iovec_t **iovecs, return false; } - if (!_append_iovec_data (*iovecs, - capacity, - count, - op_update->full_collection_name, - op_update->full_collection_name_len)) { + if (!_append_iovec_data ( + *iovecs, capacity, count, op_update->full_collection_name, op_update->full_collection_name_len)) { return false; } @@ -1359,19 +1244,12 @@ _append_iovec_op_update (mongoc_iovec_t **iovecs, return false; } - if (!_append_iovec_data (*iovecs, - capacity, - count, - op_update->selector, - (size_t) _int32_from_le (op_update->selector))) { + if (!_append_iovec_data ( + *iovecs, capacity, count, op_update->selector, (size_t) _int32_from_le (op_update->selector))) { return false; } - if (!_append_iovec_data (*iovecs, - capacity, - count, - op_update->update, - (size_t) _int32_from_le (op_update->update))) { + if (!_append_iovec_data (*iovecs, capacity, count, op_update->update, (size_t) _int32_from_le (op_update->update))) { return false; } @@ -1397,19 +1275,12 @@ _append_iovec_op_insert (mongoc_iovec_t **iovecs, return false; } - if (!_append_iovec_data (*iovecs, - capacity, - count, - op_insert->full_collection_name, - op_insert->full_collection_name_len)) { + if (!_append_iovec_data ( + *iovecs, capacity, count, op_insert->full_collection_name, op_insert->full_collection_name_len)) { return false; } - if (!_append_iovec_data (*iovecs, - capacity, - count, - op_insert->documents, - op_insert->documents_len)) { + if (!_append_iovec_data (*iovecs, capacity, count, op_insert->documents, op_insert->documents_len)) { return false; } @@ -1431,48 +1302,35 @@ _append_iovec_op_query (mongoc_iovec_t **iovecs, BSON_ASSERT_PARAM (header_iovecs); _append_iovec_reserve_space_for ( - iovecs, - capacity, - header_iovecs, - 5u + (size_t) (!!op_query->return_fields_selector)); + iovecs, capacity, header_iovecs, 5u + (size_t) (!!op_query->return_fields_selector)); if (!_append_iovec_int32_t (*iovecs, capacity, count, &op_query->flags)) { return false; } - if (!_append_iovec_data (*iovecs, - capacity, - count, - op_query->full_collection_name, - op_query->full_collection_name_len)) { + if (!_append_iovec_data ( + *iovecs, capacity, count, op_query->full_collection_name, op_query->full_collection_name_len)) { return false; } - if (!_append_iovec_int32_t ( - *iovecs, capacity, count, &op_query->number_to_skip)) { + if (!_append_iovec_int32_t (*iovecs, capacity, count, &op_query->number_to_skip)) { return false; } - if (!_append_iovec_int32_t ( - *iovecs, capacity, count, &op_query->number_to_return)) { + if (!_append_iovec_int32_t (*iovecs, capacity, count, &op_query->number_to_return)) { return false; } - if (!_append_iovec_data (*iovecs, - capacity, - count, - op_query->query, - (size_t) _int32_from_le (op_query->query))) { + if (!_append_iovec_data (*iovecs, capacity, count, op_query->query, (size_t) _int32_from_le (op_query->query))) { return false; } if (op_query->return_fields_selector) { - if (!_append_iovec_data ( - *iovecs, - capacity, - count, - op_query->return_fields_selector, - (size_t) _int32_from_le (op_query->return_fields_selector))) { + if (!_append_iovec_data (*iovecs, + capacity, + count, + op_query->return_fields_selector, + (size_t) _int32_from_le (op_query->return_fields_selector))) { return false; } } @@ -1499,21 +1357,16 @@ _append_iovec_op_get_more (mongoc_iovec_t **iovecs, return false; } - if (!_append_iovec_data (*iovecs, - capacity, - count, - op_get_more->full_collection_name, - op_get_more->full_collection_name_len)) { + if (!_append_iovec_data ( + *iovecs, capacity, count, op_get_more->full_collection_name, op_get_more->full_collection_name_len)) { return false; } - if (!_append_iovec_int32_t ( - *iovecs, capacity, count, &op_get_more->number_to_return)) { + if (!_append_iovec_int32_t (*iovecs, capacity, count, &op_get_more->number_to_return)) { return false; } - if (!_append_iovec_int64_t ( - *iovecs, capacity, count, &op_get_more->cursor_id)) { + if (!_append_iovec_int64_t (*iovecs, capacity, count, &op_get_more->cursor_id)) { return false; } @@ -1539,11 +1392,8 @@ _append_iovec_op_delete (mongoc_iovec_t **iovecs, return false; } - if (!_append_iovec_data (*iovecs, - capacity, - count, - op_delete->full_collection_name, - op_delete->full_collection_name_len)) { + if (!_append_iovec_data ( + *iovecs, capacity, count, op_delete->full_collection_name, op_delete->full_collection_name_len)) { return false; } @@ -1551,11 +1401,8 @@ _append_iovec_op_delete (mongoc_iovec_t **iovecs, return false; } - if (!_append_iovec_data (*iovecs, - capacity, - count, - op_delete->selector, - (size_t) _int32_from_le (op_delete->selector))) { + if (!_append_iovec_data ( + *iovecs, capacity, count, op_delete->selector, (size_t) _int32_from_le (op_delete->selector))) { return false; } @@ -1584,8 +1431,7 @@ _append_iovec_op_kill_cursors (mongoc_iovec_t **iovecs, return false; } - if (!_append_iovec_int32_t ( - *iovecs, capacity, count, &op_kill_cursors->number_of_cursor_ids)) { + if (!_append_iovec_int32_t (*iovecs, capacity, count, &op_kill_cursors->number_of_cursor_ids)) { return false; } @@ -1599,11 +1445,8 @@ _append_iovec_op_kill_cursors (mongoc_iovec_t **iovecs, } if (number_of_cursor_ids > 0 && - !_append_iovec_data (*iovecs, - capacity, - count, - op_kill_cursors->cursor_ids, - (size_t) number_of_cursor_ids * sizeof (int64_t))) { + !_append_iovec_data ( + *iovecs, capacity, count, op_kill_cursors->cursor_ids, (size_t) number_of_cursor_ids * sizeof (int64_t))) { return false; } @@ -1624,14 +1467,10 @@ mcd_rpc_message_to_iovecs (mcd_rpc_message *rpc, size_t *count) size_t capacity = 4u; *count = 0u; - (void) _append_iovec_int32_t ( - header_iovecs, &capacity, count, &rpc->msg_header.message_length); - (void) _append_iovec_int32_t ( - header_iovecs, &capacity, count, &rpc->msg_header.request_id); - (void) _append_iovec_int32_t ( - header_iovecs, &capacity, count, &rpc->msg_header.response_to); - (void) _append_iovec_int32_t ( - header_iovecs, &capacity, count, &rpc->msg_header.op_code); + (void) _append_iovec_int32_t (header_iovecs, &capacity, count, &rpc->msg_header.message_length); + (void) _append_iovec_int32_t (header_iovecs, &capacity, count, &rpc->msg_header.request_id); + (void) _append_iovec_int32_t (header_iovecs, &capacity, count, &rpc->msg_header.response_to); + (void) _append_iovec_int32_t (header_iovecs, &capacity, count, &rpc->msg_header.op_code); mongoc_iovec_t *iovecs = NULL; mongoc_iovec_t *ret = NULL; @@ -1643,65 +1482,56 @@ mcd_rpc_message_to_iovecs (mcd_rpc_message *rpc, size_t *count) switch (op_code) { case MONGOC_OP_CODE_COMPRESSED: - if (!_append_iovec_op_compressed ( - &iovecs, &capacity, count, &rpc->op_compressed, header_iovecs)) { + if (!_append_iovec_op_compressed (&iovecs, &capacity, count, &rpc->op_compressed, header_iovecs)) { goto fail; } break; case MONGOC_OP_CODE_MSG: { - if (!_append_iovec_op_msg ( - &iovecs, &capacity, count, &rpc->op_msg, header_iovecs)) { + if (!_append_iovec_op_msg (&iovecs, &capacity, count, &rpc->op_msg, header_iovecs)) { goto fail; } break; } case MONGOC_OP_CODE_REPLY: - if (!_append_iovec_op_reply ( - &iovecs, &capacity, count, &rpc->op_reply, header_iovecs)) { + if (!_append_iovec_op_reply (&iovecs, &capacity, count, &rpc->op_reply, header_iovecs)) { goto fail; } break; case MONGOC_OP_CODE_UPDATE: - if (!_append_iovec_op_update ( - &iovecs, &capacity, count, &rpc->op_update, header_iovecs)) { + if (!_append_iovec_op_update (&iovecs, &capacity, count, &rpc->op_update, header_iovecs)) { goto fail; } break; case MONGOC_OP_CODE_INSERT: - if (!_append_iovec_op_insert ( - &iovecs, &capacity, count, &rpc->op_insert, header_iovecs)) { + if (!_append_iovec_op_insert (&iovecs, &capacity, count, &rpc->op_insert, header_iovecs)) { goto fail; } break; case MONGOC_OP_CODE_QUERY: - if (!_append_iovec_op_query ( - &iovecs, &capacity, count, &rpc->op_query, header_iovecs)) { + if (!_append_iovec_op_query (&iovecs, &capacity, count, &rpc->op_query, header_iovecs)) { goto fail; } break; case MONGOC_OP_CODE_GET_MORE: - if (!_append_iovec_op_get_more ( - &iovecs, &capacity, count, &rpc->op_get_more, header_iovecs)) { + if (!_append_iovec_op_get_more (&iovecs, &capacity, count, &rpc->op_get_more, header_iovecs)) { goto fail; } break; case MONGOC_OP_CODE_DELETE: - if (!_append_iovec_op_delete ( - &iovecs, &capacity, count, &rpc->op_delete, header_iovecs)) { + if (!_append_iovec_op_delete (&iovecs, &capacity, count, &rpc->op_delete, header_iovecs)) { goto fail; } break; case MONGOC_OP_CODE_KILL_CURSORS: - if (!_append_iovec_op_kill_cursors ( - &iovecs, &capacity, count, &rpc->op_kill_cursors, header_iovecs)) { + if (!_append_iovec_op_kill_cursors (&iovecs, &capacity, count, &rpc->op_kill_cursors, header_iovecs)) { goto fail; } break; @@ -1936,8 +1766,7 @@ mcd_rpc_op_compressed_get_compressed_message_length (const mcd_rpc_message *rpc) } int32_t -mcd_rpc_op_compressed_set_original_opcode (mcd_rpc_message *rpc, - int32_t original_opcode) +mcd_rpc_op_compressed_set_original_opcode (mcd_rpc_message *rpc, int32_t original_opcode) { ASSERT_MCD_RPC_ACCESSOR_PRECONDITIONS; BSON_ASSERT (rpc->msg_header.op_code == MONGOC_OP_CODE_COMPRESSED); @@ -1946,8 +1775,7 @@ mcd_rpc_op_compressed_set_original_opcode (mcd_rpc_message *rpc, } int32_t -mcd_rpc_op_compressed_set_uncompressed_size (mcd_rpc_message *rpc, - int32_t uncompressed_size) +mcd_rpc_op_compressed_set_uncompressed_size (mcd_rpc_message *rpc, int32_t uncompressed_size) { ASSERT_MCD_RPC_ACCESSOR_PRECONDITIONS; BSON_ASSERT (rpc->msg_header.op_code == MONGOC_OP_CODE_COMPRESSED); @@ -1956,8 +1784,7 @@ mcd_rpc_op_compressed_set_uncompressed_size (mcd_rpc_message *rpc, } int32_t -mcd_rpc_op_compressed_set_compressor_id (mcd_rpc_message *rpc, - uint8_t compressor_id) +mcd_rpc_op_compressed_set_compressor_id (mcd_rpc_message *rpc, uint8_t compressor_id) { ASSERT_MCD_RPC_ACCESSOR_PRECONDITIONS; BSON_ASSERT (rpc->msg_header.op_code == MONGOC_OP_CODE_COMPRESSED); @@ -2036,8 +1863,7 @@ mcd_rpc_op_msg_section_get_body (const mcd_rpc_message *rpc, size_t index) } const void * -mcd_rpc_op_msg_section_get_document_sequence (const mcd_rpc_message *rpc, - size_t index) +mcd_rpc_op_msg_section_get_document_sequence (const mcd_rpc_message *rpc, size_t index) { ASSERT_MCD_RPC_ACCESSOR_PRECONDITIONS; BSON_ASSERT (rpc->msg_header.op_code == MONGOC_OP_CODE_MSG); @@ -2049,8 +1875,7 @@ mcd_rpc_op_msg_section_get_document_sequence (const mcd_rpc_message *rpc, } size_t -mcd_rpc_op_msg_section_get_document_sequence_length (const mcd_rpc_message *rpc, - size_t index) +mcd_rpc_op_msg_section_get_document_sequence_length (const mcd_rpc_message *rpc, size_t index) { ASSERT_MCD_RPC_ACCESSOR_PRECONDITIONS; BSON_ASSERT (rpc->msg_header.op_code == MONGOC_OP_CODE_MSG); @@ -2062,9 +1887,7 @@ mcd_rpc_op_msg_section_get_document_sequence_length (const mcd_rpc_message *rpc, } int32_t -mcd_rpc_op_msg_section_set_kind (mcd_rpc_message *rpc, - size_t index, - uint8_t kind) +mcd_rpc_op_msg_section_set_kind (mcd_rpc_message *rpc, size_t index, uint8_t kind) { ASSERT_MCD_RPC_ACCESSOR_PRECONDITIONS; BSON_ASSERT (rpc->msg_header.op_code == MONGOC_OP_CODE_MSG); @@ -2074,9 +1897,7 @@ mcd_rpc_op_msg_section_set_kind (mcd_rpc_message *rpc, } int32_t -mcd_rpc_op_msg_section_set_length (mcd_rpc_message *rpc, - size_t index, - int32_t length) +mcd_rpc_op_msg_section_set_length (mcd_rpc_message *rpc, size_t index, int32_t length) { ASSERT_MCD_RPC_ACCESSOR_PRECONDITIONS; BSON_ASSERT (rpc->msg_header.op_code == MONGOC_OP_CODE_MSG); @@ -2087,9 +1908,7 @@ mcd_rpc_op_msg_section_set_length (mcd_rpc_message *rpc, } int32_t -mcd_rpc_op_msg_section_set_identifier (mcd_rpc_message *rpc, - size_t index, - const char *identifier) +mcd_rpc_op_msg_section_set_identifier (mcd_rpc_message *rpc, size_t index, const char *identifier) { ASSERT_MCD_RPC_ACCESSOR_PRECONDITIONS; BSON_ASSERT (rpc->msg_header.op_code == MONGOC_OP_CODE_MSG); @@ -2098,19 +1917,15 @@ mcd_rpc_op_msg_section_set_identifier (mcd_rpc_message *rpc, const size_t identifier_len = identifier ? strlen (identifier) + 1u : 0u; - rpc->op_msg.sections[index].payload.document_sequence.identifier = - identifier; - rpc->op_msg.sections[index].payload.document_sequence.identifier_len = - identifier_len; + rpc->op_msg.sections[index].payload.document_sequence.identifier = identifier; + rpc->op_msg.sections[index].payload.document_sequence.identifier_len = identifier_len; BSON_ASSERT (bson_in_range_unsigned (int32_t, identifier_len)); return (int32_t) identifier_len; } int32_t -mcd_rpc_op_msg_section_set_body (mcd_rpc_message *rpc, - size_t index, - const void *body) +mcd_rpc_op_msg_section_set_body (mcd_rpc_message *rpc, size_t index, const void *body) { ASSERT_MCD_RPC_ACCESSOR_PRECONDITIONS; BSON_ASSERT (rpc->msg_header.op_code == MONGOC_OP_CODE_MSG); @@ -2136,13 +1951,10 @@ mcd_rpc_op_msg_section_set_document_sequence (mcd_rpc_message *rpc, BSON_ASSERT (index < rpc->op_msg.sections_count); BSON_ASSERT (rpc->op_msg.sections[index].kind == 1); - const size_t bson_objects_len = - document_sequence ? document_sequence_length : 0u; + const size_t bson_objects_len = document_sequence ? document_sequence_length : 0u; - rpc->op_msg.sections[index].payload.document_sequence.bson_objects = - document_sequence; - rpc->op_msg.sections[index].payload.document_sequence.bson_objects_len = - bson_objects_len; + rpc->op_msg.sections[index].payload.document_sequence.bson_objects = document_sequence; + rpc->op_msg.sections[index].payload.document_sequence.bson_objects_len = bson_objects_len; BSON_ASSERT (bson_in_range_unsigned (int32_t, document_sequence_length)); return (int32_t) bson_objects_len; @@ -2188,8 +2000,7 @@ mcd_rpc_op_msg_set_sections_count (mcd_rpc_message *rpc, size_t section_count) ASSERT_MCD_RPC_ACCESSOR_PRECONDITIONS; BSON_ASSERT (rpc->msg_header.op_code == MONGOC_OP_CODE_MSG); - rpc->op_msg.sections = bson_realloc ( - rpc->op_msg.sections, section_count * sizeof (mcd_rpc_op_msg_section)); + rpc->op_msg.sections = bson_realloc (rpc->op_msg.sections, section_count * sizeof (mcd_rpc_op_msg_section)); rpc->op_msg.sections_count = section_count; } @@ -2253,8 +2064,7 @@ mcd_rpc_op_reply_get_documents_len (const mcd_rpc_message *rpc) } int32_t -mcd_rpc_op_reply_set_response_flags (mcd_rpc_message *rpc, - int32_t response_flags) +mcd_rpc_op_reply_set_response_flags (mcd_rpc_message *rpc, int32_t response_flags) { ASSERT_MCD_RPC_ACCESSOR_PRECONDITIONS; rpc->op_reply.response_flags = response_flags; @@ -2278,8 +2088,7 @@ mcd_rpc_op_reply_set_starting_from (mcd_rpc_message *rpc, int32_t starting_from) } int32_t -mcd_rpc_op_reply_set_number_returned (mcd_rpc_message *rpc, - int32_t number_returned) +mcd_rpc_op_reply_set_number_returned (mcd_rpc_message *rpc, int32_t number_returned) { ASSERT_MCD_RPC_ACCESSOR_PRECONDITIONS; rpc->op_reply.number_returned = number_returned; @@ -2287,9 +2096,7 @@ mcd_rpc_op_reply_set_number_returned (mcd_rpc_message *rpc, } int32_t -mcd_rpc_op_reply_set_documents (mcd_rpc_message *rpc, - const void *documents, - size_t documents_len) +mcd_rpc_op_reply_set_documents (mcd_rpc_message *rpc, const void *documents, size_t documents_len) { ASSERT_MCD_RPC_ACCESSOR_PRECONDITIONS; @@ -2334,13 +2141,11 @@ mcd_rpc_op_update_get_update (const mcd_rpc_message *rpc) } int32_t -mcd_rpc_op_update_set_full_collection_name (mcd_rpc_message *rpc, - const char *full_collection_name) +mcd_rpc_op_update_set_full_collection_name (mcd_rpc_message *rpc, const char *full_collection_name) { ASSERT_MCD_RPC_ACCESSOR_PRECONDITIONS; - const size_t length = - full_collection_name ? strlen (full_collection_name) + 1u : 0u; + const size_t length = full_collection_name ? strlen (full_collection_name) + 1u : 0u; BSON_ASSERT (rpc->msg_header.op_code == MONGOC_OP_CODE_UPDATE); rpc->op_update.full_collection_name = full_collection_name; @@ -2417,14 +2222,12 @@ mcd_rpc_op_insert_set_flags (mcd_rpc_message *rpc, int32_t flags) } int32_t -mcd_rpc_op_insert_set_full_collection_name (mcd_rpc_message *rpc, - const char *full_collection_name) +mcd_rpc_op_insert_set_full_collection_name (mcd_rpc_message *rpc, const char *full_collection_name) { ASSERT_MCD_RPC_ACCESSOR_PRECONDITIONS; BSON_ASSERT (rpc->msg_header.op_code == MONGOC_OP_CODE_INSERT); - const size_t length = - full_collection_name ? strlen (full_collection_name) + 1u : 0u; + const size_t length = full_collection_name ? strlen (full_collection_name) + 1u : 0u; rpc->op_insert.full_collection_name = full_collection_name; rpc->op_insert.full_collection_name_len = length; @@ -2434,9 +2237,7 @@ mcd_rpc_op_insert_set_full_collection_name (mcd_rpc_message *rpc, } int32_t -mcd_rpc_op_insert_set_documents (mcd_rpc_message *rpc, - const void *documents, - size_t documents_len) +mcd_rpc_op_insert_set_documents (mcd_rpc_message *rpc, const void *documents, size_t documents_len) { ASSERT_MCD_RPC_ACCESSOR_PRECONDITIONS; BSON_ASSERT (rpc->msg_header.op_code == MONGOC_OP_CODE_INSERT); @@ -2507,14 +2308,12 @@ mcd_rpc_op_query_set_flags (mcd_rpc_message *rpc, int32_t flags) } int32_t -mcd_rpc_op_query_set_full_collection_name (mcd_rpc_message *rpc, - const char *full_collection_name) +mcd_rpc_op_query_set_full_collection_name (mcd_rpc_message *rpc, const char *full_collection_name) { ASSERT_MCD_RPC_ACCESSOR_PRECONDITIONS; BSON_ASSERT (rpc->msg_header.op_code == MONGOC_OP_CODE_QUERY); - const size_t length = - full_collection_name ? strlen (full_collection_name) + 1u : 0u; + const size_t length = full_collection_name ? strlen (full_collection_name) + 1u : 0u; rpc->op_query.full_collection_name = full_collection_name; rpc->op_query.full_collection_name_len = length; @@ -2524,8 +2323,7 @@ mcd_rpc_op_query_set_full_collection_name (mcd_rpc_message *rpc, } int32_t -mcd_rpc_op_query_set_number_to_skip (mcd_rpc_message *rpc, - int32_t number_to_skip) +mcd_rpc_op_query_set_number_to_skip (mcd_rpc_message *rpc, int32_t number_to_skip) { ASSERT_MCD_RPC_ACCESSOR_PRECONDITIONS; BSON_ASSERT (rpc->msg_header.op_code == MONGOC_OP_CODE_QUERY); @@ -2534,8 +2332,7 @@ mcd_rpc_op_query_set_number_to_skip (mcd_rpc_message *rpc, } int32_t -mcd_rpc_op_query_set_number_to_return (mcd_rpc_message *rpc, - int32_t number_to_return) +mcd_rpc_op_query_set_number_to_return (mcd_rpc_message *rpc, int32_t number_to_return) { ASSERT_MCD_RPC_ACCESSOR_PRECONDITIONS; BSON_ASSERT (rpc->msg_header.op_code == MONGOC_OP_CODE_QUERY); @@ -2553,8 +2350,7 @@ mcd_rpc_op_query_set_query (mcd_rpc_message *rpc, const void *query) } int32_t -mcd_rpc_op_query_set_return_fields_selector (mcd_rpc_message *rpc, - const void *return_fields_selector) +mcd_rpc_op_query_set_return_fields_selector (mcd_rpc_message *rpc, const void *return_fields_selector) { ASSERT_MCD_RPC_ACCESSOR_PRECONDITIONS; BSON_ASSERT (rpc->msg_header.op_code == MONGOC_OP_CODE_QUERY); @@ -2588,14 +2384,12 @@ mcd_rpc_op_get_more_get_cursor_id (const mcd_rpc_message *rpc) } int32_t -mcd_rpc_op_get_more_set_full_collection_name (mcd_rpc_message *rpc, - const char *full_collection_name) +mcd_rpc_op_get_more_set_full_collection_name (mcd_rpc_message *rpc, const char *full_collection_name) { ASSERT_MCD_RPC_ACCESSOR_PRECONDITIONS; BSON_ASSERT (rpc->msg_header.op_code == MONGOC_OP_CODE_GET_MORE); - const size_t length = - full_collection_name ? strlen (full_collection_name) + 1u : 0u; + const size_t length = full_collection_name ? strlen (full_collection_name) + 1u : 0u; rpc->op_get_more.full_collection_name = full_collection_name; rpc->op_get_more.full_collection_name_len = length; @@ -2605,8 +2399,7 @@ mcd_rpc_op_get_more_set_full_collection_name (mcd_rpc_message *rpc, } int32_t -mcd_rpc_op_get_more_set_number_to_return (mcd_rpc_message *rpc, - int32_t number_to_return) +mcd_rpc_op_get_more_set_number_to_return (mcd_rpc_message *rpc, int32_t number_to_return) { ASSERT_MCD_RPC_ACCESSOR_PRECONDITIONS; BSON_ASSERT (rpc->msg_header.op_code == MONGOC_OP_CODE_GET_MORE); @@ -2649,14 +2442,12 @@ mcd_rpc_op_delete_get_selector (const mcd_rpc_message *rpc) } int32_t -mcd_rpc_op_delete_set_full_collection_name (mcd_rpc_message *rpc, - const char *full_collection_name) +mcd_rpc_op_delete_set_full_collection_name (mcd_rpc_message *rpc, const char *full_collection_name) { ASSERT_MCD_RPC_ACCESSOR_PRECONDITIONS; BSON_ASSERT (rpc->msg_header.op_code == MONGOC_OP_CODE_DELETE); - const size_t length = - full_collection_name ? strlen (full_collection_name) + 1u : 0u; + const size_t length = full_collection_name ? strlen (full_collection_name) + 1u : 0u; rpc->op_delete.full_collection_name = full_collection_name; rpc->op_delete.full_collection_name_len = length; @@ -2697,23 +2488,17 @@ mcd_rpc_op_kill_cursors_get_cursor_ids (const mcd_rpc_message *rpc) { ASSERT_MCD_RPC_ACCESSOR_PRECONDITIONS; BSON_ASSERT (rpc->msg_header.op_code == MONGOC_OP_CODE_KILL_CURSORS); - return rpc->op_kill_cursors.number_of_cursor_ids > 0 - ? rpc->op_kill_cursors.cursor_ids - : NULL; + return rpc->op_kill_cursors.number_of_cursor_ids > 0 ? rpc->op_kill_cursors.cursor_ids : NULL; } int32_t -mcd_rpc_op_kill_cursors_set_cursor_ids (mcd_rpc_message *rpc, - const int64_t *cursor_ids, - int32_t number_of_cursor_ids) +mcd_rpc_op_kill_cursors_set_cursor_ids (mcd_rpc_message *rpc, const int64_t *cursor_ids, int32_t number_of_cursor_ids) { ASSERT_MCD_RPC_ACCESSOR_PRECONDITIONS; BSON_ASSERT (rpc->msg_header.op_code == MONGOC_OP_CODE_KILL_CURSORS); - BSON_ASSERT (bson_cmp_less_su (number_of_cursor_ids, - (size_t) INT32_MAX / sizeof (int64_t))); + BSON_ASSERT (bson_cmp_less_su (number_of_cursor_ids, (size_t) INT32_MAX / sizeof (int64_t))); - const size_t cursor_ids_length = - (size_t) number_of_cursor_ids * sizeof (int64_t); + const size_t cursor_ids_length = (size_t) number_of_cursor_ids * sizeof (int64_t); rpc->op_kill_cursors.number_of_cursor_ids = number_of_cursor_ids; diff --git a/src/libmongoc/src/mongoc/mcd-rpc.h b/src/libmongoc/src/mongoc/mcd-rpc.h index ba66ea7a45..fd59145daf 100644 --- a/src/libmongoc/src/mongoc/mcd-rpc.h +++ b/src/libmongoc/src/mongoc/mcd-rpc.h @@ -93,9 +93,7 @@ typedef union _mcd_rpc_message mcd_rpc_message; // // Returns the new RPC message object on success. Returns `NULL` on failure. mcd_rpc_message * -mcd_rpc_message_from_data (const void *data, - size_t length, - const void **data_end); +mcd_rpc_message_from_data (const void *data, size_t length, const void **data_end); // The in-place version of `mcd_rpc_message_from_data`. // @@ -103,10 +101,7 @@ mcd_rpc_message_from_data (const void *data, // // Returns `true` on success. Returns `false` on failure. bool -mcd_rpc_message_from_data_in_place (mcd_rpc_message *rpc, - const void *data, - size_t length, - const void **data_end); +mcd_rpc_message_from_data_in_place (mcd_rpc_message *rpc, const void *data, size_t length, const void **data_end); // Convert the given RPC message object into an array of iovec structures, // putting the RPC message object in an iovecs state. The return value must be @@ -168,8 +163,7 @@ mcd_rpc_header_get_op_code (const mcd_rpc_message *rpc); // // Returns the length of the field as part of msgHeader.messageLength. int32_t -mcd_rpc_header_set_message_length (mcd_rpc_message *rpc, - int32_t message_length); +mcd_rpc_header_set_message_length (mcd_rpc_message *rpc, int32_t message_length); // Set the msgHeader.requestId field. // @@ -222,29 +216,25 @@ mcd_rpc_op_compressed_get_compressed_message (const mcd_rpc_message *rpc); // // The msgHeader.opCode field MUST equal MONGOC_OP_CODE_COMPRESSED. size_t -mcd_rpc_op_compressed_get_compressed_message_length ( - const mcd_rpc_message *rpc); +mcd_rpc_op_compressed_get_compressed_message_length (const mcd_rpc_message *rpc); // Set the OP_COMPRESSED originalOpcode field. // // The msgHeader.opCode field MUST equal MONGOC_OP_CODE_COMPRESSED. int32_t -mcd_rpc_op_compressed_set_original_opcode (mcd_rpc_message *rpc, - int32_t original_opcode); +mcd_rpc_op_compressed_set_original_opcode (mcd_rpc_message *rpc, int32_t original_opcode); // Set the OP_COMPRESSED uncompressedSize field. // // The msgHeader.opCode field MUST equal MONGOC_OP_CODE_COMPRESSED. int32_t -mcd_rpc_op_compressed_set_uncompressed_size (mcd_rpc_message *rpc, - int32_t uncompressed_size); +mcd_rpc_op_compressed_set_uncompressed_size (mcd_rpc_message *rpc, int32_t uncompressed_size); // Set the OP_COMPRESSED compressorId field. // // The msgHeader.opCode field MUST equal MONGOC_OP_CODE_COMPRESSED. int32_t -mcd_rpc_op_compressed_set_compressor_id (mcd_rpc_message *rpc, - uint8_t compressor_id); +mcd_rpc_op_compressed_set_compressor_id (mcd_rpc_message *rpc, uint8_t compressor_id); // Set the OP_COMPRESSED compressedMessage field. // @@ -279,8 +269,7 @@ mcd_rpc_op_msg_section_get_length (const mcd_rpc_message *rpc, size_t index); // The given index MUST be a valid index into the OP_MSG sections array. // The section kind at the given index MUST equal 1. const char * -mcd_rpc_op_msg_section_get_identifier (const mcd_rpc_message *rpc, - size_t index); +mcd_rpc_op_msg_section_get_identifier (const mcd_rpc_message *rpc, size_t index); // Get a pointer to the beginning of the single BSON object of the OP_MSG body // section at the given index. @@ -298,8 +287,7 @@ mcd_rpc_op_msg_section_get_body (const mcd_rpc_message *rpc, size_t index); // The given index MUST be a valid index into the OP_MSG sections array. // The section kind at the given index MUST equal 1. const void * -mcd_rpc_op_msg_section_get_document_sequence (const mcd_rpc_message *rpc, - size_t index); +mcd_rpc_op_msg_section_get_document_sequence (const mcd_rpc_message *rpc, size_t index); // Get the length of the document sequence of the OP_MSG document sequence // section at the given index. @@ -310,17 +298,14 @@ mcd_rpc_op_msg_section_get_document_sequence (const mcd_rpc_message *rpc, // The given index MUST be a valid index into the OP_MSG sections array. // The section kind at the given index MUST equal 1. size_t -mcd_rpc_op_msg_section_get_document_sequence_length (const mcd_rpc_message *rpc, - size_t index); +mcd_rpc_op_msg_section_get_document_sequence_length (const mcd_rpc_message *rpc, size_t index); // Set the kind byte for the OP_MSG section at the given index. // // The msgHeader.opCode field MUST equal MONGOC_OP_CODE_MSG. // The given index MUST be a valid index into the OP_MSG sections array. int32_t -mcd_rpc_op_msg_section_set_kind (mcd_rpc_message *rpc, - size_t index, - uint8_t kind); +mcd_rpc_op_msg_section_set_kind (mcd_rpc_message *rpc, size_t index, uint8_t kind); // Set the length of the OP_MSG document sequence section at the given index. // @@ -331,9 +316,7 @@ mcd_rpc_op_msg_section_set_kind (mcd_rpc_message *rpc, // The given index MUST be a valid index into the OP_MSG sections array. // The section kind at the given index MUST equal 1. int32_t -mcd_rpc_op_msg_section_set_length (mcd_rpc_message *rpc, - size_t index, - int32_t length); +mcd_rpc_op_msg_section_set_length (mcd_rpc_message *rpc, size_t index, int32_t length); // Set the document sequence identifier of the OP_MSG document sequence section // at the given index. @@ -342,9 +325,7 @@ mcd_rpc_op_msg_section_set_length (mcd_rpc_message *rpc, // The given index MUST be a valid index into the OP_MSG sections array. // The section kind at the given index MUST equal 1. int32_t -mcd_rpc_op_msg_section_set_identifier (mcd_rpc_message *rpc, - size_t index, - const char *identifier); +mcd_rpc_op_msg_section_set_identifier (mcd_rpc_message *rpc, size_t index, const char *identifier); // Set the BSON object for the OP_MSG body section at the given index. // @@ -355,9 +336,7 @@ mcd_rpc_op_msg_section_set_identifier (mcd_rpc_message *rpc, // The given index MUST be a valid index into the OP_MSG sections array. // The section kind at the given index MUST equal 0. int32_t -mcd_rpc_op_msg_section_set_body (mcd_rpc_message *rpc, - size_t index, - const void *body); +mcd_rpc_op_msg_section_set_body (mcd_rpc_message *rpc, size_t index, const void *body); // Set the document sequence for the OP_MSG document sequence section at the // given index. @@ -458,8 +437,7 @@ mcd_rpc_op_reply_get_documents_len (const mcd_rpc_message *rpc); // // The msgHeader.opCode field MUST equal MONGOC_OP_CODE_REPLY. int32_t -mcd_rpc_op_reply_set_response_flags (mcd_rpc_message *rpc, - int32_t response_flags); +mcd_rpc_op_reply_set_response_flags (mcd_rpc_message *rpc, int32_t response_flags); // Set the OP_REPLY cursorID field. // @@ -471,15 +449,13 @@ mcd_rpc_op_reply_set_cursor_id (mcd_rpc_message *rpc, int64_t cursor_id); // // The msgHeader.opCode field MUST equal MONGOC_OP_CODE_REPLY. int32_t -mcd_rpc_op_reply_set_starting_from (mcd_rpc_message *rpc, - int32_t starting_from); +mcd_rpc_op_reply_set_starting_from (mcd_rpc_message *rpc, int32_t starting_from); // Set the OP_REPLY numberReturned field. // // The msgHeader.opCode field MUST equal MONGOC_OP_CODE_REPLY. int32_t -mcd_rpc_op_reply_set_number_returned (mcd_rpc_message *rpc, - int32_t number_returned); +mcd_rpc_op_reply_set_number_returned (mcd_rpc_message *rpc, int32_t number_returned); // Set the OP_REPLY documents field. // @@ -487,9 +463,7 @@ mcd_rpc_op_reply_set_number_returned (mcd_rpc_message *rpc, // // The msgHeader.opCode field MUST equal MONGOC_OP_CODE_REPLY. int32_t -mcd_rpc_op_reply_set_documents (mcd_rpc_message *rpc, - const void *documents, - size_t documents_len); +mcd_rpc_op_reply_set_documents (mcd_rpc_message *rpc, const void *documents, size_t documents_len); // Get the OP_UPDATE fullCollectionName field. @@ -520,8 +494,7 @@ mcd_rpc_op_update_get_update (const mcd_rpc_message *rpc); // // The msgHeader.opCode field MUST equal MONGOC_OP_CODE_UPDATE. int32_t -mcd_rpc_op_update_set_full_collection_name (mcd_rpc_message *rpc, - const char *full_collection_name); +mcd_rpc_op_update_set_full_collection_name (mcd_rpc_message *rpc, const char *full_collection_name); // Set the OP_UPDATE flags field. // @@ -578,8 +551,7 @@ mcd_rpc_op_insert_set_flags (mcd_rpc_message *rpc, int32_t flags); // // The msgHeader.opCode field MUST equal MONGOC_OP_CODE_INSERT. int32_t -mcd_rpc_op_insert_set_full_collection_name (mcd_rpc_message *rpc, - const char *full_collection_name); +mcd_rpc_op_insert_set_full_collection_name (mcd_rpc_message *rpc, const char *full_collection_name); // Set the OP_INSERT documents array. // @@ -587,9 +559,7 @@ mcd_rpc_op_insert_set_full_collection_name (mcd_rpc_message *rpc, // // The msgHeader.opCode field MUST equal MONGOC_OP_CODE_INSERT. int32_t -mcd_rpc_op_insert_set_documents (mcd_rpc_message *rpc, - const void *documents, - size_t documents_len); +mcd_rpc_op_insert_set_documents (mcd_rpc_message *rpc, const void *documents, size_t documents_len); // Get the OP_QUERY flags field. @@ -640,22 +610,19 @@ mcd_rpc_op_query_set_flags (mcd_rpc_message *rpc, int32_t flags); // // The msgHeader.opCode field MUST equal MONGOC_OP_CODE_QUERY. int32_t -mcd_rpc_op_query_set_full_collection_name (mcd_rpc_message *rpc, - const char *full_collection_name); +mcd_rpc_op_query_set_full_collection_name (mcd_rpc_message *rpc, const char *full_collection_name); // Set the OP_QUERY numberToSkip field. // // The msgHeader.opCode field MUST equal MONGOC_OP_CODE_QUERY. int32_t -mcd_rpc_op_query_set_number_to_skip (mcd_rpc_message *rpc, - int32_t number_to_skip); +mcd_rpc_op_query_set_number_to_skip (mcd_rpc_message *rpc, int32_t number_to_skip); // Set the OP_QUERY numberToReturn field. // // The msgHeader.opCode field MUST equal MONGOC_OP_CODE_QUERY. int32_t -mcd_rpc_op_query_set_number_to_return (mcd_rpc_message *rpc, - int32_t number_to_return); +mcd_rpc_op_query_set_number_to_return (mcd_rpc_message *rpc, int32_t number_to_return); // Set the OP_QUERY query field. // @@ -669,8 +636,7 @@ mcd_rpc_op_query_set_query (mcd_rpc_message *rpc, const void *query); // // The msgHeader.opCode field MUST equal MONGOC_OP_CODE_QUERY. int32_t -mcd_rpc_op_query_set_return_fields_selector ( - mcd_rpc_message *rpc, const void *return_fields_selector); +mcd_rpc_op_query_set_return_fields_selector (mcd_rpc_message *rpc, const void *return_fields_selector); // Get the OP_GET_MORE fullCollectionName field. @@ -695,15 +661,13 @@ mcd_rpc_op_get_more_get_cursor_id (const mcd_rpc_message *rpc); // // The msgHeader.opCode field MUST equal MONGOC_OP_CODE_GET_MORE. int32_t -mcd_rpc_op_get_more_set_full_collection_name (mcd_rpc_message *rpc, - const char *full_collection_name); +mcd_rpc_op_get_more_set_full_collection_name (mcd_rpc_message *rpc, const char *full_collection_name); // Set the OP_GET_MORE numberToReturn field. // // The msgHeader.opCode field MUST equal MONGOC_OP_CODE_GET_MORE. int32_t -mcd_rpc_op_get_more_set_number_to_return (mcd_rpc_message *rpc, - int32_t number_to_return); +mcd_rpc_op_get_more_set_number_to_return (mcd_rpc_message *rpc, int32_t number_to_return); // Set the OP_GET_MORE cursorID field. // @@ -734,8 +698,7 @@ mcd_rpc_op_delete_get_selector (const mcd_rpc_message *rpc); // // The msgHeader.opCode field MUST equal MONGOC_OP_CODE_DELETE. int32_t -mcd_rpc_op_delete_set_full_collection_name (mcd_rpc_message *rpc, - const char *full_collection_name); +mcd_rpc_op_delete_set_full_collection_name (mcd_rpc_message *rpc, const char *full_collection_name); // Set the OP_DELETE flags field. // @@ -768,9 +731,7 @@ mcd_rpc_op_kill_cursors_get_cursor_ids (const mcd_rpc_message *rpc); // // The msgHeader.opCode field MUST equal MONGOC_OP_CODE_KILL_CURSORS. int32_t -mcd_rpc_op_kill_cursors_set_cursor_ids (mcd_rpc_message *rpc, - const int64_t *cursor_ids, - int32_t number_of_cursor_ids); +mcd_rpc_op_kill_cursors_set_cursor_ids (mcd_rpc_message *rpc, const int64_t *cursor_ids, int32_t number_of_cursor_ids); #ifdef __cplusplus diff --git a/src/libmongoc/src/mongoc/mcd-time.h b/src/libmongoc/src/mongoc/mcd-time.h index 4a1e3f9fc4..81177de0ea 100644 --- a/src/libmongoc/src/mongoc/mcd-time.h +++ b/src/libmongoc/src/mongoc/mcd-time.h @@ -282,8 +282,7 @@ mcd_duration_compare (mcd_duration left, mcd_duration right) static BSON_INLINE mcd_duration mcd_duration_clamp (mcd_duration dur, mcd_duration min, mcd_duration max) { - BSON_ASSERT (mcd_duration_compare (min, max) <= 0 && - "Invalid min-max range given to mcd_duration_clamp()"); + BSON_ASSERT (mcd_duration_compare (min, max) <= 0 && "Invalid min-max range given to mcd_duration_clamp()"); if (mcd_duration_compare (dur, min) < 0) { // The duration is less than the minimum return min; diff --git a/src/libmongoc/src/mongoc/mongoc-aggregate.c b/src/libmongoc/src/mongoc/mongoc-aggregate.c index cb9f778e59..608e383510 100644 --- a/src/libmongoc/src/mongoc/mongoc-aggregate.c +++ b/src/libmongoc/src/mongoc/mongoc-aggregate.c @@ -87,27 +87,23 @@ _has_write_key (bson_iter_t *iter) */ static bool -_make_agg_cmd (const char *ns, - const bson_t *pipeline, - mongoc_aggregate_opts_t *opts, - bson_t *command, - bson_error_t *err) +_make_agg_cmd ( + const char *ns, const bson_t *pipeline, mongoc_aggregate_opts_t *opts, bson_t *command, bson_error_t *err) { const char *const dot = strstr (ns, "."); const char *error = NULL; const char *error_hint = NULL; - bsonBuild ( - *command, - kv ("aggregate", - if (dot, - /* Note: we're not validating that the collection name's length is - one or more characters, as functions such as - mongoc_client_get_collection also do not validate. */ - // If 'ns' contains a dot, insert the string after the dot: - then (cstr (dot + 1)), - // Otherwise just an integer 1: - else (int32 (1))))); + bsonBuild (*command, + kv ("aggregate", + if (dot, + /* Note: we're not validating that the collection name's length is + one or more characters, as functions such as + mongoc_client_get_collection also do not validate. */ + // If 'ns' contains a dot, insert the string after the dot: + then (cstr (dot + 1)), + // Otherwise just an integer 1: + else (int32 (1))))); if ((error = bsonBuildError)) { error_hint = "append-aggregate"; goto fail; @@ -117,14 +113,13 @@ _make_agg_cmd (const char *ns, * The following will allow @pipeline to be either an array of * items for the pipeline, or {"pipeline": [...]}. */ - bsonParse ( - *pipeline, - find (keyWithType ("pipeline", array), - // There is a "pipeline" array in the document - append (*command, kv ("pipeline", iterValue (bsonVisitIter)))), - else ( // We did not find a "pipeline" array. copy the pipeline as - // an array into the command - append (*command, kv ("pipeline", array (insert (*pipeline, true)))))); + bsonParse (*pipeline, + find (keyWithType ("pipeline", array), + // There is a "pipeline" array in the document + append (*command, kv ("pipeline", iterValue (bsonVisitIter)))), + else ( // We did not find a "pipeline" array. copy the pipeline as + // an array into the command + append (*command, kv ("pipeline", array (insert (*pipeline, true)))))); if ((error = bsonParseError)) { error_hint = "append-pipeline"; goto fail; @@ -141,23 +136,20 @@ _make_agg_cmd (const char *ns, find (lastElement, // If it has an "$out" or "$merge" key, it is a // writing aggregate command. - parse (find (key ("$out", "$merge"), - do (has_write_key = true))))))); + parse (find (key ("$out", "$merge"), do (has_write_key = true))))))); if ((error = bsonParseError)) { error_hint = "parse-pipeline"; goto fail; } - bsonBuildAppend ( - *command, - kv ("cursor", - // If batchSize is set, and if we are not a writing command with zero - // batchSize, append 'batchSize' to the cursor, otherwise leave the - // 'cursor' as an empty subdocument. - doc (if (opts->batchSize_is_set && - !(has_write_key && opts->batchSize == 0), - then (kv ("batchSize", int32 (opts->batchSize))))))); + bsonBuildAppend (*command, + kv ("cursor", + // If batchSize is set, and if we are not a writing command with zero + // batchSize, append 'batchSize' to the cursor, otherwise leave the + // 'cursor' as an empty subdocument. + doc (if (opts->batchSize_is_set && !(has_write_key && opts->batchSize == 0), + then (kv ("batchSize", int32 (opts->batchSize))))))); if ((error = bsonBuildError)) { error_hint = "build-cursor"; goto fail; @@ -253,23 +245,16 @@ _mongoc_aggregate (mongoc_client_t *client, bson_concat (&cursor_opts /* destination */, opts /* source */); } - parsed_opts = - _mongoc_aggregate_opts_parse (client, opts, &aggregate_opts, &opts_err); + parsed_opts = _mongoc_aggregate_opts_parse (client, opts, &aggregate_opts, &opts_err); if (parsed_opts) { - created_command = _make_agg_cmd ( - ns, pipeline, &aggregate_opts, &command, &create_cmd_err); + created_command = _make_agg_cmd (ns, pipeline, &aggregate_opts, &command, &create_cmd_err); } else { created_command = false; } - cursor = _mongoc_cursor_cmd_new (client, - ns, - created_command ? &command : NULL, - &cursor_opts, - user_rp, - default_rp, - default_rc); + cursor = _mongoc_cursor_cmd_new ( + client, ns, created_command ? &command : NULL, &cursor_opts, user_rp, default_rp, default_rc); bson_destroy (&command); bson_destroy (&cursor_opts); @@ -294,15 +279,12 @@ _mongoc_aggregate (mongoc_client_t *client, } /* pipeline could be like {pipeline: [{$out: 'test'}]} or [{$out: 'test'}] */ - if (bson_iter_init_find (&iter, pipeline, "pipeline") && - BSON_ITER_HOLDS_ARRAY (&iter) && bson_iter_recurse (&iter, &ar)) { + if (bson_iter_init_find (&iter, pipeline, "pipeline") && BSON_ITER_HOLDS_ARRAY (&iter) && + bson_iter_recurse (&iter, &ar)) { has_write_key = _has_write_key (&ar); } else { if (!bson_iter_init (&iter, pipeline)) { - bson_set_error (&cursor->error, - MONGOC_ERROR_BSON, - MONGOC_ERROR_BSON_INVALID, - "Pipeline is invalid BSON"); + bson_set_error (&cursor->error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "Pipeline is invalid BSON"); GOTO (done); } has_write_key = _has_write_key (&iter); diff --git a/src/libmongoc/src/mongoc/mongoc-apm-private.h b/src/libmongoc/src/mongoc/mongoc-apm-private.h index 2cff6dffd1..66642ad8e4 100644 --- a/src/libmongoc/src/mongoc/mongoc-apm-private.h +++ b/src/libmongoc/src/mongoc/mongoc-apm-private.h @@ -219,8 +219,7 @@ mongoc_apm_command_failed_cleanup (mongoc_apm_command_failed_t *event); * @param body The body of the command request, reply, or failure. */ bool -mongoc_apm_is_sensitive_command_message (const char *command_name, - const bson_t *body); +mongoc_apm_is_sensitive_command_message (const char *command_name, const bson_t *body); BSON_END_DECLS diff --git a/src/libmongoc/src/mongoc/mongoc-apm.c b/src/libmongoc/src/mongoc/mongoc-apm.c index ddde680539..4f13226260 100644 --- a/src/libmongoc/src/mongoc/mongoc-apm.c +++ b/src/libmongoc/src/mongoc/mongoc-apm.c @@ -29,8 +29,7 @@ static bson_oid_t kObjectIdZero = {{0}}; */ static void -append_documents_from_cmd (const mongoc_cmd_t *cmd, - mongoc_apm_command_started_t *event) +append_documents_from_cmd (const mongoc_cmd_t *cmd, mongoc_apm_command_started_t *event) { if (!cmd->payload || !cmd->payload_size) { return; @@ -95,8 +94,7 @@ mongoc_apm_command_started_init (mongoc_apm_command_started_t *event, * events. */ if (bson_has_field (command, "$readPreference")) { - if (bson_iter_init_find (&iter, command, "$query") && - BSON_ITER_HOLDS_DOCUMENT (&iter)) { + if (bson_iter_init_find (&iter, command, "$query") && BSON_ITER_HOLDS_DOCUMENT (&iter)) { bson_iter_document (&iter, &len, &data); event->command = bson_new_from_data (data, len); event->command_owned = true; @@ -158,19 +156,18 @@ mongoc_apm_command_started_init_with_cmd (mongoc_apm_command_started_t *event, bool *is_redacted, /* out */ void *context) { - mongoc_apm_command_started_init ( - event, - cmd->command, - cmd->db_name, - cmd->command_name, - request_id, - cmd->operation_id, - &cmd->server_stream->sd->host, - cmd->server_stream->sd->id, - &cmd->server_stream->sd->service_id, - cmd->server_stream->sd->server_connection_id, - is_redacted, - context); + mongoc_apm_command_started_init (event, + cmd->command, + cmd->db_name, + cmd->command_name, + request_id, + cmd->operation_id, + &cmd->server_stream->sd->host, + cmd->server_stream->sd->id, + &cmd->server_stream->sd->service_id, + cmd->server_stream->sd->server_connection_id, + is_redacted, + context); /* OP_MSG document sequence for insert, update, or delete? */ append_documents_from_cmd (cmd, event); @@ -214,8 +211,7 @@ mongoc_apm_command_succeeded_init (mongoc_apm_command_succeeded_t *event, { BSON_ASSERT (reply); - if (force_redaction || - mongoc_apm_is_sensitive_command_message (command_name, reply)) { + if (force_redaction || mongoc_apm_is_sensitive_command_message (command_name, reply)) { event->reply = bson_copy (reply); event->reply_owned = true; @@ -277,8 +273,7 @@ mongoc_apm_command_failed_init (mongoc_apm_command_failed_t *event, { BSON_ASSERT (reply); - if (force_redaction || - mongoc_apm_is_sensitive_command_message (command_name, reply)) { + if (force_redaction || mongoc_apm_is_sensitive_command_message (command_name, reply)) { event->reply = bson_copy (reply); event->reply_owned = true; @@ -319,40 +314,35 @@ mongoc_apm_command_failed_cleanup (mongoc_apm_command_failed_t *event) /* command-started event fields */ const bson_t * -mongoc_apm_command_started_get_command ( - const mongoc_apm_command_started_t *event) +mongoc_apm_command_started_get_command (const mongoc_apm_command_started_t *event) { return event->command; } const char * -mongoc_apm_command_started_get_database_name ( - const mongoc_apm_command_started_t *event) +mongoc_apm_command_started_get_database_name (const mongoc_apm_command_started_t *event) { return event->database_name; } const char * -mongoc_apm_command_started_get_command_name ( - const mongoc_apm_command_started_t *event) +mongoc_apm_command_started_get_command_name (const mongoc_apm_command_started_t *event) { return event->command_name; } int64_t -mongoc_apm_command_started_get_request_id ( - const mongoc_apm_command_started_t *event) +mongoc_apm_command_started_get_request_id (const mongoc_apm_command_started_t *event) { return event->request_id; } int64_t -mongoc_apm_command_started_get_operation_id ( - const mongoc_apm_command_started_t *event) +mongoc_apm_command_started_get_operation_id (const mongoc_apm_command_started_t *event) { return event->operation_id; } @@ -366,16 +356,14 @@ mongoc_apm_command_started_get_host (const mongoc_apm_command_started_t *event) uint32_t -mongoc_apm_command_started_get_server_id ( - const mongoc_apm_command_started_t *event) +mongoc_apm_command_started_get_server_id (const mongoc_apm_command_started_t *event) { return event->server_id; } const bson_oid_t * -mongoc_apm_command_started_get_service_id ( - const mongoc_apm_command_started_t *event) +mongoc_apm_command_started_get_service_id (const mongoc_apm_command_started_t *event) { if (0 == bson_oid_compare (&event->service_id, &kObjectIdZero)) { /* serviceId is unset. */ @@ -387,16 +375,12 @@ mongoc_apm_command_started_get_service_id ( int32_t -mongoc_apm_command_started_get_server_connection_id ( - const mongoc_apm_command_started_t *event) -{ - if (event->server_connection_id > INT32_MAX || - event->server_connection_id < INT32_MIN) { - MONGOC_WARNING ( - "Server connection ID %" PRId64 - " is outside of int32 range. Returning -1. Use " - "mongoc_apm_command_started_get_server_connection_id_int64.", - event->server_connection_id); +mongoc_apm_command_started_get_server_connection_id (const mongoc_apm_command_started_t *event) +{ + if (event->server_connection_id > INT32_MAX || event->server_connection_id < INT32_MIN) { + MONGOC_WARNING ("Server connection ID %" PRId64 " is outside of int32 range. Returning -1. Use " + "mongoc_apm_command_started_get_server_connection_id_int64.", + event->server_connection_id); return MONGOC_NO_SERVER_CONNECTION_ID; } @@ -405,16 +389,14 @@ mongoc_apm_command_started_get_server_connection_id ( int64_t -mongoc_apm_command_started_get_server_connection_id_int64 ( - const mongoc_apm_command_started_t *event) +mongoc_apm_command_started_get_server_connection_id_int64 (const mongoc_apm_command_started_t *event) { return event->server_connection_id; } void * -mongoc_apm_command_started_get_context ( - const mongoc_apm_command_started_t *event) +mongoc_apm_command_started_get_context (const mongoc_apm_command_started_t *event) { return event->context; } @@ -423,64 +405,56 @@ mongoc_apm_command_started_get_context ( /* command-succeeded event fields */ int64_t -mongoc_apm_command_succeeded_get_duration ( - const mongoc_apm_command_succeeded_t *event) +mongoc_apm_command_succeeded_get_duration (const mongoc_apm_command_succeeded_t *event) { return event->duration; } const bson_t * -mongoc_apm_command_succeeded_get_reply ( - const mongoc_apm_command_succeeded_t *event) +mongoc_apm_command_succeeded_get_reply (const mongoc_apm_command_succeeded_t *event) { return event->reply; } const char * -mongoc_apm_command_succeeded_get_command_name ( - const mongoc_apm_command_succeeded_t *event) +mongoc_apm_command_succeeded_get_command_name (const mongoc_apm_command_succeeded_t *event) { return event->command_name; } int64_t -mongoc_apm_command_succeeded_get_request_id ( - const mongoc_apm_command_succeeded_t *event) +mongoc_apm_command_succeeded_get_request_id (const mongoc_apm_command_succeeded_t *event) { return event->request_id; } int64_t -mongoc_apm_command_succeeded_get_operation_id ( - const mongoc_apm_command_succeeded_t *event) +mongoc_apm_command_succeeded_get_operation_id (const mongoc_apm_command_succeeded_t *event) { return event->operation_id; } const mongoc_host_list_t * -mongoc_apm_command_succeeded_get_host ( - const mongoc_apm_command_succeeded_t *event) +mongoc_apm_command_succeeded_get_host (const mongoc_apm_command_succeeded_t *event) { return event->host; } uint32_t -mongoc_apm_command_succeeded_get_server_id ( - const mongoc_apm_command_succeeded_t *event) +mongoc_apm_command_succeeded_get_server_id (const mongoc_apm_command_succeeded_t *event) { return event->server_id; } const bson_oid_t * -mongoc_apm_command_succeeded_get_service_id ( - const mongoc_apm_command_succeeded_t *event) +mongoc_apm_command_succeeded_get_service_id (const mongoc_apm_command_succeeded_t *event) { if (0 == bson_oid_compare (&event->service_id, &kObjectIdZero)) { /* serviceId is unset. */ @@ -492,16 +466,12 @@ mongoc_apm_command_succeeded_get_service_id ( int32_t -mongoc_apm_command_succeeded_get_server_connection_id ( - const mongoc_apm_command_succeeded_t *event) -{ - if (event->server_connection_id > INT32_MAX || - event->server_connection_id < INT32_MIN) { - MONGOC_WARNING ( - "Server connection ID %" PRId64 - " is outside of int32 range. Returning -1. Use " - "mongoc_apm_command_succeeded_get_server_connection_id_int64.", - event->server_connection_id); +mongoc_apm_command_succeeded_get_server_connection_id (const mongoc_apm_command_succeeded_t *event) +{ + if (event->server_connection_id > INT32_MAX || event->server_connection_id < INT32_MIN) { + MONGOC_WARNING ("Server connection ID %" PRId64 " is outside of int32 range. Returning -1. Use " + "mongoc_apm_command_succeeded_get_server_connection_id_int64.", + event->server_connection_id); return MONGOC_NO_SERVER_CONNECTION_ID; } @@ -510,16 +480,14 @@ mongoc_apm_command_succeeded_get_server_connection_id ( int64_t -mongoc_apm_command_succeeded_get_server_connection_id_int64 ( - const mongoc_apm_command_succeeded_t *event) +mongoc_apm_command_succeeded_get_server_connection_id_int64 (const mongoc_apm_command_succeeded_t *event) { return event->server_connection_id; } void * -mongoc_apm_command_succeeded_get_context ( - const mongoc_apm_command_succeeded_t *event) +mongoc_apm_command_succeeded_get_context (const mongoc_apm_command_succeeded_t *event) { return event->context; } @@ -528,24 +496,21 @@ mongoc_apm_command_succeeded_get_context ( /* command-failed event fields */ int64_t -mongoc_apm_command_failed_get_duration ( - const mongoc_apm_command_failed_t *event) +mongoc_apm_command_failed_get_duration (const mongoc_apm_command_failed_t *event) { return event->duration; } const char * -mongoc_apm_command_failed_get_command_name ( - const mongoc_apm_command_failed_t *event) +mongoc_apm_command_failed_get_command_name (const mongoc_apm_command_failed_t *event) { return event->command_name; } void -mongoc_apm_command_failed_get_error (const mongoc_apm_command_failed_t *event, - bson_error_t *error) +mongoc_apm_command_failed_get_error (const mongoc_apm_command_failed_t *event, bson_error_t *error) { memcpy (error, event->error, sizeof *event->error); } @@ -557,16 +522,14 @@ mongoc_apm_command_failed_get_reply (const mongoc_apm_command_failed_t *event) } int64_t -mongoc_apm_command_failed_get_request_id ( - const mongoc_apm_command_failed_t *event) +mongoc_apm_command_failed_get_request_id (const mongoc_apm_command_failed_t *event) { return event->request_id; } int64_t -mongoc_apm_command_failed_get_operation_id ( - const mongoc_apm_command_failed_t *event) +mongoc_apm_command_failed_get_operation_id (const mongoc_apm_command_failed_t *event) { return event->operation_id; } @@ -580,16 +543,14 @@ mongoc_apm_command_failed_get_host (const mongoc_apm_command_failed_t *event) uint32_t -mongoc_apm_command_failed_get_server_id ( - const mongoc_apm_command_failed_t *event) +mongoc_apm_command_failed_get_server_id (const mongoc_apm_command_failed_t *event) { return event->server_id; } const bson_oid_t * -mongoc_apm_command_failed_get_service_id ( - const mongoc_apm_command_failed_t *event) +mongoc_apm_command_failed_get_service_id (const mongoc_apm_command_failed_t *event) { if (0 == bson_oid_compare (&event->service_id, &kObjectIdZero)) { /* serviceId is unset. */ @@ -601,16 +562,12 @@ mongoc_apm_command_failed_get_service_id ( int32_t -mongoc_apm_command_failed_get_server_connection_id ( - const mongoc_apm_command_failed_t *event) -{ - if (event->server_connection_id > INT32_MAX || - event->server_connection_id < INT32_MIN) { - MONGOC_WARNING ( - "Server connection ID %" PRId64 - " is outside of int32 range. Returning -1. Use " - "mongoc_apm_command_failed_get_server_connection_id_int64.", - event->server_connection_id); +mongoc_apm_command_failed_get_server_connection_id (const mongoc_apm_command_failed_t *event) +{ + if (event->server_connection_id > INT32_MAX || event->server_connection_id < INT32_MIN) { + MONGOC_WARNING ("Server connection ID %" PRId64 " is outside of int32 range. Returning -1. Use " + "mongoc_apm_command_failed_get_server_connection_id_int64.", + event->server_connection_id); return MONGOC_NO_SERVER_CONNECTION_ID; } @@ -619,8 +576,7 @@ mongoc_apm_command_failed_get_server_connection_id ( int64_t -mongoc_apm_command_failed_get_server_connection_id_int64 ( - const mongoc_apm_command_failed_t *event) +mongoc_apm_command_failed_get_server_connection_id_int64 (const mongoc_apm_command_failed_t *event) { return event->server_connection_id; } @@ -643,24 +599,21 @@ mongoc_apm_server_changed_get_host (const mongoc_apm_server_changed_t *event) void -mongoc_apm_server_changed_get_topology_id ( - const mongoc_apm_server_changed_t *event, bson_oid_t *topology_id) +mongoc_apm_server_changed_get_topology_id (const mongoc_apm_server_changed_t *event, bson_oid_t *topology_id) { bson_oid_copy (&event->topology_id, topology_id); } const mongoc_server_description_t * -mongoc_apm_server_changed_get_previous_description ( - const mongoc_apm_server_changed_t *event) +mongoc_apm_server_changed_get_previous_description (const mongoc_apm_server_changed_t *event) { return event->previous_description; } const mongoc_server_description_t * -mongoc_apm_server_changed_get_new_description ( - const mongoc_apm_server_changed_t *event) +mongoc_apm_server_changed_get_new_description (const mongoc_apm_server_changed_t *event) { return event->new_description; } @@ -683,8 +636,7 @@ mongoc_apm_server_opening_get_host (const mongoc_apm_server_opening_t *event) void -mongoc_apm_server_opening_get_topology_id ( - const mongoc_apm_server_opening_t *event, bson_oid_t *topology_id) +mongoc_apm_server_opening_get_topology_id (const mongoc_apm_server_opening_t *event, bson_oid_t *topology_id) { bson_oid_copy (&event->topology_id, topology_id); } @@ -707,8 +659,7 @@ mongoc_apm_server_closed_get_host (const mongoc_apm_server_closed_t *event) void -mongoc_apm_server_closed_get_topology_id ( - const mongoc_apm_server_closed_t *event, bson_oid_t *topology_id) +mongoc_apm_server_closed_get_topology_id (const mongoc_apm_server_closed_t *event, bson_oid_t *topology_id) { bson_oid_copy (&event->topology_id, topology_id); } @@ -724,32 +675,28 @@ mongoc_apm_server_closed_get_context (const mongoc_apm_server_closed_t *event) /* topology-changed event fields */ void -mongoc_apm_topology_changed_get_topology_id ( - const mongoc_apm_topology_changed_t *event, bson_oid_t *topology_id) +mongoc_apm_topology_changed_get_topology_id (const mongoc_apm_topology_changed_t *event, bson_oid_t *topology_id) { bson_oid_copy (&event->topology_id, topology_id); } const mongoc_topology_description_t * -mongoc_apm_topology_changed_get_previous_description ( - const mongoc_apm_topology_changed_t *event) +mongoc_apm_topology_changed_get_previous_description (const mongoc_apm_topology_changed_t *event) { return event->previous_description; } const mongoc_topology_description_t * -mongoc_apm_topology_changed_get_new_description ( - const mongoc_apm_topology_changed_t *event) +mongoc_apm_topology_changed_get_new_description (const mongoc_apm_topology_changed_t *event) { return event->new_description; } void * -mongoc_apm_topology_changed_get_context ( - const mongoc_apm_topology_changed_t *event) +mongoc_apm_topology_changed_get_context (const mongoc_apm_topology_changed_t *event) { return event->context; } @@ -758,16 +705,14 @@ mongoc_apm_topology_changed_get_context ( /* topology-opening event field */ void -mongoc_apm_topology_opening_get_topology_id ( - const mongoc_apm_topology_opening_t *event, bson_oid_t *topology_id) +mongoc_apm_topology_opening_get_topology_id (const mongoc_apm_topology_opening_t *event, bson_oid_t *topology_id) { bson_oid_copy (&event->topology_id, topology_id); } void * -mongoc_apm_topology_opening_get_context ( - const mongoc_apm_topology_opening_t *event) +mongoc_apm_topology_opening_get_context (const mongoc_apm_topology_opening_t *event) { return event->context; } @@ -776,16 +721,14 @@ mongoc_apm_topology_opening_get_context ( /* topology-closed event field */ void -mongoc_apm_topology_closed_get_topology_id ( - const mongoc_apm_topology_closed_t *event, bson_oid_t *topology_id) +mongoc_apm_topology_closed_get_topology_id (const mongoc_apm_topology_closed_t *event, bson_oid_t *topology_id) { bson_oid_copy (&event->topology_id, topology_id); } void * -mongoc_apm_topology_closed_get_context ( - const mongoc_apm_topology_closed_t *event) +mongoc_apm_topology_closed_get_context (const mongoc_apm_topology_closed_t *event) { return event->context; } @@ -794,23 +737,20 @@ mongoc_apm_topology_closed_get_context ( /* heartbeat-started event field */ const mongoc_host_list_t * -mongoc_apm_server_heartbeat_started_get_host ( - const mongoc_apm_server_heartbeat_started_t *event) +mongoc_apm_server_heartbeat_started_get_host (const mongoc_apm_server_heartbeat_started_t *event) { return event->host; } void * -mongoc_apm_server_heartbeat_started_get_context ( - const mongoc_apm_server_heartbeat_started_t *event) +mongoc_apm_server_heartbeat_started_get_context (const mongoc_apm_server_heartbeat_started_t *event) { return event->context; } bool -mongoc_apm_server_heartbeat_started_get_awaited ( - const mongoc_apm_server_heartbeat_started_t *event) +mongoc_apm_server_heartbeat_started_get_awaited (const mongoc_apm_server_heartbeat_started_t *event) { return event->awaited; } @@ -819,39 +759,34 @@ mongoc_apm_server_heartbeat_started_get_awaited ( /* heartbeat-succeeded event fields */ int64_t -mongoc_apm_server_heartbeat_succeeded_get_duration ( - const mongoc_apm_server_heartbeat_succeeded_t *event) +mongoc_apm_server_heartbeat_succeeded_get_duration (const mongoc_apm_server_heartbeat_succeeded_t *event) { return event->duration_usec; } const bson_t * -mongoc_apm_server_heartbeat_succeeded_get_reply ( - const mongoc_apm_server_heartbeat_succeeded_t *event) +mongoc_apm_server_heartbeat_succeeded_get_reply (const mongoc_apm_server_heartbeat_succeeded_t *event) { return event->reply; } const mongoc_host_list_t * -mongoc_apm_server_heartbeat_succeeded_get_host ( - const mongoc_apm_server_heartbeat_succeeded_t *event) +mongoc_apm_server_heartbeat_succeeded_get_host (const mongoc_apm_server_heartbeat_succeeded_t *event) { return event->host; } void * -mongoc_apm_server_heartbeat_succeeded_get_context ( - const mongoc_apm_server_heartbeat_succeeded_t *event) +mongoc_apm_server_heartbeat_succeeded_get_context (const mongoc_apm_server_heartbeat_succeeded_t *event) { return event->context; } bool -mongoc_apm_server_heartbeat_succeeded_get_awaited ( - const mongoc_apm_server_heartbeat_succeeded_t *event) +mongoc_apm_server_heartbeat_succeeded_get_awaited (const mongoc_apm_server_heartbeat_succeeded_t *event) { return event->awaited; } @@ -860,39 +795,34 @@ mongoc_apm_server_heartbeat_succeeded_get_awaited ( /* heartbeat-failed event fields */ int64_t -mongoc_apm_server_heartbeat_failed_get_duration ( - const mongoc_apm_server_heartbeat_failed_t *event) +mongoc_apm_server_heartbeat_failed_get_duration (const mongoc_apm_server_heartbeat_failed_t *event) { return event->duration_usec; } void -mongoc_apm_server_heartbeat_failed_get_error ( - const mongoc_apm_server_heartbeat_failed_t *event, bson_error_t *error) +mongoc_apm_server_heartbeat_failed_get_error (const mongoc_apm_server_heartbeat_failed_t *event, bson_error_t *error) { memcpy (error, event->error, sizeof *event->error); } const mongoc_host_list_t * -mongoc_apm_server_heartbeat_failed_get_host ( - const mongoc_apm_server_heartbeat_failed_t *event) +mongoc_apm_server_heartbeat_failed_get_host (const mongoc_apm_server_heartbeat_failed_t *event) { return event->host; } void * -mongoc_apm_server_heartbeat_failed_get_context ( - const mongoc_apm_server_heartbeat_failed_t *event) +mongoc_apm_server_heartbeat_failed_get_context (const mongoc_apm_server_heartbeat_failed_t *event) { return event->context; } bool -mongoc_apm_server_heartbeat_failed_get_awaited ( - const mongoc_apm_server_heartbeat_failed_t *event) +mongoc_apm_server_heartbeat_failed_get_awaited (const mongoc_apm_server_heartbeat_failed_t *event) { return event->awaited; } @@ -918,98 +848,86 @@ mongoc_apm_callbacks_destroy (mongoc_apm_callbacks_t *callbacks) void -mongoc_apm_set_command_started_cb (mongoc_apm_callbacks_t *callbacks, - mongoc_apm_command_started_cb_t cb) +mongoc_apm_set_command_started_cb (mongoc_apm_callbacks_t *callbacks, mongoc_apm_command_started_cb_t cb) { callbacks->started = cb; } void -mongoc_apm_set_command_succeeded_cb (mongoc_apm_callbacks_t *callbacks, - mongoc_apm_command_succeeded_cb_t cb) +mongoc_apm_set_command_succeeded_cb (mongoc_apm_callbacks_t *callbacks, mongoc_apm_command_succeeded_cb_t cb) { callbacks->succeeded = cb; } void -mongoc_apm_set_command_failed_cb (mongoc_apm_callbacks_t *callbacks, - mongoc_apm_command_failed_cb_t cb) +mongoc_apm_set_command_failed_cb (mongoc_apm_callbacks_t *callbacks, mongoc_apm_command_failed_cb_t cb) { callbacks->failed = cb; } void -mongoc_apm_set_server_changed_cb (mongoc_apm_callbacks_t *callbacks, - mongoc_apm_server_changed_cb_t cb) +mongoc_apm_set_server_changed_cb (mongoc_apm_callbacks_t *callbacks, mongoc_apm_server_changed_cb_t cb) { callbacks->server_changed = cb; } void -mongoc_apm_set_server_opening_cb (mongoc_apm_callbacks_t *callbacks, - mongoc_apm_server_opening_cb_t cb) +mongoc_apm_set_server_opening_cb (mongoc_apm_callbacks_t *callbacks, mongoc_apm_server_opening_cb_t cb) { callbacks->server_opening = cb; } void -mongoc_apm_set_server_closed_cb (mongoc_apm_callbacks_t *callbacks, - mongoc_apm_server_closed_cb_t cb) +mongoc_apm_set_server_closed_cb (mongoc_apm_callbacks_t *callbacks, mongoc_apm_server_closed_cb_t cb) { callbacks->server_closed = cb; } void -mongoc_apm_set_topology_changed_cb (mongoc_apm_callbacks_t *callbacks, - mongoc_apm_topology_changed_cb_t cb) +mongoc_apm_set_topology_changed_cb (mongoc_apm_callbacks_t *callbacks, mongoc_apm_topology_changed_cb_t cb) { callbacks->topology_changed = cb; } void -mongoc_apm_set_topology_opening_cb (mongoc_apm_callbacks_t *callbacks, - mongoc_apm_topology_opening_cb_t cb) +mongoc_apm_set_topology_opening_cb (mongoc_apm_callbacks_t *callbacks, mongoc_apm_topology_opening_cb_t cb) { callbacks->topology_opening = cb; } void -mongoc_apm_set_topology_closed_cb (mongoc_apm_callbacks_t *callbacks, - mongoc_apm_topology_closed_cb_t cb) +mongoc_apm_set_topology_closed_cb (mongoc_apm_callbacks_t *callbacks, mongoc_apm_topology_closed_cb_t cb) { callbacks->topology_closed = cb; } void -mongoc_apm_set_server_heartbeat_started_cb ( - mongoc_apm_callbacks_t *callbacks, - mongoc_apm_server_heartbeat_started_cb_t cb) +mongoc_apm_set_server_heartbeat_started_cb (mongoc_apm_callbacks_t *callbacks, + mongoc_apm_server_heartbeat_started_cb_t cb) { callbacks->server_heartbeat_started = cb; } void -mongoc_apm_set_server_heartbeat_succeeded_cb ( - mongoc_apm_callbacks_t *callbacks, - mongoc_apm_server_heartbeat_succeeded_cb_t cb) +mongoc_apm_set_server_heartbeat_succeeded_cb (mongoc_apm_callbacks_t *callbacks, + mongoc_apm_server_heartbeat_succeeded_cb_t cb) { callbacks->server_heartbeat_succeeded = cb; } void -mongoc_apm_set_server_heartbeat_failed_cb ( - mongoc_apm_callbacks_t *callbacks, - mongoc_apm_server_heartbeat_failed_cb_t cb) +mongoc_apm_set_server_heartbeat_failed_cb (mongoc_apm_callbacks_t *callbacks, + mongoc_apm_server_heartbeat_failed_cb_t cb) { callbacks->server_heartbeat_failed = cb; } @@ -1017,24 +935,18 @@ mongoc_apm_set_server_heartbeat_failed_cb ( static bool _mongoc_apm_is_sensitive_command_name (const char *command_name) { - return 0 == strcasecmp (command_name, "authenticate") || - 0 == strcasecmp (command_name, "saslStart") || - 0 == strcasecmp (command_name, "saslContinue") || - 0 == strcasecmp (command_name, "getnonce") || - 0 == strcasecmp (command_name, "createUser") || - 0 == strcasecmp (command_name, "updateUser") || - 0 == strcasecmp (command_name, "copydbgetnonce") || - 0 == strcasecmp (command_name, "copydbsaslstart") || + return 0 == strcasecmp (command_name, "authenticate") || 0 == strcasecmp (command_name, "saslStart") || + 0 == strcasecmp (command_name, "saslContinue") || 0 == strcasecmp (command_name, "getnonce") || + 0 == strcasecmp (command_name, "createUser") || 0 == strcasecmp (command_name, "updateUser") || + 0 == strcasecmp (command_name, "copydbgetnonce") || 0 == strcasecmp (command_name, "copydbsaslstart") || 0 == strcasecmp (command_name, "copydb"); } static bool -_mongoc_apm_is_sensitive_hello_message (const char *command_name, - const bson_t *body) +_mongoc_apm_is_sensitive_hello_message (const char *command_name, const bson_t *body) { const bool is_hello = - (0 == strcasecmp (command_name, "hello") || - 0 == strcasecmp (command_name, HANDSHAKE_CMD_LEGACY_HELLO)); + (0 == strcasecmp (command_name, "hello") || 0 == strcasecmp (command_name, HANDSHAKE_CMD_LEGACY_HELLO)); if (!is_hello) { return false; @@ -1053,8 +965,7 @@ _mongoc_apm_is_sensitive_hello_message (const char *command_name, } bool -mongoc_apm_is_sensitive_command_message (const char *command_name, - const bson_t *body) +mongoc_apm_is_sensitive_command_message (const char *command_name, const bson_t *body) { BSON_ASSERT (body); diff --git a/src/libmongoc/src/mongoc/mongoc-apm.h b/src/libmongoc/src/mongoc/mongoc-apm.h index 70e3044831..d7e765b8b8 100644 --- a/src/libmongoc/src/mongoc/mongoc-apm.h +++ b/src/libmongoc/src/mongoc/mongoc-apm.h @@ -66,12 +66,9 @@ typedef struct _mongoc_apm_server_closed_t mongoc_apm_server_closed_t; typedef struct _mongoc_apm_topology_changed_t mongoc_apm_topology_changed_t; typedef struct _mongoc_apm_topology_opening_t mongoc_apm_topology_opening_t; typedef struct _mongoc_apm_topology_closed_t mongoc_apm_topology_closed_t; -typedef struct _mongoc_apm_server_heartbeat_started_t - mongoc_apm_server_heartbeat_started_t; -typedef struct _mongoc_apm_server_heartbeat_succeeded_t - mongoc_apm_server_heartbeat_succeeded_t; -typedef struct _mongoc_apm_server_heartbeat_failed_t - mongoc_apm_server_heartbeat_failed_t; +typedef struct _mongoc_apm_server_heartbeat_started_t mongoc_apm_server_heartbeat_started_t; +typedef struct _mongoc_apm_server_heartbeat_succeeded_t mongoc_apm_server_heartbeat_succeeded_t; +typedef struct _mongoc_apm_server_heartbeat_failed_t mongoc_apm_server_heartbeat_failed_t; /* * event field accessors @@ -80,266 +77,192 @@ typedef struct _mongoc_apm_server_heartbeat_failed_t /* command-started event fields */ MONGOC_EXPORT (const bson_t *) -mongoc_apm_command_started_get_command ( - const mongoc_apm_command_started_t *event); +mongoc_apm_command_started_get_command (const mongoc_apm_command_started_t *event); MONGOC_EXPORT (const char *) -mongoc_apm_command_started_get_database_name ( - const mongoc_apm_command_started_t *event); +mongoc_apm_command_started_get_database_name (const mongoc_apm_command_started_t *event); MONGOC_EXPORT (const char *) -mongoc_apm_command_started_get_command_name ( - const mongoc_apm_command_started_t *event); +mongoc_apm_command_started_get_command_name (const mongoc_apm_command_started_t *event); MONGOC_EXPORT (int64_t) -mongoc_apm_command_started_get_request_id ( - const mongoc_apm_command_started_t *event); +mongoc_apm_command_started_get_request_id (const mongoc_apm_command_started_t *event); MONGOC_EXPORT (int64_t) -mongoc_apm_command_started_get_operation_id ( - const mongoc_apm_command_started_t *event); +mongoc_apm_command_started_get_operation_id (const mongoc_apm_command_started_t *event); MONGOC_EXPORT (const mongoc_host_list_t *) mongoc_apm_command_started_get_host (const mongoc_apm_command_started_t *event); MONGOC_EXPORT (uint32_t) -mongoc_apm_command_started_get_server_id ( - const mongoc_apm_command_started_t *event); +mongoc_apm_command_started_get_server_id (const mongoc_apm_command_started_t *event); MONGOC_EXPORT (const bson_oid_t *) -mongoc_apm_command_started_get_service_id ( - const mongoc_apm_command_started_t *event); +mongoc_apm_command_started_get_service_id (const mongoc_apm_command_started_t *event); MONGOC_EXPORT (int32_t) -mongoc_apm_command_started_get_server_connection_id ( - const mongoc_apm_command_started_t *event) - BSON_GNUC_DEPRECATED_FOR ( - "mongoc_apm_command_started_get_server_connection_id_int64"); +mongoc_apm_command_started_get_server_connection_id (const mongoc_apm_command_started_t *event) + BSON_GNUC_DEPRECATED_FOR ("mongoc_apm_command_started_get_server_connection_id_int64"); MONGOC_EXPORT (int64_t) -mongoc_apm_command_started_get_server_connection_id_int64 ( - const mongoc_apm_command_started_t *event); +mongoc_apm_command_started_get_server_connection_id_int64 (const mongoc_apm_command_started_t *event); MONGOC_EXPORT (void *) -mongoc_apm_command_started_get_context ( - const mongoc_apm_command_started_t *event); +mongoc_apm_command_started_get_context (const mongoc_apm_command_started_t *event); /* command-succeeded event fields */ MONGOC_EXPORT (int64_t) -mongoc_apm_command_succeeded_get_duration ( - const mongoc_apm_command_succeeded_t *event); +mongoc_apm_command_succeeded_get_duration (const mongoc_apm_command_succeeded_t *event); MONGOC_EXPORT (const bson_t *) -mongoc_apm_command_succeeded_get_reply ( - const mongoc_apm_command_succeeded_t *event); +mongoc_apm_command_succeeded_get_reply (const mongoc_apm_command_succeeded_t *event); MONGOC_EXPORT (const char *) -mongoc_apm_command_succeeded_get_command_name ( - const mongoc_apm_command_succeeded_t *event); +mongoc_apm_command_succeeded_get_command_name (const mongoc_apm_command_succeeded_t *event); MONGOC_EXPORT (int64_t) -mongoc_apm_command_succeeded_get_request_id ( - const mongoc_apm_command_succeeded_t *event); +mongoc_apm_command_succeeded_get_request_id (const mongoc_apm_command_succeeded_t *event); MONGOC_EXPORT (int64_t) -mongoc_apm_command_succeeded_get_operation_id ( - const mongoc_apm_command_succeeded_t *event); +mongoc_apm_command_succeeded_get_operation_id (const mongoc_apm_command_succeeded_t *event); MONGOC_EXPORT (const mongoc_host_list_t *) -mongoc_apm_command_succeeded_get_host ( - const mongoc_apm_command_succeeded_t *event); +mongoc_apm_command_succeeded_get_host (const mongoc_apm_command_succeeded_t *event); MONGOC_EXPORT (uint32_t) -mongoc_apm_command_succeeded_get_server_id ( - const mongoc_apm_command_succeeded_t *event); +mongoc_apm_command_succeeded_get_server_id (const mongoc_apm_command_succeeded_t *event); MONGOC_EXPORT (const bson_oid_t *) -mongoc_apm_command_succeeded_get_service_id ( - const mongoc_apm_command_succeeded_t *event); +mongoc_apm_command_succeeded_get_service_id (const mongoc_apm_command_succeeded_t *event); MONGOC_EXPORT (int32_t) -mongoc_apm_command_succeeded_get_server_connection_id ( - const mongoc_apm_command_succeeded_t *event) - BSON_GNUC_DEPRECATED_FOR ( - "mongoc_apm_command_succeeded_get_server_connection_id_int64"); +mongoc_apm_command_succeeded_get_server_connection_id (const mongoc_apm_command_succeeded_t *event) + BSON_GNUC_DEPRECATED_FOR ("mongoc_apm_command_succeeded_get_server_connection_id_int64"); MONGOC_EXPORT (int64_t) -mongoc_apm_command_succeeded_get_server_connection_id_int64 ( - const mongoc_apm_command_succeeded_t *event); +mongoc_apm_command_succeeded_get_server_connection_id_int64 (const mongoc_apm_command_succeeded_t *event); MONGOC_EXPORT (void *) -mongoc_apm_command_succeeded_get_context ( - const mongoc_apm_command_succeeded_t *event); +mongoc_apm_command_succeeded_get_context (const mongoc_apm_command_succeeded_t *event); /* command-failed event fields */ MONGOC_EXPORT (int64_t) -mongoc_apm_command_failed_get_duration ( - const mongoc_apm_command_failed_t *event); +mongoc_apm_command_failed_get_duration (const mongoc_apm_command_failed_t *event); MONGOC_EXPORT (const char *) -mongoc_apm_command_failed_get_command_name ( - const mongoc_apm_command_failed_t *event); +mongoc_apm_command_failed_get_command_name (const mongoc_apm_command_failed_t *event); /* retrieve the error by filling out the passed-in "error" struct */ MONGOC_EXPORT (void) -mongoc_apm_command_failed_get_error (const mongoc_apm_command_failed_t *event, - bson_error_t *error); +mongoc_apm_command_failed_get_error (const mongoc_apm_command_failed_t *event, bson_error_t *error); MONGOC_EXPORT (const bson_t *) mongoc_apm_command_failed_get_reply (const mongoc_apm_command_failed_t *event); MONGOC_EXPORT (int64_t) -mongoc_apm_command_failed_get_request_id ( - const mongoc_apm_command_failed_t *event); +mongoc_apm_command_failed_get_request_id (const mongoc_apm_command_failed_t *event); MONGOC_EXPORT (int64_t) -mongoc_apm_command_failed_get_operation_id ( - const mongoc_apm_command_failed_t *event); +mongoc_apm_command_failed_get_operation_id (const mongoc_apm_command_failed_t *event); MONGOC_EXPORT (const mongoc_host_list_t *) mongoc_apm_command_failed_get_host (const mongoc_apm_command_failed_t *event); MONGOC_EXPORT (uint32_t) -mongoc_apm_command_failed_get_server_id ( - const mongoc_apm_command_failed_t *event); +mongoc_apm_command_failed_get_server_id (const mongoc_apm_command_failed_t *event); MONGOC_EXPORT (const bson_oid_t *) -mongoc_apm_command_failed_get_service_id ( - const mongoc_apm_command_failed_t *event); +mongoc_apm_command_failed_get_service_id (const mongoc_apm_command_failed_t *event); MONGOC_EXPORT (int32_t) -mongoc_apm_command_failed_get_server_connection_id ( - const mongoc_apm_command_failed_t *event) - BSON_GNUC_DEPRECATED_FOR ( - "mongoc_apm_command_failed_get_server_connection_id_int64"); +mongoc_apm_command_failed_get_server_connection_id (const mongoc_apm_command_failed_t *event) + BSON_GNUC_DEPRECATED_FOR ("mongoc_apm_command_failed_get_server_connection_id_int64"); MONGOC_EXPORT (int64_t) -mongoc_apm_command_failed_get_server_connection_id_int64 ( - const mongoc_apm_command_failed_t *event); +mongoc_apm_command_failed_get_server_connection_id_int64 (const mongoc_apm_command_failed_t *event); MONGOC_EXPORT (void *) -mongoc_apm_command_failed_get_context ( - const mongoc_apm_command_failed_t *event); +mongoc_apm_command_failed_get_context (const mongoc_apm_command_failed_t *event); /* server-changed event fields */ MONGOC_EXPORT (const mongoc_host_list_t *) mongoc_apm_server_changed_get_host (const mongoc_apm_server_changed_t *event); MONGOC_EXPORT (void) -mongoc_apm_server_changed_get_topology_id ( - const mongoc_apm_server_changed_t *event, bson_oid_t *topology_id); +mongoc_apm_server_changed_get_topology_id (const mongoc_apm_server_changed_t *event, bson_oid_t *topology_id); MONGOC_EXPORT (const mongoc_server_description_t *) -mongoc_apm_server_changed_get_previous_description ( - const mongoc_apm_server_changed_t *event); +mongoc_apm_server_changed_get_previous_description (const mongoc_apm_server_changed_t *event); MONGOC_EXPORT (const mongoc_server_description_t *) -mongoc_apm_server_changed_get_new_description ( - const mongoc_apm_server_changed_t *event); +mongoc_apm_server_changed_get_new_description (const mongoc_apm_server_changed_t *event); MONGOC_EXPORT (void *) -mongoc_apm_server_changed_get_context ( - const mongoc_apm_server_changed_t *event); +mongoc_apm_server_changed_get_context (const mongoc_apm_server_changed_t *event); /* server-opening event fields */ MONGOC_EXPORT (const mongoc_host_list_t *) mongoc_apm_server_opening_get_host (const mongoc_apm_server_opening_t *event); MONGOC_EXPORT (void) -mongoc_apm_server_opening_get_topology_id ( - const mongoc_apm_server_opening_t *event, bson_oid_t *topology_id); +mongoc_apm_server_opening_get_topology_id (const mongoc_apm_server_opening_t *event, bson_oid_t *topology_id); MONGOC_EXPORT (void *) -mongoc_apm_server_opening_get_context ( - const mongoc_apm_server_opening_t *event); +mongoc_apm_server_opening_get_context (const mongoc_apm_server_opening_t *event); /* server-closed event fields */ MONGOC_EXPORT (const mongoc_host_list_t *) mongoc_apm_server_closed_get_host (const mongoc_apm_server_closed_t *event); MONGOC_EXPORT (void) -mongoc_apm_server_closed_get_topology_id ( - const mongoc_apm_server_closed_t *event, bson_oid_t *topology_id); +mongoc_apm_server_closed_get_topology_id (const mongoc_apm_server_closed_t *event, bson_oid_t *topology_id); MONGOC_EXPORT (void *) mongoc_apm_server_closed_get_context (const mongoc_apm_server_closed_t *event); /* topology-changed event fields */ MONGOC_EXPORT (void) -mongoc_apm_topology_changed_get_topology_id ( - const mongoc_apm_topology_changed_t *event, bson_oid_t *topology_id); +mongoc_apm_topology_changed_get_topology_id (const mongoc_apm_topology_changed_t *event, bson_oid_t *topology_id); MONGOC_EXPORT (const mongoc_topology_description_t *) -mongoc_apm_topology_changed_get_previous_description ( - const mongoc_apm_topology_changed_t *event); +mongoc_apm_topology_changed_get_previous_description (const mongoc_apm_topology_changed_t *event); MONGOC_EXPORT (const mongoc_topology_description_t *) -mongoc_apm_topology_changed_get_new_description ( - const mongoc_apm_topology_changed_t *event); +mongoc_apm_topology_changed_get_new_description (const mongoc_apm_topology_changed_t *event); MONGOC_EXPORT (void *) -mongoc_apm_topology_changed_get_context ( - const mongoc_apm_topology_changed_t *event); +mongoc_apm_topology_changed_get_context (const mongoc_apm_topology_changed_t *event); /* topology-opening event field */ MONGOC_EXPORT (void) -mongoc_apm_topology_opening_get_topology_id ( - const mongoc_apm_topology_opening_t *event, bson_oid_t *topology_id); +mongoc_apm_topology_opening_get_topology_id (const mongoc_apm_topology_opening_t *event, bson_oid_t *topology_id); MONGOC_EXPORT (void *) -mongoc_apm_topology_opening_get_context ( - const mongoc_apm_topology_opening_t *event); +mongoc_apm_topology_opening_get_context (const mongoc_apm_topology_opening_t *event); /* topology-closed event field */ MONGOC_EXPORT (void) -mongoc_apm_topology_closed_get_topology_id ( - const mongoc_apm_topology_closed_t *event, bson_oid_t *topology_id); +mongoc_apm_topology_closed_get_topology_id (const mongoc_apm_topology_closed_t *event, bson_oid_t *topology_id); MONGOC_EXPORT (void *) -mongoc_apm_topology_closed_get_context ( - const mongoc_apm_topology_closed_t *event); +mongoc_apm_topology_closed_get_context (const mongoc_apm_topology_closed_t *event); /* heartbeat-started event field */ MONGOC_EXPORT (const mongoc_host_list_t *) -mongoc_apm_server_heartbeat_started_get_host ( - const mongoc_apm_server_heartbeat_started_t *event); +mongoc_apm_server_heartbeat_started_get_host (const mongoc_apm_server_heartbeat_started_t *event); MONGOC_EXPORT (void *) -mongoc_apm_server_heartbeat_started_get_context ( - const mongoc_apm_server_heartbeat_started_t *event); +mongoc_apm_server_heartbeat_started_get_context (const mongoc_apm_server_heartbeat_started_t *event); MONGOC_EXPORT (bool) -mongoc_apm_server_heartbeat_started_get_awaited ( - const mongoc_apm_server_heartbeat_started_t *event); +mongoc_apm_server_heartbeat_started_get_awaited (const mongoc_apm_server_heartbeat_started_t *event); /* heartbeat-succeeded event fields */ MONGOC_EXPORT (int64_t) -mongoc_apm_server_heartbeat_succeeded_get_duration ( - const mongoc_apm_server_heartbeat_succeeded_t *event); +mongoc_apm_server_heartbeat_succeeded_get_duration (const mongoc_apm_server_heartbeat_succeeded_t *event); MONGOC_EXPORT (const bson_t *) -mongoc_apm_server_heartbeat_succeeded_get_reply ( - const mongoc_apm_server_heartbeat_succeeded_t *event); +mongoc_apm_server_heartbeat_succeeded_get_reply (const mongoc_apm_server_heartbeat_succeeded_t *event); MONGOC_EXPORT (const mongoc_host_list_t *) -mongoc_apm_server_heartbeat_succeeded_get_host ( - const mongoc_apm_server_heartbeat_succeeded_t *event); +mongoc_apm_server_heartbeat_succeeded_get_host (const mongoc_apm_server_heartbeat_succeeded_t *event); MONGOC_EXPORT (void *) -mongoc_apm_server_heartbeat_succeeded_get_context ( - const mongoc_apm_server_heartbeat_succeeded_t *event); +mongoc_apm_server_heartbeat_succeeded_get_context (const mongoc_apm_server_heartbeat_succeeded_t *event); MONGOC_EXPORT (bool) -mongoc_apm_server_heartbeat_succeeded_get_awaited ( - const mongoc_apm_server_heartbeat_succeeded_t *event); +mongoc_apm_server_heartbeat_succeeded_get_awaited (const mongoc_apm_server_heartbeat_succeeded_t *event); /* heartbeat-failed event fields */ MONGOC_EXPORT (int64_t) -mongoc_apm_server_heartbeat_failed_get_duration ( - const mongoc_apm_server_heartbeat_failed_t *event); +mongoc_apm_server_heartbeat_failed_get_duration (const mongoc_apm_server_heartbeat_failed_t *event); MONGOC_EXPORT (void) -mongoc_apm_server_heartbeat_failed_get_error ( - const mongoc_apm_server_heartbeat_failed_t *event, bson_error_t *error); +mongoc_apm_server_heartbeat_failed_get_error (const mongoc_apm_server_heartbeat_failed_t *event, bson_error_t *error); MONGOC_EXPORT (const mongoc_host_list_t *) -mongoc_apm_server_heartbeat_failed_get_host ( - const mongoc_apm_server_heartbeat_failed_t *event); +mongoc_apm_server_heartbeat_failed_get_host (const mongoc_apm_server_heartbeat_failed_t *event); MONGOC_EXPORT (void *) -mongoc_apm_server_heartbeat_failed_get_context ( - const mongoc_apm_server_heartbeat_failed_t *event); +mongoc_apm_server_heartbeat_failed_get_context (const mongoc_apm_server_heartbeat_failed_t *event); MONGOC_EXPORT (bool) -mongoc_apm_server_heartbeat_failed_get_awaited ( - const mongoc_apm_server_heartbeat_failed_t *event); +mongoc_apm_server_heartbeat_failed_get_awaited (const mongoc_apm_server_heartbeat_failed_t *event); /* * callbacks */ -typedef void (*mongoc_apm_command_started_cb_t) ( - const mongoc_apm_command_started_t *event); -typedef void (*mongoc_apm_command_succeeded_cb_t) ( - const mongoc_apm_command_succeeded_t *event); -typedef void (*mongoc_apm_command_failed_cb_t) ( - const mongoc_apm_command_failed_t *event); -typedef void (*mongoc_apm_server_changed_cb_t) ( - const mongoc_apm_server_changed_t *event); -typedef void (*mongoc_apm_server_opening_cb_t) ( - const mongoc_apm_server_opening_t *event); -typedef void (*mongoc_apm_server_closed_cb_t) ( - const mongoc_apm_server_closed_t *event); -typedef void (*mongoc_apm_topology_changed_cb_t) ( - const mongoc_apm_topology_changed_t *event); -typedef void (*mongoc_apm_topology_opening_cb_t) ( - const mongoc_apm_topology_opening_t *event); -typedef void (*mongoc_apm_topology_closed_cb_t) ( - const mongoc_apm_topology_closed_t *event); -typedef void (*mongoc_apm_server_heartbeat_started_cb_t) ( - const mongoc_apm_server_heartbeat_started_t *event); -typedef void (*mongoc_apm_server_heartbeat_succeeded_cb_t) ( - const mongoc_apm_server_heartbeat_succeeded_t *event); -typedef void (*mongoc_apm_server_heartbeat_failed_cb_t) ( - const mongoc_apm_server_heartbeat_failed_t *event); +typedef void (*mongoc_apm_command_started_cb_t) (const mongoc_apm_command_started_t *event); +typedef void (*mongoc_apm_command_succeeded_cb_t) (const mongoc_apm_command_succeeded_t *event); +typedef void (*mongoc_apm_command_failed_cb_t) (const mongoc_apm_command_failed_t *event); +typedef void (*mongoc_apm_server_changed_cb_t) (const mongoc_apm_server_changed_t *event); +typedef void (*mongoc_apm_server_opening_cb_t) (const mongoc_apm_server_opening_t *event); +typedef void (*mongoc_apm_server_closed_cb_t) (const mongoc_apm_server_closed_t *event); +typedef void (*mongoc_apm_topology_changed_cb_t) (const mongoc_apm_topology_changed_t *event); +typedef void (*mongoc_apm_topology_opening_cb_t) (const mongoc_apm_topology_opening_t *event); +typedef void (*mongoc_apm_topology_closed_cb_t) (const mongoc_apm_topology_closed_t *event); +typedef void (*mongoc_apm_server_heartbeat_started_cb_t) (const mongoc_apm_server_heartbeat_started_t *event); +typedef void (*mongoc_apm_server_heartbeat_succeeded_cb_t) (const mongoc_apm_server_heartbeat_succeeded_t *event); +typedef void (*mongoc_apm_server_heartbeat_failed_cb_t) (const mongoc_apm_server_heartbeat_failed_t *event); /* * registering callbacks @@ -350,44 +273,32 @@ mongoc_apm_callbacks_new (void) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (void) mongoc_apm_callbacks_destroy (mongoc_apm_callbacks_t *callbacks); MONGOC_EXPORT (void) -mongoc_apm_set_command_started_cb (mongoc_apm_callbacks_t *callbacks, - mongoc_apm_command_started_cb_t cb); +mongoc_apm_set_command_started_cb (mongoc_apm_callbacks_t *callbacks, mongoc_apm_command_started_cb_t cb); MONGOC_EXPORT (void) -mongoc_apm_set_command_succeeded_cb (mongoc_apm_callbacks_t *callbacks, - mongoc_apm_command_succeeded_cb_t cb); +mongoc_apm_set_command_succeeded_cb (mongoc_apm_callbacks_t *callbacks, mongoc_apm_command_succeeded_cb_t cb); MONGOC_EXPORT (void) -mongoc_apm_set_command_failed_cb (mongoc_apm_callbacks_t *callbacks, - mongoc_apm_command_failed_cb_t cb); +mongoc_apm_set_command_failed_cb (mongoc_apm_callbacks_t *callbacks, mongoc_apm_command_failed_cb_t cb); MONGOC_EXPORT (void) -mongoc_apm_set_server_changed_cb (mongoc_apm_callbacks_t *callbacks, - mongoc_apm_server_changed_cb_t cb); +mongoc_apm_set_server_changed_cb (mongoc_apm_callbacks_t *callbacks, mongoc_apm_server_changed_cb_t cb); MONGOC_EXPORT (void) -mongoc_apm_set_server_opening_cb (mongoc_apm_callbacks_t *callbacks, - mongoc_apm_server_opening_cb_t cb); +mongoc_apm_set_server_opening_cb (mongoc_apm_callbacks_t *callbacks, mongoc_apm_server_opening_cb_t cb); MONGOC_EXPORT (void) -mongoc_apm_set_server_closed_cb (mongoc_apm_callbacks_t *callbacks, - mongoc_apm_server_closed_cb_t cb); +mongoc_apm_set_server_closed_cb (mongoc_apm_callbacks_t *callbacks, mongoc_apm_server_closed_cb_t cb); MONGOC_EXPORT (void) -mongoc_apm_set_topology_changed_cb (mongoc_apm_callbacks_t *callbacks, - mongoc_apm_topology_changed_cb_t cb); +mongoc_apm_set_topology_changed_cb (mongoc_apm_callbacks_t *callbacks, mongoc_apm_topology_changed_cb_t cb); MONGOC_EXPORT (void) -mongoc_apm_set_topology_opening_cb (mongoc_apm_callbacks_t *callbacks, - mongoc_apm_topology_opening_cb_t cb); +mongoc_apm_set_topology_opening_cb (mongoc_apm_callbacks_t *callbacks, mongoc_apm_topology_opening_cb_t cb); MONGOC_EXPORT (void) -mongoc_apm_set_topology_closed_cb (mongoc_apm_callbacks_t *callbacks, - mongoc_apm_topology_closed_cb_t cb); +mongoc_apm_set_topology_closed_cb (mongoc_apm_callbacks_t *callbacks, mongoc_apm_topology_closed_cb_t cb); MONGOC_EXPORT (void) -mongoc_apm_set_server_heartbeat_started_cb ( - mongoc_apm_callbacks_t *callbacks, - mongoc_apm_server_heartbeat_started_cb_t cb); +mongoc_apm_set_server_heartbeat_started_cb (mongoc_apm_callbacks_t *callbacks, + mongoc_apm_server_heartbeat_started_cb_t cb); MONGOC_EXPORT (void) -mongoc_apm_set_server_heartbeat_succeeded_cb ( - mongoc_apm_callbacks_t *callbacks, - mongoc_apm_server_heartbeat_succeeded_cb_t cb); +mongoc_apm_set_server_heartbeat_succeeded_cb (mongoc_apm_callbacks_t *callbacks, + mongoc_apm_server_heartbeat_succeeded_cb_t cb); MONGOC_EXPORT (void) -mongoc_apm_set_server_heartbeat_failed_cb ( - mongoc_apm_callbacks_t *callbacks, - mongoc_apm_server_heartbeat_failed_cb_t cb); +mongoc_apm_set_server_heartbeat_failed_cb (mongoc_apm_callbacks_t *callbacks, + mongoc_apm_server_heartbeat_failed_cb_t cb); BSON_END_DECLS #endif /* MONGOC_APM_H */ diff --git a/src/libmongoc/src/mongoc/mongoc-array-private.h b/src/libmongoc/src/mongoc/mongoc-array-private.h index 73b598f1bc..bbc7198c6b 100644 --- a/src/libmongoc/src/mongoc/mongoc-array-private.h +++ b/src/libmongoc/src/mongoc/mongoc-array-private.h @@ -37,25 +37,20 @@ struct _mongoc_array_t { }; -#define mongoc_array_aligned_init(a, Type) \ - _mongoc_array_aligned_init (a, BSON_ALIGNOF (Type), sizeof (Type)) +#define mongoc_array_aligned_init(a, Type) _mongoc_array_aligned_init (a, BSON_ALIGNOF (Type), sizeof (Type)) #define _mongoc_array_append_val(a, v) _mongoc_array_append_vals (a, &v, 1) #define _mongoc_array_index(a, t, i) (((t *) (a)->data)[i]) #define _mongoc_array_clear(a) (a)->len = 0 void -_mongoc_array_aligned_init (mongoc_array_t *array, - size_t element_alignment, - size_t element_size); +_mongoc_array_aligned_init (mongoc_array_t *array, size_t element_alignment, size_t element_size); void _mongoc_array_init (mongoc_array_t *array, size_t element_size); void _mongoc_array_copy (mongoc_array_t *dst, const mongoc_array_t *src); void -_mongoc_array_append_vals (mongoc_array_t *array, - const void *data, - uint32_t n_elements); +_mongoc_array_append_vals (mongoc_array_t *array, const void *data, uint32_t n_elements); void _mongoc_array_destroy (mongoc_array_t *array); diff --git a/src/libmongoc/src/mongoc/mongoc-array.c b/src/libmongoc/src/mongoc/mongoc-array.c index 08543d5249..b714a4f254 100644 --- a/src/libmongoc/src/mongoc/mongoc-array.c +++ b/src/libmongoc/src/mongoc/mongoc-array.c @@ -33,9 +33,7 @@ _mongoc_array_init (mongoc_array_t *array, size_t element_size) void -_mongoc_array_aligned_init (mongoc_array_t *array, - size_t element_alignment, - size_t element_size) +_mongoc_array_aligned_init (mongoc_array_t *array, size_t element_alignment, size_t element_size) { BSON_ASSERT_PARAM (array); BSON_ASSERT (element_alignment > 0); @@ -93,9 +91,7 @@ _mongoc_array_destroy (mongoc_array_t *array) void -_mongoc_array_append_vals (mongoc_array_t *array, - const void *data, - uint32_t n_elements) +_mongoc_array_append_vals (mongoc_array_t *array, const void *data, uint32_t n_elements) { size_t len; size_t off; diff --git a/src/libmongoc/src/mongoc/mongoc-async-cmd-private.h b/src/libmongoc/src/mongoc/mongoc-async-cmd-private.h index ccf58dfb36..25cd892d01 100644 --- a/src/libmongoc/src/mongoc/mongoc-async-cmd-private.h +++ b/src/libmongoc/src/mongoc/mongoc-async-cmd-private.h @@ -97,11 +97,7 @@ mongoc_async_cmd_run (mongoc_async_cmd_t *acmd); #ifdef MONGOC_ENABLE_SSL int -mongoc_async_cmd_tls_setup (mongoc_stream_t *stream, - int *events, - void *ctx, - int32_t timeout_msec, - bson_error_t *error); +mongoc_async_cmd_tls_setup (mongoc_stream_t *stream, int *events, void *ctx, int32_t timeout_msec, bson_error_t *error); #endif BSON_END_DECLS diff --git a/src/libmongoc/src/mongoc/mongoc-async-cmd.c b/src/libmongoc/src/mongoc/mongoc-async-cmd.c index 3ba8996183..56c857c84f 100644 --- a/src/libmongoc/src/mongoc/mongoc-async-cmd.c +++ b/src/libmongoc/src/mongoc/mongoc-async-cmd.c @@ -37,8 +37,7 @@ #undef MONGOC_LOG_DOMAIN #define MONGOC_LOG_DOMAIN "async" -typedef mongoc_async_cmd_result_t (*_mongoc_async_cmd_phase_t) ( - mongoc_async_cmd_t *cmd); +typedef mongoc_async_cmd_result_t (*_mongoc_async_cmd_phase_t) (mongoc_async_cmd_t *cmd); mongoc_async_cmd_result_t _mongoc_async_cmd_phase_initiate (mongoc_async_cmd_t *cmd); @@ -63,11 +62,7 @@ static const _mongoc_async_cmd_phase_t gMongocCMDPhases[] = { #ifdef MONGOC_ENABLE_SSL int -mongoc_async_cmd_tls_setup (mongoc_stream_t *stream, - int *events, - void *ctx, - int32_t timeout_msec, - bson_error_t *error) +mongoc_async_cmd_tls_setup (mongoc_stream_t *stream, int *events, void *ctx, int32_t timeout_msec, bson_error_t *error) { mongoc_stream_t *tls_stream; const char *host = (const char *) ctx; @@ -78,13 +73,11 @@ mongoc_async_cmd_tls_setup (mongoc_stream_t *stream, tls_stream = mongoc_stream_get_base_stream (tls_stream)) { } -#if defined(MONGOC_ENABLE_SSL_OPENSSL) || \ - defined(MONGOC_ENABLE_SSL_SECURE_CHANNEL) +#if defined(MONGOC_ENABLE_SSL_OPENSSL) || defined(MONGOC_ENABLE_SSL_SECURE_CHANNEL) /* pass 0 for the timeout to begin / continue non-blocking handshake */ timeout_msec = 0; #endif - if (mongoc_stream_tls_handshake ( - tls_stream, host, timeout_msec, &retry_events, error)) { + if (mongoc_stream_tls_handshake (tls_stream, host, timeout_msec, &retry_events, error)) { return 1; } @@ -135,38 +128,29 @@ mongoc_async_cmd_run (mongoc_async_cmd_t *acmd) } static void -_mongoc_async_cmd_init_send (const int32_t cmd_opcode, - mongoc_async_cmd_t *acmd, - const char *dbname) +_mongoc_async_cmd_init_send (const int32_t cmd_opcode, mongoc_async_cmd_t *acmd, const char *dbname) { - BSON_ASSERT (cmd_opcode == MONGOC_OP_CODE_QUERY || - cmd_opcode == MONGOC_OP_CODE_MSG); + BSON_ASSERT (cmd_opcode == MONGOC_OP_CODE_QUERY || cmd_opcode == MONGOC_OP_CODE_MSG); int32_t message_length = 0; message_length += mcd_rpc_header_set_message_length (acmd->rpc, 0); - message_length += - mcd_rpc_header_set_request_id (acmd->rpc, ++acmd->async->request_id); + message_length += mcd_rpc_header_set_request_id (acmd->rpc, ++acmd->async->request_id); message_length += mcd_rpc_header_set_response_to (acmd->rpc, 0); message_length += mcd_rpc_header_set_op_code (acmd->rpc, cmd_opcode); if (cmd_opcode == MONGOC_OP_CODE_QUERY) { acmd->ns = bson_strdup_printf ("%s.$cmd", dbname); - message_length += mcd_rpc_op_query_set_flags ( - acmd->rpc, MONGOC_OP_QUERY_FLAG_SECONDARY_OK); - message_length += - mcd_rpc_op_query_set_full_collection_name (acmd->rpc, acmd->ns); + message_length += mcd_rpc_op_query_set_flags (acmd->rpc, MONGOC_OP_QUERY_FLAG_SECONDARY_OK); + message_length += mcd_rpc_op_query_set_full_collection_name (acmd->rpc, acmd->ns); message_length += mcd_rpc_op_query_set_number_to_skip (acmd->rpc, 0); message_length += mcd_rpc_op_query_set_number_to_return (acmd->rpc, -1); - message_length += - mcd_rpc_op_query_set_query (acmd->rpc, bson_get_data (&acmd->cmd)); + message_length += mcd_rpc_op_query_set_query (acmd->rpc, bson_get_data (&acmd->cmd)); } else { mcd_rpc_op_msg_set_sections_count (acmd->rpc, 1u); - message_length += - mcd_rpc_op_msg_set_flag_bits (acmd->rpc, MONGOC_OP_MSG_FLAG_NONE); + message_length += mcd_rpc_op_msg_set_flag_bits (acmd->rpc, MONGOC_OP_MSG_FLAG_NONE); message_length += mcd_rpc_op_msg_section_set_kind (acmd->rpc, 0u, 0); - message_length += mcd_rpc_op_msg_section_set_body ( - acmd->rpc, 0u, bson_get_data (&acmd->cmd)); + message_length += mcd_rpc_op_msg_section_set_body (acmd->rpc, 0u, bson_get_data (&acmd->cmd)); } mcd_rpc_message_set_length (acmd->rpc, message_length); @@ -290,11 +274,7 @@ _mongoc_async_cmd_phase_setup (mongoc_async_cmd_t *acmd) int retval; BSON_ASSERT (acmd->timeout_msec < INT32_MAX); - retval = acmd->setup (acmd->stream, - &acmd->events, - acmd->setup_ctx, - (int32_t) acmd->timeout_msec, - &acmd->error); + retval = acmd->setup (acmd->stream, &acmd->events, acmd->setup_ctx, (int32_t) acmd->timeout_msec, &acmd->error); switch (retval) { case -1: return MONGOC_ASYNC_CMD_ERROR; @@ -365,10 +345,7 @@ _mongoc_async_cmd_phase_send (mongoc_async_cmd_t *acmd) } if (bytes < 0) { - bson_set_error (&acmd->error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_SOCKET, - "Failed to write rpc bytes."); + bson_set_error (&acmd->error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "Failed to write rpc bytes."); return MONGOC_ASYNC_CMD_ERROR; } @@ -390,8 +367,7 @@ _mongoc_async_cmd_phase_send (mongoc_async_cmd_t *acmd) mongoc_async_cmd_result_t _mongoc_async_cmd_phase_recv_len (mongoc_async_cmd_t *acmd) { - ssize_t bytes = _mongoc_buffer_try_append_from_stream ( - &acmd->buffer, acmd->stream, acmd->bytes_to_read, 0); + ssize_t bytes = _mongoc_buffer_try_append_from_stream (&acmd->buffer, acmd->stream, acmd->bytes_to_read, 0); uint32_t msg_len; if (bytes <= 0 && mongoc_stream_should_retry (acmd->stream)) { @@ -399,18 +375,13 @@ _mongoc_async_cmd_phase_recv_len (mongoc_async_cmd_t *acmd) } if (bytes < 0) { - bson_set_error (&acmd->error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_SOCKET, - "Failed to receive length header from server."); + bson_set_error ( + &acmd->error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "Failed to receive length header from server."); return MONGOC_ASYNC_CMD_ERROR; } if (bytes == 0) { - bson_set_error (&acmd->error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_SOCKET, - "Server closed connection."); + bson_set_error (&acmd->error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "Server closed connection."); return MONGOC_ASYNC_CMD_ERROR; } @@ -420,12 +391,9 @@ _mongoc_async_cmd_phase_recv_len (mongoc_async_cmd_t *acmd) memcpy (&msg_len, acmd->buffer.data, 4); msg_len = BSON_UINT32_FROM_LE (msg_len); - if (msg_len < 16 || msg_len > MONGOC_DEFAULT_MAX_MSG_SIZE || - msg_len < acmd->buffer.len) { - bson_set_error (&acmd->error, - MONGOC_ERROR_PROTOCOL, - MONGOC_ERROR_PROTOCOL_INVALID_REPLY, - "Invalid reply from server."); + if (msg_len < 16 || msg_len > MONGOC_DEFAULT_MAX_MSG_SIZE || msg_len < acmd->buffer.len) { + bson_set_error ( + &acmd->error, MONGOC_ERROR_PROTOCOL, MONGOC_ERROR_PROTOCOL_INVALID_REPLY, "Invalid reply from server."); return MONGOC_ASYNC_CMD_ERROR; } @@ -441,26 +409,20 @@ _mongoc_async_cmd_phase_recv_len (mongoc_async_cmd_t *acmd) mongoc_async_cmd_result_t _mongoc_async_cmd_phase_recv_rpc (mongoc_async_cmd_t *acmd) { - ssize_t bytes = _mongoc_buffer_try_append_from_stream ( - &acmd->buffer, acmd->stream, acmd->bytes_to_read, 0); + ssize_t bytes = _mongoc_buffer_try_append_from_stream (&acmd->buffer, acmd->stream, acmd->bytes_to_read, 0); if (bytes <= 0 && mongoc_stream_should_retry (acmd->stream)) { return MONGOC_ASYNC_CMD_IN_PROGRESS; } if (bytes < 0) { - bson_set_error (&acmd->error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_SOCKET, - "Failed to receive rpc bytes from server."); + bson_set_error ( + &acmd->error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "Failed to receive rpc bytes from server."); return MONGOC_ASYNC_CMD_ERROR; } if (bytes == 0) { - bson_set_error (&acmd->error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_SOCKET, - "Server closed connection."); + bson_set_error (&acmd->error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "Server closed connection."); return MONGOC_ASYNC_CMD_ERROR; } @@ -468,12 +430,9 @@ _mongoc_async_cmd_phase_recv_rpc (mongoc_async_cmd_t *acmd) if (!acmd->bytes_to_read) { mcd_rpc_message_reset (acmd->rpc); - if (!mcd_rpc_message_from_data_in_place ( - acmd->rpc, acmd->buffer.data, acmd->buffer.len, NULL)) { - bson_set_error (&acmd->error, - MONGOC_ERROR_PROTOCOL, - MONGOC_ERROR_PROTOCOL_INVALID_REPLY, - "Invalid reply from server."); + if (!mcd_rpc_message_from_data_in_place (acmd->rpc, acmd->buffer.data, acmd->buffer.len, NULL)) { + bson_set_error ( + &acmd->error, MONGOC_ERROR_PROTOCOL, MONGOC_ERROR_PROTOCOL_INVALID_REPLY, "Invalid reply from server."); return MONGOC_ASYNC_CMD_ERROR; } mcd_rpc_message_ingress (acmd->rpc); @@ -481,8 +440,7 @@ _mongoc_async_cmd_phase_recv_rpc (mongoc_async_cmd_t *acmd) void *decompressed_data; size_t decompressed_data_len; - if (!mcd_rpc_message_decompress_if_necessary ( - acmd->rpc, &decompressed_data, &decompressed_data_len)) { + if (!mcd_rpc_message_decompress_if_necessary (acmd->rpc, &decompressed_data, &decompressed_data_len)) { bson_set_error (&acmd->error, MONGOC_ERROR_PROTOCOL, MONGOC_ERROR_PROTOCOL_INVALID_REPLY, @@ -492,18 +450,12 @@ _mongoc_async_cmd_phase_recv_rpc (mongoc_async_cmd_t *acmd) if (decompressed_data) { _mongoc_buffer_destroy (&acmd->buffer); - _mongoc_buffer_init (&acmd->buffer, - decompressed_data, - decompressed_data_len, - NULL, - NULL); + _mongoc_buffer_init (&acmd->buffer, decompressed_data, decompressed_data_len, NULL, NULL); } if (!mcd_rpc_message_get_body (acmd->rpc, &acmd->reply)) { - bson_set_error (&acmd->error, - MONGOC_ERROR_PROTOCOL, - MONGOC_ERROR_PROTOCOL_INVALID_REPLY, - "Invalid reply from server"); + bson_set_error ( + &acmd->error, MONGOC_ERROR_PROTOCOL, MONGOC_ERROR_PROTOCOL_INVALID_REPLY, "Invalid reply from server"); return MONGOC_ASYNC_CMD_ERROR; } diff --git a/src/libmongoc/src/mongoc/mongoc-async-private.h b/src/libmongoc/src/mongoc/mongoc-async-private.h index c44a6d76ba..2399af4fa9 100644 --- a/src/libmongoc/src/mongoc/mongoc-async-private.h +++ b/src/libmongoc/src/mongoc/mongoc-async-private.h @@ -45,14 +45,10 @@ typedef void (*mongoc_async_cmd_cb_t) (struct _mongoc_async_cmd *acmd, const bson_t *bson, int64_t duration_usec); -typedef mongoc_stream_t *(*mongoc_async_cmd_initiate_t) ( - struct _mongoc_async_cmd *); - -typedef int (*mongoc_async_cmd_setup_t) (mongoc_stream_t *stream, - int *events, - void *ctx, - int32_t timeout_msec, - bson_error_t *error); +typedef mongoc_stream_t *(*mongoc_async_cmd_initiate_t) (struct _mongoc_async_cmd *); + +typedef int (*mongoc_async_cmd_setup_t) ( + mongoc_stream_t *stream, int *events, void *ctx, int32_t timeout_msec, bson_error_t *error); mongoc_async_t * diff --git a/src/libmongoc/src/mongoc/mongoc-async.c b/src/libmongoc/src/mongoc/mongoc-async.c index ae6bb1fd5c..4b7835435f 100644 --- a/src/libmongoc/src/mongoc/mongoc-async.c +++ b/src/libmongoc/src/mongoc/mongoc-async.c @@ -74,10 +74,8 @@ mongoc_async_run (mongoc_async_t *async) while (async->ncmds) { /* ncmds grows if we discover a replica & start calling hello on it */ if (poll_size < async->ncmds) { - poller = (mongoc_stream_poll_t *) bson_realloc ( - poller, sizeof (*poller) * async->ncmds); - acmds_polled = (mongoc_async_cmd_t **) bson_realloc ( - acmds_polled, sizeof (*acmds_polled) * async->ncmds); + poller = (mongoc_stream_poll_t *) bson_realloc (poller, sizeof (*poller) * async->ncmds); + acmds_polled = (mongoc_async_cmd_t **) bson_realloc (acmds_polled, sizeof (*acmds_polled) * async->ncmds); poll_size = async->ncmds; } @@ -99,8 +97,7 @@ mongoc_async_run (mongoc_async_t *async) } } else { /* don't poll longer than the earliest cmd ready to init. */ - expire_at = BSON_MIN ( - expire_at, acmd->connect_started + acmd->initiate_delay_ms); + expire_at = BSON_MIN (expire_at, acmd->connect_started + acmd->initiate_delay_ms); } } @@ -109,8 +106,7 @@ mongoc_async_run (mongoc_async_t *async) poller[nstreams].stream = acmd->stream; poller[nstreams].events = acmd->events; poller[nstreams].revents = 0; - expire_at = BSON_MIN ( - expire_at, acmd->connect_started + acmd->timeout_msec * 1000); + expire_at = BSON_MIN (expire_at, acmd->connect_started + acmd->timeout_msec * 1000); ++nstreams; } } @@ -125,8 +121,7 @@ mongoc_async_run (mongoc_async_t *async) if (nstreams > 0) { /* we need at least one stream to poll. */ - nactive = - mongoc_stream_poll (poller, nstreams, (int32_t) poll_timeout_msec); + nactive = mongoc_stream_poll (poller, nstreams, (int32_t) poll_timeout_msec); } else { /* currently this does not get hit. we always have at least one command * initialized with a stream. */ @@ -142,21 +137,18 @@ mongoc_async_run (mongoc_async_t *async) bson_set_error (&iter->error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_CONNECT, - hup ? "connection refused" - : "unknown connection error"); + hup ? "connection refused" : "unknown connection error"); } else { bson_set_error (&iter->error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, - hup ? "connection closed" - : "unknown socket error"); + hup ? "connection closed" : "unknown socket error"); } iter->state = MONGOC_ASYNC_CMD_ERROR_STATE; } - if ((poller[i].revents & poller[i].events) || - iter->state == MONGOC_ASYNC_CMD_ERROR_STATE) { + if ((poller[i].revents & poller[i].events) || iter->state == MONGOC_ASYNC_CMD_ERROR_STATE) { (void) mongoc_async_cmd_run (iter); nactive--; } @@ -170,27 +162,18 @@ mongoc_async_run (mongoc_async_t *async) DL_FOREACH_SAFE (async->cmds, acmd, tmp) { /* check if an initiated cmd has passed the connection timeout. */ - if (acmd->state != MONGOC_ASYNC_CMD_INITIATE && - now > acmd->connect_started + acmd->timeout_msec * 1000) { + if (acmd->state != MONGOC_ASYNC_CMD_INITIATE && now > acmd->connect_started + acmd->timeout_msec * 1000) { bson_set_error (&acmd->error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_CONNECT, - acmd->state == MONGOC_ASYNC_CMD_SEND - ? "connection timeout" - : "socket timeout"); + acmd->state == MONGOC_ASYNC_CMD_SEND ? "connection timeout" : "socket timeout"); - acmd->cb (acmd, - MONGOC_ASYNC_CMD_TIMEOUT, - NULL, - (now - acmd->connect_started) / 1000); + acmd->cb (acmd, MONGOC_ASYNC_CMD_TIMEOUT, NULL, (now - acmd->connect_started) / 1000); /* Remove acmd from the async->cmds doubly-linked list */ mongoc_async_cmd_destroy (acmd); } else if (acmd->state == MONGOC_ASYNC_CMD_CANCELED_STATE) { - acmd->cb (acmd, - MONGOC_ASYNC_CMD_ERROR, - NULL, - (now - acmd->connect_started) / 1000); + acmd->cb (acmd, MONGOC_ASYNC_CMD_ERROR, NULL, (now - acmd->connect_started) / 1000); /* Remove acmd from the async->cmds doubly-linked list */ mongoc_async_cmd_destroy (acmd); diff --git a/src/libmongoc/src/mongoc/mongoc-buffer-private.h b/src/libmongoc/src/mongoc/mongoc-buffer-private.h index 36c71446d3..42248c29e1 100644 --- a/src/libmongoc/src/mongoc/mongoc-buffer-private.h +++ b/src/libmongoc/src/mongoc/mongoc-buffer-private.h @@ -40,23 +40,15 @@ struct _mongoc_buffer_t { void -_mongoc_buffer_init (mongoc_buffer_t *buffer, - uint8_t *buf, - size_t buflen, - bson_realloc_func realloc_func, - void *realloc_data); +_mongoc_buffer_init ( + mongoc_buffer_t *buffer, uint8_t *buf, size_t buflen, bson_realloc_func realloc_func, void *realloc_data); bool -_mongoc_buffer_append (mongoc_buffer_t *buffer, - const uint8_t *data, - size_t data_size); +_mongoc_buffer_append (mongoc_buffer_t *buffer, const uint8_t *data, size_t data_size); bool -_mongoc_buffer_append_from_stream (mongoc_buffer_t *buffer, - mongoc_stream_t *stream, - size_t size, - int64_t timeout_msec, - bson_error_t *error); +_mongoc_buffer_append_from_stream ( + mongoc_buffer_t *buffer, mongoc_stream_t *stream, size_t size, int64_t timeout_msec, bson_error_t *error); ssize_t _mongoc_buffer_try_append_from_stream (mongoc_buffer_t *buffer, @@ -65,11 +57,8 @@ _mongoc_buffer_try_append_from_stream (mongoc_buffer_t *buffer, int64_t timeout_msec); ssize_t -_mongoc_buffer_fill (mongoc_buffer_t *buffer, - mongoc_stream_t *stream, - size_t min_bytes, - int64_t timeout_msec, - bson_error_t *error); +_mongoc_buffer_fill ( + mongoc_buffer_t *buffer, mongoc_stream_t *stream, size_t min_bytes, int64_t timeout_msec, bson_error_t *error); void _mongoc_buffer_destroy (mongoc_buffer_t *buffer); diff --git a/src/libmongoc/src/mongoc/mongoc-buffer.c b/src/libmongoc/src/mongoc/mongoc-buffer.c index d8bd2892d6..846cb74edd 100644 --- a/src/libmongoc/src/mongoc/mongoc-buffer.c +++ b/src/libmongoc/src/mongoc/mongoc-buffer.c @@ -36,8 +36,7 @@ make_space_for (mongoc_buffer_t *buffer, size_t data_size) { if (buffer->len + data_size > buffer->datalen) { buffer->datalen = bson_next_power_of_two (buffer->len + data_size); - buffer->data = (uint8_t *) buffer->realloc_func ( - buffer->data, buffer->datalen, buffer->realloc_data); + buffer->data = (uint8_t *) buffer->realloc_func (buffer->data, buffer->datalen, buffer->realloc_data); } } @@ -56,11 +55,8 @@ make_space_for (mongoc_buffer_t *buffer, size_t data_size) * cleaning up the data structure. */ void -_mongoc_buffer_init (mongoc_buffer_t *buffer, - uint8_t *buf, - size_t buflen, - bson_realloc_func realloc_func, - void *realloc_data) +_mongoc_buffer_init ( + mongoc_buffer_t *buffer, uint8_t *buf, size_t buflen, bson_realloc_func realloc_func, void *realloc_data) { BSON_ASSERT_PARAM (buffer); BSON_ASSERT (buflen || !buf); @@ -129,9 +125,7 @@ _mongoc_buffer_clear (mongoc_buffer_t *buffer, bool zero) bool -_mongoc_buffer_append (mongoc_buffer_t *buffer, - const uint8_t *data, - size_t data_size) +_mongoc_buffer_append (mongoc_buffer_t *buffer, const uint8_t *data, size_t data_size) { uint8_t *buf; @@ -171,11 +165,8 @@ _mongoc_buffer_append (mongoc_buffer_t *buffer, * Returns: true if successful; otherwise false and @error is set. */ bool -_mongoc_buffer_append_from_stream (mongoc_buffer_t *buffer, - mongoc_stream_t *stream, - size_t size, - int64_t timeout_msec, - bson_error_t *error) +_mongoc_buffer_append_from_stream ( + mongoc_buffer_t *buffer, mongoc_stream_t *stream, size_t size, int64_t timeout_msec, bson_error_t *error) { uint8_t *buf; ssize_t ret; @@ -199,8 +190,7 @@ _mongoc_buffer_append_from_stream (mongoc_buffer_t *buffer, bson_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, - "timeout_msec value %" PRId64 - " exceeds supported 32-bit range", + "timeout_msec value %" PRId64 " exceeds supported 32-bit range", timeout_msec); RETURN (false); } @@ -233,11 +223,8 @@ _mongoc_buffer_append_from_stream (mongoc_buffer_t *buffer, * Returns: The number of buffered bytes, or -1 on failure. */ ssize_t -_mongoc_buffer_fill (mongoc_buffer_t *buffer, - mongoc_stream_t *stream, - size_t min_bytes, - int64_t timeout_msec, - bson_error_t *error) +_mongoc_buffer_fill ( + mongoc_buffer_t *buffer, mongoc_stream_t *stream, size_t min_bytes, int64_t timeout_msec, bson_error_t *error) { ssize_t ret; size_t avail_bytes; @@ -266,24 +253,15 @@ _mongoc_buffer_fill (mongoc_buffer_t *buffer, bson_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, - "timeout_msec value %" PRId64 - " exceeds supported 32-bit range", + "timeout_msec value %" PRId64 " exceeds supported 32-bit range", timeout_msec); RETURN (false); } - ret = mongoc_stream_read (stream, - &buffer->data[buffer->len], - avail_bytes, - min_bytes, - (int32_t) timeout_msec); + ret = mongoc_stream_read (stream, &buffer->data[buffer->len], avail_bytes, min_bytes, (int32_t) timeout_msec); if (ret < 0) { - bson_set_error (error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_SOCKET, - "Failed to buffer %zu bytes", - min_bytes); + bson_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "Failed to buffer %zu bytes", min_bytes); RETURN (-1); } @@ -342,9 +320,7 @@ _mongoc_buffer_try_append_from_stream (mongoc_buffer_t *buffer, if (BSON_UNLIKELY (!bson_in_range_signed (int32_t, timeout_msec))) { // CDRIVER-4589 - MONGOC_ERROR ("timeout_msec value %" PRId64 - " exceeds supported 32-bit range", - timeout_msec); + MONGOC_ERROR ("timeout_msec value %" PRId64 " exceeds supported 32-bit range", timeout_msec); RETURN (-1); } diff --git a/src/libmongoc/src/mongoc/mongoc-bulk-operation.c b/src/libmongoc/src/mongoc/mongoc-bulk-operation.c index d5a4a67e0b..36449cf42f 100644 --- a/src/libmongoc/src/mongoc/mongoc-bulk-operation.c +++ b/src/libmongoc/src/mongoc/mongoc-bulk-operation.c @@ -64,12 +64,11 @@ mongoc_bulk_operation_new (bool ordered) mongoc_bulk_operation_t * -_mongoc_bulk_operation_new ( - mongoc_client_t *client, /* IN */ - const char *database, /* IN */ - const char *collection, /* IN */ - mongoc_bulk_write_flags_t flags, /* IN */ - const mongoc_write_concern_t *write_concern) /* IN */ +_mongoc_bulk_operation_new (mongoc_client_t *client, /* IN */ + const char *database, /* IN */ + const char *collection, /* IN */ + mongoc_bulk_write_flags_t flags, /* IN */ + const mongoc_write_concern_t *write_concern) /* IN */ { mongoc_bulk_operation_t *bulk; @@ -96,8 +95,7 @@ mongoc_bulk_operation_destroy (mongoc_bulk_operation_t *bulk) /* IN */ if (bulk) { for (size_t i = 0; i < bulk->commands.len; i++) { - command = - &_mongoc_array_index (&bulk->commands, mongoc_write_command_t, i); + command = &_mongoc_array_index (&bulk->commands, mongoc_write_command_t, i); _mongoc_write_command_destroy (command); } @@ -139,12 +137,11 @@ mongoc_bulk_operation_destroy (mongoc_bulk_operation_t *bulk) /* IN */ static bool -_mongoc_bulk_operation_remove_with_opts ( - mongoc_bulk_operation_t *bulk, - const bson_t *selector, - const mongoc_bulk_remove_opts_t *remove_opts, - int32_t limit, - bson_error_t *error) /* OUT */ +_mongoc_bulk_operation_remove_with_opts (mongoc_bulk_operation_t *bulk, + const bson_t *selector, + const mongoc_bulk_remove_opts_t *remove_opts, + int32_t limit, + bson_error_t *error) /* OUT */ { mongoc_write_command_t command = {0}; mongoc_write_command_t *last; @@ -185,8 +182,7 @@ _mongoc_bulk_operation_remove_with_opts ( } if (bulk->commands.len) { - last = &_mongoc_array_index ( - &bulk->commands, mongoc_write_command_t, bulk->commands.len - 1); + last = &_mongoc_array_index (&bulk->commands, mongoc_write_command_t, bulk->commands.len - 1); if (last->type == MONGOC_WRITE_COMMAND_DELETE) { last->flags.has_collation |= has_collation; last->flags.has_delete_hint |= has_delete_hint; @@ -205,8 +201,7 @@ _mongoc_bulk_operation_remove_with_opts ( bson_append_document (&cmd_opts, "let", 3, &bulk->let); } - _mongoc_write_command_init_delete ( - &command, selector, &cmd_opts, &opts, bulk->flags, bulk->operation_id); + _mongoc_write_command_init_delete (&command, selector, &cmd_opts, &opts, bulk->flags, bulk->operation_id); command.flags.has_collation = has_collation; command.flags.has_delete_hint = has_delete_hint; @@ -235,14 +230,12 @@ mongoc_bulk_operation_remove_one_with_opts (mongoc_bulk_operation_t *bulk, BULK_RETURN_IF_PRIOR_ERROR; - if (!_mongoc_bulk_remove_one_opts_parse ( - bulk->client, opts, &remove_opts, error)) { + if (!_mongoc_bulk_remove_one_opts_parse (bulk->client, opts, &remove_opts, error)) { _mongoc_bulk_remove_one_opts_cleanup (&remove_opts); RETURN (false); } - ret = _mongoc_bulk_operation_remove_with_opts ( - bulk, selector, &remove_opts.remove, 1, error); + ret = _mongoc_bulk_operation_remove_with_opts (bulk, selector, &remove_opts.remove, 1, error); _mongoc_bulk_remove_one_opts_cleanup (&remove_opts); RETURN (ret); @@ -262,14 +255,12 @@ mongoc_bulk_operation_remove_many_with_opts (mongoc_bulk_operation_t *bulk, BULK_RETURN_IF_PRIOR_ERROR; - if (!_mongoc_bulk_remove_many_opts_parse ( - bulk->client, opts, &remove_opts, error)) { + if (!_mongoc_bulk_remove_many_opts_parse (bulk->client, opts, &remove_opts, error)) { _mongoc_bulk_remove_many_opts_cleanup (&remove_opts); RETURN (false); } - ret = _mongoc_bulk_operation_remove_with_opts ( - bulk, selector, &remove_opts.remove, 0, error); + ret = _mongoc_bulk_operation_remove_with_opts (bulk, selector, &remove_opts.remove, 0, error); _mongoc_bulk_remove_many_opts_cleanup (&remove_opts); RETURN (ret); @@ -286,8 +277,7 @@ mongoc_bulk_operation_remove (mongoc_bulk_operation_t *bulk, /* IN */ BULK_EXIT_IF_PRIOR_ERROR; - if (!mongoc_bulk_operation_remove_many_with_opts ( - bulk, selector, NULL, error)) { + if (!mongoc_bulk_operation_remove_many_with_opts (bulk, selector, NULL, error)) { MONGOC_WARNING ("%s", error->message); } @@ -309,8 +299,7 @@ mongoc_bulk_operation_remove_one (mongoc_bulk_operation_t *bulk, /* IN */ BULK_EXIT_IF_PRIOR_ERROR; - if (!mongoc_bulk_operation_remove_one_with_opts ( - bulk, selector, NULL, error)) { + if (!mongoc_bulk_operation_remove_one_with_opts (bulk, selector, NULL, error)) { MONGOC_WARNING ("%s", error->message); } @@ -322,8 +311,7 @@ mongoc_bulk_operation_remove_one (mongoc_bulk_operation_t *bulk, /* IN */ } void -mongoc_bulk_operation_delete (mongoc_bulk_operation_t *bulk, - const bson_t *selector) +mongoc_bulk_operation_delete (mongoc_bulk_operation_t *bulk, const bson_t *selector) { ENTRY; @@ -333,8 +321,7 @@ mongoc_bulk_operation_delete (mongoc_bulk_operation_t *bulk, } void -mongoc_bulk_operation_delete_one (mongoc_bulk_operation_t *bulk, - const bson_t *selector) +mongoc_bulk_operation_delete_one (mongoc_bulk_operation_t *bulk, const bson_t *selector) { ENTRY; @@ -344,16 +331,14 @@ mongoc_bulk_operation_delete_one (mongoc_bulk_operation_t *bulk, } void -mongoc_bulk_operation_insert (mongoc_bulk_operation_t *bulk, - const bson_t *document) +mongoc_bulk_operation_insert (mongoc_bulk_operation_t *bulk, const bson_t *document) { ENTRY; BSON_ASSERT_PARAM (bulk); BSON_ASSERT_PARAM (document); - if (!mongoc_bulk_operation_insert_with_opts ( - bulk, document, NULL /* opts */, &bulk->result.error)) { + if (!mongoc_bulk_operation_insert_with_opts (bulk, document, NULL /* opts */, &bulk->result.error)) { MONGOC_WARNING ("%s", bulk->result.error.message); } @@ -379,8 +364,7 @@ mongoc_bulk_operation_insert_with_opts (mongoc_bulk_operation_t *bulk, BULK_RETURN_IF_PRIOR_ERROR; - if (!_mongoc_bulk_insert_opts_parse ( - bulk->client, opts, &insert_opts, error)) { + if (!_mongoc_bulk_insert_opts_parse (bulk->client, opts, &insert_opts, error)) { GOTO (done); } @@ -392,8 +376,7 @@ mongoc_bulk_operation_insert_with_opts (mongoc_bulk_operation_t *bulk, * no reason to concatenate cmd_opts with &insert_opts.extra. */ if (bulk->commands.len) { - last = &_mongoc_array_index ( - &bulk->commands, mongoc_write_command_t, bulk->commands.len - 1); + last = &_mongoc_array_index (&bulk->commands, mongoc_write_command_t, bulk->commands.len - 1); if (last->type == MONGOC_WRITE_COMMAND_INSERT) { _mongoc_write_command_insert_append (last, document); @@ -406,8 +389,7 @@ mongoc_bulk_operation_insert_with_opts (mongoc_bulk_operation_t *bulk, bson_append_value (&cmd_opts, "comment", 7, &bulk->comment); } - _mongoc_write_command_init_insert ( - &command, document, &cmd_opts, bulk->flags, bulk->operation_id); + _mongoc_write_command_init_insert (&command, document, &cmd_opts, bulk->flags, bulk->operation_id); _mongoc_array_append_val (&bulk->commands, command); @@ -421,13 +403,12 @@ mongoc_bulk_operation_insert_with_opts (mongoc_bulk_operation_t *bulk, } static void -_mongoc_bulk_operation_update_append ( - mongoc_bulk_operation_t *bulk, - const bson_t *selector, - const bson_t *document, - const mongoc_bulk_update_opts_t *update_opts, - const bson_t *array_filters, - const bson_t *extra_opts) +_mongoc_bulk_operation_update_append (mongoc_bulk_operation_t *bulk, + const bson_t *selector, + const bson_t *document, + const mongoc_bulk_update_opts_t *update_opts, + const bson_t *array_filters, + const bson_t *extra_opts) { mongoc_write_command_t command = {0}; mongoc_write_command_t *last; @@ -461,8 +442,7 @@ _mongoc_bulk_operation_update_append ( } if (bulk->commands.len) { - last = &_mongoc_array_index ( - &bulk->commands, mongoc_write_command_t, bulk->commands.len - 1); + last = &_mongoc_array_index (&bulk->commands, mongoc_write_command_t, bulk->commands.len - 1); if (last->type == MONGOC_WRITE_COMMAND_UPDATE) { last->flags.has_array_filters |= has_array_filters; last->flags.has_collation |= has_collation; @@ -481,13 +461,7 @@ _mongoc_bulk_operation_update_append ( bson_append_document (&cmd_opts, "let", 3, &bulk->let); } - _mongoc_write_command_init_update (&command, - selector, - document, - &cmd_opts, - &opts, - bulk->flags, - bulk->operation_id); + _mongoc_write_command_init_update (&command, selector, document, &cmd_opts, &opts, bulk->flags, bulk->operation_id); command.flags.has_array_filters = has_array_filters; command.flags.has_collation = has_collation; @@ -502,15 +476,14 @@ _mongoc_bulk_operation_update_append ( } static bool -_mongoc_bulk_operation_update_with_opts ( - mongoc_bulk_operation_t *bulk, - const bson_t *selector, - const bson_t *document, - const mongoc_bulk_update_opts_t *update_opts, - const bson_t *array_filters, - const bson_t *extra_opts, - bool multi, - bson_error_t *error) /* OUT */ +_mongoc_bulk_operation_update_with_opts (mongoc_bulk_operation_t *bulk, + const bson_t *selector, + const bson_t *document, + const mongoc_bulk_update_opts_t *update_opts, + const bson_t *array_filters, + const bson_t *extra_opts, + bool multi, + bson_error_t *error) /* OUT */ { ENTRY; @@ -534,8 +507,7 @@ _mongoc_bulk_operation_update_with_opts ( RETURN (false); } - _mongoc_bulk_operation_update_append ( - bulk, selector, document, update_opts, array_filters, extra_opts); + _mongoc_bulk_operation_update_append (bulk, selector, document, update_opts, array_filters, extra_opts); RETURN (true); } @@ -554,8 +526,7 @@ mongoc_bulk_operation_update_one_with_opts (mongoc_bulk_operation_t *bulk, BULK_RETURN_IF_PRIOR_ERROR; - if (!_mongoc_bulk_update_one_opts_parse ( - bulk->client, opts, &update_opts, error)) { + if (!_mongoc_bulk_update_one_opts_parse (bulk->client, opts, &update_opts, error)) { _mongoc_bulk_update_one_opts_cleanup (&update_opts); RETURN (false); } @@ -587,8 +558,7 @@ mongoc_bulk_operation_update_many_with_opts (mongoc_bulk_operation_t *bulk, BULK_RETURN_IF_PRIOR_ERROR; - if (!_mongoc_bulk_update_many_opts_parse ( - bulk->client, opts, &update_opts, error)) { + if (!_mongoc_bulk_update_many_opts_parse (bulk->client, opts, &update_opts, error)) { _mongoc_bulk_update_many_opts_cleanup (&update_opts); RETURN (false); } @@ -624,8 +594,7 @@ mongoc_bulk_operation_update (mongoc_bulk_operation_t *bulk, BSON_APPEND_BOOL (&opts, "upsert", upsert); } - if (!mongoc_bulk_operation_update_many_with_opts ( - bulk, selector, document, &opts, error)) { + if (!mongoc_bulk_operation_update_many_with_opts (bulk, selector, document, &opts, error)) { MONGOC_WARNING ("%s", error->message); } @@ -654,8 +623,7 @@ mongoc_bulk_operation_update_one (mongoc_bulk_operation_t *bulk, bson_init (&opts); BSON_APPEND_BOOL (&opts, "upsert", upsert); - if (!mongoc_bulk_operation_update_one_with_opts ( - bulk, selector, document, &opts, error)) { + if (!mongoc_bulk_operation_update_one_with_opts (bulk, selector, document, &opts, error)) { MONGOC_WARNING ("%s", error->message); } @@ -687,8 +655,7 @@ mongoc_bulk_operation_replace_one_with_opts (mongoc_bulk_operation_t *bulk, BULK_RETURN_IF_PRIOR_ERROR; - if (!_mongoc_bulk_replace_one_opts_parse ( - bulk->client, opts, &repl_opts, error)) { + if (!_mongoc_bulk_replace_one_opts_parse (bulk->client, opts, &repl_opts, error)) { GOTO (done); } @@ -707,8 +674,7 @@ mongoc_bulk_operation_replace_one_with_opts (mongoc_bulk_operation_t *bulk, GOTO (done); } - _mongoc_bulk_operation_update_append ( - bulk, selector, document, update_opts, NULL, &repl_opts.extra); + _mongoc_bulk_operation_update_append (bulk, selector, document, update_opts, NULL, &repl_opts.extra); ret = true; done: @@ -729,8 +695,7 @@ mongoc_bulk_operation_replace_one (mongoc_bulk_operation_t *bulk, BSON_APPEND_BOOL (&opts, "upsert", upsert); - if (!mongoc_bulk_operation_replace_one_with_opts ( - bulk, selector, document, &opts, error)) { + if (!mongoc_bulk_operation_replace_one_with_opts (bulk, selector, document, &opts, error)) { MONGOC_WARNING ("%s", error->message); } @@ -798,25 +763,16 @@ mongoc_bulk_operation_execute (mongoc_bulk_operation_t *bulk, /* IN */ } if (!bulk->commands.len) { - bson_set_error (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Cannot do an empty bulk write"); + bson_set_error (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Cannot do an empty bulk write"); GOTO (err); } for (size_t i = 0u; i < bulk->commands.len; i++) { if (bulk->server_id) { - server_stream = - mongoc_cluster_stream_for_server (cluster, - bulk->server_id, - true /* reconnect_ok */, - bulk->session, - reply, - error); + server_stream = mongoc_cluster_stream_for_server ( + cluster, bulk->server_id, true /* reconnect_ok */, bulk->session, reply, error); } else { - server_stream = mongoc_cluster_stream_for_writes ( - cluster, bulk->session, NULL, reply, error); + server_stream = mongoc_cluster_stream_for_writes (cluster, bulk->session, NULL, reply, error); } if (!server_stream) { @@ -824,8 +780,7 @@ mongoc_bulk_operation_execute (mongoc_bulk_operation_t *bulk, /* IN */ RETURN (false); } - command = - &_mongoc_array_index (&bulk->commands, mongoc_write_command_t, i); + command = &_mongoc_array_index (&bulk->commands, mongoc_write_command_t, i); _mongoc_write_command_execute (command, bulk->client, @@ -844,8 +799,7 @@ mongoc_bulk_operation_execute (mongoc_bulk_operation_t *bulk, /* IN */ bulk->server_id = bulk->result.retry_server_id; } - if (bulk->result.failed && - (bulk->flags.ordered || bulk->result.must_stop)) { + if (bulk->result.failed && (bulk->flags.ordered || bulk->result.must_stop)) { mongoc_server_stream_cleanup (server_stream); GOTO (cleanup); } @@ -871,8 +825,7 @@ mongoc_bulk_operation_execute (mongoc_bulk_operation_t *bulk, /* IN */ } void -mongoc_bulk_operation_set_write_concern ( - mongoc_bulk_operation_t *bulk, const mongoc_write_concern_t *write_concern) +mongoc_bulk_operation_set_write_concern (mongoc_bulk_operation_t *bulk, const mongoc_write_concern_t *write_concern) { BSON_ASSERT_PARAM (bulk); @@ -897,8 +850,7 @@ mongoc_bulk_operation_get_write_concern (const mongoc_bulk_operation_t *bulk) void -mongoc_bulk_operation_set_database (mongoc_bulk_operation_t *bulk, - const char *database) +mongoc_bulk_operation_set_database (mongoc_bulk_operation_t *bulk, const char *database) { BSON_ASSERT_PARAM (bulk); @@ -911,8 +863,7 @@ mongoc_bulk_operation_set_database (mongoc_bulk_operation_t *bulk, void -mongoc_bulk_operation_set_collection (mongoc_bulk_operation_t *bulk, - const char *collection) +mongoc_bulk_operation_set_collection (mongoc_bulk_operation_t *bulk, const char *collection) { BSON_ASSERT_PARAM (bulk); @@ -946,9 +897,8 @@ mongoc_bulk_operation_set_client (mongoc_bulk_operation_t *bulk, void *client) void -mongoc_bulk_operation_set_client_session ( - mongoc_bulk_operation_t *bulk, - struct _mongoc_client_session_t *client_session) +mongoc_bulk_operation_set_client_session (mongoc_bulk_operation_t *bulk, + struct _mongoc_client_session_t *client_session) { BSON_ASSERT_PARAM (bulk); BSON_ASSERT_PARAM (client_session); @@ -971,8 +921,7 @@ mongoc_bulk_operation_get_hint (const mongoc_bulk_operation_t *bulk) void -mongoc_bulk_operation_set_hint (mongoc_bulk_operation_t *bulk, - uint32_t server_id) +mongoc_bulk_operation_set_hint (mongoc_bulk_operation_t *bulk, uint32_t server_id) { BSON_ASSERT_PARAM (bulk); @@ -981,8 +930,7 @@ mongoc_bulk_operation_set_hint (mongoc_bulk_operation_t *bulk, void -mongoc_bulk_operation_set_bypass_document_validation ( - mongoc_bulk_operation_t *bulk, bool bypass) +mongoc_bulk_operation_set_bypass_document_validation (mongoc_bulk_operation_t *bulk, bool bypass) { BSON_ASSERT_PARAM (bulk); @@ -991,8 +939,7 @@ mongoc_bulk_operation_set_bypass_document_validation ( void -mongoc_bulk_operation_set_comment (mongoc_bulk_operation_t *bulk, - const bson_value_t *comment) +mongoc_bulk_operation_set_comment (mongoc_bulk_operation_t *bulk, const bson_value_t *comment) { BSON_ASSERT_PARAM (bulk); BSON_ASSERT_PARAM (comment); diff --git a/src/libmongoc/src/mongoc/mongoc-bulk-operation.h b/src/libmongoc/src/mongoc/mongoc-bulk-operation.h index 515bfb2f6a..a12befa49c 100644 --- a/src/libmongoc/src/mongoc/mongoc-bulk-operation.h +++ b/src/libmongoc/src/mongoc/mongoc-bulk-operation.h @@ -44,36 +44,29 @@ typedef struct _mongoc_bulk_write_flags_t mongoc_bulk_write_flags_t; MONGOC_EXPORT (void) mongoc_bulk_operation_destroy (mongoc_bulk_operation_t *bulk); MONGOC_EXPORT (uint32_t) -mongoc_bulk_operation_execute (mongoc_bulk_operation_t *bulk, - bson_t *reply, - bson_error_t *error); +mongoc_bulk_operation_execute (mongoc_bulk_operation_t *bulk, bson_t *reply, bson_error_t *error); MONGOC_EXPORT (void) -mongoc_bulk_operation_delete (mongoc_bulk_operation_t *bulk, - const bson_t *selector) +mongoc_bulk_operation_delete (mongoc_bulk_operation_t *bulk, const bson_t *selector) BSON_GNUC_DEPRECATED_FOR (mongoc_bulk_operation_remove); MONGOC_EXPORT (void) -mongoc_bulk_operation_delete_one (mongoc_bulk_operation_t *bulk, - const bson_t *selector) +mongoc_bulk_operation_delete_one (mongoc_bulk_operation_t *bulk, const bson_t *selector) BSON_GNUC_DEPRECATED_FOR (mongoc_bulk_operation_remove_one); MONGOC_EXPORT (void) -mongoc_bulk_operation_insert (mongoc_bulk_operation_t *bulk, - const bson_t *document); +mongoc_bulk_operation_insert (mongoc_bulk_operation_t *bulk, const bson_t *document); MONGOC_EXPORT (bool) mongoc_bulk_operation_insert_with_opts (mongoc_bulk_operation_t *bulk, const bson_t *document, const bson_t *opts, bson_error_t *error); /* OUT */ MONGOC_EXPORT (void) -mongoc_bulk_operation_remove (mongoc_bulk_operation_t *bulk, - const bson_t *selector); +mongoc_bulk_operation_remove (mongoc_bulk_operation_t *bulk, const bson_t *selector); MONGOC_EXPORT (bool) mongoc_bulk_operation_remove_many_with_opts (mongoc_bulk_operation_t *bulk, const bson_t *selector, const bson_t *opts, bson_error_t *error); /* OUT */ MONGOC_EXPORT (void) -mongoc_bulk_operation_remove_one (mongoc_bulk_operation_t *bulk, - const bson_t *selector); +mongoc_bulk_operation_remove_one (mongoc_bulk_operation_t *bulk, const bson_t *selector); MONGOC_EXPORT (bool) mongoc_bulk_operation_remove_one_with_opts (mongoc_bulk_operation_t *bulk, const bson_t *selector, @@ -113,14 +106,11 @@ mongoc_bulk_operation_update_one_with_opts (mongoc_bulk_operation_t *bulk, const bson_t *opts, bson_error_t *error); /* OUT */ MONGOC_EXPORT (void) -mongoc_bulk_operation_set_bypass_document_validation ( - mongoc_bulk_operation_t *bulk, bool bypass); +mongoc_bulk_operation_set_bypass_document_validation (mongoc_bulk_operation_t *bulk, bool bypass); MONGOC_EXPORT (void) -mongoc_bulk_operation_set_comment (mongoc_bulk_operation_t *bulk, - const bson_value_t *comment); +mongoc_bulk_operation_set_comment (mongoc_bulk_operation_t *bulk, const bson_value_t *comment); MONGOC_EXPORT (void) -mongoc_bulk_operation_set_let (mongoc_bulk_operation_t *bulk, - const bson_t *let); +mongoc_bulk_operation_set_let (mongoc_bulk_operation_t *bulk, const bson_t *let); /* @@ -131,25 +121,20 @@ mongoc_bulk_operation_set_let (mongoc_bulk_operation_t *bulk, MONGOC_EXPORT (mongoc_bulk_operation_t *) mongoc_bulk_operation_new (bool ordered) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (void) -mongoc_bulk_operation_set_write_concern ( - mongoc_bulk_operation_t *bulk, const mongoc_write_concern_t *write_concern); +mongoc_bulk_operation_set_write_concern (mongoc_bulk_operation_t *bulk, const mongoc_write_concern_t *write_concern); MONGOC_EXPORT (void) -mongoc_bulk_operation_set_database (mongoc_bulk_operation_t *bulk, - const char *database); +mongoc_bulk_operation_set_database (mongoc_bulk_operation_t *bulk, const char *database); MONGOC_EXPORT (void) -mongoc_bulk_operation_set_collection (mongoc_bulk_operation_t *bulk, - const char *collection); +mongoc_bulk_operation_set_collection (mongoc_bulk_operation_t *bulk, const char *collection); MONGOC_EXPORT (void) mongoc_bulk_operation_set_client (mongoc_bulk_operation_t *bulk, void *client); MONGOC_EXPORT (void) -mongoc_bulk_operation_set_client_session ( - mongoc_bulk_operation_t *bulk, - struct _mongoc_client_session_t *client_session); +mongoc_bulk_operation_set_client_session (mongoc_bulk_operation_t *bulk, + struct _mongoc_client_session_t *client_session); /* These names include the term "hint" for backward compatibility, should be * mongoc_bulk_operation_get_server_id, mongoc_bulk_operation_set_server_id. */ MONGOC_EXPORT (void) -mongoc_bulk_operation_set_hint (mongoc_bulk_operation_t *bulk, - uint32_t server_id); +mongoc_bulk_operation_set_hint (mongoc_bulk_operation_t *bulk, uint32_t server_id); MONGOC_EXPORT (uint32_t) mongoc_bulk_operation_get_hint (const mongoc_bulk_operation_t *bulk); MONGOC_EXPORT (const mongoc_write_concern_t *) diff --git a/src/libmongoc/src/mongoc/mongoc-change-stream-private.h b/src/libmongoc/src/mongoc/mongoc-change-stream-private.h index a38e5ba623..994fa498fc 100644 --- a/src/libmongoc/src/mongoc/mongoc-change-stream-private.h +++ b/src/libmongoc/src/mongoc/mongoc-change-stream-private.h @@ -70,18 +70,12 @@ struct _mongoc_change_stream_t { }; mongoc_change_stream_t * -_mongoc_change_stream_new_from_collection (const mongoc_collection_t *coll, - const bson_t *pipeline, - const bson_t *opts); +_mongoc_change_stream_new_from_collection (const mongoc_collection_t *coll, const bson_t *pipeline, const bson_t *opts); mongoc_change_stream_t * -_mongoc_change_stream_new_from_database (const mongoc_database_t *db, - const bson_t *pipeline, - const bson_t *opts); +_mongoc_change_stream_new_from_database (const mongoc_database_t *db, const bson_t *pipeline, const bson_t *opts); mongoc_change_stream_t * -_mongoc_change_stream_new_from_client (mongoc_client_t *client, - const bson_t *pipeline, - const bson_t *opts); +_mongoc_change_stream_new_from_client (mongoc_client_t *client, const bson_t *pipeline, const bson_t *opts); #endif /* MONGOC_CHANGE_STREAM_PRIVATE_H */ diff --git a/src/libmongoc/src/mongoc/mongoc-change-stream.c b/src/libmongoc/src/mongoc/mongoc-change-stream.c index 7fb5ecfcdf..1921c96f53 100644 --- a/src/libmongoc/src/mongoc/mongoc-change-stream.c +++ b/src/libmongoc/src/mongoc/mongoc-change-stream.c @@ -25,11 +25,8 @@ #include "mongoc-error.h" #include "mongoc-error-private.h" -#define CHANGE_STREAM_ERR(_str) \ - bson_set_error (&stream->err, \ - MONGOC_ERROR_CURSOR, \ - MONGOC_ERROR_BSON, \ - "Could not set " _str) +#define CHANGE_STREAM_ERR(_str) \ + bson_set_error (&stream->err, MONGOC_ERROR_CURSOR, MONGOC_ERROR_BSON, "Could not set " _str) /* the caller knows either a client or server error has occurred. * `reply` contains the server reply or an empty document. */ @@ -111,8 +108,7 @@ _make_command (mongoc_change_stream_t *stream, bson_t *command) bson_t cursor_doc; if (stream->change_stream_type == MONGOC_CHANGE_STREAM_COLLECTION) { - bson_append_utf8 ( - command, "aggregate", 9, stream->coll, (int) strlen (stream->coll)); + bson_append_utf8 (command, "aggregate", 9, stream->coll, (int) strlen (stream->coll)); } else { bson_append_int32 (command, "aggregate", 9, 1); } @@ -121,8 +117,7 @@ _make_command (mongoc_change_stream_t *stream, bson_t *command) /* append the $changeStream stage. */ bson_array_builder_append_document_begin (pipeline, &change_stream_stage); - bson_append_document_begin ( - &change_stream_stage, "$changeStream", 13, &change_stream_doc); + bson_append_document_begin (&change_stream_stage, "$changeStream", 13, &change_stream_doc); if (stream->full_document) { bson_concat (&change_stream_doc, stream->full_document); } @@ -130,9 +125,7 @@ _make_command (mongoc_change_stream_t *stream, bson_t *command) bson_concat (&change_stream_doc, stream->full_document_before_change); } if (stream->show_expanded_events) { - BSON_APPEND_BOOL (&change_stream_doc, - "showExpandedEvents", - stream->show_expanded_events); + BSON_APPEND_BOOL (&change_stream_doc, "showExpandedEvents", stream->show_expanded_events); } if (stream->resumed) { @@ -141,24 +134,18 @@ _make_command (mongoc_change_stream_t *stream, bson_t *command) if (!bson_empty (&stream->resume_token)) { /* If the ChangeStream was started with startAfter and has yet to return a result document: */ - if (!bson_empty (&stream->opts.startAfter) && - !stream->has_returned_results) { + if (!bson_empty (&stream->opts.startAfter) && !stream->has_returned_results) { /* The driver MUST set startAfter to the cached resumeToken */ - BSON_APPEND_DOCUMENT ( - &change_stream_doc, "startAfter", &stream->resume_token); + BSON_APPEND_DOCUMENT (&change_stream_doc, "startAfter", &stream->resume_token); } else { /* The driver MUST set resumeAfter to the cached resumeToken */ - BSON_APPEND_DOCUMENT ( - &change_stream_doc, "resumeAfter", &stream->resume_token); + BSON_APPEND_DOCUMENT (&change_stream_doc, "resumeAfter", &stream->resume_token); } - } else if (!_mongoc_timestamp_empty (&stream->operation_time) && - stream->max_wire_version >= WIRE_VERSION_4_0) { + } else if (!_mongoc_timestamp_empty (&stream->operation_time) && stream->max_wire_version >= WIRE_VERSION_4_0) { /* Else if there is no cached resumeToken and the ChangeStream has a saved operation time and the max wire version is >= 7, the driver MUST set startAtOperationTime */ - _mongoc_timestamp_append (&stream->operation_time, - &change_stream_doc, - "startAtOperationTime"); + _mongoc_timestamp_append (&stream->operation_time, &change_stream_doc, "startAtOperationTime"); } } else { /* Change streams spec: "startAtOperationTime, resumeAfter, and startAfter @@ -166,25 +153,21 @@ _make_command (mongoc_change_stream_t *stream, bson_t *command) * an error. Drivers MUST NOT throw a custom error, and MUST defer to the * server error." */ if (!bson_empty (&stream->opts.resumeAfter)) { - BSON_APPEND_DOCUMENT ( - &change_stream_doc, "resumeAfter", &stream->opts.resumeAfter); + BSON_APPEND_DOCUMENT (&change_stream_doc, "resumeAfter", &stream->opts.resumeAfter); /* Update the cached resume token */ _set_resume_token (stream, &stream->opts.resumeAfter); } if (!bson_empty (&stream->opts.startAfter)) { - BSON_APPEND_DOCUMENT ( - &change_stream_doc, "startAfter", &stream->opts.startAfter); + BSON_APPEND_DOCUMENT (&change_stream_doc, "startAfter", &stream->opts.startAfter); /* Update the cached resume token (take precedence over resumeAfter) */ _set_resume_token (stream, &stream->opts.startAfter); } if (!_mongoc_timestamp_empty (&stream->operation_time)) { - _mongoc_timestamp_append (&stream->operation_time, - &change_stream_doc, - "startAtOperationTime"); + _mongoc_timestamp_append (&stream->operation_time, &change_stream_doc, "startAtOperationTime"); } } @@ -195,16 +178,14 @@ _make_command (mongoc_change_stream_t *stream, bson_t *command) bson_array_builder_append_document_end (pipeline, &change_stream_stage); /* Append user pipeline if it exists */ - if (bson_iter_init_find (&iter, &stream->pipeline_to_append, "pipeline") && - BSON_ITER_HOLDS_ARRAY (&iter)) { + if (bson_iter_init_find (&iter, &stream->pipeline_to_append, "pipeline") && BSON_ITER_HOLDS_ARRAY (&iter)) { bson_iter_t child_iter; BSON_ASSERT (bson_iter_recurse (&iter, &child_iter)); while (bson_iter_next (&child_iter)) { /* the user pipeline may consist of invalid stages or non-documents. * append anyway, and rely on the server error. */ - bson_array_builder_append_value (pipeline, - bson_iter_value (&child_iter)); + bson_array_builder_append_value (pipeline, bson_iter_value (&child_iter)); } } @@ -253,8 +234,7 @@ _make_cursor (mongoc_change_stream_t *stream) } if (bson_iter_init_find (&iter, &command_opts, "sessionId")) { - if (!_mongoc_client_session_from_iter ( - stream->client, &iter, &cs, &stream->err)) { + if (!_mongoc_client_session_from_iter (stream->client, &iter, &cs, &stream->err)) { goto cleanup; } } else if (stream->implicit_session) { @@ -278,8 +258,7 @@ _make_cursor (mongoc_change_stream_t *stream) cs = mongoc_client_start_session (stream->client, session_opts, NULL); stream->implicit_session = cs; mongoc_session_opts_destroy (session_opts); - if (cs && - !mongoc_client_session_append (cs, &command_opts, &stream->err)) { + if (cs && !mongoc_client_session_append (cs, &command_opts, &stream->err)) { goto cleanup; } } @@ -288,12 +267,8 @@ _make_cursor (mongoc_change_stream_t *stream) goto cleanup; } - server_stream = mongoc_cluster_stream_for_reads (&stream->client->cluster, - stream->read_prefs, - cs, - NULL, - &reply, - &stream->err); + server_stream = + mongoc_cluster_stream_for_reads (&stream->client->cluster, stream->read_prefs, cs, NULL, &reply, &stream->err); if (!server_stream) { bson_destroy (&stream->err_doc); bson_copy_to (&reply, &stream->err_doc); @@ -313,25 +288,16 @@ _make_cursor (mongoc_change_stream_t *stream) /* even though serverId has already been set, still pass the read prefs. * they are necessary for OP_MSG if sending to a secondary. */ - if (!mongoc_client_read_command_with_opts (stream->client, - stream->db, - &command, - stream->read_prefs, - &command_opts, - &reply, - &stream->err)) { + if (!mongoc_client_read_command_with_opts ( + stream->client, stream->db, &command, stream->read_prefs, &command_opts, &reply, &stream->err)) { bson_destroy (&stream->err_doc); bson_copy_to (&reply, &stream->err_doc); bson_destroy (&reply); goto cleanup; } - bson_append_bool ( - &getmore_opts, MONGOC_CURSOR_TAILABLE, MONGOC_CURSOR_TAILABLE_LEN, true); - bson_append_bool (&getmore_opts, - MONGOC_CURSOR_AWAIT_DATA, - MONGOC_CURSOR_AWAIT_DATA_LEN, - true); + bson_append_bool (&getmore_opts, MONGOC_CURSOR_TAILABLE, MONGOC_CURSOR_TAILABLE_LEN, true); + bson_append_bool (&getmore_opts, MONGOC_CURSOR_AWAIT_DATA, MONGOC_CURSOR_AWAIT_DATA_LEN, true); /* maxTimeMS is only appended to getMores if these are set in cursor opts. */ if (stream->max_await_time_ms > 0) { @@ -342,15 +308,11 @@ _make_cursor (mongoc_change_stream_t *stream) } if (stream->batch_size > 0) { - bson_append_int32 (&getmore_opts, - MONGOC_CURSOR_BATCH_SIZE, - MONGOC_CURSOR_BATCH_SIZE_LEN, - stream->batch_size); + bson_append_int32 (&getmore_opts, MONGOC_CURSOR_BATCH_SIZE, MONGOC_CURSOR_BATCH_SIZE_LEN, stream->batch_size); } /* steals reply. */ - stream->cursor = - _mongoc_cursor_change_stream_new (stream->client, &reply, &getmore_opts); + stream->cursor = _mongoc_cursor_change_stream_new (stream->client, &reply, &getmore_opts); if (mongoc_cursor_error (stream->cursor, NULL)) { goto cleanup; @@ -359,24 +321,15 @@ _make_cursor (mongoc_change_stream_t *stream) /* Change stream spec: "When aggregate or getMore returns: If an empty batch * was returned and a postBatchResumeToken was included, cache it." */ if (_mongoc_cursor_change_stream_end_of_batch (stream->cursor) && - _mongoc_cursor_change_stream_has_post_batch_resume_token ( - stream->cursor)) { - _set_resume_token ( - stream, - _mongoc_cursor_change_stream_get_post_batch_resume_token ( - stream->cursor)); + _mongoc_cursor_change_stream_has_post_batch_resume_token (stream->cursor)) { + _set_resume_token (stream, _mongoc_cursor_change_stream_get_post_batch_resume_token (stream->cursor)); } /* Change stream spec: startAtOperationTime */ - if (bson_empty (&stream->opts.resumeAfter) && - bson_empty (&stream->opts.startAfter) && - _mongoc_timestamp_empty (&stream->operation_time) && - stream->max_wire_version >= WIRE_VERSION_4_0 && + if (bson_empty (&stream->opts.resumeAfter) && bson_empty (&stream->opts.startAfter) && + _mongoc_timestamp_empty (&stream->operation_time) && stream->max_wire_version >= WIRE_VERSION_4_0 && bson_empty (&stream->resume_token) && - bson_iter_init_find ( - &iter, - _mongoc_cursor_change_stream_get_reply (stream->cursor), - "operationTime") && + bson_iter_init_find (&iter, _mongoc_cursor_change_stream_get_reply (stream->cursor), "operationTime") && BSON_ITER_HOLDS_TIMESTAMP (&iter)) { _mongoc_timestamp_set_from_bson (&stream->operation_time, &iter); } @@ -399,9 +352,7 @@ _make_cursor (mongoc_change_stream_t *stream) *-------------------------------------------------------------------------- */ void -_change_stream_init (mongoc_change_stream_t *stream, - const bson_t *pipeline, - const bson_t *opts) +_change_stream_init (mongoc_change_stream_t *stream, const bson_t *pipeline, const bson_t *opts) { BSON_ASSERT (pipeline); @@ -411,23 +362,20 @@ _change_stream_init (mongoc_change_stream_t *stream, bson_init (&stream->resume_token); bson_init (&stream->err_doc); - if (!_mongoc_change_stream_opts_parse ( - stream->client, opts, &stream->opts, &stream->err)) { + if (!_mongoc_change_stream_opts_parse (stream->client, opts, &stream->opts, &stream->err)) { return; } if (stream->opts.fullDocument) { - stream->full_document = - BCON_NEW ("fullDocument", stream->opts.fullDocument); + stream->full_document = BCON_NEW ("fullDocument", stream->opts.fullDocument); } if (stream->opts.fullDocumentBeforeChange) { - stream->full_document_before_change = BCON_NEW ( - "fullDocumentBeforeChange", stream->opts.fullDocumentBeforeChange); + stream->full_document_before_change = + BCON_NEW ("fullDocumentBeforeChange", stream->opts.fullDocumentBeforeChange); } - _mongoc_timestamp_set (&stream->operation_time, - &stream->opts.startAtOperationTime); + _mongoc_timestamp_set (&stream->operation_time, &stream->opts.startAtOperationTime); stream->batch_size = stream->opts.batchSize; stream->max_await_time_ms = stream->opts.maxAwaitTimeMS; @@ -441,16 +389,12 @@ _change_stream_init (mongoc_change_stream_t *stream, */ if (!bson_empty (pipeline)) { bson_iter_t iter; - if (bson_iter_init_find (&iter, pipeline, "pipeline") && - BSON_ITER_HOLDS_ARRAY (&iter)) { - if (!BSON_APPEND_VALUE (&stream->pipeline_to_append, - "pipeline", - bson_iter_value (&iter))) { + if (bson_iter_init_find (&iter, pipeline, "pipeline") && BSON_ITER_HOLDS_ARRAY (&iter)) { + if (!BSON_APPEND_VALUE (&stream->pipeline_to_append, "pipeline", bson_iter_value (&iter))) { CHANGE_STREAM_ERR ("pipeline"); } } else { - if (!BSON_APPEND_ARRAY ( - &stream->pipeline_to_append, "pipeline", pipeline)) { + if (!BSON_APPEND_ARRAY (&stream->pipeline_to_append, "pipeline", pipeline)) { CHANGE_STREAM_ERR ("pipeline"); } } @@ -462,9 +406,7 @@ _change_stream_init (mongoc_change_stream_t *stream, } mongoc_change_stream_t * -_mongoc_change_stream_new_from_collection (const mongoc_collection_t *coll, - const bson_t *pipeline, - const bson_t *opts) +_mongoc_change_stream_new_from_collection (const mongoc_collection_t *coll, const bson_t *pipeline, const bson_t *opts) { mongoc_change_stream_t *stream; BSON_ASSERT (coll); @@ -481,9 +423,7 @@ _mongoc_change_stream_new_from_collection (const mongoc_collection_t *coll, } mongoc_change_stream_t * -_mongoc_change_stream_new_from_database (const mongoc_database_t *db, - const bson_t *pipeline, - const bson_t *opts) +_mongoc_change_stream_new_from_database (const mongoc_database_t *db, const bson_t *pipeline, const bson_t *opts) { mongoc_change_stream_t *stream; BSON_ASSERT (db); @@ -500,9 +440,7 @@ _mongoc_change_stream_new_from_database (const mongoc_database_t *db, } mongoc_change_stream_t * -_mongoc_change_stream_new_from_client (mongoc_client_t *client, - const bson_t *pipeline, - const bson_t *opts) +_mongoc_change_stream_new_from_client (mongoc_client_t *client, const bson_t *pipeline, const bson_t *opts) { mongoc_change_stream_t *stream; BSON_ASSERT (client); @@ -591,8 +529,7 @@ mongoc_change_stream_next (mongoc_change_stream_t *stream, const bson_t **bson) * resume. */ stream->has_returned_results = true; - if (!bson_iter_init_find (&iter, *bson, "_id") || - !BSON_ITER_HOLDS_DOCUMENT (&iter)) { + if (!bson_iter_init_find (&iter, *bson, "_id") || !BSON_ITER_HOLDS_DOCUMENT (&iter)) { bson_set_error (&stream->err, MONGOC_ERROR_CURSOR, MONGOC_ERROR_CHANGE_STREAM_NO_RESUME_TOKEN, @@ -614,12 +551,8 @@ mongoc_change_stream_next (mongoc_change_stream_t *stream, const bson_t **bson) /* Change stream spec: Updating the Cached Resume Token */ if (stream->cursor && !mongoc_cursor_error (stream->cursor, NULL) && _mongoc_cursor_change_stream_end_of_batch (stream->cursor) && - _mongoc_cursor_change_stream_has_post_batch_resume_token ( - stream->cursor)) { - _set_resume_token ( - stream, - _mongoc_cursor_change_stream_get_post_batch_resume_token ( - stream->cursor)); + _mongoc_cursor_change_stream_has_post_batch_resume_token (stream->cursor)) { + _set_resume_token (stream, _mongoc_cursor_change_stream_get_post_batch_resume_token (stream->cursor)); } @@ -638,9 +571,7 @@ mongoc_change_stream_next (mongoc_change_stream_t *stream, const bson_t **bson) } bool -mongoc_change_stream_error_document (const mongoc_change_stream_t *stream, - bson_error_t *err, - const bson_t **bson) +mongoc_change_stream_error_document (const mongoc_change_stream_t *stream, bson_error_t *err, const bson_t **bson) { BSON_ASSERT (stream); diff --git a/src/libmongoc/src/mongoc/mongoc-change-stream.h b/src/libmongoc/src/mongoc/mongoc-change-stream.h index ad64f8f55b..a71b1de715 100644 --- a/src/libmongoc/src/mongoc/mongoc-change-stream.h +++ b/src/libmongoc/src/mongoc/mongoc-change-stream.h @@ -37,9 +37,7 @@ MONGOC_EXPORT (bool) mongoc_change_stream_next (mongoc_change_stream_t *, const bson_t **); MONGOC_EXPORT (bool) -mongoc_change_stream_error_document (const mongoc_change_stream_t *, - bson_error_t *, - const bson_t **); +mongoc_change_stream_error_document (const mongoc_change_stream_t *, bson_error_t *, const bson_t **); BSON_END_DECLS diff --git a/src/libmongoc/src/mongoc/mongoc-client-pool-private.h b/src/libmongoc/src/mongoc/mongoc-client-pool-private.h index fbdf85ce68..f71d77df49 100644 --- a/src/libmongoc/src/mongoc/mongoc-client-pool-private.h +++ b/src/libmongoc/src/mongoc/mongoc-client-pool-private.h @@ -29,9 +29,7 @@ BSON_BEGIN_DECLS /* for tests */ void -_mongoc_client_pool_set_stream_initiator (mongoc_client_pool_t *pool, - mongoc_stream_initiator_t si, - void *user_data); +_mongoc_client_pool_set_stream_initiator (mongoc_client_pool_t *pool, mongoc_stream_initiator_t si, void *user_data); size_t mongoc_client_pool_get_size (mongoc_client_pool_t *pool); size_t diff --git a/src/libmongoc/src/mongoc/mongoc-client-pool.c b/src/libmongoc/src/mongoc/mongoc-client-pool.c index 486b5c5c69..c59e979f55 100644 --- a/src/libmongoc/src/mongoc/mongoc-client-pool.c +++ b/src/libmongoc/src/mongoc/mongoc-client-pool.c @@ -57,33 +57,28 @@ struct _mongoc_client_pool_t { #ifdef MONGOC_ENABLE_SSL void -mongoc_client_pool_set_ssl_opts (mongoc_client_pool_t *pool, - const mongoc_ssl_opt_t *opts) +mongoc_client_pool_set_ssl_opts (mongoc_client_pool_t *pool, const mongoc_ssl_opt_t *opts) { BSON_ASSERT_PARAM (pool); bson_mutex_lock (&pool->mutex); - _mongoc_ssl_opts_cleanup (&pool->ssl_opts, - false /* don't free internal opts. */); + _mongoc_ssl_opts_cleanup (&pool->ssl_opts, false /* don't free internal opts. */); pool->ssl_opts_set = false; if (opts) { - _mongoc_ssl_opts_copy_to ( - opts, &pool->ssl_opts, false /* don't overwrite internal opts. */); + _mongoc_ssl_opts_copy_to (opts, &pool->ssl_opts, false /* don't overwrite internal opts. */); pool->ssl_opts_set = true; } - mongoc_topology_scanner_set_ssl_opts (pool->topology->scanner, - &pool->ssl_opts); + mongoc_topology_scanner_set_ssl_opts (pool->topology->scanner, &pool->ssl_opts); bson_mutex_unlock (&pool->mutex); } void -_mongoc_client_pool_set_internal_tls_opts ( - mongoc_client_pool_t *pool, _mongoc_internal_tls_opts_t *internal) +_mongoc_client_pool_set_internal_tls_opts (mongoc_client_pool_t *pool, _mongoc_internal_tls_opts_t *internal) { BSON_ASSERT_PARAM (pool); @@ -93,8 +88,7 @@ _mongoc_client_pool_set_internal_tls_opts ( return; } pool->ssl_opts.internal = bson_malloc (sizeof (_mongoc_internal_tls_opts_t)); - memcpy ( - pool->ssl_opts.internal, internal, sizeof (_mongoc_internal_tls_opts_t)); + memcpy (pool->ssl_opts.internal, internal, sizeof (_mongoc_internal_tls_opts_t)); bson_mutex_unlock (&pool->mutex); } #endif @@ -165,10 +159,8 @@ mongoc_client_pool_new_with_error (const mongoc_uri_t *uri, bson_error_t *error) b = mongoc_uri_get_options (pool->uri); if (bson_iter_init_find_case (&iter, b, MONGOC_URI_MINPOOLSIZE)) { - MONGOC_WARNING ( - MONGOC_URI_MINPOOLSIZE - " is deprecated; its behavior does not match its name, and its actual" - " behavior will likely hurt performance."); + MONGOC_WARNING (MONGOC_URI_MINPOOLSIZE " is deprecated; its behavior does not match its name, and its actual" + " behavior will likely hurt performance."); if (BSON_ITER_HOLDS_INT32 (&iter)) { pool->min_pool_size = BSON_MAX (0, bson_iter_int32 (&iter)); @@ -181,8 +173,7 @@ mongoc_client_pool_new_with_error (const mongoc_uri_t *uri, bson_error_t *error) } } - appname = - mongoc_uri_get_option_as_utf8 (pool->uri, MONGOC_URI_APPNAME, NULL); + appname = mongoc_uri_get_option_as_utf8 (pool->uri, MONGOC_URI_APPNAME, NULL); if (appname) { /* the appname should have already been validated */ BSON_ASSERT (mongoc_client_pool_set_appname (pool, appname)); @@ -222,8 +213,7 @@ mongoc_client_pool_destroy (mongoc_client_pool_t *pool) mongoc_client_pool_push (pool, client); } - while ( - (client = (mongoc_client_t *) _mongoc_queue_pop_head (&pool->queue))) { + while ((client = (mongoc_client_t *) _mongoc_queue_pop_head (&pool->queue))) { mongoc_client_destroy (client); } @@ -271,15 +261,12 @@ _initialize_new_client (mongoc_client_pool_t *pool, mongoc_client_t *client) /* for tests */ mongoc_client_set_stream_initiator ( - client, - pool->topology->scanner->initiator, - pool->topology->scanner->initiator_context); + client, pool->topology->scanner->initiator, pool->topology->scanner->initiator_context); pool->client_initialized = true; client->is_pooled = true; client->error_api_version = pool->error_api_version; - _mongoc_client_set_apm_callbacks_private ( - client, &pool->apm_callbacks, pool->apm_context); + _mongoc_client_set_apm_callbacks_private (client, &pool->apm_callbacks, pool->apm_context); client->api = mongoc_server_api_copy (pool->api); @@ -303,11 +290,9 @@ mongoc_client_pool_pop (mongoc_client_pool_t *pool) BSON_ASSERT_PARAM (pool); - wait_queue_timeout_ms = mongoc_uri_get_option_as_int32 ( - pool->uri, MONGOC_URI_WAITQUEUETIMEOUTMS, -1); + wait_queue_timeout_ms = mongoc_uri_get_option_as_int32 (pool->uri, MONGOC_URI_WAITQUEUETIMEOUTMS, -1); if (wait_queue_timeout_ms > 0) { - expire_at_ms = - (bson_get_monotonic_time () / 1000) + wait_queue_timeout_ms; + expire_at_ms = (bson_get_monotonic_time () / 1000) + wait_queue_timeout_ms; } bson_mutex_lock (&pool->mutex); @@ -322,8 +307,7 @@ mongoc_client_pool_pop (mongoc_client_pool_t *pool) if (wait_queue_timeout_ms > 0) { now_ms = bson_get_monotonic_time () / 1000; if (now_ms < expire_at_ms) { - r = mongoc_cond_timedwait ( - &pool->cond, &pool->mutex, expire_at_ms - now_ms); + r = mongoc_cond_timedwait (&pool->cond, &pool->mutex, expire_at_ms - now_ms); if (mongo_cond_ret_is_timedout (r)) { GOTO (done); } @@ -385,8 +369,7 @@ mongoc_client_pool_push (mongoc_client_pool_t *pool, mongoc_client_t *client) bson_mutex_lock (&pool->mutex); _mongoc_queue_push_head (&pool->queue, client); - if (pool->min_pool_size && - _mongoc_queue_get_length (&pool->queue) > pool->min_pool_size) { + if (pool->min_pool_size && _mongoc_queue_get_length (&pool->queue) > pool->min_pool_size) { mongoc_client_t *old_client; old_client = (mongoc_client_t *) _mongoc_queue_pop_tail (&pool->queue); if (old_client) { @@ -403,14 +386,11 @@ mongoc_client_pool_push (mongoc_client_pool_t *pool, mongoc_client_t *client) /* for tests */ void -_mongoc_client_pool_set_stream_initiator (mongoc_client_pool_t *pool, - mongoc_stream_initiator_t si, - void *context) +_mongoc_client_pool_set_stream_initiator (mongoc_client_pool_t *pool, mongoc_stream_initiator_t si, void *context) { BSON_ASSERT_PARAM (pool); - mongoc_topology_scanner_set_stream_initiator ( - pool->topology->scanner, si, context); + mongoc_topology_scanner_set_stream_initiator (pool->topology->scanner, si, context); } /* for tests */ @@ -474,9 +454,8 @@ mongoc_client_pool_min_size (mongoc_client_pool_t *pool, uint32_t min_pool_size) ENTRY; BSON_ASSERT_PARAM (pool); - MONGOC_WARNING ( - "mongoc_client_pool_min_size is deprecated; its behavior does not match" - " its name, and its actual behavior will likely hurt performance."); + MONGOC_WARNING ("mongoc_client_pool_min_size is deprecated; its behavior does not match" + " its name, and its actual behavior will likely hurt performance."); bson_mutex_lock (&pool->mutex); pool->min_pool_size = min_pool_size; @@ -486,9 +465,7 @@ mongoc_client_pool_min_size (mongoc_client_pool_t *pool, uint32_t min_pool_size) } bool -mongoc_client_pool_set_apm_callbacks (mongoc_client_pool_t *pool, - mongoc_apm_callbacks_t *callbacks, - void *context) +mongoc_client_pool_set_apm_callbacks (mongoc_client_pool_t *pool, mongoc_apm_callbacks_t *callbacks, void *context) { BSON_ASSERT_PARAM (pool); @@ -503,14 +480,11 @@ mongoc_client_pool_set_apm_callbacks (mongoc_client_pool_t *pool, tdmod = mc_tpld_modify_begin (topology); if (callbacks) { - memcpy (&tdmod.new_td->apm_callbacks, - callbacks, - sizeof (mongoc_apm_callbacks_t)); + memcpy (&tdmod.new_td->apm_callbacks, callbacks, sizeof (mongoc_apm_callbacks_t)); memcpy (&pool->apm_callbacks, callbacks, sizeof (mongoc_apm_callbacks_t)); } - mongoc_topology_set_apm_callbacks ( - topology, tdmod.new_td, callbacks, context); + mongoc_topology_set_apm_callbacks (topology, tdmod.new_td, callbacks, context); tdmod.new_td->apm_context = context; pool->apm_context = context; pool->apm_callbacks_set = true; @@ -523,8 +497,7 @@ mongoc_client_pool_set_apm_callbacks (mongoc_client_pool_t *pool, bool mongoc_client_pool_set_error_api (mongoc_client_pool_t *pool, int32_t version) { - if (version != MONGOC_ERROR_API_VERSION_LEGACY && - version != MONGOC_ERROR_API_VERSION_2) { + if (version != MONGOC_ERROR_API_VERSION_LEGACY && version != MONGOC_ERROR_API_VERSION_2) { MONGOC_ERROR ("Unsupported Error API Version: %" PRId32, version); return false; } @@ -563,23 +536,18 @@ mongoc_client_pool_enable_auto_encryption (mongoc_client_pool_t *pool, { BSON_ASSERT_PARAM (pool); - return _mongoc_cse_client_pool_enable_auto_encryption ( - pool->topology, opts, error); + return _mongoc_cse_client_pool_enable_auto_encryption (pool->topology, opts, error); } bool -mongoc_client_pool_set_server_api (mongoc_client_pool_t *pool, - const mongoc_server_api_t *api, - bson_error_t *error) +mongoc_client_pool_set_server_api (mongoc_client_pool_t *pool, const mongoc_server_api_t *api, bson_error_t *error) { BSON_ASSERT_PARAM (pool); BSON_ASSERT_PARAM (api); if (pool->api) { - bson_set_error (error, - MONGOC_ERROR_POOL, - MONGOC_ERROR_POOL_API_ALREADY_SET, - "Cannot set server api more than once per pool"); + bson_set_error ( + error, MONGOC_ERROR_POOL, MONGOC_ERROR_POOL_API_ALREADY_SET, "Cannot set server api more than once per pool"); return false; } diff --git a/src/libmongoc/src/mongoc/mongoc-client-pool.h b/src/libmongoc/src/mongoc/mongoc-client-pool.h index c4df560fe4..384b44522b 100644 --- a/src/libmongoc/src/mongoc/mongoc-client-pool.h +++ b/src/libmongoc/src/mongoc/mongoc-client-pool.h @@ -40,46 +40,35 @@ typedef struct _mongoc_client_pool_t mongoc_client_pool_t; MONGOC_EXPORT (mongoc_client_pool_t *) mongoc_client_pool_new (const mongoc_uri_t *uri) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (mongoc_client_pool_t *) -mongoc_client_pool_new_with_error (const mongoc_uri_t *uri, bson_error_t *error) - BSON_GNUC_WARN_UNUSED_RESULT; +mongoc_client_pool_new_with_error (const mongoc_uri_t *uri, bson_error_t *error) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (void) mongoc_client_pool_destroy (mongoc_client_pool_t *pool); MONGOC_EXPORT (mongoc_client_t *) -mongoc_client_pool_pop (mongoc_client_pool_t *pool) - BSON_GNUC_WARN_UNUSED_RESULT; +mongoc_client_pool_pop (mongoc_client_pool_t *pool) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (void) mongoc_client_pool_push (mongoc_client_pool_t *pool, mongoc_client_t *client); MONGOC_EXPORT (mongoc_client_t *) -mongoc_client_pool_try_pop (mongoc_client_pool_t *pool) - BSON_GNUC_WARN_UNUSED_RESULT; +mongoc_client_pool_try_pop (mongoc_client_pool_t *pool) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (void) -mongoc_client_pool_max_size (mongoc_client_pool_t *pool, - uint32_t max_pool_size); +mongoc_client_pool_max_size (mongoc_client_pool_t *pool, uint32_t max_pool_size); MONGOC_EXPORT (void) -mongoc_client_pool_min_size (mongoc_client_pool_t *pool, - uint32_t min_pool_size) BSON_GNUC_DEPRECATED; +mongoc_client_pool_min_size (mongoc_client_pool_t *pool, uint32_t min_pool_size) BSON_GNUC_DEPRECATED; #ifdef MONGOC_ENABLE_SSL MONGOC_EXPORT (void) -mongoc_client_pool_set_ssl_opts (mongoc_client_pool_t *pool, - const mongoc_ssl_opt_t *opts); +mongoc_client_pool_set_ssl_opts (mongoc_client_pool_t *pool, const mongoc_ssl_opt_t *opts); #endif MONGOC_EXPORT (bool) -mongoc_client_pool_set_apm_callbacks (mongoc_client_pool_t *pool, - mongoc_apm_callbacks_t *callbacks, - void *context); +mongoc_client_pool_set_apm_callbacks (mongoc_client_pool_t *pool, mongoc_apm_callbacks_t *callbacks, void *context); MONGOC_EXPORT (bool) mongoc_client_pool_set_error_api (mongoc_client_pool_t *pool, int32_t version); MONGOC_EXPORT (bool) -mongoc_client_pool_set_appname (mongoc_client_pool_t *pool, - const char *appname); +mongoc_client_pool_set_appname (mongoc_client_pool_t *pool, const char *appname); MONGOC_EXPORT (bool) mongoc_client_pool_enable_auto_encryption (mongoc_client_pool_t *pool, mongoc_auto_encryption_opts_t *opts, bson_error_t *error); MONGOC_EXPORT (bool) -mongoc_client_pool_set_server_api (mongoc_client_pool_t *pool, - const mongoc_server_api_t *api, - bson_error_t *error); +mongoc_client_pool_set_server_api (mongoc_client_pool_t *pool, const mongoc_server_api_t *api, bson_error_t *error); BSON_END_DECLS diff --git a/src/libmongoc/src/mongoc/mongoc-client-private.h b/src/libmongoc/src/mongoc/mongoc-client-private.h index 7a90dbe69f..510765ccf6 100644 --- a/src/libmongoc/src/mongoc/mongoc-client-private.h +++ b/src/libmongoc/src/mongoc/mongoc-client-private.h @@ -134,8 +134,7 @@ typedef enum { MONGOC_CMD_RW = 3, } mongoc_command_mode_t; -BSON_STATIC_ASSERT2 (mongoc_cmd_rw, - MONGOC_CMD_RW == (MONGOC_CMD_READ | MONGOC_CMD_WRITE)); +BSON_STATIC_ASSERT2 (mongoc_cmd_rw, MONGOC_CMD_RW == (MONGOC_CMD_READ | MONGOC_CMD_WRITE)); /* TODO (CDRIVER-4052): Move MONGOC_RR_DEFAULT_BUFFER_SIZE and @@ -153,9 +152,7 @@ mongoc_client_t * _mongoc_client_new_from_topology (mongoc_topology_t *topology); bool -_mongoc_client_set_apm_callbacks_private (mongoc_client_t *client, - mongoc_apm_callbacks_t *callbacks, - void *context); +_mongoc_client_set_apm_callbacks_private (mongoc_client_t *client, mongoc_apm_callbacks_t *callbacks, void *context); mongoc_stream_t * mongoc_client_default_stream_initiator (const mongoc_uri_t *uri, @@ -164,9 +161,7 @@ mongoc_client_default_stream_initiator (const mongoc_uri_t *uri, bson_error_t *error); mongoc_stream_t * -_mongoc_client_create_stream (mongoc_client_t *client, - const mongoc_host_list_t *host, - bson_error_t *error); +_mongoc_client_create_stream (mongoc_client_t *client, const mongoc_host_list_t *host, bson_error_t *error); bool _mongoc_client_recv (mongoc_client_t *client, @@ -198,8 +193,7 @@ _mongoc_client_command_with_opts (mongoc_client_t *client, bson_error_t *error); mongoc_server_session_t * -_mongoc_client_pop_server_session (mongoc_client_t *client, - bson_error_t *error); +_mongoc_client_pop_server_session (mongoc_client_t *client, bson_error_t *error); bool _mongoc_client_lookup_session (const mongoc_client_t *client, @@ -208,19 +202,15 @@ _mongoc_client_lookup_session (const mongoc_client_t *client, bson_error_t *error); void -_mongoc_client_unregister_session (mongoc_client_t *client, - mongoc_client_session_t *session); +_mongoc_client_unregister_session (mongoc_client_t *client, mongoc_client_session_t *session); void -_mongoc_client_push_server_session (mongoc_client_t *client, - mongoc_server_session_t *server_session); +_mongoc_client_push_server_session (mongoc_client_t *client, mongoc_server_session_t *server_session); void _mongoc_client_end_sessions (mongoc_client_t *client); mongoc_stream_t * -mongoc_client_connect_tcp (int32_t connecttimeoutms, - const mongoc_host_list_t *host, - bson_error_t *error); +mongoc_client_connect_tcp (int32_t connecttimeoutms, const mongoc_host_list_t *host, bson_error_t *error); mongoc_stream_t * mongoc_client_connect (bool buffered, diff --git a/src/libmongoc/src/mongoc/mongoc-client-session-private.h b/src/libmongoc/src/mongoc/mongoc-client-session-private.h index 7821ea630f..54a241c098 100644 --- a/src/libmongoc/src/mongoc/mongoc-client-session-private.h +++ b/src/libmongoc/src/mongoc/mongoc-client-session-private.h @@ -88,9 +88,7 @@ struct _mongoc_client_session_t { }; bool -_mongoc_parse_cluster_time (const bson_t *cluster_time, - uint32_t *timestamp, - uint32_t *increment); +_mongoc_parse_cluster_time (const bson_t *cluster_time, uint32_t *timestamp, uint32_t *increment); bool _mongoc_cluster_time_greater (const bson_t *new, const bson_t *old); @@ -102,15 +100,13 @@ _mongoc_client_session_handle_reply (mongoc_client_session_t *session, const bson_t *reply); bool -_mongoc_server_session_init (mongoc_server_session_t *session, - bson_error_t *error); +_mongoc_server_session_init (mongoc_server_session_t *session, bson_error_t *error); void _mongoc_server_session_destroy (mongoc_server_session_t *session); bool -_mongoc_server_session_timed_out (const mongoc_server_session_t *server_session, - int64_t session_timeout_minutes); +_mongoc_server_session_timed_out (const mongoc_server_session_t *server_session, int64_t session_timeout_minutes); mongoc_client_session_t * _mongoc_client_session_new (mongoc_client_t *client, @@ -128,16 +124,13 @@ bool _mongoc_client_session_in_txn (const mongoc_client_session_t *session); bool -_mongoc_client_session_in_txn_or_ending ( - const mongoc_client_session_t *session); +_mongoc_client_session_in_txn_or_ending (const mongoc_client_session_t *session); bool _mongoc_client_session_txn_in_progress (const mongoc_client_session_t *session); bool -_mongoc_client_session_append_txn (mongoc_client_session_t *session, - bson_t *cmd, - bson_error_t *error); +_mongoc_client_session_append_txn (mongoc_client_session_t *session, bson_t *cmd, bson_error_t *error); void _mongoc_client_session_append_read_concern (const mongoc_client_session_t *cs, @@ -149,13 +142,10 @@ void _mongoc_client_session_unpin (mongoc_client_session_t *session); void -_mongoc_client_session_pin (mongoc_client_session_t *session, - uint32_t server_id); +_mongoc_client_session_pin (mongoc_client_session_t *session, uint32_t server_id); void -_mongoc_client_session_set_snapshot_time (mongoc_client_session_t *session, - uint32_t t, - uint32_t i); +_mongoc_client_session_set_snapshot_time (mongoc_client_session_t *session, uint32_t t, uint32_t i); void _mongoc_client_session_clear_snapshot_time (mongoc_client_session_t *session); diff --git a/src/libmongoc/src/mongoc/mongoc-client-session.c b/src/libmongoc/src/mongoc/mongoc-client-session.c index 8299e52434..9db86bf63d 100644 --- a/src/libmongoc/src/mongoc/mongoc-client-session.c +++ b/src/libmongoc/src/mongoc/mongoc-client-session.c @@ -70,8 +70,7 @@ txn_opts_cleanup (mongoc_transaction_opt_t *opts) static void -txn_opts_copy (const mongoc_transaction_opt_t *src, - mongoc_transaction_opt_t *dst) +txn_opts_copy (const mongoc_transaction_opt_t *src, mongoc_transaction_opt_t *dst) { txn_opts_cleanup (dst); /* null inputs are ok for these copy functions */ @@ -99,8 +98,7 @@ txn_abort (mongoc_client_session_t *session, bson_t *reply, bson_error_t *error) } if (session->txn.opts.write_concern) { - if (!mongoc_write_concern_append (session->txn.opts.write_concern, - &opts)) { + if (!mongoc_write_concern_append (session->txn.opts.write_concern, &opts)) { bson_set_error (err_ptr, MONGOC_ERROR_TRANSACTION, MONGOC_ERROR_TRANSACTION_INVALID_STATE, @@ -116,8 +114,7 @@ txn_abort (mongoc_client_session_t *session, bson_t *reply, bson_error_t *error) /* 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); + 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. Note that a @@ -125,8 +122,7 @@ txn_abort (mongoc_client_session_t *session, bson_t *reply, bson_error_t *error) if (mongoc_error_has_label (&reply_local, RETRYABLE_WRITE_ERROR)) { _mongoc_client_session_unpin (session); bson_destroy (&reply_local); - r = mongoc_client_write_command_with_opts ( - session->client, "admin", &cmd, &opts, &reply_local, err_ptr); + r = mongoc_client_write_command_with_opts (session->client, "admin", &cmd, &opts, &reply_local, err_ptr); } if (!r) { @@ -149,16 +145,14 @@ create_commit_retry_wc (const mongoc_write_concern_t *existing_wc) { mongoc_write_concern_t *wc; - wc = existing_wc ? mongoc_write_concern_copy (existing_wc) - : mongoc_write_concern_new (); + wc = existing_wc ? mongoc_write_concern_copy (existing_wc) : mongoc_write_concern_new (); /* Transactions spec: "If the modified write concern does not include a * wtimeout value, drivers MUST also apply wtimeout: 10000 to the write * concern in order to avoid waiting forever if the majority write concern * cannot be satisfied." */ if (mongoc_write_concern_get_wtimeout_int64 (wc) <= 0) { - mongoc_write_concern_set_wtimeout_int64 ( - wc, MONGOC_DEFAULT_WTIMEOUT_FOR_COMMIT_RETRY); + mongoc_write_concern_set_wtimeout_int64 (wc, MONGOC_DEFAULT_WTIMEOUT_FOR_COMMIT_RETRY); } /* Transactions spec: "If the transaction is using a write concern that is @@ -171,10 +165,7 @@ create_commit_retry_wc (const mongoc_write_concern_t *existing_wc) static bool -txn_commit (mongoc_client_session_t *session, - bool explicitly_retrying, - bson_t *reply, - bson_error_t *error) +txn_commit (mongoc_client_session_t *session, bool explicitly_retrying, bson_t *reply, bson_error_t *error) { bson_t cmd = BSON_INITIALIZER; bson_t opts = BSON_INITIALIZER; @@ -199,12 +190,8 @@ txn_commit (mongoc_client_session_t *session, } if (session->txn.opts.max_commit_time_ms != DEFAULT_MAX_COMMIT_TIME_MS) { - if (!bson_append_int64 ( - &opts, "maxTimeMS", -1, session->txn.opts.max_commit_time_ms)) { - bson_set_error (err_ptr, - MONGOC_ERROR_BSON, - MONGOC_ERROR_BSON_INVALID, - "error appending maxCommitTimeMS"); + if (!bson_append_int64 (&opts, "maxTimeMS", -1, session->txn.opts.max_commit_time_ms)) { + bson_set_error (err_ptr, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "error appending maxCommitTimeMS"); GOTO (done); } } @@ -214,14 +201,12 @@ txn_commit (mongoc_client_session_t *session, * commitTransaction again, drivers MUST apply w:majority to the write * concern of the commitTransaction command." */ if (!retry_wc && (retrying_after_error || explicitly_retrying)) { - retry_wc = create_commit_retry_wc (session->txn.opts.write_concern - ? session->txn.opts.write_concern - : session->client->write_concern); + retry_wc = create_commit_retry_wc (session->txn.opts.write_concern ? session->txn.opts.write_concern + : session->client->write_concern); } if (retry_wc || session->txn.opts.write_concern) { - if (!mongoc_write_concern_append ( - retry_wc ? retry_wc : session->txn.opts.write_concern, &opts)) { + if (!mongoc_write_concern_append (retry_wc ? retry_wc : session->txn.opts.write_concern, &opts)) { bson_set_error (err_ptr, MONGOC_ERROR_TRANSACTION, MONGOC_ERROR_TRANSACTION_INVALID_STATE, @@ -232,8 +217,7 @@ txn_commit (mongoc_client_session_t *session, /* 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); + 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. Note that a @@ -249,20 +233,16 @@ txn_commit (mongoc_client_session_t *session, /* Transactions Spec: "add the UnknownTransactionCommitResult error label * when commitTransaction fails with a network error, server selection * error, MaxTimeMSExpired error, or write concern failed / timeout." */ - if (!r && (err_ptr->domain == MONGOC_ERROR_SERVER_SELECTION || - error_type == MONGOC_WRITE_ERR_RETRY || - error_type == MONGOC_WRITE_ERR_WRITE_CONCERN || - err_ptr->code == MONGOC_ERROR_MAX_TIME_MS_EXPIRED)) { + if (!r && (err_ptr->domain == MONGOC_ERROR_SERVER_SELECTION || error_type == MONGOC_WRITE_ERR_RETRY || + error_type == MONGOC_WRITE_ERR_WRITE_CONCERN || err_ptr->code == MONGOC_ERROR_MAX_TIME_MS_EXPIRED)) { /* Drivers MUST unpin a ClientSession when any individual * commitTransaction command attempt fails with an * UnknownTransactionCommitResult error label. Do this even if we won't * actually apply the error label due to reply being NULL */ _mongoc_client_session_unpin (session); if (reply) { - bsonBuildAppend (*reply, - insert (reply_local, not(key ("errorLabels")))); - _mongoc_error_copy_labels_and_upsert ( - &reply_local, reply, UNKNOWN_COMMIT_RESULT); + bsonBuildAppend (*reply, insert (reply_local, not(key ("errorLabels")))); + _mongoc_error_copy_labels_and_upsert (&reply_local, reply, UNKNOWN_COMMIT_RESULT); } } else if (reply) { /* maintain invariants: reply & reply_local are valid until the end */ @@ -288,8 +268,7 @@ mongoc_transaction_opt_t * mongoc_transaction_opts_new (void) { mongoc_transaction_opt_t *opts; - opts = (mongoc_transaction_opt_t *) bson_malloc0 ( - sizeof (mongoc_transaction_opt_t)); + opts = (mongoc_transaction_opt_t *) bson_malloc0 (sizeof (mongoc_transaction_opt_t)); opts->max_commit_time_ms = DEFAULT_MAX_COMMIT_TIME_MS; return opts; @@ -329,8 +308,7 @@ mongoc_transaction_opts_destroy (mongoc_transaction_opt_t *opts) void -mongoc_transaction_opts_set_max_commit_time_ms (mongoc_transaction_opt_t *opts, - int64_t max_commit_time_ms) +mongoc_transaction_opts_set_max_commit_time_ms (mongoc_transaction_opt_t *opts, int64_t max_commit_time_ms) { BSON_ASSERT (opts); opts->max_commit_time_ms = max_commit_time_ms; @@ -346,8 +324,7 @@ mongoc_transaction_opts_get_max_commit_time_ms (mongoc_transaction_opt_t *opts) void -mongoc_transaction_opts_set_read_concern ( - mongoc_transaction_opt_t *opts, const mongoc_read_concern_t *read_concern) +mongoc_transaction_opts_set_read_concern (mongoc_transaction_opt_t *opts, const mongoc_read_concern_t *read_concern) { BSON_ASSERT (opts); mongoc_read_concern_destroy (opts->read_concern); @@ -364,8 +341,7 @@ mongoc_transaction_opts_get_read_concern (const mongoc_transaction_opt_t *opts) void -mongoc_transaction_opts_set_write_concern ( - mongoc_transaction_opt_t *opts, const mongoc_write_concern_t *write_concern) +mongoc_transaction_opts_set_write_concern (mongoc_transaction_opt_t *opts, const mongoc_write_concern_t *write_concern) { BSON_ASSERT (opts); mongoc_write_concern_destroy (opts->write_concern); @@ -382,8 +358,7 @@ mongoc_transaction_opts_get_write_concern (const mongoc_transaction_opt_t *opts) void -mongoc_transaction_opts_set_read_prefs (mongoc_transaction_opt_t *opts, - const mongoc_read_prefs_t *read_prefs) +mongoc_transaction_opts_set_read_prefs (mongoc_transaction_opt_t *opts, const mongoc_read_prefs_t *read_prefs) { BSON_ASSERT (opts); mongoc_read_prefs_destroy (opts->read_prefs); @@ -407,8 +382,7 @@ mongoc_session_opts_get_causal_consistency (const mongoc_session_opt_t *opts) /* Causal Consistency spec: If no value is provided for causalConsistency * and snapshot reads are not requested a value of true is implied. */ - if (!mongoc_optional_is_set (&opts->causal_consistency) && - !mongoc_optional_value (&opts->snapshot)) { + if (!mongoc_optional_is_set (&opts->causal_consistency) && !mongoc_optional_value (&opts->snapshot)) { RETURN (true); } @@ -426,8 +400,7 @@ mongoc_session_opts_get_snapshot (const mongoc_session_opt_t *opts) } void -mongoc_session_opts_set_causal_consistency (mongoc_session_opt_t *opts, - bool causal_consistency) +mongoc_session_opts_set_causal_consistency (mongoc_session_opt_t *opts, bool causal_consistency) { ENTRY; @@ -462,8 +435,7 @@ mongoc_session_opts_new (void) } void -mongoc_session_opts_set_default_transaction_opts ( - mongoc_session_opt_t *opts, const mongoc_transaction_opt_t *txn_opts) +mongoc_session_opts_set_default_transaction_opts (mongoc_session_opt_t *opts, const mongoc_transaction_opt_t *txn_opts) { ENTRY; @@ -481,8 +453,7 @@ mongoc_session_opts_set_default_transaction_opts ( const mongoc_transaction_opt_t * -mongoc_session_opts_get_default_transaction_opts ( - const mongoc_session_opt_t *opts) +mongoc_session_opts_get_default_transaction_opts (const mongoc_session_opt_t *opts) { ENTRY; @@ -493,8 +464,7 @@ mongoc_session_opts_get_default_transaction_opts ( mongoc_transaction_opt_t * -mongoc_session_opts_get_transaction_opts ( - const mongoc_client_session_t *session) +mongoc_session_opts_get_transaction_opts (const mongoc_client_session_t *session) { ENTRY; @@ -508,8 +478,7 @@ mongoc_session_opts_get_transaction_opts ( } static void -_mongoc_session_opts_copy (const mongoc_session_opt_t *src, - mongoc_session_opt_t *dst) +_mongoc_session_opts_copy (const mongoc_session_opt_t *src, mongoc_session_opt_t *dst) { mongoc_optional_copy (&src->causal_consistency, &dst->causal_consistency); mongoc_optional_copy (&src->snapshot, &dst->snapshot); @@ -593,15 +562,12 @@ _mongoc_server_session_uuid (uint8_t *data /* OUT */, bson_error_t *error) bool -_mongoc_parse_cluster_time (const bson_t *cluster_time, - uint32_t *timestamp, - uint32_t *increment) +_mongoc_parse_cluster_time (const bson_t *cluster_time, uint32_t *timestamp, uint32_t *increment) { bson_iter_t iter; char *s; - if (!cluster_time || - !bson_iter_init_find (&iter, cluster_time, "clusterTime") || + if (!cluster_time || !bson_iter_init_find (&iter, cluster_time, "clusterTime") || !BSON_ITER_HOLDS_TIMESTAMP (&iter)) { s = bson_as_json (cluster_time, NULL); MONGOC_ERROR ("Cannot parse cluster time from %s\n", s); @@ -620,8 +586,7 @@ _mongoc_cluster_time_greater (const bson_t *new, const bson_t *old) { uint32_t new_t, new_i, old_t, old_i; - if (!_mongoc_parse_cluster_time (new, &new_t, &new_i) || - !_mongoc_parse_cluster_time (old, &old_t, &old_i)) { + if (!_mongoc_parse_cluster_time (new, &new_t, &new_i) || !_mongoc_parse_cluster_time (old, &old_t, &old_i)) { return false; } @@ -653,8 +618,7 @@ _mongoc_client_session_handle_reply (mongoc_client_session_t *session, } is_find_aggregate_distinct = - (!strcmp (cmd_name, "find") || !strcmp (cmd_name, "aggregate") || - !strcmp (cmd_name, "distinct")); + (!strcmp (cmd_name, "find") || !strcmp (cmd_name, "aggregate") || !strcmp (cmd_name, "distinct")); if (mongoc_error_has_label (reply, "TransientTransactionError")) { /* Transaction Spec: "Drivers MUST unpin a ClientSession when a command @@ -666,31 +630,24 @@ _mongoc_client_session_handle_reply (mongoc_client_session_t *session, } while (bson_iter_next (&iter)) { - if (!strcmp (bson_iter_key (&iter), "$clusterTime") && - BSON_ITER_HOLDS_DOCUMENT (&iter)) { + if (!strcmp (bson_iter_key (&iter), "$clusterTime") && BSON_ITER_HOLDS_DOCUMENT (&iter)) { bson_iter_document (&iter, &len, &data); BSON_ASSERT (bson_init_static (&cluster_time, data, (size_t) len)); mongoc_client_session_advance_cluster_time (session, &cluster_time); - } else if (!strcmp (bson_iter_key (&iter), "operationTime") && - BSON_ITER_HOLDS_TIMESTAMP (&iter) && is_acknowledged) { + } else if (!strcmp (bson_iter_key (&iter), "operationTime") && BSON_ITER_HOLDS_TIMESTAMP (&iter) && + is_acknowledged) { bson_iter_timestamp (&iter, &operation_t, &operation_i); - mongoc_client_session_advance_operation_time ( - session, operation_t, operation_i); - } else if (is_find_aggregate_distinct && - !strcmp (bson_iter_key (&iter), "atClusterTime") && - mongoc_session_opts_get_snapshot (&session->opts) && - !session->snapshot_time_set) { + mongoc_client_session_advance_operation_time (session, operation_t, operation_i); + } else if (is_find_aggregate_distinct && !strcmp (bson_iter_key (&iter), "atClusterTime") && + mongoc_session_opts_get_snapshot (&session->opts) && !session->snapshot_time_set) { /* If command is "find", "aggregate" or "distinct", atClusterTime is on * top level of reply, snapshot is enabled for the session, and * snapshot_time has not already been set, set it. */ bson_iter_timestamp (&iter, &snapshot_t, &snapshot_i); - _mongoc_client_session_set_snapshot_time ( - session, snapshot_t, snapshot_i); - } else if (is_find_aggregate_distinct && - !strcmp (bson_iter_key (&iter), "cursor") && - mongoc_session_opts_get_snapshot (&session->opts) && - !session->snapshot_time_set) { + _mongoc_client_session_set_snapshot_time (session, snapshot_t, snapshot_i); + } else if (is_find_aggregate_distinct && !strcmp (bson_iter_key (&iter), "cursor") && + mongoc_session_opts_get_snapshot (&session->opts) && !session->snapshot_time_set) { /* If command is "find", "aggregate" or "distinct", cursor is present, * snapshot is enabled for the session, and snapshot_time has not * already been set, try to find atClusterTime in cursor field to set @@ -700,11 +657,9 @@ _mongoc_client_session_handle_reply (mongoc_client_session_t *session, while (bson_iter_next (&cursor_iter)) { /* If atClusterTime is in cursor and is a valid timestamp, use it to * set snapshot_time. */ - if (!strcmp (bson_iter_key (&cursor_iter), "atClusterTime") && - BSON_ITER_HOLDS_TIMESTAMP (&cursor_iter)) { + if (!strcmp (bson_iter_key (&cursor_iter), "atClusterTime") && BSON_ITER_HOLDS_TIMESTAMP (&cursor_iter)) { bson_iter_timestamp (&cursor_iter, &snapshot_t, &snapshot_i); - _mongoc_client_session_set_snapshot_time ( - session, snapshot_t, snapshot_i); + _mongoc_client_session_set_snapshot_time (session, snapshot_t, snapshot_i); } } } @@ -725,15 +680,13 @@ _mongoc_server_session_init (mongoc_server_session_t *self, bson_error_t *error) self->txn_number = 0; self->last_used_usec = SESSION_NEVER_USED; bson_init (&self->lsid); - BSON_APPEND_BINARY ( - &self->lsid, "id", BSON_SUBTYPE_UUID, uuid_data, sizeof uuid_data); + BSON_APPEND_BINARY (&self->lsid, "id", BSON_SUBTYPE_UUID, uuid_data, sizeof uuid_data); RETURN (true); } bool -_mongoc_server_session_timed_out (const mongoc_server_session_t *server_session, - int64_t session_timeout_minutes) +_mongoc_server_session_timed_out (const mongoc_server_session_t *server_session, int64_t session_timeout_minutes) { int64_t timeout_usec; const int64_t minute_to_usec = 60 * 1000 * 1000; @@ -751,8 +704,7 @@ _mongoc_server_session_timed_out (const mongoc_server_session_t *server_session, /* Driver Sessions Spec: if a session has less than one minute left before * becoming stale, discard it */ - timeout_usec = - server_session->last_used_usec + session_timeout_minutes * minute_to_usec; + timeout_usec = server_session->last_used_usec + session_timeout_minutes * minute_to_usec; RETURN (timeout_usec - bson_get_monotonic_time () < 1 * minute_to_usec); } @@ -794,8 +746,7 @@ _mongoc_client_session_new (mongoc_client_t *client, DEFAULT_MAX_COMMIT_TIME_MS); if (opts) { - mongoc_optional_copy (&opts->causal_consistency, - &session->opts.causal_consistency); + mongoc_optional_copy (&opts->causal_consistency, &session->opts.causal_consistency); mongoc_optional_copy (&opts->snapshot, &session->opts.snapshot); txn_opts_set (&session->opts.default_txn_opts, opts->default_txn_opts.read_concern, @@ -862,15 +813,13 @@ mongoc_client_session_get_server_id (const mongoc_client_session_t *session) } void -mongoc_client_session_advance_cluster_time (mongoc_client_session_t *session, - const bson_t *cluster_time) +mongoc_client_session_advance_cluster_time (mongoc_client_session_t *session, const bson_t *cluster_time) { uint32_t t, i; ENTRY; - if (bson_empty (&session->cluster_time) && - _mongoc_parse_cluster_time (cluster_time, &t, &i)) { + if (bson_empty (&session->cluster_time) && _mongoc_parse_cluster_time (cluster_time, &t, &i)) { bson_destroy (&session->cluster_time); bson_copy_to (cluster_time, &session->cluster_time); EXIT; @@ -885,10 +834,9 @@ mongoc_client_session_advance_cluster_time (mongoc_client_session_t *session, } void -mongoc_client_session_get_operation_time ( - const mongoc_client_session_t *session, - uint32_t *timestamp, - uint32_t *increment) +mongoc_client_session_get_operation_time (const mongoc_client_session_t *session, + uint32_t *timestamp, + uint32_t *increment) { BSON_ASSERT (session); BSON_ASSERT (timestamp); @@ -899,17 +847,14 @@ mongoc_client_session_get_operation_time ( } void -mongoc_client_session_advance_operation_time (mongoc_client_session_t *session, - uint32_t timestamp, - uint32_t increment) +mongoc_client_session_advance_operation_time (mongoc_client_session_t *session, uint32_t timestamp, uint32_t increment) { ENTRY; BSON_ASSERT (session); if (timestamp > session->operation_timestamp || - (timestamp == session->operation_timestamp && - increment > session->operation_increment)) { + (timestamp == session->operation_timestamp && increment > session->operation_increment)) { session->operation_timestamp = timestamp; session->operation_increment = increment; } @@ -936,17 +881,14 @@ _max_time_ms_failure (bson_t *reply) /* We can fail with a maxTimeMS error with the error code at the top level, or nested within a writeConcernError. */ - if (bson_iter_init_find (&iter, reply, "codeName") && - BSON_ITER_HOLDS_UTF8 (&iter) && + if (bson_iter_init_find (&iter, reply, "codeName") && BSON_ITER_HOLDS_UTF8 (&iter) && 0 == strcmp (bson_iter_utf8 (&iter, NULL), MAX_TIME_MS_EXPIRED)) { return true; } bson_iter_init (&iter, reply); - if (bson_iter_find_descendant ( - &iter, "writeConcernError.codeName", &descendant) && - BSON_ITER_HOLDS_UTF8 (&descendant) && - 0 == strcmp (bson_iter_utf8 (&descendant, NULL), MAX_TIME_MS_EXPIRED)) { + if (bson_iter_find_descendant (&iter, "writeConcernError.codeName", &descendant) && + BSON_ITER_HOLDS_UTF8 (&descendant) && 0 == strcmp (bson_iter_utf8 (&descendant, NULL), MAX_TIME_MS_EXPIRED)) { return true; } @@ -954,13 +896,12 @@ _max_time_ms_failure (bson_t *reply) } bool -mongoc_client_session_with_transaction ( - mongoc_client_session_t *session, - mongoc_client_session_with_transaction_cb_t cb, - const mongoc_transaction_opt_t *opts, - void *ctx, - bson_t *reply, - bson_error_t *error) +mongoc_client_session_with_transaction (mongoc_client_session_t *session, + mongoc_client_session_with_transaction_cb_t cb, + const mongoc_transaction_opt_t *opts, + void *ctx, + bson_t *reply, + bson_error_t *error) { mongoc_internal_transaction_state_t state; int64_t timeout; @@ -971,8 +912,7 @@ mongoc_client_session_with_transaction ( ENTRY; - timeout = session->with_txn_timeout_ms > 0 ? session->with_txn_timeout_ms - : WITH_TXN_TIMEOUT_MS; + timeout = session->with_txn_timeout_ms > 0 ? session->with_txn_timeout_ms : WITH_TXN_TIMEOUT_MS; expire_at = bson_get_monotonic_time () + ((int64_t) timeout * 1000); @@ -1001,14 +941,11 @@ mongoc_client_session_with_transaction ( } if (!res) { - if (state == MONGOC_INTERNAL_TRANSACTION_STARTING || - state == MONGOC_INTERNAL_TRANSACTION_IN_PROGRESS) { - BSON_ASSERT ( - mongoc_client_session_abort_transaction (session, NULL)); + if (state == MONGOC_INTERNAL_TRANSACTION_STARTING || state == MONGOC_INTERNAL_TRANSACTION_IN_PROGRESS) { + BSON_ASSERT (mongoc_client_session_abort_transaction (session, NULL)); } - if (mongoc_error_has_label (active_reply, TRANSIENT_TXN_ERR) && - !timeout_exceeded (expire_at)) { + if (mongoc_error_has_label (active_reply, TRANSIENT_TXN_ERR) && !timeout_exceeded (expire_at)) { bson_destroy (active_reply); active_reply = NULL; continue; @@ -1018,10 +955,8 @@ mongoc_client_session_with_transaction ( GOTO (done); } - if (state == MONGOC_INTERNAL_TRANSACTION_ABORTED || - state == MONGOC_INTERNAL_TRANSACTION_NONE || - state == MONGOC_INTERNAL_TRANSACTION_COMMITTED || - state == MONGOC_INTERNAL_TRANSACTION_COMMITTED_EMPTY) { + if (state == MONGOC_INTERNAL_TRANSACTION_ABORTED || state == MONGOC_INTERNAL_TRANSACTION_NONE || + state == MONGOC_INTERNAL_TRANSACTION_COMMITTED || state == MONGOC_INTERNAL_TRANSACTION_COMMITTED_EMPTY) { GOTO (done); } @@ -1038,8 +973,7 @@ mongoc_client_session_with_transaction ( commit_transaction, which requires this like our other public functions that take a bson_t reply. */ while (true) { - res = mongoc_client_session_commit_transaction ( - session, active_reply, error); + res = mongoc_client_session_commit_transaction (session, active_reply, error); if (!res) { /* If we have a MaxTimeMsExpired error, fail and propogate @@ -1048,8 +982,7 @@ mongoc_client_session_with_transaction ( GOTO (done); } - if (mongoc_error_has_label (active_reply, UNKNOWN_COMMIT_RESULT) && - !timeout_exceeded (expire_at)) { + if (mongoc_error_has_label (active_reply, UNKNOWN_COMMIT_RESULT) && !timeout_exceeded (expire_at)) { /* Commit_transaction applies majority write concern on retry * attempts. * @@ -1060,8 +993,7 @@ mongoc_client_session_with_transaction ( continue; } - if (mongoc_error_has_label (active_reply, TRANSIENT_TXN_ERR) && - !timeout_exceeded (expire_at)) { + if (mongoc_error_has_label (active_reply, TRANSIENT_TXN_ERR) && !timeout_exceeded (expire_at)) { /* In the case of a transient txn error, go back to outside loop. We must set the reply to NULL so it may be used by the cb. */ bson_destroy (active_reply); @@ -1104,12 +1036,8 @@ mongoc_client_session_start_transaction (mongoc_client_session_t *session, BSON_ASSERT (session); ret = true; - server_stream = - mongoc_cluster_stream_for_writes (&session->client->cluster, - session, - NULL /* deprioritized servers */, - NULL /* reply */, - error); + server_stream = mongoc_cluster_stream_for_writes ( + &session->client->cluster, session, NULL /* deprioritized servers */, NULL /* reply */, error); if (!server_stream) { ret = false; GOTO (done); @@ -1125,8 +1053,7 @@ mongoc_client_session_start_transaction (mongoc_client_session_t *session, } if (server_stream->sd->max_wire_version < 7 || - (server_stream->sd->max_wire_version < 8 && - server_stream->sd->type == MONGOC_SERVER_MONGOS)) { + (server_stream->sd->max_wire_version < 8 && server_stream->sd->type == MONGOC_SERVER_MONGOS)) { bson_set_error (error, MONGOC_ERROR_TRANSACTION, MONGOC_ERROR_TRANSACTION_INVALID_STATE, @@ -1140,15 +1067,12 @@ mongoc_client_session_start_transaction (mongoc_client_session_t *session, switch (session->txn.state) { case MONGOC_INTERNAL_TRANSACTION_STARTING: case MONGOC_INTERNAL_TRANSACTION_IN_PROGRESS: - bson_set_error (error, - MONGOC_ERROR_TRANSACTION, - MONGOC_ERROR_TRANSACTION_INVALID_STATE, - "Transaction already in progress"); + bson_set_error ( + error, MONGOC_ERROR_TRANSACTION, MONGOC_ERROR_TRANSACTION_INVALID_STATE, "Transaction already in progress"); ret = false; GOTO (done); case MONGOC_INTERNAL_TRANSACTION_ENDING: - MONGOC_ERROR ( - "starting txn in invalid state MONGOC_INTERNAL_TRANSACTION_ENDING"); + MONGOC_ERROR ("starting txn in invalid state MONGOC_INTERNAL_TRANSACTION_ENDING"); abort (); case MONGOC_INTERNAL_TRANSACTION_COMMITTED: case MONGOC_INTERNAL_TRANSACTION_COMMITTED_EMPTY: @@ -1167,20 +1091,15 @@ mongoc_client_session_start_transaction (mongoc_client_session_t *session, session->opts.default_txn_opts.max_commit_time_ms); if (opts) { - txn_opts_set (&session->txn.opts, - opts->read_concern, - opts->write_concern, - opts->read_prefs, - opts->max_commit_time_ms); + txn_opts_set ( + &session->txn.opts, opts->read_concern, opts->write_concern, opts->read_prefs, opts->max_commit_time_ms); } - if (!mongoc_write_concern_is_acknowledged ( - session->txn.opts.write_concern)) { - bson_set_error ( - error, - MONGOC_ERROR_TRANSACTION, - MONGOC_ERROR_TRANSACTION_INVALID_STATE, - "Transactions do not support unacknowledged write concern"); + if (!mongoc_write_concern_is_acknowledged (session->txn.opts.write_concern)) { + bson_set_error (error, + MONGOC_ERROR_TRANSACTION, + MONGOC_ERROR_TRANSACTION_INVALID_STATE, + "Transactions do not support unacknowledged write concern"); ret = false; GOTO (done); } @@ -1214,8 +1133,7 @@ mongoc_client_session_in_transaction (const mongoc_client_session_t *session) mongoc_transaction_state_t -mongoc_client_session_get_transaction_state ( - const mongoc_client_session_t *session) +mongoc_client_session_get_transaction_state (const mongoc_client_session_t *session) { ENTRY; @@ -1238,16 +1156,13 @@ mongoc_client_session_get_transaction_state ( "getting transaction state"); abort (); default: - MONGOC_ERROR ("invalid state %d when getting transaction state", - (int) session->txn.state); + MONGOC_ERROR ("invalid state %d when getting transaction state", (int) session->txn.state); abort (); } } bool -mongoc_client_session_commit_transaction (mongoc_client_session_t *session, - bson_t *reply, - bson_error_t *error) +mongoc_client_session_commit_transaction (mongoc_client_session_t *session, bson_t *reply, bson_error_t *error) { bool r = false; @@ -1279,10 +1194,8 @@ mongoc_client_session_commit_transaction (mongoc_client_session_t *session, switch (session->txn.state) { case MONGOC_INTERNAL_TRANSACTION_NONE: - bson_set_error (error, - MONGOC_ERROR_TRANSACTION, - MONGOC_ERROR_TRANSACTION_INVALID_STATE, - "No transaction started"); + bson_set_error ( + error, MONGOC_ERROR_TRANSACTION, MONGOC_ERROR_TRANSACTION_INVALID_STATE, "No transaction started"); _mongoc_bson_init_if_set (reply); break; case MONGOC_INTERNAL_TRANSACTION_STARTING: @@ -1294,8 +1207,7 @@ mongoc_client_session_commit_transaction (mongoc_client_session_t *session, break; case MONGOC_INTERNAL_TRANSACTION_COMMITTED: case MONGOC_INTERNAL_TRANSACTION_IN_PROGRESS: { - bool explicitly_retrying = - (session->txn.state == MONGOC_INTERNAL_TRANSACTION_COMMITTED); + bool explicitly_retrying = (session->txn.state == MONGOC_INTERNAL_TRANSACTION_COMMITTED); /* in MONGOC_INTERNAL_TRANSACTION_ENDING we add txnNumber and autocommit: * false to the commitTransaction command, but if it fails with network * error we add UnknownTransactionCommitResult not @@ -1306,16 +1218,14 @@ mongoc_client_session_commit_transaction (mongoc_client_session_t *session, break; } case MONGOC_INTERNAL_TRANSACTION_ENDING: - MONGOC_ERROR ( - "commit called in invalid state MONGOC_INTERNAL_TRANSACTION_ENDING"); + MONGOC_ERROR ("commit called in invalid state MONGOC_INTERNAL_TRANSACTION_ENDING"); abort (); case MONGOC_INTERNAL_TRANSACTION_ABORTED: default: - bson_set_error ( - error, - MONGOC_ERROR_TRANSACTION, - MONGOC_ERROR_TRANSACTION_INVALID_STATE, - "Cannot call commitTransaction after calling abortTransaction"); + bson_set_error (error, + MONGOC_ERROR_TRANSACTION, + MONGOC_ERROR_TRANSACTION_INVALID_STATE, + "Cannot call commitTransaction after calling abortTransaction"); _mongoc_bson_init_if_set (reply); break; } @@ -1325,8 +1235,7 @@ mongoc_client_session_commit_transaction (mongoc_client_session_t *session, bool -mongoc_client_session_abort_transaction (mongoc_client_session_t *session, - bson_error_t *error) +mongoc_client_session_abort_transaction (mongoc_client_session_t *session, bson_error_t *error) { ENTRY; @@ -1352,28 +1261,22 @@ mongoc_client_session_abort_transaction (mongoc_client_session_t *session, RETURN (true); case MONGOC_INTERNAL_TRANSACTION_COMMITTED: case MONGOC_INTERNAL_TRANSACTION_COMMITTED_EMPTY: - bson_set_error ( - error, - MONGOC_ERROR_TRANSACTION, - MONGOC_ERROR_TRANSACTION_INVALID_STATE, - "Cannot call abortTransaction after calling commitTransaction"); - RETURN (false); - case MONGOC_INTERNAL_TRANSACTION_ABORTED: bson_set_error (error, MONGOC_ERROR_TRANSACTION, MONGOC_ERROR_TRANSACTION_INVALID_STATE, - "Cannot call abortTransaction twice"); + "Cannot call abortTransaction after calling commitTransaction"); + RETURN (false); + case MONGOC_INTERNAL_TRANSACTION_ABORTED: + bson_set_error ( + error, MONGOC_ERROR_TRANSACTION, MONGOC_ERROR_TRANSACTION_INVALID_STATE, "Cannot call abortTransaction twice"); RETURN (false); case MONGOC_INTERNAL_TRANSACTION_ENDING: - MONGOC_ERROR ( - "abort called in invalid state MONGOC_INTERNAL_TRANSACTION_ENDING"); + MONGOC_ERROR ("abort called in invalid state MONGOC_INTERNAL_TRANSACTION_ENDING"); abort (); case MONGOC_INTERNAL_TRANSACTION_NONE: default: - bson_set_error (error, - MONGOC_ERROR_TRANSACTION, - MONGOC_ERROR_TRANSACTION_INVALID_STATE, - "No transaction started"); + bson_set_error ( + error, MONGOC_ERROR_TRANSACTION, MONGOC_ERROR_TRANSACTION_INVALID_STATE, "No transaction started"); RETURN (false); } } @@ -1390,15 +1293,11 @@ _mongoc_client_session_from_iter (mongoc_client_t *client, /* must be int64 that fits in uint32 */ if (!BSON_ITER_HOLDS_INT64 (iter) || bson_iter_int64 (iter) > 0xffffffff) { - bson_set_error (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Invalid sessionId"); + bson_set_error (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid sessionId"); RETURN (false); } - RETURN (_mongoc_client_lookup_session ( - client, (uint32_t) bson_iter_int64 (iter), cs, error)); + RETURN (_mongoc_client_lookup_session (client, (uint32_t) bson_iter_int64 (iter), cs, error)); } /* Returns true if in the middle of a transaction. Note: this returns false if @@ -1479,9 +1378,7 @@ _mongoc_client_session_txn_in_progress (const mongoc_client_session_t *session) */ bool -_mongoc_client_session_append_txn (mongoc_client_session_t *session, - bson_t *cmd, - bson_error_t *error) +_mongoc_client_session_append_txn (mongoc_client_session_t *session, bson_t *cmd, bson_error_t *error) { mongoc_transaction_t *txn; @@ -1492,10 +1389,7 @@ _mongoc_client_session_append_txn (mongoc_client_session_t *session, } if (bson_empty0 (cmd)) { - bson_set_error (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Empty command in transaction"); + bson_set_error (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Empty command in transaction"); RETURN (false); } @@ -1510,15 +1404,13 @@ _mongoc_client_session_append_txn (mongoc_client_session_t *session, /* FALL THROUGH */ case MONGOC_INTERNAL_TRANSACTION_IN_PROGRESS: case MONGOC_INTERNAL_TRANSACTION_ENDING: - bson_append_int64 ( - cmd, "txnNumber", 9, session->server_session->txn_number); + bson_append_int64 (cmd, "txnNumber", 9, session->server_session->txn_number); bson_append_bool (cmd, "autocommit", 10, false); RETURN (true); case MONGOC_INTERNAL_TRANSACTION_COMMITTED: if (!strcmp (_mongoc_get_command_name (cmd), "commitTransaction")) { /* send commitTransaction again */ - bson_append_int64 ( - cmd, "txnNumber", 9, session->server_session->txn_number); + bson_append_int64 (cmd, "txnNumber", 9, session->server_session->txn_number); bson_append_bool (cmd, "autocommit", 10, false); RETURN (true); } @@ -1584,14 +1476,11 @@ _mongoc_client_session_append_read_concern (const mongoc_client_session_t *cs, return; } - has_timestamp = - (txn_state == MONGOC_INTERNAL_TRANSACTION_STARTING || is_read_command) && - mongoc_session_opts_get_causal_consistency (&cs->opts) && - cs->operation_timestamp; + has_timestamp = (txn_state == MONGOC_INTERNAL_TRANSACTION_STARTING || is_read_command) && + mongoc_session_opts_get_causal_consistency (&cs->opts) && cs->operation_timestamp; is_snapshot = mongoc_session_opts_get_snapshot (&cs->opts); user_rc_has_level = rc && bson_has_field (rc, "level"); - txn_has_level = txn_state == MONGOC_INTERNAL_TRANSACTION_STARTING && - !mongoc_read_concern_is_default (txn_rc); + txn_has_level = txn_state == MONGOC_INTERNAL_TRANSACTION_STARTING && !mongoc_read_concern_is_default (txn_rc); has_level = user_rc_has_level || txn_has_level; /* do not append read concern if no causal consistency, snapshot disabled and @@ -1613,25 +1502,16 @@ _mongoc_client_session_append_read_concern (const mongoc_client_session_t *cs, } } if (is_snapshot) { - bson_append_utf8 ( - &child, "level", 5, MONGOC_READ_CONCERN_LEVEL_SNAPSHOT, -1); + bson_append_utf8 (&child, "level", 5, MONGOC_READ_CONCERN_LEVEL_SNAPSHOT, -1); } /* append afterClusterTime if causal consistency and operation_time is set. * otherwise append atClusterTime if snapshot enabled and snapshot_time is * set. */ if (has_timestamp) { - bson_append_timestamp (&child, - "afterClusterTime", - 16, - cs->operation_timestamp, - cs->operation_increment); + bson_append_timestamp (&child, "afterClusterTime", 16, cs->operation_timestamp, cs->operation_increment); } else if (is_snapshot && cs->snapshot_time_set) { - bson_append_timestamp (&child, - "atClusterTime", - 13, - cs->snapshot_time_timestamp, - cs->snapshot_time_increment); + bson_append_timestamp (&child, "atClusterTime", 13, cs->snapshot_time_timestamp, cs->snapshot_time_increment); } bson_append_document_end (cmd, &child); @@ -1639,19 +1519,15 @@ _mongoc_client_session_append_read_concern (const mongoc_client_session_t *cs, bool -mongoc_client_session_append (const mongoc_client_session_t *client_session, - bson_t *opts, - bson_error_t *error) +mongoc_client_session_append (const mongoc_client_session_t *client_session, bson_t *opts, bson_error_t *error) { ENTRY; BSON_ASSERT (client_session); BSON_ASSERT (opts); - if (!bson_append_int64 ( - opts, "sessionId", 9, client_session->client_session_id)) { - bson_set_error ( - error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "invalid opts"); + if (!bson_append_int64 (opts, "sessionId", 9, client_session->client_session_id)) { + bson_set_error (error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "invalid opts"); RETURN (false); } @@ -1675,13 +1551,11 @@ mongoc_client_session_destroy (mongoc_client_session_t *session) } _mongoc_client_unregister_session (session->client, session); - _mongoc_client_push_server_session (session->client, - session->server_session); + _mongoc_client_push_server_session (session->client, session->server_session); } else { /** If the client has been reset, destroy the server session instead of * pushing it back into the topology's pool. */ - mongoc_server_session_pool_drop (session->client->topology->session_pool, - session->server_session); + mongoc_server_session_pool_drop (session->client->topology->session_pool, session->server_session); } txn_opts_cleanup (&session->opts.default_txn_opts); @@ -1703,8 +1577,7 @@ _mongoc_client_session_unpin (mongoc_client_session_t *session) } void -_mongoc_client_session_pin (mongoc_client_session_t *session, - uint32_t server_id) +_mongoc_client_session_pin (mongoc_client_session_t *session, uint32_t server_id) { BSON_ASSERT (session); @@ -1712,9 +1585,7 @@ _mongoc_client_session_pin (mongoc_client_session_t *session, } void -_mongoc_client_session_set_snapshot_time (mongoc_client_session_t *session, - uint32_t t, - uint32_t i) +_mongoc_client_session_set_snapshot_time (mongoc_client_session_t *session, uint32_t t, uint32_t i) { BSON_ASSERT (session); BSON_ASSERT (!session->snapshot_time_set); diff --git a/src/libmongoc/src/mongoc/mongoc-client-session.h b/src/libmongoc/src/mongoc/mongoc-client-session.h index b274261722..4429a2eab9 100644 --- a/src/libmongoc/src/mongoc/mongoc-client-session.h +++ b/src/libmongoc/src/mongoc/mongoc-client-session.h @@ -27,11 +27,10 @@ BSON_BEGIN_DECLS -typedef bool (*mongoc_client_session_with_transaction_cb_t) ( - mongoc_client_session_t *session, - void *ctx, - bson_t **reply, - bson_error_t *error); +typedef bool (*mongoc_client_session_with_transaction_cb_t) (mongoc_client_session_t *session, + void *ctx, + bson_t **reply, + bson_error_t *error); typedef enum { MONGOC_TRANSACTION_NONE = 0, @@ -47,37 +46,31 @@ MONGOC_EXPORT (mongoc_transaction_opt_t *) mongoc_transaction_opts_new (void) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (mongoc_transaction_opt_t *) -mongoc_transaction_opts_clone (const mongoc_transaction_opt_t *opts) - BSON_GNUC_WARN_UNUSED_RESULT; +mongoc_transaction_opts_clone (const mongoc_transaction_opt_t *opts) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (void) mongoc_transaction_opts_destroy (mongoc_transaction_opt_t *opts); MONGOC_EXPORT (void) -mongoc_transaction_opts_set_max_commit_time_ms (mongoc_transaction_opt_t *opts, - int64_t max_commit_time_ms); +mongoc_transaction_opts_set_max_commit_time_ms (mongoc_transaction_opt_t *opts, int64_t max_commit_time_ms); MONGOC_EXPORT (int64_t) mongoc_transaction_opts_get_max_commit_time_ms (mongoc_transaction_opt_t *opts); MONGOC_EXPORT (void) -mongoc_transaction_opts_set_read_concern ( - mongoc_transaction_opt_t *opts, const mongoc_read_concern_t *read_concern); +mongoc_transaction_opts_set_read_concern (mongoc_transaction_opt_t *opts, const mongoc_read_concern_t *read_concern); MONGOC_EXPORT (const mongoc_read_concern_t *) mongoc_transaction_opts_get_read_concern (const mongoc_transaction_opt_t *opts); MONGOC_EXPORT (void) -mongoc_transaction_opts_set_write_concern ( - mongoc_transaction_opt_t *opts, const mongoc_write_concern_t *write_concern); +mongoc_transaction_opts_set_write_concern (mongoc_transaction_opt_t *opts, const mongoc_write_concern_t *write_concern); MONGOC_EXPORT (const mongoc_write_concern_t *) -mongoc_transaction_opts_get_write_concern ( - const mongoc_transaction_opt_t *opts); +mongoc_transaction_opts_get_write_concern (const mongoc_transaction_opt_t *opts); MONGOC_EXPORT (void) -mongoc_transaction_opts_set_read_prefs (mongoc_transaction_opt_t *opts, - const mongoc_read_prefs_t *read_prefs); +mongoc_transaction_opts_set_read_prefs (mongoc_transaction_opt_t *opts, const mongoc_read_prefs_t *read_prefs); MONGOC_EXPORT (const mongoc_read_prefs_t *) mongoc_transaction_opts_get_read_prefs (const mongoc_transaction_opt_t *opts); @@ -86,8 +79,7 @@ MONGOC_EXPORT (mongoc_session_opt_t *) mongoc_session_opts_new (void) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (void) -mongoc_session_opts_set_causal_consistency (mongoc_session_opt_t *opts, - bool causal_consistency); +mongoc_session_opts_set_causal_consistency (mongoc_session_opt_t *opts, bool causal_consistency); MONGOC_EXPORT (bool) mongoc_session_opts_get_causal_consistency (const mongoc_session_opt_t *opts); @@ -99,20 +91,16 @@ MONGOC_EXPORT (bool) mongoc_session_opts_get_snapshot (const mongoc_session_opt_t *opts); MONGOC_EXPORT (void) -mongoc_session_opts_set_default_transaction_opts ( - mongoc_session_opt_t *opts, const mongoc_transaction_opt_t *txn_opts); +mongoc_session_opts_set_default_transaction_opts (mongoc_session_opt_t *opts, const mongoc_transaction_opt_t *txn_opts); MONGOC_EXPORT (const mongoc_transaction_opt_t *) -mongoc_session_opts_get_default_transaction_opts ( - const mongoc_session_opt_t *opts); +mongoc_session_opts_get_default_transaction_opts (const mongoc_session_opt_t *opts); MONGOC_EXPORT (mongoc_transaction_opt_t *) -mongoc_session_opts_get_transaction_opts ( - const mongoc_client_session_t *session) BSON_GNUC_WARN_UNUSED_RESULT; +mongoc_session_opts_get_transaction_opts (const mongoc_client_session_t *session) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (mongoc_session_opt_t *) -mongoc_session_opts_clone (const mongoc_session_opt_t *opts) - BSON_GNUC_WARN_UNUSED_RESULT; +mongoc_session_opts_clone (const mongoc_session_opt_t *opts) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (void) mongoc_session_opts_destroy (mongoc_session_opt_t *opts); @@ -130,31 +118,26 @@ MONGOC_EXPORT (const bson_t *) mongoc_client_session_get_cluster_time (const mongoc_client_session_t *session); MONGOC_EXPORT (void) -mongoc_client_session_advance_cluster_time (mongoc_client_session_t *session, - const bson_t *cluster_time); +mongoc_client_session_advance_cluster_time (mongoc_client_session_t *session, const bson_t *cluster_time); MONGOC_EXPORT (void) -mongoc_client_session_get_operation_time ( - const mongoc_client_session_t *session, - uint32_t *timestamp, - uint32_t *increment); +mongoc_client_session_get_operation_time (const mongoc_client_session_t *session, + uint32_t *timestamp, + uint32_t *increment); MONGOC_EXPORT (uint32_t) mongoc_client_session_get_server_id (const mongoc_client_session_t *session); MONGOC_EXPORT (void) -mongoc_client_session_advance_operation_time (mongoc_client_session_t *session, - uint32_t timestamp, - uint32_t increment); +mongoc_client_session_advance_operation_time (mongoc_client_session_t *session, uint32_t timestamp, uint32_t increment); MONGOC_EXPORT (bool) -mongoc_client_session_with_transaction ( - mongoc_client_session_t *session, - mongoc_client_session_with_transaction_cb_t cb, - const mongoc_transaction_opt_t *opts, - void *ctx, - bson_t *reply, - bson_error_t *error); +mongoc_client_session_with_transaction (mongoc_client_session_t *session, + mongoc_client_session_with_transaction_cb_t cb, + const mongoc_transaction_opt_t *opts, + void *ctx, + bson_t *reply, + bson_error_t *error); MONGOC_EXPORT (bool) mongoc_client_session_start_transaction (mongoc_client_session_t *session, @@ -165,22 +148,16 @@ MONGOC_EXPORT (bool) mongoc_client_session_in_transaction (const mongoc_client_session_t *session); MONGOC_EXPORT (mongoc_transaction_state_t) -mongoc_client_session_get_transaction_state ( - const mongoc_client_session_t *session); +mongoc_client_session_get_transaction_state (const mongoc_client_session_t *session); MONGOC_EXPORT (bool) -mongoc_client_session_commit_transaction (mongoc_client_session_t *session, - bson_t *reply, - bson_error_t *error); +mongoc_client_session_commit_transaction (mongoc_client_session_t *session, bson_t *reply, bson_error_t *error); MONGOC_EXPORT (bool) -mongoc_client_session_abort_transaction (mongoc_client_session_t *session, - bson_error_t *error); +mongoc_client_session_abort_transaction (mongoc_client_session_t *session, bson_error_t *error); MONGOC_EXPORT (bool) -mongoc_client_session_append (const mongoc_client_session_t *client_session, - bson_t *opts, - bson_error_t *error); +mongoc_client_session_append (const mongoc_client_session_t *client_session, bson_t *opts, bson_error_t *error); /* There is no mongoc_client_session_end, only mongoc_client_session_destroy. * Driver Sessions Spec: "In languages that have idiomatic ways of disposing of diff --git a/src/libmongoc/src/mongoc/mongoc-client-side-encryption-private.h b/src/libmongoc/src/mongoc/mongoc-client-side-encryption-private.h index e9533bb6f2..6339d8eee2 100644 --- a/src/libmongoc/src/mongoc/mongoc-client-side-encryption-private.h +++ b/src/libmongoc/src/mongoc/mongoc-client-side-encryption-private.h @@ -36,23 +36,18 @@ _mongoc_cse_auto_encrypt (mongoc_client_t *client, bson_error_t *error); bool -_mongoc_cse_auto_decrypt (mongoc_client_t *client, - const char *db_name, - const bson_t *reply, - bson_t *decrypted, - bson_error_t *error); +_mongoc_cse_auto_decrypt ( + mongoc_client_t *client, const char *db_name, const bson_t *reply, bson_t *decrypted, bson_error_t *error); bool -_mongoc_cse_client_enable_auto_encryption ( - mongoc_client_t *client, - mongoc_auto_encryption_opts_t *opts /* may be NULL */, - bson_error_t *error); +_mongoc_cse_client_enable_auto_encryption (mongoc_client_t *client, + mongoc_auto_encryption_opts_t *opts /* may be NULL */, + bson_error_t *error); bool -_mongoc_cse_client_pool_enable_auto_encryption ( - mongoc_topology_t *topology, - mongoc_auto_encryption_opts_t *opts /* may be NULL */, - bson_error_t *error); +_mongoc_cse_client_pool_enable_auto_encryption (mongoc_topology_t *topology, + mongoc_auto_encryption_opts_t *opts /* may be NULL */, + bson_error_t *error); /* If this returns true, client side encryption is enabled * on the client (or it's parent client pool), and cannot @@ -100,10 +95,7 @@ typedef bool (*auto_datakey_factory) (struct auto_datakey_context *ctx); * @retval false Otherwise */ bool -_mongoc_encryptedFields_fill_auto_datakeys (bson_t *out_fields, - const bson_t *in_fields, - auto_datakey_factory factory, - void *userdata, - bson_error_t *error); +_mongoc_encryptedFields_fill_auto_datakeys ( + bson_t *out_fields, const bson_t *in_fields, auto_datakey_factory factory, void *userdata, bson_error_t *error); #endif /* MONGOC_CLIENT_SIDE_ENCRYPTION_PRIVATE_H */ diff --git a/src/libmongoc/src/mongoc/mongoc-client-side-encryption.c b/src/libmongoc/src/mongoc/mongoc-client-side-encryption.c index 2e344f35f8..2dddff9412 100644 --- a/src/libmongoc/src/mongoc/mongoc-client-side-encryption.c +++ b/src/libmongoc/src/mongoc/mongoc-client-side-encryption.c @@ -53,9 +53,7 @@ struct _mongoc_auto_encryption_opts_t { }; static void -_set_creds_callback (mc_kms_credentials_callback *cb, - mongoc_kms_credentials_provider_callback_fn fn, - void *userdata) +_set_creds_callback (mc_kms_credentials_callback *cb, mongoc_kms_credentials_provider_callback_fn fn, void *userdata) { BSON_ASSERT (cb); cb->fn = fn; @@ -85,8 +83,7 @@ mongoc_auto_encryption_opts_destroy (mongoc_auto_encryption_opts_t *opts) } void -mongoc_auto_encryption_opts_set_keyvault_client ( - mongoc_auto_encryption_opts_t *opts, mongoc_client_t *client) +mongoc_auto_encryption_opts_set_keyvault_client (mongoc_auto_encryption_opts_t *opts, mongoc_client_t *client) { if (!opts) { return; @@ -96,8 +93,7 @@ mongoc_auto_encryption_opts_set_keyvault_client ( } void -mongoc_auto_encryption_opts_set_keyvault_client_pool ( - mongoc_auto_encryption_opts_t *opts, mongoc_client_pool_t *pool) +mongoc_auto_encryption_opts_set_keyvault_client_pool (mongoc_auto_encryption_opts_t *opts, mongoc_client_pool_t *pool) { if (!opts) { return; @@ -107,8 +103,9 @@ mongoc_auto_encryption_opts_set_keyvault_client_pool ( } void -mongoc_auto_encryption_opts_set_keyvault_namespace ( - mongoc_auto_encryption_opts_t *opts, const char *db, const char *coll) +mongoc_auto_encryption_opts_set_keyvault_namespace (mongoc_auto_encryption_opts_t *opts, + const char *db, + const char *coll) { if (!opts) { return; @@ -122,8 +119,7 @@ mongoc_auto_encryption_opts_set_keyvault_namespace ( } void -mongoc_auto_encryption_opts_set_kms_providers ( - mongoc_auto_encryption_opts_t *opts, const bson_t *providers) +mongoc_auto_encryption_opts_set_kms_providers (mongoc_auto_encryption_opts_t *opts, const bson_t *providers) { if (!opts) { return; @@ -147,8 +143,7 @@ _bson_copy_or_null (const bson_t *bson) } void -mongoc_auto_encryption_opts_set_tls_opts (mongoc_auto_encryption_opts_t *opts, - const bson_t *tls_opts) +mongoc_auto_encryption_opts_set_tls_opts (mongoc_auto_encryption_opts_t *opts, const bson_t *tls_opts) { if (!opts) { return; @@ -158,8 +153,7 @@ mongoc_auto_encryption_opts_set_tls_opts (mongoc_auto_encryption_opts_t *opts, } void -mongoc_auto_encryption_opts_set_schema_map (mongoc_auto_encryption_opts_t *opts, - const bson_t *schema_map) +mongoc_auto_encryption_opts_set_schema_map (mongoc_auto_encryption_opts_t *opts, const bson_t *schema_map) { if (!opts) { return; @@ -173,8 +167,8 @@ mongoc_auto_encryption_opts_set_schema_map (mongoc_auto_encryption_opts_t *opts, } void -mongoc_auto_encryption_opts_set_encrypted_fields_map ( - mongoc_auto_encryption_opts_t *opts, const bson_t *encrypted_fields_map) +mongoc_auto_encryption_opts_set_encrypted_fields_map (mongoc_auto_encryption_opts_t *opts, + const bson_t *encrypted_fields_map) { if (!opts) { return; @@ -187,8 +181,8 @@ mongoc_auto_encryption_opts_set_encrypted_fields_map ( } void -mongoc_auto_encryption_opts_set_bypass_auto_encryption ( - mongoc_auto_encryption_opts_t *opts, bool bypass_auto_encryption) +mongoc_auto_encryption_opts_set_bypass_auto_encryption (mongoc_auto_encryption_opts_t *opts, + bool bypass_auto_encryption) { if (!opts) { return; @@ -197,8 +191,7 @@ mongoc_auto_encryption_opts_set_bypass_auto_encryption ( } void -mongoc_auto_encryption_opts_set_bypass_query_analysis ( - mongoc_auto_encryption_opts_t *opts, bool bypass_query_analysis) +mongoc_auto_encryption_opts_set_bypass_query_analysis (mongoc_auto_encryption_opts_t *opts, bool bypass_query_analysis) { if (!opts) { return; @@ -207,8 +200,7 @@ mongoc_auto_encryption_opts_set_bypass_query_analysis ( } void -mongoc_auto_encryption_opts_set_extra (mongoc_auto_encryption_opts_t *opts, - const bson_t *extra) +mongoc_auto_encryption_opts_set_extra (mongoc_auto_encryption_opts_t *opts, const bson_t *extra) { if (!opts) { return; @@ -221,10 +213,9 @@ mongoc_auto_encryption_opts_set_extra (mongoc_auto_encryption_opts_t *opts, } void -mongoc_auto_encryption_opts_set_kms_credential_provider_callback ( - mongoc_auto_encryption_opts_t *opts, - mongoc_kms_credentials_provider_callback_fn fn, - void *userdata) +mongoc_auto_encryption_opts_set_kms_credential_provider_callback (mongoc_auto_encryption_opts_t *opts, + mongoc_kms_credentials_provider_callback_fn fn, + void *userdata) { _set_creds_callback (&opts->creds_cb, fn, userdata); } @@ -263,8 +254,8 @@ mongoc_client_encryption_opts_destroy (mongoc_client_encryption_opts_t *opts) } void -mongoc_client_encryption_opts_set_keyvault_client ( - mongoc_client_encryption_opts_t *opts, mongoc_client_t *keyvault_client) +mongoc_client_encryption_opts_set_keyvault_client (mongoc_client_encryption_opts_t *opts, + mongoc_client_t *keyvault_client) { if (!opts) { return; @@ -273,8 +264,9 @@ mongoc_client_encryption_opts_set_keyvault_client ( } void -mongoc_client_encryption_opts_set_keyvault_namespace ( - mongoc_client_encryption_opts_t *opts, const char *db, const char *coll) +mongoc_client_encryption_opts_set_keyvault_namespace (mongoc_client_encryption_opts_t *opts, + const char *db, + const char *coll) { if (!opts) { return; @@ -288,8 +280,7 @@ mongoc_client_encryption_opts_set_keyvault_namespace ( } void -mongoc_client_encryption_opts_set_kms_providers ( - mongoc_client_encryption_opts_t *opts, const bson_t *kms_providers) +mongoc_client_encryption_opts_set_kms_providers (mongoc_client_encryption_opts_t *opts, const bson_t *kms_providers) { if (!opts) { return; @@ -302,8 +293,7 @@ mongoc_client_encryption_opts_set_kms_providers ( } void -mongoc_client_encryption_opts_set_tls_opts ( - mongoc_client_encryption_opts_t *opts, const bson_t *tls_opts) +mongoc_client_encryption_opts_set_tls_opts (mongoc_client_encryption_opts_t *opts, const bson_t *tls_opts) { if (!opts) { return; @@ -313,10 +303,9 @@ mongoc_client_encryption_opts_set_tls_opts ( } void -mongoc_client_encryption_opts_set_kms_credential_provider_callback ( - mongoc_client_encryption_opts_t *opts, - mongoc_kms_credentials_provider_callback_fn fn, - void *userdata) +mongoc_client_encryption_opts_set_kms_credential_provider_callback (mongoc_client_encryption_opts_t *opts, + mongoc_kms_credentials_provider_callback_fn fn, + void *userdata) { BSON_ASSERT_PARAM (opts); opts->creds_cb.fn = fn; @@ -355,8 +344,7 @@ _clear_datakey_keyaltnames (mongoc_client_encryption_datakey_opts_t *opts) } void -mongoc_client_encryption_datakey_opts_destroy ( - mongoc_client_encryption_datakey_opts_t *opts) +mongoc_client_encryption_datakey_opts_destroy (mongoc_client_encryption_datakey_opts_t *opts) { if (!opts) { return; @@ -370,8 +358,8 @@ mongoc_client_encryption_datakey_opts_destroy ( } void -mongoc_client_encryption_datakey_opts_set_masterkey ( - mongoc_client_encryption_datakey_opts_t *opts, const bson_t *masterkey) +mongoc_client_encryption_datakey_opts_set_masterkey (mongoc_client_encryption_datakey_opts_t *opts, + const bson_t *masterkey) { if (!opts) { return; @@ -384,10 +372,9 @@ mongoc_client_encryption_datakey_opts_set_masterkey ( } void -mongoc_client_encryption_datakey_opts_set_keyaltnames ( - mongoc_client_encryption_datakey_opts_t *opts, - char **keyaltnames, - uint32_t keyaltnames_count) +mongoc_client_encryption_datakey_opts_set_keyaltnames (mongoc_client_encryption_datakey_opts_t *opts, + char **keyaltnames, + uint32_t keyaltnames_count) { if (!opts) { return; @@ -407,10 +394,9 @@ mongoc_client_encryption_datakey_opts_set_keyaltnames ( } void -mongoc_client_encryption_datakey_opts_set_keymaterial ( - mongoc_client_encryption_datakey_opts_t *opts, - const uint8_t *data, - uint32_t len) +mongoc_client_encryption_datakey_opts_set_keymaterial (mongoc_client_encryption_datakey_opts_t *opts, + const uint8_t *data, + uint32_t len) { if (!opts) { return; @@ -464,8 +450,7 @@ mongoc_client_encryption_encrypt_opts_new (void) } void -mongoc_client_encryption_encrypt_range_opts_destroy ( - mongoc_client_encryption_encrypt_range_opts_t *range_opts) +mongoc_client_encryption_encrypt_range_opts_destroy (mongoc_client_encryption_encrypt_range_opts_t *range_opts) { if (!range_opts) { return; @@ -481,8 +466,7 @@ mongoc_client_encryption_encrypt_range_opts_destroy ( } void -mongoc_client_encryption_encrypt_opts_destroy ( - mongoc_client_encryption_encrypt_opts_t *opts) +mongoc_client_encryption_encrypt_opts_destroy (mongoc_client_encryption_encrypt_opts_t *opts) { if (!opts) { return; @@ -496,8 +480,8 @@ mongoc_client_encryption_encrypt_opts_destroy ( } void -mongoc_client_encryption_encrypt_opts_set_keyid ( - mongoc_client_encryption_encrypt_opts_t *opts, const bson_value_t *keyid) +mongoc_client_encryption_encrypt_opts_set_keyid (mongoc_client_encryption_encrypt_opts_t *opts, + const bson_value_t *keyid) { if (!opts) { return; @@ -510,8 +494,8 @@ mongoc_client_encryption_encrypt_opts_set_keyid ( } void -mongoc_client_encryption_encrypt_opts_set_keyaltname ( - mongoc_client_encryption_encrypt_opts_t *opts, const char *keyaltname) +mongoc_client_encryption_encrypt_opts_set_keyaltname (mongoc_client_encryption_encrypt_opts_t *opts, + const char *keyaltname) { if (!opts) { return; @@ -522,8 +506,8 @@ mongoc_client_encryption_encrypt_opts_set_keyaltname ( } void -mongoc_client_encryption_encrypt_opts_set_algorithm ( - mongoc_client_encryption_encrypt_opts_t *opts, const char *algorithm) +mongoc_client_encryption_encrypt_opts_set_algorithm (mongoc_client_encryption_encrypt_opts_t *opts, + const char *algorithm) { if (!opts) { return; @@ -534,8 +518,8 @@ mongoc_client_encryption_encrypt_opts_set_algorithm ( } void -mongoc_client_encryption_encrypt_opts_set_contention_factor ( - mongoc_client_encryption_encrypt_opts_t *opts, int64_t contention_factor) +mongoc_client_encryption_encrypt_opts_set_contention_factor (mongoc_client_encryption_encrypt_opts_t *opts, + int64_t contention_factor) { if (!opts) { return; @@ -545,8 +529,8 @@ mongoc_client_encryption_encrypt_opts_set_contention_factor ( } void -mongoc_client_encryption_encrypt_opts_set_query_type ( - mongoc_client_encryption_encrypt_opts_t *opts, const char *query_type) +mongoc_client_encryption_encrypt_opts_set_query_type (mongoc_client_encryption_encrypt_opts_t *opts, + const char *query_type) { if (!opts) { return; @@ -566,17 +550,16 @@ mongoc_client_encryption_encrypt_range_opts_new (void) } void -mongoc_client_encryption_encrypt_range_opts_set_sparsity ( - mongoc_client_encryption_encrypt_range_opts_t *range_opts, int64_t sparsity) +mongoc_client_encryption_encrypt_range_opts_set_sparsity (mongoc_client_encryption_encrypt_range_opts_t *range_opts, + int64_t sparsity) { BSON_ASSERT_PARAM (range_opts); range_opts->sparsity = sparsity; } void -mongoc_client_encryption_encrypt_range_opts_set_min ( - mongoc_client_encryption_encrypt_range_opts_t *range_opts, - const bson_value_t *min) +mongoc_client_encryption_encrypt_range_opts_set_min (mongoc_client_encryption_encrypt_range_opts_t *range_opts, + const bson_value_t *min) { BSON_ASSERT_PARAM (range_opts); BSON_ASSERT_PARAM (min); @@ -589,9 +572,8 @@ mongoc_client_encryption_encrypt_range_opts_set_min ( } void -mongoc_client_encryption_encrypt_range_opts_set_max ( - mongoc_client_encryption_encrypt_range_opts_t *range_opts, - const bson_value_t *max) +mongoc_client_encryption_encrypt_range_opts_set_max (mongoc_client_encryption_encrypt_range_opts_t *range_opts, + const bson_value_t *max) { BSON_ASSERT_PARAM (range_opts); BSON_ASSERT_PARAM (max); @@ -604,8 +586,8 @@ mongoc_client_encryption_encrypt_range_opts_set_max ( } void -mongoc_client_encryption_encrypt_range_opts_set_precision ( - mongoc_client_encryption_encrypt_range_opts_t *range_opts, int32_t precision) +mongoc_client_encryption_encrypt_range_opts_set_precision (mongoc_client_encryption_encrypt_range_opts_t *range_opts, + int32_t precision) { BSON_ASSERT_PARAM (range_opts); range_opts->precision.set = true; @@ -616,8 +598,7 @@ static mongoc_client_encryption_encrypt_range_opts_t * copy_range_opts (const mongoc_client_encryption_encrypt_range_opts_t *opts) { BSON_ASSERT_PARAM (opts); - mongoc_client_encryption_encrypt_range_opts_t *opts_new = - mongoc_client_encryption_encrypt_range_opts_new (); + mongoc_client_encryption_encrypt_range_opts_t *opts_new = mongoc_client_encryption_encrypt_range_opts_new (); if (opts->min.set) { bson_value_copy (&opts->min.value, &opts_new->min.value); opts_new->min.set = true; @@ -635,9 +616,8 @@ copy_range_opts (const mongoc_client_encryption_encrypt_range_opts_t *opts) } void -mongoc_client_encryption_encrypt_opts_set_range_opts ( - mongoc_client_encryption_encrypt_opts_t *opts, - const mongoc_client_encryption_encrypt_range_opts_t *range_opts) +mongoc_client_encryption_encrypt_opts_set_range_opts (mongoc_client_encryption_encrypt_opts_t *opts, + const mongoc_client_encryption_encrypt_range_opts_t *range_opts) { BSON_ASSERT_PARAM (opts); @@ -661,8 +641,7 @@ mongoc_client_encryption_rewrap_many_datakey_result_t * mongoc_client_encryption_rewrap_many_datakey_result_new (void) { mongoc_client_encryption_rewrap_many_datakey_result_t *const res = - BSON_ALIGNED_ALLOC0 ( - mongoc_client_encryption_rewrap_many_datakey_result_t); + BSON_ALIGNED_ALLOC0 (mongoc_client_encryption_rewrap_many_datakey_result_t); bson_init (&res->bulk_write_result); @@ -729,11 +708,8 @@ _mongoc_cse_auto_encrypt (mongoc_client_t *client, } bool -_mongoc_cse_auto_decrypt (mongoc_client_t *client, - const char *db_name, - const bson_t *reply, - bson_t *decrypted, - bson_error_t *error) +_mongoc_cse_auto_decrypt ( + mongoc_client_t *client, const char *db_name, const bson_t *reply, bson_t *decrypted, bson_error_t *error) { BSON_UNUSED (client); BSON_UNUSED (db_name); @@ -745,10 +721,9 @@ _mongoc_cse_auto_decrypt (mongoc_client_t *client, } bool -_mongoc_cse_client_enable_auto_encryption ( - mongoc_client_t *client, - mongoc_auto_encryption_opts_t *opts /* may be NULL */, - bson_error_t *error) +_mongoc_cse_client_enable_auto_encryption (mongoc_client_t *client, + mongoc_auto_encryption_opts_t *opts /* may be NULL */, + bson_error_t *error) { BSON_UNUSED (client); BSON_UNUSED (opts); @@ -757,10 +732,9 @@ _mongoc_cse_client_enable_auto_encryption ( } bool -_mongoc_cse_client_pool_enable_auto_encryption ( - mongoc_topology_t *topology, - mongoc_auto_encryption_opts_t *opts /* may be NULL */, - bson_error_t *error) +_mongoc_cse_client_pool_enable_auto_encryption (mongoc_topology_t *topology, + mongoc_auto_encryption_opts_t *opts /* may be NULL */, + bson_error_t *error) { BSON_UNUSED (topology); BSON_UNUSED (opts); @@ -770,12 +744,11 @@ _mongoc_cse_client_pool_enable_auto_encryption ( bool -mongoc_client_encryption_create_datakey ( - mongoc_client_encryption_t *client_encryption, - const char *kms_provider, - const mongoc_client_encryption_datakey_opts_t *opts, - bson_value_t *keyid, - bson_error_t *error) +mongoc_client_encryption_create_datakey (mongoc_client_encryption_t *client_encryption, + const char *kms_provider, + const mongoc_client_encryption_datakey_opts_t *opts, + bson_value_t *keyid, + bson_error_t *error) { BSON_UNUSED (client_encryption); BSON_UNUSED (kms_provider); @@ -790,13 +763,12 @@ mongoc_client_encryption_create_datakey ( bool -mongoc_client_encryption_rewrap_many_datakey ( - mongoc_client_encryption_t *client_encryption, - const bson_t *filter, - const char *provider, - const bson_t *master_key, - mongoc_client_encryption_rewrap_many_datakey_result_t *result, - bson_error_t *error) +mongoc_client_encryption_rewrap_many_datakey (mongoc_client_encryption_t *client_encryption, + const bson_t *filter, + const char *provider, + const bson_t *master_key, + mongoc_client_encryption_rewrap_many_datakey_result_t *result, + bson_error_t *error) { BSON_UNUSED (client_encryption); BSON_UNUSED (filter); @@ -809,11 +781,10 @@ mongoc_client_encryption_rewrap_many_datakey ( bool -mongoc_client_encryption_delete_key ( - mongoc_client_encryption_t *client_encryption, - const bson_value_t *keyid, - bson_t *reply, - bson_error_t *error) +mongoc_client_encryption_delete_key (mongoc_client_encryption_t *client_encryption, + const bson_value_t *keyid, + bson_t *reply, + bson_error_t *error) { BSON_UNUSED (client_encryption); BSON_UNUSED (keyid); @@ -840,8 +811,7 @@ mongoc_client_encryption_get_key (mongoc_client_encryption_t *client_encryption, mongoc_cursor_t * -mongoc_client_encryption_get_keys ( - mongoc_client_encryption_t *client_encryption, bson_error_t *error) +mongoc_client_encryption_get_keys (mongoc_client_encryption_t *client_encryption, bson_error_t *error) { BSON_UNUSED (client_encryption); @@ -852,12 +822,11 @@ mongoc_client_encryption_get_keys ( bool -mongoc_client_encryption_add_key_alt_name ( - mongoc_client_encryption_t *client_encryption, - const bson_value_t *keyid, - const char *keyaltname, - bson_t *key_doc, - bson_error_t *error) +mongoc_client_encryption_add_key_alt_name (mongoc_client_encryption_t *client_encryption, + const bson_value_t *keyid, + const char *keyaltname, + bson_t *key_doc, + bson_error_t *error) { BSON_UNUSED (client_encryption); BSON_UNUSED (keyid); @@ -870,12 +839,11 @@ mongoc_client_encryption_add_key_alt_name ( bool -mongoc_client_encryption_remove_key_alt_name ( - mongoc_client_encryption_t *client_encryption, - const bson_value_t *keyid, - const char *keyaltname, - bson_t *key_doc, - bson_error_t *error) +mongoc_client_encryption_remove_key_alt_name (mongoc_client_encryption_t *client_encryption, + const bson_value_t *keyid, + const char *keyaltname, + bson_t *key_doc, + bson_error_t *error) { BSON_UNUSED (client_encryption); BSON_UNUSED (keyid); @@ -888,11 +856,10 @@ mongoc_client_encryption_remove_key_alt_name ( bool -mongoc_client_encryption_get_key_by_alt_name ( - mongoc_client_encryption_t *client_encryption, - const char *keyaltname, - bson_t *key_doc, - bson_error_t *error) +mongoc_client_encryption_get_key_by_alt_name (mongoc_client_encryption_t *client_encryption, + const char *keyaltname, + bson_t *key_doc, + bson_error_t *error) { BSON_UNUSED (client_encryption); BSON_UNUSED (keyaltname); @@ -904,8 +871,7 @@ mongoc_client_encryption_get_key_by_alt_name ( MONGOC_EXPORT (mongoc_client_encryption_t *) -mongoc_client_encryption_new (mongoc_client_encryption_opts_t *opts, - bson_error_t *error) +mongoc_client_encryption_new (mongoc_client_encryption_opts_t *opts, bson_error_t *error) { BSON_UNUSED (opts); @@ -939,12 +905,11 @@ mongoc_client_encryption_encrypt (mongoc_client_encryption_t *client_encryption, } bool -mongoc_client_encryption_encrypt_expression ( - mongoc_client_encryption_t *client_encryption, - const bson_t *expr, - mongoc_client_encryption_encrypt_opts_t *opts, - bson_t *expr_encrypted, - bson_error_t *error) +mongoc_client_encryption_encrypt_expression (mongoc_client_encryption_t *client_encryption, + const bson_t *expr, + mongoc_client_encryption_encrypt_opts_t *opts, + bson_t *expr_encrypted, + bson_error_t *error) { BSON_ASSERT_PARAM (client_encryption); BSON_ASSERT_PARAM (expr); @@ -982,15 +947,14 @@ _mongoc_cse_is_enabled (mongoc_client_t *client) } mongoc_collection_t * -mongoc_client_encryption_create_encrypted_collection ( - mongoc_client_encryption_t *enc, - struct _mongoc_database_t *database, - const char *name, - const bson_t *in_options, - bson_t *opt_out_options, - const char *const kms_provider, - const bson_t *opt_masterkey, - bson_error_t *error) +mongoc_client_encryption_create_encrypted_collection (mongoc_client_encryption_t *enc, + struct _mongoc_database_t *database, + const char *name, + const bson_t *in_options, + bson_t *opt_out_options, + const char *const kms_provider, + const bson_t *opt_masterkey, + bson_error_t *error) { BSON_UNUSED (enc); BSON_UNUSED (database); @@ -1010,27 +974,22 @@ mongoc_client_encryption_create_encrypted_collection ( * libmongocrypt. */ static void -append_bson_range_opts (bson_t *bson_range_opts, - const mongoc_client_encryption_encrypt_opts_t *opts) +append_bson_range_opts (bson_t *bson_range_opts, const mongoc_client_encryption_encrypt_opts_t *opts) { BSON_ASSERT_PARAM (bson_range_opts); BSON_ASSERT_PARAM (opts); if (opts->range_opts->min.set) { - BSON_ASSERT (BSON_APPEND_VALUE ( - bson_range_opts, "min", &opts->range_opts->min.value)); + BSON_ASSERT (BSON_APPEND_VALUE (bson_range_opts, "min", &opts->range_opts->min.value)); } if (opts->range_opts->max.set) { - BSON_ASSERT (BSON_APPEND_VALUE ( - bson_range_opts, "max", &opts->range_opts->max.value)); + BSON_ASSERT (BSON_APPEND_VALUE (bson_range_opts, "max", &opts->range_opts->max.value)); } if (opts->range_opts->precision.set) { - BSON_ASSERT (BSON_APPEND_INT32 ( - bson_range_opts, "precision", opts->range_opts->precision.value)); + BSON_ASSERT (BSON_APPEND_INT32 (bson_range_opts, "precision", opts->range_opts->precision.value)); } if (opts->range_opts->sparsity) { - BSON_ASSERT (BSON_APPEND_INT64 ( - bson_range_opts, "sparsity", opts->range_opts->sparsity)); + BSON_ASSERT (BSON_APPEND_INT64 (bson_range_opts, "sparsity", opts->range_opts->sparsity)); } } @@ -1053,8 +1012,7 @@ _prep_for_auto_encryption (const mongoc_cmd_t *cmd, bson_t *out) { /* If there is no type=1 payload, return the command unchanged. */ if (!cmd->payload || !cmd->payload_size) { - BSON_ASSERT (bson_init_static ( - out, bson_get_data (cmd->command), cmd->command->len)); + BSON_ASSERT (bson_init_static (out, bson_get_data (cmd->command), cmd->command->len)); return; } @@ -1076,13 +1034,11 @@ _get_mongocryptd_client (mongoc_client_t *client_encrypted) if (client_encrypted->topology->single_threaded) { return client_encrypted->topology->mongocryptd_client; } - return mongoc_client_pool_pop ( - client_encrypted->topology->mongocryptd_client_pool); + return mongoc_client_pool_pop (client_encrypted->topology->mongocryptd_client_pool); } void -_release_mongocryptd_client (mongoc_client_t *client_encrypted, - mongoc_client_t *mongocryptd_client) +_release_mongocryptd_client (mongoc_client_t *client_encrypted, mongoc_client_t *mongocryptd_client) { BSON_ASSERT_PARAM (client_encrypted); @@ -1090,9 +1046,7 @@ _release_mongocryptd_client (mongoc_client_t *client_encrypted, return; } if (!client_encrypted->topology->single_threaded) { - mongoc_client_pool_push ( - client_encrypted->topology->mongocryptd_client_pool, - mongocryptd_client); + mongoc_client_pool_push (client_encrypted->topology->mongocryptd_client_pool, mongocryptd_client); } } @@ -1129,8 +1083,7 @@ _get_keyvault_coll (mongoc_client_t *client_encrypted) } } else { if (client_encrypted->topology->keyvault_client_pool) { - keyvault_client = mongoc_client_pool_pop ( - client_encrypted->topology->keyvault_client_pool); + keyvault_client = mongoc_client_pool_pop (client_encrypted->topology->keyvault_client_pool); } else { keyvault_client = client_encrypted; } @@ -1151,8 +1104,7 @@ _get_keyvault_coll (mongoc_client_t *client_encrypted) } void -_release_keyvault_coll (mongoc_client_t *client_encrypted, - mongoc_collection_t *keyvault_coll) +_release_keyvault_coll (mongoc_client_t *client_encrypted, mongoc_collection_t *keyvault_coll) { mongoc_client_t *keyvault_client; @@ -1164,17 +1116,13 @@ _release_keyvault_coll (mongoc_client_t *client_encrypted, keyvault_client = keyvault_coll->client; mongoc_collection_destroy (keyvault_coll); - if (!client_encrypted->topology->single_threaded && - client_encrypted->topology->keyvault_client_pool) { - mongoc_client_pool_push (client_encrypted->topology->keyvault_client_pool, - keyvault_client); + if (!client_encrypted->topology->single_threaded && client_encrypted->topology->keyvault_client_pool) { + mongoc_client_pool_push (client_encrypted->topology->keyvault_client_pool, keyvault_client); } } static bool -_spawn_mongocryptd (const char *mongocryptd_spawn_path, - const bson_t *mongocryptd_spawn_args, - bson_error_t *error); +_spawn_mongocryptd (const char *mongocryptd_spawn_path, const bson_t *mongocryptd_spawn_args, bson_error_t *error); /*-------------------------------------------------------------------------- * @@ -1225,12 +1173,11 @@ _mongoc_cse_auto_encrypt (mongoc_client_t *client_encrypted, } if (cmd->server_stream->sd->max_wire_version < WIRE_VERSION_CSE) { - bson_set_error ( - error, - MONGOC_ERROR_PROTOCOL, - MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION, - "%s", - "Auto-encryption requires a minimum MongoDB version of 4.2"); + bson_set_error (error, + MONGOC_ERROR_PROTOCOL, + MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION, + "%s", + "Auto-encryption requires a minimum MongoDB version of 4.2"); GOTO (fail); } @@ -1256,12 +1203,11 @@ _mongoc_cse_auto_encrypt (mongoc_client_t *client_encrypted, * MongoClient to mongocryptd fails. If the MongoClient fails to connect * after spawning, the server selection error is propagated to the user. */ - if (!client_encrypted->topology->mongocryptd_bypass_spawn && - error->domain == MONGOC_ERROR_SERVER_SELECTION && !retried) { - if (!_spawn_mongocryptd ( - client_encrypted->topology->mongocryptd_spawn_path, - client_encrypted->topology->mongocryptd_spawn_args, - error)) { + if (!client_encrypted->topology->mongocryptd_bypass_spawn && error->domain == MONGOC_ERROR_SERVER_SELECTION && + !retried) { + if (!_spawn_mongocryptd (client_encrypted->topology->mongocryptd_spawn_path, + client_encrypted->topology->mongocryptd_spawn_args, + error)) { GOTO (fail); } /* Respawn and retry. */ @@ -1314,11 +1260,8 @@ _mongoc_cse_auto_encrypt (mongoc_client_t *client_encrypted, *-------------------------------------------------------------------------- */ bool -_mongoc_cse_auto_decrypt (mongoc_client_t *client_encrypted, - const char *db_name, - const bson_t *reply, - bson_t *decrypted, - bson_error_t *error) +_mongoc_cse_auto_decrypt ( + mongoc_client_t *client_encrypted, const char *db_name, const bson_t *reply, bson_t *decrypted, bson_error_t *error) { bool ret = false; mongoc_collection_t *keyvault_coll = NULL; @@ -1329,11 +1272,7 @@ _mongoc_cse_auto_decrypt (mongoc_client_t *client_encrypted, BSON_UNUSED (db_name); keyvault_coll = _get_keyvault_coll (client_encrypted); - if (!_mongoc_crypt_auto_decrypt (client_encrypted->topology->crypt, - keyvault_coll, - reply, - decrypted, - error)) { + if (!_mongoc_crypt_auto_decrypt (client_encrypted->topology->crypt, keyvault_coll, reply, decrypted, error)) { GOTO (fail); } @@ -1398,15 +1337,14 @@ _do_spawn (const char *path, char **args, bson_error_t *error) long lastError = GetLastError (); LPSTR message = NULL; - FormatMessageA ( - FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_ARGUMENT_ARRAY | - FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, - lastError, - 0, - (LPSTR) &message, - 0, - NULL); + FormatMessageA (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_ARGUMENT_ARRAY | FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, + lastError, + 0, + (LPSTR) &message, + 0, + NULL); bson_set_error (error, MONGOC_ERROR_CLIENT, @@ -1594,9 +1532,7 @@ _do_spawn (const char *path, char **args, bson_error_t *error) *-------------------------------------------------------------------------- */ static bool -_spawn_mongocryptd (const char *mongocryptd_spawn_path, - const bson_t *mongocryptd_spawn_args, - bson_error_t *error) +_spawn_mongocryptd (const char *mongocryptd_spawn_path, const bson_t *mongocryptd_spawn_args, bson_error_t *error) { char **args = NULL; bson_iter_t iter; @@ -1618,11 +1554,8 @@ _spawn_mongocryptd (const char *mongocryptd_spawn_path, } /* Check if the arg starts with --idleShutdownTimeoutSecs= or is equal * to --idleShutdownTimeoutSecs */ - if (0 == strncmp ("--idleShutdownTimeoutSecs=", - bson_iter_utf8 (&iter, NULL), - 26) || - 0 == strcmp ("--idleShutdownTimeoutSecs", - bson_iter_utf8 (&iter, NULL))) { + if (0 == strncmp ("--idleShutdownTimeoutSecs=", bson_iter_utf8 (&iter, NULL), 26) || + 0 == strcmp ("--idleShutdownTimeoutSecs", bson_iter_utf8 (&iter, NULL))) { passed_idle_shutdown_timeout_secs = true; } num_args++; @@ -1658,10 +1591,7 @@ _spawn_mongocryptd (const char *mongocryptd_spawn_path, } static bool -_parse_extra (const bson_t *extra, - mongoc_topology_t *topology, - mongoc_uri_t **uri, - bson_error_t *error) +_parse_extra (const bson_t *extra, mongoc_topology_t *topology, mongoc_uri_t **uri, bson_error_t *error) { bson_iter_t iter; bool ret = false; @@ -1672,26 +1602,23 @@ _parse_extra (const bson_t *extra, if (extra) { if (bson_iter_init_find (&iter, extra, "mongocryptdBypassSpawn")) { if (!BSON_ITER_HOLDS_BOOL (&iter)) { - bson_set_error ( - error, - MONGOC_ERROR_CLIENT, - MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG, - "Expected bool for option 'mongocryptdBypassSpawn'"); + bson_set_error (error, + MONGOC_ERROR_CLIENT, + MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG, + "Expected bool for option 'mongocryptdBypassSpawn'"); GOTO (fail); } topology->mongocryptd_bypass_spawn = bson_iter_bool (&iter); } if (bson_iter_init_find (&iter, extra, "mongocryptdSpawnPath")) { if (!BSON_ITER_HOLDS_UTF8 (&iter)) { - bson_set_error ( - error, - MONGOC_ERROR_CLIENT, - MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG, - "Expected string for option 'mongocryptdSpawnPath'"); + bson_set_error (error, + MONGOC_ERROR_CLIENT, + MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG, + "Expected string for option 'mongocryptdSpawnPath'"); GOTO (fail); } - topology->mongocryptd_spawn_path = - bson_strdup (bson_iter_utf8 (&iter, NULL)); + topology->mongocryptd_spawn_path = bson_strdup (bson_iter_utf8 (&iter, NULL)); } if (bson_iter_init_find (&iter, extra, "mongocryptdSpawnArgs")) { uint32_t array_len; @@ -1705,8 +1632,7 @@ _parse_extra (const bson_t *extra, GOTO (fail); } bson_iter_array (&iter, &array_len, &array_data); - topology->mongocryptd_spawn_args = - bson_new_from_data (array_data, array_len); + topology->mongocryptd_spawn_args = bson_new_from_data (array_data, array_len); } if (bson_iter_init_find (&iter, extra, "mongocryptdURI")) { @@ -1733,10 +1659,8 @@ _parse_extra (const bson_t *extra, } size_t len; const char *ptr = bson_iter_utf8_unsafe (&iter, &len); - bson_free (topology->clientSideEncryption.autoOptions.extraOptions - .cryptSharedLibPath); - topology->clientSideEncryption.autoOptions.extraOptions - .cryptSharedLibPath = bson_strdup (ptr); + bson_free (topology->clientSideEncryption.autoOptions.extraOptions.cryptSharedLibPath); + topology->clientSideEncryption.autoOptions.extraOptions.cryptSharedLibPath = bson_strdup (ptr); } if (bson_iter_init_find (&iter, extra, "cryptSharedLibRequired")) { @@ -1747,8 +1671,7 @@ _parse_extra (const bson_t *extra, "Expected a bool for 'cryptSharedLibRequired'"); GOTO (fail); } - topology->clientSideEncryption.autoOptions.extraOptions - .cryptSharedLibRequired = bson_iter_bool_unsafe (&iter); + topology->clientSideEncryption.autoOptions.extraOptions.cryptSharedLibRequired = bson_iter_bool_unsafe (&iter); } } @@ -1760,8 +1683,7 @@ _parse_extra (const bson_t *extra, GOTO (fail); } - if (!mongoc_uri_set_option_as_int32 ( - *uri, MONGOC_URI_SERVERSELECTIONTIMEOUTMS, 10000)) { + if (!mongoc_uri_set_option_as_int32 (*uri, MONGOC_URI_SERVERSELECTIONTIMEOUTMS, 10000)) { _uri_construction_error (error); GOTO (fail); } @@ -1784,19 +1706,16 @@ _mongoc_cse_client_enable_auto_encryption (mongoc_client_t *client, BSON_ASSERT (client); if (!client->topology->single_threaded) { - bson_set_error ( - error, - MONGOC_ERROR_CLIENT, - MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG, - "Automatic encryption on pooled clients must be set on the pool"); + bson_set_error (error, + MONGOC_ERROR_CLIENT, + MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG, + "Automatic encryption on pooled clients must be set on the pool"); GOTO (fail); } if (!opts) { - bson_set_error (error, - MONGOC_ERROR_CLIENT, - MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG, - "Auto encryption options required"); + bson_set_error ( + error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG, "Auto encryption options required"); GOTO (fail); } @@ -1809,8 +1728,7 @@ _mongoc_cse_client_enable_auto_encryption (mongoc_client_t *client, GOTO (fail); } - if (opts->keyvault_client && - !opts->keyvault_client->topology->single_threaded) { + if (opts->keyvault_client && !opts->keyvault_client->topology->single_threaded) { bson_set_error (error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG, @@ -1821,26 +1739,20 @@ _mongoc_cse_client_enable_auto_encryption (mongoc_client_t *client, /* Check for required options */ if (!opts->keyvault_db || !opts->keyvault_coll) { - bson_set_error (error, - MONGOC_ERROR_CLIENT, - MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG, - "Key vault namespace option required"); + bson_set_error ( + error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG, "Key vault namespace option required"); GOTO (fail); } if (!opts->kms_providers) { - bson_set_error (error, - MONGOC_ERROR_CLIENT, - MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG, - "KMS providers option required"); + bson_set_error ( + error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG, "KMS providers option required"); GOTO (fail); } if (client->topology->cse_state != MONGOC_CSE_DISABLED) { - bson_set_error (error, - MONGOC_ERROR_CLIENT, - MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE, - "Automatic encryption already set"); + bson_set_error ( + error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE, "Automatic encryption already set"); GOTO (fail); } else { client->topology->cse_state = MONGOC_CSE_ENABLED; @@ -1855,10 +1767,8 @@ _mongoc_cse_client_enable_auto_encryption (mongoc_client_t *client, opts->schema_map, opts->encrypted_fields_map, opts->tls_opts, - client->topology->clientSideEncryption.autoOptions - .extraOptions.cryptSharedLibPath, - client->topology->clientSideEncryption.autoOptions - .extraOptions.cryptSharedLibRequired, + client->topology->clientSideEncryption.autoOptions.extraOptions.cryptSharedLibPath, + client->topology->clientSideEncryption.autoOptions.extraOptions.cryptSharedLibRequired, opts->bypass_auto_encryption, opts->bypass_query_analysis, opts->creds_cb, @@ -1867,18 +1777,15 @@ _mongoc_cse_client_enable_auto_encryption (mongoc_client_t *client, GOTO (fail); } - const bool have_crypt_shared = - _mongoc_crypt_get_crypt_shared_version (client->topology->crypt) != NULL; + const bool have_crypt_shared = _mongoc_crypt_get_crypt_shared_version (client->topology->crypt) != NULL; client->topology->bypass_auto_encryption = opts->bypass_auto_encryption; client->topology->bypass_query_analysis = opts->bypass_query_analysis; - if (!client->topology->bypass_auto_encryption && - !client->topology->bypass_query_analysis && !have_crypt_shared) { + if (!client->topology->bypass_auto_encryption && !client->topology->bypass_query_analysis && !have_crypt_shared) { if (!client->topology->mongocryptd_bypass_spawn) { - if (!_spawn_mongocryptd (client->topology->mongocryptd_spawn_path, - client->topology->mongocryptd_spawn_args, - error)) { + if (!_spawn_mongocryptd ( + client->topology->mongocryptd_spawn_path, client->topology->mongocryptd_spawn_args, error)) { GOTO (fail); } } @@ -1889,14 +1796,12 @@ _mongoc_cse_client_enable_auto_encryption (mongoc_client_t *client, * serverSelectionTimeoutMS expires). Override this, since the first * attempt to connect to mongocryptd may fail when spawning, as it * takes some time for mongocryptd to listen on sockets. */ - if (!mongoc_uri_set_option_as_bool ( - mongocryptd_uri, MONGOC_URI_SERVERSELECTIONTRYONCE, false)) { + if (!mongoc_uri_set_option_as_bool (mongocryptd_uri, MONGOC_URI_SERVERSELECTIONTRYONCE, false)) { _uri_construction_error (error); GOTO (fail); } - client->topology->mongocryptd_client = - mongoc_client_new_from_uri (mongocryptd_uri); + client->topology->mongocryptd_client = mongoc_client_new_from_uri (mongocryptd_uri); if (!client->topology->mongocryptd_client) { bson_set_error (error, @@ -1910,14 +1815,12 @@ _mongoc_cse_client_enable_auto_encryption (mongoc_client_t *client, * another attempt. Meaning if the first attempt to mongocryptd fails * to connect, then the user observes a 5 second delay. This is not * configurable in the URI, so override. */ - _mongoc_topology_bypass_cooldown ( - client->topology->mongocryptd_client->topology); + _mongoc_topology_bypass_cooldown (client->topology->mongocryptd_client->topology); /* Also, since single threaded server selection can foreseeably take * connectTimeoutMS (which by default is longer than 10 seconds), reduce * this as well. */ - if (!mongoc_uri_set_option_as_int32 ( - mongocryptd_uri, MONGOC_URI_CONNECTTIMEOUTMS, 10000)) { + if (!mongoc_uri_set_option_as_int32 (mongocryptd_uri, MONGOC_URI_CONNECTTIMEOUTMS, 10000)) { _uri_construction_error (error); GOTO (fail); } @@ -1930,8 +1833,7 @@ _mongoc_cse_client_enable_auto_encryption (mongoc_client_t *client, } if (opts->encrypted_fields_map) { - client->topology->encrypted_fields_map = - bson_copy (opts->encrypted_fields_map); + client->topology->encrypted_fields_map = bson_copy (opts->encrypted_fields_map); } ret = true; @@ -1941,10 +1843,9 @@ _mongoc_cse_client_enable_auto_encryption (mongoc_client_t *client, } bool -_mongoc_cse_client_pool_enable_auto_encryption ( - mongoc_topology_t *topology, - mongoc_auto_encryption_opts_t *opts, - bson_error_t *error) +_mongoc_cse_client_pool_enable_auto_encryption (mongoc_topology_t *topology, + mongoc_auto_encryption_opts_t *opts, + bson_error_t *error) { bool setup_okay = false; mongoc_uri_t *mongocryptd_uri = NULL; @@ -1952,10 +1853,8 @@ _mongoc_cse_client_pool_enable_auto_encryption ( BSON_ASSERT (topology); if (!opts) { - bson_set_error (error, - MONGOC_ERROR_CLIENT, - MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG, - "Auto encryption options required"); + bson_set_error ( + error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG, "Auto encryption options required"); GOTO (fail); } @@ -1970,42 +1869,30 @@ _mongoc_cse_client_pool_enable_auto_encryption ( /* Check for required options */ if (!opts->keyvault_db || !opts->keyvault_coll) { - bson_set_error (error, - MONGOC_ERROR_CLIENT, - MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG, - "Key vault namespace option required"); + bson_set_error ( + error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG, "Key vault namespace option required"); GOTO (fail); } if (!opts->kms_providers) { - bson_set_error (error, - MONGOC_ERROR_CLIENT, - MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG, - "KMS providers option required"); + bson_set_error ( + error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG, "KMS providers option required"); GOTO (fail); } - prev_cse_state = - bson_atomic_int_compare_exchange_strong ((int *) &topology->cse_state, - MONGOC_CSE_DISABLED, - MONGOC_CSE_STARTING, - bson_memory_order_acquire); + prev_cse_state = bson_atomic_int_compare_exchange_strong ( + (int *) &topology->cse_state, MONGOC_CSE_DISABLED, MONGOC_CSE_STARTING, bson_memory_order_acquire); while (prev_cse_state == MONGOC_CSE_STARTING) { /* Another thread is starting client-side encryption. It may take some * time to start, but don't continue until it is finished. */ bson_thrd_yield (); - prev_cse_state = - bson_atomic_int_compare_exchange_strong ((int *) &topology->cse_state, - MONGOC_CSE_DISABLED, - MONGOC_CSE_STARTING, - bson_memory_order_acquire); + prev_cse_state = bson_atomic_int_compare_exchange_strong ( + (int *) &topology->cse_state, MONGOC_CSE_DISABLED, MONGOC_CSE_STARTING, bson_memory_order_acquire); } if (prev_cse_state == MONGOC_CSE_ENABLED) { - bson_set_error (error, - MONGOC_ERROR_CLIENT, - MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE, - "Automatic encryption already set"); + bson_set_error ( + error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE, "Automatic encryption already set"); GOTO (fail); } @@ -2015,19 +1902,16 @@ _mongoc_cse_client_pool_enable_auto_encryption ( GOTO (fail); } - topology->crypt = - _mongoc_crypt_new (opts->kms_providers, - opts->schema_map, - opts->encrypted_fields_map, - opts->tls_opts, - topology->clientSideEncryption.autoOptions.extraOptions - .cryptSharedLibPath, - topology->clientSideEncryption.autoOptions.extraOptions - .cryptSharedLibRequired, - opts->bypass_auto_encryption, - opts->bypass_query_analysis, - opts->creds_cb, - error); + topology->crypt = _mongoc_crypt_new (opts->kms_providers, + opts->schema_map, + opts->encrypted_fields_map, + opts->tls_opts, + topology->clientSideEncryption.autoOptions.extraOptions.cryptSharedLibPath, + topology->clientSideEncryption.autoOptions.extraOptions.cryptSharedLibRequired, + opts->bypass_auto_encryption, + opts->bypass_query_analysis, + opts->creds_cb, + error); if (!topology->crypt) { GOTO (fail); } @@ -2037,15 +1921,12 @@ _mongoc_cse_client_pool_enable_auto_encryption ( if (!topology->bypass_auto_encryption && !topology->bypass_query_analysis) { if (!topology->mongocryptd_bypass_spawn) { - if (!_spawn_mongocryptd (topology->mongocryptd_spawn_path, - topology->mongocryptd_spawn_args, - error)) { + if (!_spawn_mongocryptd (topology->mongocryptd_spawn_path, topology->mongocryptd_spawn_args, error)) { GOTO (fail); } } - topology->mongocryptd_client_pool = - mongoc_client_pool_new (mongocryptd_uri); + topology->mongocryptd_client_pool = mongoc_client_pool_new (mongocryptd_uri); if (!topology->mongocryptd_client_pool) { bson_set_error (error, @@ -2071,10 +1952,8 @@ _mongoc_cse_client_pool_enable_auto_encryption ( fail: if (prev_cse_state == MONGOC_CSE_DISABLED) { /* We need to set the new CSE state. */ - mongoc_topology_cse_state_t new_state = - setup_okay ? MONGOC_CSE_ENABLED : MONGOC_CSE_DISABLED; - bson_atomic_int_exchange ( - (int *) &topology->cse_state, new_state, bson_memory_order_release); + mongoc_topology_cse_state_t new_state = setup_okay ? MONGOC_CSE_ENABLED : MONGOC_CSE_DISABLED; + bson_atomic_int_exchange ((int *) &topology->cse_state, new_state, bson_memory_order_release); } mongoc_uri_destroy (mongocryptd_uri); RETURN (setup_okay); @@ -2087,8 +1966,7 @@ struct _mongoc_client_encryption_t { }; mongoc_client_encryption_t * -mongoc_client_encryption_new (mongoc_client_encryption_opts_t *opts, - bson_error_t *error) +mongoc_client_encryption_new (mongoc_client_encryption_opts_t *opts, bson_error_t *error) { mongoc_client_encryption_t *client_encryption = NULL; bool success = false; @@ -2096,8 +1974,7 @@ mongoc_client_encryption_new (mongoc_client_encryption_opts_t *opts, mongoc_read_concern_t *rc = NULL; /* Check for required options */ - if (!opts || !opts->keyvault_client || !opts->keyvault_db || - !opts->keyvault_coll) { + if (!opts || !opts->keyvault_client || !opts->keyvault_db || !opts->keyvault_coll) { bson_set_error (error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG, @@ -2106,16 +1983,14 @@ mongoc_client_encryption_new (mongoc_client_encryption_opts_t *opts, } if (!opts->kms_providers) { - bson_set_error (error, - MONGOC_ERROR_CLIENT, - MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG, - "KMS providers option required"); + bson_set_error ( + error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG, "KMS providers option required"); goto fail; } client_encryption = bson_malloc0 (sizeof (*client_encryption)); - client_encryption->keyvault_coll = mongoc_client_get_collection ( - opts->keyvault_client, opts->keyvault_db, opts->keyvault_coll); + client_encryption->keyvault_coll = + mongoc_client_get_collection (opts->keyvault_client, opts->keyvault_db, opts->keyvault_coll); wc = mongoc_write_concern_new (); mongoc_write_concern_set_w (wc, MONGOC_WRITE_CONCERN_W_MAJORITY); mongoc_collection_set_write_concern (client_encryption->keyvault_coll, wc); @@ -2124,18 +1999,17 @@ mongoc_client_encryption_new (mongoc_client_encryption_opts_t *opts, mongoc_collection_set_read_concern (client_encryption->keyvault_coll, rc); client_encryption->kms_providers = bson_copy (opts->kms_providers); - client_encryption->crypt = - _mongoc_crypt_new (opts->kms_providers, - NULL /* schema_map */, - NULL /* encrypted_fields_map */, - opts->tls_opts, - NULL /* No crypt_shared path */, - false /* crypt_shared not requried */, - true, /* bypassAutoEncryption (We are explicit) */ - false, - /* bypass_query_analysis. Not applicable. */ - opts->creds_cb, - error); + client_encryption->crypt = _mongoc_crypt_new (opts->kms_providers, + NULL /* schema_map */, + NULL /* encrypted_fields_map */, + opts->tls_opts, + NULL /* No crypt_shared path */, + false /* crypt_shared not requried */, + true, /* bypassAutoEncryption (We are explicit) */ + false, + /* bypass_query_analysis. Not applicable. */ + opts->creds_cb, + error); if (!client_encryption->crypt) { goto fail; } @@ -2167,27 +2041,24 @@ mongoc_client_encryption_destroy (mongoc_client_encryption_t *client_encryption) static bool _coll_has_write_concern_majority (const mongoc_collection_t *coll) { - const mongoc_write_concern_t *const wc = - mongoc_collection_get_write_concern (coll); + const mongoc_write_concern_t *const wc = mongoc_collection_get_write_concern (coll); return wc && mongoc_write_concern_get_wmajority (wc); } static bool _coll_has_read_concern_majority (const mongoc_collection_t *coll) { - const mongoc_read_concern_t *const rc = - mongoc_collection_get_read_concern (coll); + const mongoc_read_concern_t *const rc = mongoc_collection_get_read_concern (coll); const char *const level = rc ? mongoc_read_concern_get_level (rc) : NULL; return level && strcmp (level, MONGOC_READ_CONCERN_LEVEL_MAJORITY) == 0; } bool -mongoc_client_encryption_create_datakey ( - mongoc_client_encryption_t *client_encryption, - const char *kms_provider, - const mongoc_client_encryption_datakey_opts_t *opts, - bson_value_t *keyid, - bson_error_t *error) +mongoc_client_encryption_create_datakey (mongoc_client_encryption_t *client_encryption, + const char *kms_provider, + const mongoc_client_encryption_datakey_opts_t *opts, + bson_value_t *keyid, + bson_error_t *error) { bool ret = false; bson_t datakey = BSON_INITIALIZER; @@ -2197,14 +2068,10 @@ mongoc_client_encryption_create_datakey ( BSON_ASSERT_PARAM (client_encryption); - BSON_ASSERT ( - _coll_has_write_concern_majority (client_encryption->keyvault_coll)); + BSON_ASSERT (_coll_has_write_concern_majority (client_encryption->keyvault_coll)); if (!opts) { - bson_set_error (error, - MONGOC_ERROR_CLIENT, - MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG, - "required 'opts' unset"); + bson_set_error (error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG, "required 'opts' unset"); GOTO (fail); } @@ -2227,11 +2094,8 @@ mongoc_client_encryption_create_datakey ( GOTO (fail); } - if (!mongoc_collection_insert_one (client_encryption->keyvault_coll, - &datakey, - NULL /* opts */, - NULL /* reply */, - error)) { + if (!mongoc_collection_insert_one ( + client_encryption->keyvault_coll, &datakey, NULL /* opts */, NULL /* reply */, error)) { GOTO (fail); } @@ -2267,18 +2131,16 @@ mongoc_client_encryption_create_datakey ( } bool -mongoc_client_encryption_rewrap_many_datakey ( - mongoc_client_encryption_t *client_encryption, - const bson_t *filter, - const char *provider, - const bson_t *master_key, - mongoc_client_encryption_rewrap_many_datakey_result_t *result, - bson_error_t *error) +mongoc_client_encryption_rewrap_many_datakey (mongoc_client_encryption_t *client_encryption, + const bson_t *filter, + const char *provider, + const bson_t *master_key, + mongoc_client_encryption_rewrap_many_datakey_result_t *result, + bson_error_t *error) { bson_t keys = BSON_INITIALIZER; bson_t local_result = BSON_INITIALIZER; - bson_t *const bulk_write_result = - result ? &result->bulk_write_result : &local_result; + bson_t *const bulk_write_result = result ? &result->bulk_write_result : &local_result; mongoc_bulk_operation_t *bulk = NULL; bson_iter_t iter; bool ret = false; @@ -2287,29 +2149,21 @@ mongoc_client_encryption_rewrap_many_datakey ( BSON_ASSERT_PARAM (client_encryption); - BSON_ASSERT ( - _coll_has_read_concern_majority (client_encryption->keyvault_coll)); - BSON_ASSERT ( - _coll_has_write_concern_majority (client_encryption->keyvault_coll)); + BSON_ASSERT (_coll_has_read_concern_majority (client_encryption->keyvault_coll)); + BSON_ASSERT (_coll_has_write_concern_majority (client_encryption->keyvault_coll)); bson_reinit (bulk_write_result); if (master_key && !provider) { - bson_set_error ( - error, - MONGOC_ERROR_CLIENT, - MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG, - "expected 'provider' to be set to identify type of 'master_key'"); + bson_set_error (error, + MONGOC_ERROR_CLIENT, + MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG, + "expected 'provider' to be set to identify type of 'master_key'"); GOTO (fail); } - if (!_mongoc_crypt_rewrap_many_datakey (client_encryption->crypt, - client_encryption->keyvault_coll, - filter, - provider, - master_key, - &keys, - error)) { + if (!_mongoc_crypt_rewrap_many_datakey ( + client_encryption->crypt, client_encryption->keyvault_coll, filter, provider, master_key, &keys, error)) { GOTO (fail); } @@ -2320,8 +2174,7 @@ mongoc_client_encryption_rewrap_many_datakey ( return true; } - bulk = mongoc_collection_create_bulk_operation_with_opts ( - client_encryption->keyvault_coll, NULL); + bulk = mongoc_collection_create_bulk_operation_with_opts (client_encryption->keyvault_coll, NULL); BSON_ASSERT (bulk); @@ -2393,24 +2246,20 @@ mongoc_client_encryption_rewrap_many_datakey ( BSON_ASSERT (BSON_APPEND_DOCUMENT_BEGIN (&document, "$set", &child)); { if (bson_iter_init_find (&key_iter, &key, "masterKey")) { - BSON_ASSERT ( - bson_append_iter (&child, "masterKey", -1, &key_iter)); + BSON_ASSERT (bson_append_iter (&child, "masterKey", -1, &key_iter)); } if (bson_iter_init_find (&key_iter, &key, "keyMaterial")) { - BSON_ASSERT ( - bson_append_iter (&child, "keyMaterial", -1, &key_iter)); + BSON_ASSERT (bson_append_iter (&child, "keyMaterial", -1, &key_iter)); } } BSON_ASSERT (bson_append_document_end (&document, &child)); } /* Update updateDate field. */ - BCON_APPEND ( - &document, "$currentDate", "{", "updateDate", BCON_BOOL (true), "}"); + BCON_APPEND (&document, "$currentDate", "{", "updateDate", BCON_BOOL (true), "}"); - if (!mongoc_bulk_operation_update_one_with_opts ( - bulk, &selector, &document, NULL, error)) { + if (!mongoc_bulk_operation_update_one_with_opts (bulk, &selector, &document, NULL, error)) { goto doc_done; } @@ -2441,11 +2290,10 @@ mongoc_client_encryption_rewrap_many_datakey ( } bool -mongoc_client_encryption_delete_key ( - mongoc_client_encryption_t *client_encryption, - const bson_value_t *keyid, - bson_t *reply, - bson_error_t *error) +mongoc_client_encryption_delete_key (mongoc_client_encryption_t *client_encryption, + const bson_value_t *keyid, + bson_t *reply, + bson_error_t *error) { bool ret = false; bson_t selector = BSON_INITIALIZER; @@ -2455,21 +2303,16 @@ mongoc_client_encryption_delete_key ( BSON_ASSERT_PARAM (client_encryption); BSON_ASSERT_PARAM (keyid); - BSON_ASSERT ( - _coll_has_write_concern_majority (client_encryption->keyvault_coll)); + BSON_ASSERT (_coll_has_write_concern_majority (client_encryption->keyvault_coll)); BSON_ASSERT (keyid->value_type == BSON_TYPE_BINARY); BSON_ASSERT (keyid->value.v_binary.subtype == BSON_SUBTYPE_UUID); BSON_ASSERT (keyid->value.v_binary.data_len > 0u); - BSON_ASSERT (BSON_APPEND_BINARY (&selector, - "_id", - keyid->value.v_binary.subtype, - keyid->value.v_binary.data, - keyid->value.v_binary.data_len)); + BSON_ASSERT (BSON_APPEND_BINARY ( + &selector, "_id", keyid->value.v_binary.subtype, keyid->value.v_binary.data, keyid->value.v_binary.data_len)); - ret = mongoc_collection_delete_one ( - client_encryption->keyvault_coll, &selector, NULL, reply, error); + ret = mongoc_collection_delete_one (client_encryption->keyvault_coll, &selector, NULL, reply, error); bson_destroy (&selector); @@ -2495,19 +2338,14 @@ mongoc_client_encryption_get_key (mongoc_client_encryption_t *client_encryption, BSON_ASSERT (keyid->value.v_binary.subtype == BSON_SUBTYPE_UUID); BSON_ASSERT (keyid->value.v_binary.data_len > 0u); - BSON_ASSERT (BSON_APPEND_BINARY (&filter, - "_id", - keyid->value.v_binary.subtype, - keyid->value.v_binary.data, - keyid->value.v_binary.data_len)); + BSON_ASSERT (BSON_APPEND_BINARY ( + &filter, "_id", keyid->value.v_binary.subtype, keyid->value.v_binary.data, keyid->value.v_binary.data_len)); - BSON_ASSERT ( - _coll_has_read_concern_majority (client_encryption->keyvault_coll)); + BSON_ASSERT (_coll_has_read_concern_majority (client_encryption->keyvault_coll)); _mongoc_bson_init_if_set (key_doc); - cursor = mongoc_collection_find_with_opts ( - client_encryption->keyvault_coll, &filter, NULL, NULL); + cursor = mongoc_collection_find_with_opts (client_encryption->keyvault_coll, &filter, NULL, NULL); ret = !mongoc_cursor_error (cursor, error); @@ -2528,8 +2366,7 @@ mongoc_client_encryption_get_key (mongoc_client_encryption_t *client_encryption, } mongoc_cursor_t * -mongoc_client_encryption_get_keys ( - mongoc_client_encryption_t *client_encryption, bson_error_t *error) +mongoc_client_encryption_get_keys (mongoc_client_encryption_t *client_encryption, bson_error_t *error) { mongoc_cursor_t *cursor = NULL; bson_t filter = BSON_INITIALIZER; @@ -2540,12 +2377,10 @@ mongoc_client_encryption_get_keys ( BSON_ASSERT_PARAM (client_encryption); - BSON_ASSERT ( - _coll_has_read_concern_majority (client_encryption->keyvault_coll)); + BSON_ASSERT (_coll_has_read_concern_majority (client_encryption->keyvault_coll)); /* If an error occurred, user should query cursor error. */ - cursor = mongoc_collection_find_with_opts ( - client_encryption->keyvault_coll, &filter, NULL, NULL); + cursor = mongoc_collection_find_with_opts (client_encryption->keyvault_coll, &filter, NULL, NULL); bson_destroy (&filter); @@ -2553,15 +2388,13 @@ mongoc_client_encryption_get_keys ( } bool -mongoc_client_encryption_add_key_alt_name ( - mongoc_client_encryption_t *client_encryption, - const bson_value_t *keyid, - const char *keyaltname, - bson_t *key_doc, - bson_error_t *error) -{ - mongoc_find_and_modify_opts_t *const opts = - mongoc_find_and_modify_opts_new (); +mongoc_client_encryption_add_key_alt_name (mongoc_client_encryption_t *client_encryption, + const bson_value_t *keyid, + const char *keyaltname, + bson_t *key_doc, + bson_error_t *error) +{ + mongoc_find_and_modify_opts_t *const opts = mongoc_find_and_modify_opts_new (); bson_t query = BSON_INITIALIZER; bool ret = false; bson_t local_reply; @@ -2572,32 +2405,26 @@ mongoc_client_encryption_add_key_alt_name ( BSON_ASSERT_PARAM (keyid); BSON_ASSERT_PARAM (keyaltname); - BSON_ASSERT ( - _coll_has_read_concern_majority (client_encryption->keyvault_coll)); - BSON_ASSERT ( - _coll_has_write_concern_majority (client_encryption->keyvault_coll)); + BSON_ASSERT (_coll_has_read_concern_majority (client_encryption->keyvault_coll)); + BSON_ASSERT (_coll_has_write_concern_majority (client_encryption->keyvault_coll)); BSON_ASSERT (keyid->value_type == BSON_TYPE_BINARY); BSON_ASSERT (keyid->value.v_binary.subtype == BSON_SUBTYPE_UUID); BSON_ASSERT (keyid->value.v_binary.data_len > 0u); - BSON_ASSERT (BSON_APPEND_BINARY (&query, - "_id", - keyid->value.v_binary.subtype, - keyid->value.v_binary.data, - keyid->value.v_binary.data_len)); + BSON_ASSERT (BSON_APPEND_BINARY ( + &query, "_id", keyid->value.v_binary.subtype, keyid->value.v_binary.data, keyid->value.v_binary.data_len)); _mongoc_bson_init_if_set (key_doc); { - bson_t *const update = BCON_NEW ( - "$addToSet", "{", "keyAltNames", BCON_UTF8 (keyaltname), "}"); + bson_t *const update = BCON_NEW ("$addToSet", "{", "keyAltNames", BCON_UTF8 (keyaltname), "}"); BSON_ASSERT (mongoc_find_and_modify_opts_set_update (opts, update)); bson_destroy (update); } - ret = mongoc_collection_find_and_modify_with_opts ( - client_encryption->keyvault_coll, &query, opts, &local_reply, error); + ret = + mongoc_collection_find_and_modify_with_opts (client_encryption->keyvault_coll, &query, opts, &local_reply, error); if (ret && key_doc) { bson_iter_t iter; @@ -2607,8 +2434,7 @@ mongoc_client_encryption_add_key_alt_name ( if (value->value_type == BSON_TYPE_DOCUMENT) { bson_t bson; - BSON_ASSERT (bson_init_static ( - &bson, value->value.v_doc.data, value->value.v_doc.data_len)); + BSON_ASSERT (bson_init_static (&bson, value->value.v_doc.data, value->value.v_doc.data_len)); bson_copy_to (&bson, key_doc); bson_destroy (&bson); } else if (value->value_type == BSON_TYPE_NULL) { @@ -2633,12 +2459,11 @@ mongoc_client_encryption_add_key_alt_name ( } bool -mongoc_client_encryption_remove_key_alt_name ( - mongoc_client_encryption_t *client_encryption, - const bson_value_t *keyid, - const char *keyaltname, - bson_t *key_doc, - bson_error_t *error) +mongoc_client_encryption_remove_key_alt_name (mongoc_client_encryption_t *client_encryption, + const bson_value_t *keyid, + const char *keyaltname, + bson_t *key_doc, + bson_error_t *error) { bson_t query = BSON_INITIALIZER; bool ret = false; @@ -2650,25 +2475,20 @@ mongoc_client_encryption_remove_key_alt_name ( BSON_ASSERT_PARAM (keyid); BSON_ASSERT_PARAM (keyaltname); - BSON_ASSERT ( - _coll_has_write_concern_majority (client_encryption->keyvault_coll)); + BSON_ASSERT (_coll_has_write_concern_majority (client_encryption->keyvault_coll)); BSON_ASSERT (keyid->value_type == BSON_TYPE_BINARY); BSON_ASSERT (keyid->value.v_binary.subtype == BSON_SUBTYPE_UUID); BSON_ASSERT (keyid->value.v_binary.data_len > 0u); - BSON_ASSERT (BSON_APPEND_BINARY (&query, - "_id", - keyid->value.v_binary.subtype, - keyid->value.v_binary.data, - keyid->value.v_binary.data_len)); + BSON_ASSERT (BSON_APPEND_BINARY ( + &query, "_id", keyid->value.v_binary.subtype, keyid->value.v_binary.data, keyid->value.v_binary.data_len)); _mongoc_bson_init_if_set (key_doc); { - mongoc_find_and_modify_opts_t *const opts = - mongoc_find_and_modify_opts_new (); + mongoc_find_and_modify_opts_t *const opts = mongoc_find_and_modify_opts_new (); /* clang-format off */ bson_t *const update = BCON_NEW ( @@ -2711,8 +2531,7 @@ mongoc_client_encryption_remove_key_alt_name ( if (value->value_type == BSON_TYPE_DOCUMENT) { bson_t bson; - BSON_ASSERT (bson_init_static ( - &bson, value->value.v_doc.data, value->value.v_doc.data_len)); + BSON_ASSERT (bson_init_static (&bson, value->value.v_doc.data, value->value.v_doc.data_len)); bson_copy_to (&bson, key_doc); bson_destroy (&bson); } else if (value->value_type == BSON_TYPE_NULL) { @@ -2736,11 +2555,10 @@ mongoc_client_encryption_remove_key_alt_name ( } bool -mongoc_client_encryption_get_key_by_alt_name ( - mongoc_client_encryption_t *client_encryption, - const char *keyaltname, - bson_t *key_doc, - bson_error_t *error) +mongoc_client_encryption_get_key_by_alt_name (mongoc_client_encryption_t *client_encryption, + const char *keyaltname, + bson_t *key_doc, + bson_error_t *error) { bson_t filter = BSON_INITIALIZER; mongoc_cursor_t *cursor = NULL; @@ -2751,15 +2569,13 @@ mongoc_client_encryption_get_key_by_alt_name ( BSON_ASSERT_PARAM (client_encryption); BSON_ASSERT_PARAM (keyaltname); - BSON_ASSERT ( - _coll_has_write_concern_majority (client_encryption->keyvault_coll)); + BSON_ASSERT (_coll_has_write_concern_majority (client_encryption->keyvault_coll)); BSON_ASSERT (BSON_APPEND_UTF8 (&filter, "keyAltNames", keyaltname)); _mongoc_bson_init_if_set (key_doc); - cursor = mongoc_collection_find_with_opts ( - client_encryption->keyvault_coll, &filter, NULL, NULL); + cursor = mongoc_collection_find_with_opts (client_encryption->keyvault_coll, &filter, NULL, NULL); ret = !mongoc_cursor_error (cursor, error); @@ -2794,10 +2610,8 @@ mongoc_client_encryption_encrypt (mongoc_client_encryption_t *client_encryption, BSON_ASSERT (client_encryption); if (!ciphertext) { - bson_set_error (error, - MONGOC_ERROR_CLIENT, - MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG, - "required 'ciphertext' unset"); + bson_set_error ( + error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG, "required 'ciphertext' unset"); GOTO (fail); } /* reset, so it is safe for caller to call bson_value_destroy on error or @@ -2805,10 +2619,7 @@ mongoc_client_encryption_encrypt (mongoc_client_encryption_t *client_encryption, ciphertext->value_type = BSON_TYPE_EOD; if (!opts) { - bson_set_error (error, - MONGOC_ERROR_CLIENT, - MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG, - "required 'opts' unset"); + bson_set_error (error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG, "required 'opts' unset"); GOTO (fail); } @@ -2817,18 +2628,17 @@ mongoc_client_encryption_encrypt (mongoc_client_encryption_t *client_encryption, append_bson_range_opts (range_opts, opts); } - if (!_mongoc_crypt_explicit_encrypt ( - client_encryption->crypt, - client_encryption->keyvault_coll, - opts->algorithm, - &opts->keyid, - opts->keyaltname, - opts->query_type, - opts->contention_factor.set ? &opts->contention_factor.value : NULL, - range_opts, - value, - ciphertext, - error)) { + if (!_mongoc_crypt_explicit_encrypt (client_encryption->crypt, + client_encryption->keyvault_coll, + opts->algorithm, + &opts->keyid, + opts->keyaltname, + opts->query_type, + opts->contention_factor.set ? &opts->contention_factor.value : NULL, + range_opts, + value, + ciphertext, + error)) { GOTO (fail); } @@ -2840,12 +2650,11 @@ mongoc_client_encryption_encrypt (mongoc_client_encryption_t *client_encryption, bool -mongoc_client_encryption_encrypt_expression ( - mongoc_client_encryption_t *client_encryption, - const bson_t *expr, - mongoc_client_encryption_encrypt_opts_t *opts, - bson_t *expr_out, - bson_error_t *error) +mongoc_client_encryption_encrypt_expression (mongoc_client_encryption_t *client_encryption, + const bson_t *expr, + mongoc_client_encryption_encrypt_opts_t *opts, + bson_t *expr_out, + bson_error_t *error) { ENTRY; @@ -2863,18 +2672,17 @@ mongoc_client_encryption_encrypt_expression ( append_bson_range_opts (range_opts, opts); } - if (!_mongoc_crypt_explicit_encrypt_expression ( - client_encryption->crypt, - client_encryption->keyvault_coll, - opts->algorithm, - &opts->keyid, - opts->keyaltname, - opts->query_type, - opts->contention_factor.set ? &opts->contention_factor.value : NULL, - range_opts, - expr, - expr_out, - error)) { + if (!_mongoc_crypt_explicit_encrypt_expression (client_encryption->crypt, + client_encryption->keyvault_coll, + opts->algorithm, + &opts->keyid, + opts->keyaltname, + opts->query_type, + opts->contention_factor.set ? &opts->contention_factor.value : NULL, + range_opts, + expr, + expr_out, + error)) { bson_destroy (range_opts); RETURN (false); } @@ -2895,10 +2703,7 @@ mongoc_client_encryption_decrypt (mongoc_client_encryption_t *client_encryption, BSON_ASSERT (client_encryption); if (!value) { - bson_set_error (error, - MONGOC_ERROR_CLIENT, - MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG, - "required 'value' unset"); + bson_set_error (error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG, "required 'value' unset"); GOTO (fail); } @@ -2906,8 +2711,7 @@ mongoc_client_encryption_decrypt (mongoc_client_encryption_t *client_encryption, * success. */ value->value_type = BSON_TYPE_EOD; - if (ciphertext->value_type != BSON_TYPE_BINARY || - ciphertext->value.v_binary.subtype != BSON_SUBTYPE_ENCRYPTED) { + if (ciphertext->value_type != BSON_TYPE_BINARY || ciphertext->value.v_binary.subtype != BSON_SUBTYPE_ENCRYPTED) { bson_set_error (error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG, @@ -2915,11 +2719,8 @@ mongoc_client_encryption_decrypt (mongoc_client_encryption_t *client_encryption, GOTO (fail); } - if (!_mongoc_crypt_explicit_decrypt (client_encryption->crypt, - client_encryption->keyvault_coll, - ciphertext, - value, - error)) { + if (!_mongoc_crypt_explicit_decrypt ( + client_encryption->crypt, client_encryption->keyvault_coll, ciphertext, value, error)) { GOTO (fail); } @@ -2934,8 +2735,8 @@ _mongoc_cse_is_enabled (mongoc_client_t *client) BSON_ASSERT_PARAM (client); while (1) { - mongoc_topology_cse_state_t state = bson_atomic_int_fetch ( - (int *) &client->topology->cse_state, bson_memory_order_relaxed); + mongoc_topology_cse_state_t state = + bson_atomic_int_fetch ((int *) &client->topology->cse_state, bson_memory_order_relaxed); if (state != MONGOC_CSE_STARTING) { return state == MONGOC_CSE_ENABLED; } @@ -2956,23 +2757,19 @@ static bool _auto_datakey (struct auto_datakey_context *ctx) { struct cec_context *cec = ctx->userdata; - return mongoc_client_encryption_create_datakey (cec->enc, - cec->kms_provider, - cec->dk_opts, - ctx->out_keyid, - ctx->out_error); + return mongoc_client_encryption_create_datakey ( + cec->enc, cec->kms_provider, cec->dk_opts, ctx->out_keyid, ctx->out_error); } mongoc_collection_t * -mongoc_client_encryption_create_encrypted_collection ( - mongoc_client_encryption_t *enc, - struct _mongoc_database_t *database, - const char *name, - const bson_t *in_options, - bson_t *opt_out_options, - const char *const kms_provider, - const bson_t *opt_masterkey, - bson_error_t *error) +mongoc_client_encryption_create_encrypted_collection (mongoc_client_encryption_t *enc, + struct _mongoc_database_t *database, + const char *name, + const bson_t *in_options, + bson_t *opt_out_options, + const char *const kms_provider, + const bson_t *opt_masterkey, + bson_error_t *error) { BSON_ASSERT_PARAM (enc); BSON_ASSERT_PARAM (database); @@ -2988,11 +2785,9 @@ mongoc_client_encryption_create_encrypted_collection ( bson_t new_encryptedFields = BSON_INITIALIZER; bson_t local_new_options = BSON_INITIALIZER; - mongoc_client_encryption_datakey_opts_t *dk_opts = - mongoc_client_encryption_datakey_opts_new (); + mongoc_client_encryption_datakey_opts_t *dk_opts = mongoc_client_encryption_datakey_opts_new (); if (opt_masterkey) { - mongoc_client_encryption_datakey_opts_set_masterkey (dk_opts, - opt_masterkey); + mongoc_client_encryption_datakey_opts_set_masterkey (dk_opts, opt_masterkey); } if (!opt_out_options) { @@ -3005,14 +2800,13 @@ mongoc_client_encryption_create_encrypted_collection ( // Look up the encryptedfields that we should use for this collection. They // may be in the given options, or they may be in the encryptedFieldsMap. - if (!_mongoc_get_collection_encryptedFields ( - database->client, - mongoc_database_get_name (database), - name, - in_options, - false /* checkEncryptedFieldsMap */, - &in_encryptedFields, - error)) { + if (!_mongoc_get_collection_encryptedFields (database->client, + mongoc_database_get_name (database), + name, + in_options, + false /* checkEncryptedFieldsMap */, + &in_encryptedFields, + error)) { // Error finding the encryptedFields goto done; } @@ -3035,26 +2829,23 @@ mongoc_client_encryption_create_encrypted_collection ( .kms_provider = kms_provider, }; bson_t fields_ref; - bsonVisitEach ( - in_encryptedFields, - case ( - // We only care about the "fields" array - when (not(key ("fields")), appendTo (new_encryptedFields)), - // Automaticall fill in the "keyId" no each field: - else ( - storeDocRef (fields_ref), do ({ - bson_t new_fields = BSON_INITIALIZER; - // Create the new fields, filling out the 'keyId' - // automatically: - if (!_mongoc_encryptedFields_fill_auto_datakeys ( - &new_fields, &fields_ref, _auto_datakey, &ctx, error)) { - bsonParseError = "Error creating datakeys"; - } else { - BSON_APPEND_ARRAY ( - &new_encryptedFields, "fields", &new_fields); - bson_destroy (&new_fields); - } - })))); + bsonVisitEach (in_encryptedFields, + case ( + // We only care about the "fields" array + when (not(key ("fields")), appendTo (new_encryptedFields)), + // Automaticall fill in the "keyId" no each field: + else (storeDocRef (fields_ref), do ({ + bson_t new_fields = BSON_INITIALIZER; + // Create the new fields, filling out the 'keyId' + // automatically: + if (!_mongoc_encryptedFields_fill_auto_datakeys ( + &new_fields, &fields_ref, _auto_datakey, &ctx, error)) { + bsonParseError = "Error creating datakeys"; + } else { + BSON_APPEND_ARRAY (&new_encryptedFields, "fields", &new_fields); + bson_destroy (&new_fields); + } + })))); if (bsonParseError) { // Error creating the new datakeys. // `error` was set by _mongoc_encryptedFields_fill_auto_datakeys @@ -3076,8 +2867,7 @@ mongoc_client_encryption_create_encrypted_collection ( goto done; } - ret = mongoc_database_create_collection ( - database, name, opt_out_options, error); + ret = mongoc_database_create_collection (database, name, opt_out_options, error); done: bson_destroy (&new_encryptedFields); @@ -3094,49 +2884,41 @@ mongoc_client_encryption_create_encrypted_collection ( /// Generate one encryptedField element. static void -_init_1_encryptedField (bson_t *out_field, - const bson_t *in_field, - auto_datakey_factory fac, - void *fac_userdata, - bson_error_t *error) +_init_1_encryptedField ( + bson_t *out_field, const bson_t *in_field, auto_datakey_factory fac, void *fac_userdata, bson_error_t *error) { BSON_ASSERT_PARAM (out_field); BSON_ASSERT_PARAM (in_field); BSON_ASSERT_PARAM (fac); BSON_ASSERT (fac_userdata || true); BSON_ASSERT (error || true); - bsonVisitEach ( - *in_field, - // If it is not a "keyId":null element, just copy it to the output. - if (not(keyWithType ("keyId", null)), - then (appendTo (*out_field), continue)), - // Otherwise: - do ({ - // Set up factory context - bson_value_t new_key = {0}; - struct auto_datakey_context ctx = { - .out_keyid = &new_key, - .out_error = error, - .userdata = fac_userdata, - }; - // Call the callback to create the new key - if (!fac (&ctx)) { - bsonParseError = "Factory function indicated failure"; - } else { - // Append to the field - BSON_APPEND_VALUE (out_field, "keyId", &new_key); - } - bson_value_destroy (&new_key); - })); + bsonVisitEach (*in_field, + // If it is not a "keyId":null element, just copy it to the output. + if (not(keyWithType ("keyId", null)), then (appendTo (*out_field), continue)), + // Otherwise: + do ({ + // Set up factory context + bson_value_t new_key = {0}; + struct auto_datakey_context ctx = { + .out_keyid = &new_key, + .out_error = error, + .userdata = fac_userdata, + }; + // Call the callback to create the new key + if (!fac (&ctx)) { + bsonParseError = "Factory function indicated failure"; + } else { + // Append to the field + BSON_APPEND_VALUE (out_field, "keyId", &new_key); + } + bson_value_destroy (&new_key); + })); } /// Generate the "encryptedFields" output for auto-datakeys static void -_init_encryptedFields (bson_t *out_fields, - const bson_t *in_fields, - auto_datakey_factory fac, - void *fac_userdata, - bson_error_t *error) +_init_encryptedFields ( + bson_t *out_fields, const bson_t *in_fields, auto_datakey_factory fac, void *fac_userdata, bson_error_t *error) { BSON_ASSERT_PARAM (out_fields); BSON_ASSERT_PARAM (in_fields); @@ -3148,43 +2930,30 @@ _init_encryptedFields (bson_t *out_fields, bsonVisitEach ( *in_fields, // Each field must be a document element - if (not(type (doc)), - then (error ("Each 'encryptedFields' element must be a document"))), + if (not(type (doc)), then (error ("Each 'encryptedFields' element must be a document"))), // Append a new element with the same name as the field: storeDocRef (cur_field), - append ( - *out_fields, - kv ( - bson_iter_key (&bsonVisitIter), - // Construct the encryptedField document from the input: - doc (do (_init_1_encryptedField ( - bsonBuildContext.doc, &cur_field, fac, fac_userdata, error)))))); + append (*out_fields, + kv (bson_iter_key (&bsonVisitIter), + // Construct the encryptedField document from the input: + doc (do (_init_1_encryptedField (bsonBuildContext.doc, &cur_field, fac, fac_userdata, error)))))); if (error && error->code == 0) { // The factory/internal code did not set error, so we may have to set it // for an error while BSON parsing/generating. if (bsonParseError) { - bson_set_error (error, - MONGOC_ERROR_BSON, - MONGOC_ERROR_BSON_INVALID, - "Error while generating datakeys: %s", - bsonParseError); + bson_set_error ( + error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "Error while generating datakeys: %s", bsonParseError); } if (bsonBuildError) { - bson_set_error (error, - MONGOC_ERROR_BSON, - MONGOC_ERROR_BSON_INVALID, - "Error while generating datakeys: %s", - bsonBuildError); + bson_set_error ( + error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "Error while generating datakeys: %s", bsonBuildError); } } } bool -_mongoc_encryptedFields_fill_auto_datakeys (bson_t *out_fields, - const bson_t *in_fields, - auto_datakey_factory factory, - void *userdata, - bson_error_t *error) +_mongoc_encryptedFields_fill_auto_datakeys ( + bson_t *out_fields, const bson_t *in_fields, auto_datakey_factory factory, void *userdata, bson_error_t *error) { BSON_ASSERT_PARAM (in_fields); BSON_ASSERT_PARAM (out_fields); @@ -3202,8 +2971,7 @@ _mongoc_encryptedFields_fill_auto_datakeys (bson_t *out_fields, } const char * -mongoc_client_encryption_get_crypt_shared_version ( - const mongoc_client_encryption_t *enc) +mongoc_client_encryption_get_crypt_shared_version (const mongoc_client_encryption_t *enc) { #ifdef MONGOC_ENABLE_CLIENT_SIDE_ENCRYPTION return _mongoc_crypt_get_crypt_shared_version (enc->crypt); diff --git a/src/libmongoc/src/mongoc/mongoc-client-side-encryption.h b/src/libmongoc/src/mongoc/mongoc-client-side-encryption.h index 3a1e81806f..07632d8572 100644 --- a/src/libmongoc/src/mongoc/mongoc-client-side-encryption.h +++ b/src/libmongoc/src/mongoc/mongoc-client-side-encryption.h @@ -29,10 +29,8 @@ struct _mongoc_cursor_t; struct _mongoc_collection_t; struct _mongoc_database_t; -#define MONGOC_AEAD_AES_256_CBC_HMAC_SHA_512_RANDOM \ - "AEAD_AES_256_CBC_HMAC_SHA_512-Random" -#define MONGOC_AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC \ - "AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic" +#define MONGOC_AEAD_AES_256_CBC_HMAC_SHA_512_RANDOM "AEAD_AES_256_CBC_HMAC_SHA_512-Random" +#define MONGOC_AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC "AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic" #define MONGOC_ENCRYPT_ALGORITHM_INDEXED "Indexed" #define MONGOC_ENCRYPT_ALGORITHM_UNINDEXED "Unindexed" #define MONGOC_ENCRYPT_ALGORITHM_RANGEPREVIEW "RangePreview" @@ -45,8 +43,10 @@ BSON_BEGIN_DECLS typedef struct _mongoc_auto_encryption_opts_t mongoc_auto_encryption_opts_t; -typedef bool (*mongoc_kms_credentials_provider_callback_fn) ( - void *userdata, const bson_t *params, bson_t *out, bson_error_t *error); +typedef bool (*mongoc_kms_credentials_provider_callback_fn) (void *userdata, + const bson_t *params, + bson_t *out, + bson_error_t *error); MONGOC_EXPORT (mongoc_auto_encryption_opts_t *) mongoc_auto_encryption_opts_new (void) BSON_GNUC_WARN_UNUSED_RESULT; @@ -55,59 +55,50 @@ MONGOC_EXPORT (void) mongoc_auto_encryption_opts_destroy (mongoc_auto_encryption_opts_t *opts); MONGOC_EXPORT (void) -mongoc_auto_encryption_opts_set_keyvault_client ( - mongoc_auto_encryption_opts_t *opts, struct _mongoc_client_t *client); +mongoc_auto_encryption_opts_set_keyvault_client (mongoc_auto_encryption_opts_t *opts, struct _mongoc_client_t *client); MONGOC_EXPORT (void) -mongoc_auto_encryption_opts_set_keyvault_client_pool ( - mongoc_auto_encryption_opts_t *opts, struct _mongoc_client_pool_t *pool); +mongoc_auto_encryption_opts_set_keyvault_client_pool (mongoc_auto_encryption_opts_t *opts, + struct _mongoc_client_pool_t *pool); MONGOC_EXPORT (void) -mongoc_auto_encryption_opts_set_keyvault_namespace ( - mongoc_auto_encryption_opts_t *opts, const char *db, const char *coll); +mongoc_auto_encryption_opts_set_keyvault_namespace (mongoc_auto_encryption_opts_t *opts, + const char *db, + const char *coll); MONGOC_EXPORT (void) -mongoc_auto_encryption_opts_set_kms_providers ( - mongoc_auto_encryption_opts_t *opts, const bson_t *kms_providers); +mongoc_auto_encryption_opts_set_kms_providers (mongoc_auto_encryption_opts_t *opts, const bson_t *kms_providers); MONGOC_EXPORT (void) -mongoc_auto_encryption_opts_set_tls_opts (mongoc_auto_encryption_opts_t *opts, - const bson_t *tls_opts); +mongoc_auto_encryption_opts_set_tls_opts (mongoc_auto_encryption_opts_t *opts, const bson_t *tls_opts); MONGOC_EXPORT (void) -mongoc_auto_encryption_opts_set_schema_map (mongoc_auto_encryption_opts_t *opts, - const bson_t *schema_map); +mongoc_auto_encryption_opts_set_schema_map (mongoc_auto_encryption_opts_t *opts, const bson_t *schema_map); MONGOC_EXPORT (void) -mongoc_auto_encryption_opts_set_encrypted_fields_map ( - mongoc_auto_encryption_opts_t *opts, const bson_t *encrypted_fields_map); +mongoc_auto_encryption_opts_set_encrypted_fields_map (mongoc_auto_encryption_opts_t *opts, + const bson_t *encrypted_fields_map); MONGOC_EXPORT (void) -mongoc_auto_encryption_opts_set_bypass_auto_encryption ( - mongoc_auto_encryption_opts_t *opts, bool bypass_auto_encryption); +mongoc_auto_encryption_opts_set_bypass_auto_encryption (mongoc_auto_encryption_opts_t *opts, + bool bypass_auto_encryption); MONGOC_EXPORT (void) -mongoc_auto_encryption_opts_set_bypass_query_analysis ( - mongoc_auto_encryption_opts_t *opts, bool bypass_query_analysis); +mongoc_auto_encryption_opts_set_bypass_query_analysis (mongoc_auto_encryption_opts_t *opts, bool bypass_query_analysis); MONGOC_EXPORT (void) -mongoc_auto_encryption_opts_set_extra (mongoc_auto_encryption_opts_t *opts, - const bson_t *extra); +mongoc_auto_encryption_opts_set_extra (mongoc_auto_encryption_opts_t *opts, const bson_t *extra); MONGOC_EXPORT (void) -mongoc_auto_encryption_opts_set_kms_credential_provider_callback ( - mongoc_auto_encryption_opts_t *opts, - mongoc_kms_credentials_provider_callback_fn fn, - void *userdata); +mongoc_auto_encryption_opts_set_kms_credential_provider_callback (mongoc_auto_encryption_opts_t *opts, + mongoc_kms_credentials_provider_callback_fn fn, + void *userdata); typedef struct _mongoc_client_encryption_opts_t mongoc_client_encryption_opts_t; typedef struct _mongoc_client_encryption_t mongoc_client_encryption_t; -typedef struct _mongoc_client_encryption_encrypt_range_opts_t - mongoc_client_encryption_encrypt_range_opts_t; -typedef struct _mongoc_client_encryption_encrypt_opts_t - mongoc_client_encryption_encrypt_opts_t; -typedef struct _mongoc_client_encryption_datakey_opts_t - mongoc_client_encryption_datakey_opts_t; +typedef struct _mongoc_client_encryption_encrypt_range_opts_t mongoc_client_encryption_encrypt_range_opts_t; +typedef struct _mongoc_client_encryption_encrypt_opts_t mongoc_client_encryption_encrypt_opts_t; +typedef struct _mongoc_client_encryption_datakey_opts_t mongoc_client_encryption_datakey_opts_t; typedef struct _mongoc_client_encryption_rewrap_many_datakey_result_t mongoc_client_encryption_rewrap_many_datakey_result_t; @@ -118,31 +109,27 @@ MONGOC_EXPORT (void) mongoc_client_encryption_opts_destroy (mongoc_client_encryption_opts_t *opts); MONGOC_EXPORT (void) -mongoc_client_encryption_opts_set_keyvault_client ( - mongoc_client_encryption_opts_t *opts, - struct _mongoc_client_t *keyvault_client); +mongoc_client_encryption_opts_set_keyvault_client (mongoc_client_encryption_opts_t *opts, + struct _mongoc_client_t *keyvault_client); MONGOC_EXPORT (void) -mongoc_client_encryption_opts_set_keyvault_namespace ( - mongoc_client_encryption_opts_t *opts, const char *db, const char *coll); +mongoc_client_encryption_opts_set_keyvault_namespace (mongoc_client_encryption_opts_t *opts, + const char *db, + const char *coll); MONGOC_EXPORT (void) -mongoc_client_encryption_opts_set_kms_providers ( - mongoc_client_encryption_opts_t *opts, const bson_t *kms_providers); +mongoc_client_encryption_opts_set_kms_providers (mongoc_client_encryption_opts_t *opts, const bson_t *kms_providers); MONGOC_EXPORT (void) -mongoc_client_encryption_opts_set_tls_opts ( - mongoc_client_encryption_opts_t *opts, const bson_t *tls_opts); +mongoc_client_encryption_opts_set_tls_opts (mongoc_client_encryption_opts_t *opts, const bson_t *tls_opts); MONGOC_EXPORT (void) -mongoc_client_encryption_opts_set_kms_credential_provider_callback ( - mongoc_client_encryption_opts_t *opts, - mongoc_kms_credentials_provider_callback_fn fn, - void *userdata); +mongoc_client_encryption_opts_set_kms_credential_provider_callback (mongoc_client_encryption_opts_t *opts, + mongoc_kms_credentials_provider_callback_fn fn, + void *userdata); MONGOC_EXPORT (mongoc_client_encryption_rewrap_many_datakey_result_t *) -mongoc_client_encryption_rewrap_many_datakey_result_new (void) - BSON_GNUC_WARN_UNUSED_RESULT; +mongoc_client_encryption_rewrap_many_datakey_result_new (void) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (void) mongoc_client_encryption_rewrap_many_datakey_result_destroy ( @@ -150,40 +137,34 @@ mongoc_client_encryption_rewrap_many_datakey_result_destroy ( MONGOC_EXPORT (const bson_t *) mongoc_client_encryption_rewrap_many_datakey_result_get_bulk_write_result ( - mongoc_client_encryption_rewrap_many_datakey_result_t *result) - BSON_GNUC_WARN_UNUSED_RESULT; + mongoc_client_encryption_rewrap_many_datakey_result_t *result) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (mongoc_client_encryption_t *) -mongoc_client_encryption_new (mongoc_client_encryption_opts_t *opts, - bson_error_t *error) BSON_GNUC_WARN_UNUSED_RESULT; +mongoc_client_encryption_new (mongoc_client_encryption_opts_t *opts, bson_error_t *error) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (void) -mongoc_client_encryption_destroy ( - mongoc_client_encryption_t *client_encryption); +mongoc_client_encryption_destroy (mongoc_client_encryption_t *client_encryption); MONGOC_EXPORT (bool) -mongoc_client_encryption_create_datakey ( - mongoc_client_encryption_t *client_encryption, - const char *kms_provider, - const mongoc_client_encryption_datakey_opts_t *opts, - bson_value_t *keyid, - bson_error_t *error); +mongoc_client_encryption_create_datakey (mongoc_client_encryption_t *client_encryption, + const char *kms_provider, + const mongoc_client_encryption_datakey_opts_t *opts, + bson_value_t *keyid, + bson_error_t *error); MONGOC_EXPORT (bool) -mongoc_client_encryption_rewrap_many_datakey ( - mongoc_client_encryption_t *client_encryption, - const bson_t *filter, - const char *provider, - const bson_t *master_key, - mongoc_client_encryption_rewrap_many_datakey_result_t *result, - bson_error_t *error); +mongoc_client_encryption_rewrap_many_datakey (mongoc_client_encryption_t *client_encryption, + const bson_t *filter, + const char *provider, + const bson_t *master_key, + mongoc_client_encryption_rewrap_many_datakey_result_t *result, + bson_error_t *error); MONGOC_EXPORT (bool) -mongoc_client_encryption_delete_key ( - mongoc_client_encryption_t *client_encryption, - const bson_value_t *keyid, - bson_t *reply, - bson_error_t *error); +mongoc_client_encryption_delete_key (mongoc_client_encryption_t *client_encryption, + const bson_value_t *keyid, + bson_t *reply, + bson_error_t *error); MONGOC_EXPORT (bool) mongoc_client_encryption_get_key (mongoc_client_encryption_t *client_encryption, @@ -192,31 +173,27 @@ mongoc_client_encryption_get_key (mongoc_client_encryption_t *client_encryption, bson_error_t *error); MONGOC_EXPORT (struct _mongoc_cursor_t *) -mongoc_client_encryption_get_keys ( - mongoc_client_encryption_t *client_encryption, bson_error_t *error); +mongoc_client_encryption_get_keys (mongoc_client_encryption_t *client_encryption, bson_error_t *error); MONGOC_EXPORT (bool) -mongoc_client_encryption_add_key_alt_name ( - mongoc_client_encryption_t *client_encryption, - const bson_value_t *keyid, - const char *keyaltname, - bson_t *key_doc, - bson_error_t *error); +mongoc_client_encryption_add_key_alt_name (mongoc_client_encryption_t *client_encryption, + const bson_value_t *keyid, + const char *keyaltname, + bson_t *key_doc, + bson_error_t *error); MONGOC_EXPORT (bool) -mongoc_client_encryption_remove_key_alt_name ( - mongoc_client_encryption_t *client_encryption, - const bson_value_t *keyid, - const char *keyaltname, - bson_t *key_doc, - bson_error_t *error); +mongoc_client_encryption_remove_key_alt_name (mongoc_client_encryption_t *client_encryption, + const bson_value_t *keyid, + const char *keyaltname, + bson_t *key_doc, + bson_error_t *error); MONGOC_EXPORT (bool) -mongoc_client_encryption_get_key_by_alt_name ( - mongoc_client_encryption_t *client_encryption, - const char *keyaltname, - bson_t *key_doc, - bson_error_t *error); +mongoc_client_encryption_get_key_by_alt_name (mongoc_client_encryption_t *client_encryption, + const char *keyaltname, + bson_t *key_doc, + bson_error_t *error); MONGOC_EXPORT (bool) mongoc_client_encryption_encrypt (mongoc_client_encryption_t *client_encryption, @@ -226,12 +203,11 @@ mongoc_client_encryption_encrypt (mongoc_client_encryption_t *client_encryption, bson_error_t *error); MONGOC_EXPORT (bool) -mongoc_client_encryption_encrypt_expression ( - mongoc_client_encryption_t *client_encryption, - const bson_t *expr, - mongoc_client_encryption_encrypt_opts_t *opts, - bson_t *expr_out, - bson_error_t *error); +mongoc_client_encryption_encrypt_expression (mongoc_client_encryption_t *client_encryption, + const bson_t *expr, + mongoc_client_encryption_encrypt_opts_t *opts, + bson_t *expr_out, + bson_error_t *error); MONGOC_EXPORT (bool) mongoc_client_encryption_decrypt (mongoc_client_encryption_t *client_encryption, @@ -243,97 +219,86 @@ MONGOC_EXPORT (mongoc_client_encryption_encrypt_opts_t *) mongoc_client_encryption_encrypt_opts_new (void) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (void) -mongoc_client_encryption_encrypt_opts_destroy ( - mongoc_client_encryption_encrypt_opts_t *opts); +mongoc_client_encryption_encrypt_opts_destroy (mongoc_client_encryption_encrypt_opts_t *opts); MONGOC_EXPORT (void) -mongoc_client_encryption_encrypt_opts_set_keyid ( - mongoc_client_encryption_encrypt_opts_t *opts, const bson_value_t *keyid); +mongoc_client_encryption_encrypt_opts_set_keyid (mongoc_client_encryption_encrypt_opts_t *opts, + const bson_value_t *keyid); MONGOC_EXPORT (void) -mongoc_client_encryption_encrypt_opts_set_keyaltname ( - mongoc_client_encryption_encrypt_opts_t *opts, const char *keyaltname); +mongoc_client_encryption_encrypt_opts_set_keyaltname (mongoc_client_encryption_encrypt_opts_t *opts, + const char *keyaltname); MONGOC_EXPORT (void) -mongoc_client_encryption_encrypt_opts_set_algorithm ( - mongoc_client_encryption_encrypt_opts_t *opts, const char *algorithm); +mongoc_client_encryption_encrypt_opts_set_algorithm (mongoc_client_encryption_encrypt_opts_t *opts, + const char *algorithm); MONGOC_EXPORT (void) -mongoc_client_encryption_encrypt_opts_set_contention_factor ( - mongoc_client_encryption_encrypt_opts_t *opts, int64_t contention_factor); +mongoc_client_encryption_encrypt_opts_set_contention_factor (mongoc_client_encryption_encrypt_opts_t *opts, + int64_t contention_factor); MONGOC_EXPORT (void) -mongoc_client_encryption_encrypt_opts_set_query_type ( - mongoc_client_encryption_encrypt_opts_t *opts, const char *query_type); +mongoc_client_encryption_encrypt_opts_set_query_type (mongoc_client_encryption_encrypt_opts_t *opts, + const char *query_type); MONGOC_EXPORT (mongoc_client_encryption_encrypt_range_opts_t *) mongoc_client_encryption_encrypt_range_opts_new (void); MONGOC_EXPORT (void) -mongoc_client_encryption_encrypt_range_opts_destroy ( - mongoc_client_encryption_encrypt_range_opts_t *range_opts); +mongoc_client_encryption_encrypt_range_opts_destroy (mongoc_client_encryption_encrypt_range_opts_t *range_opts); MONGOC_EXPORT (void) -mongoc_client_encryption_encrypt_range_opts_set_sparsity ( - mongoc_client_encryption_encrypt_range_opts_t *range_opts, int64_t sparsity); +mongoc_client_encryption_encrypt_range_opts_set_sparsity (mongoc_client_encryption_encrypt_range_opts_t *range_opts, + int64_t sparsity); MONGOC_EXPORT (void) -mongoc_client_encryption_encrypt_range_opts_set_min ( - mongoc_client_encryption_encrypt_range_opts_t *range_opts, - const bson_value_t *min); +mongoc_client_encryption_encrypt_range_opts_set_min (mongoc_client_encryption_encrypt_range_opts_t *range_opts, + const bson_value_t *min); MONGOC_EXPORT (void) -mongoc_client_encryption_encrypt_range_opts_set_max ( - mongoc_client_encryption_encrypt_range_opts_t *range_opts, - const bson_value_t *max); +mongoc_client_encryption_encrypt_range_opts_set_max (mongoc_client_encryption_encrypt_range_opts_t *range_opts, + const bson_value_t *max); MONGOC_EXPORT (void) -mongoc_client_encryption_encrypt_range_opts_set_precision ( - mongoc_client_encryption_encrypt_range_opts_t *range_opts, - int32_t precision); +mongoc_client_encryption_encrypt_range_opts_set_precision (mongoc_client_encryption_encrypt_range_opts_t *range_opts, + int32_t precision); MONGOC_EXPORT (void) -mongoc_client_encryption_encrypt_opts_set_range_opts ( - mongoc_client_encryption_encrypt_opts_t *opts, - const mongoc_client_encryption_encrypt_range_opts_t *range_opts); +mongoc_client_encryption_encrypt_opts_set_range_opts (mongoc_client_encryption_encrypt_opts_t *opts, + const mongoc_client_encryption_encrypt_range_opts_t *range_opts); MONGOC_EXPORT (mongoc_client_encryption_datakey_opts_t *) mongoc_client_encryption_datakey_opts_new (void) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (void) -mongoc_client_encryption_datakey_opts_destroy ( - mongoc_client_encryption_datakey_opts_t *opts); +mongoc_client_encryption_datakey_opts_destroy (mongoc_client_encryption_datakey_opts_t *opts); MONGOC_EXPORT (void) -mongoc_client_encryption_datakey_opts_set_masterkey ( - mongoc_client_encryption_datakey_opts_t *opts, const bson_t *masterkey); +mongoc_client_encryption_datakey_opts_set_masterkey (mongoc_client_encryption_datakey_opts_t *opts, + const bson_t *masterkey); MONGOC_EXPORT (void) -mongoc_client_encryption_datakey_opts_set_keyaltnames ( - mongoc_client_encryption_datakey_opts_t *opts, - char **keyaltnames, - uint32_t keyaltnames_count); +mongoc_client_encryption_datakey_opts_set_keyaltnames (mongoc_client_encryption_datakey_opts_t *opts, + char **keyaltnames, + uint32_t keyaltnames_count); MONGOC_EXPORT (void) -mongoc_client_encryption_datakey_opts_set_keymaterial ( - mongoc_client_encryption_datakey_opts_t *opts, - const uint8_t *data, - uint32_t len); +mongoc_client_encryption_datakey_opts_set_keymaterial (mongoc_client_encryption_datakey_opts_t *opts, + const uint8_t *data, + uint32_t len); MONGOC_EXPORT (const char *) -mongoc_client_encryption_get_crypt_shared_version ( - mongoc_client_encryption_t const *enc) BSON_GNUC_WARN_UNUSED_RESULT; +mongoc_client_encryption_get_crypt_shared_version (mongoc_client_encryption_t const *enc) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (struct _mongoc_collection_t *) -mongoc_client_encryption_create_encrypted_collection ( - mongoc_client_encryption_t *enc, - struct _mongoc_database_t *database, - const char *name, - const bson_t *in_options, - bson_t *opt_out_options, - const char *const kms_provider, - const bson_t *opt_masterkey, - bson_error_t *error) BSON_GNUC_WARN_UNUSED_RESULT; +mongoc_client_encryption_create_encrypted_collection (mongoc_client_encryption_t *enc, + struct _mongoc_database_t *database, + const char *name, + const bson_t *in_options, + bson_t *opt_out_options, + const char *const kms_provider, + const bson_t *opt_masterkey, + bson_error_t *error) BSON_GNUC_WARN_UNUSED_RESULT; BSON_END_DECLS diff --git a/src/libmongoc/src/mongoc/mongoc-client.c b/src/libmongoc/src/mongoc/mongoc-client.c index 2ec7fb6840..22de79f2fe 100644 --- a/src/libmongoc/src/mongoc/mongoc-client.c +++ b/src/libmongoc/src/mongoc/mongoc-client.c @@ -90,14 +90,10 @@ _mongoc_client_killcursors_command (mongoc_cluster_t *cluster, const char *collection, mongoc_client_session_t *cs); -#define DNS_ERROR(_msg, ...) \ - do { \ - bson_set_error (error, \ - MONGOC_ERROR_STREAM, \ - MONGOC_ERROR_STREAM_NAME_RESOLUTION, \ - _msg, \ - __VA_ARGS__); \ - GOTO (done); \ +#define DNS_ERROR(_msg, ...) \ + do { \ + bson_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_NAME_RESOLUTION, _msg, __VA_ARGS__); \ + GOTO (done); \ } while (0) @@ -113,20 +109,15 @@ typedef bool (*mongoc_rr_callback_t) (const char *hostname, bson_error_t *error); static bool -srv_callback (const char *hostname, - PDNS_RECORD pdns, - mongoc_rr_data_t *rr_data, - bson_error_t *error) +srv_callback (const char *hostname, PDNS_RECORD pdns, mongoc_rr_data_t *rr_data, bson_error_t *error) { mongoc_host_list_t new_host; if (rr_data && rr_data->hosts) { - _mongoc_host_list_remove_host ( - &(rr_data->hosts), pdns->Data.SRV.pNameTarget, pdns->Data.SRV.wPort); + _mongoc_host_list_remove_host (&(rr_data->hosts), pdns->Data.SRV.pNameTarget, pdns->Data.SRV.wPort); } - if (!_mongoc_host_list_from_hostport_with_err ( - &new_host, pdns->Data.SRV.pNameTarget, pdns->Data.SRV.wPort, error)) { + if (!_mongoc_host_list_from_hostport_with_err (&new_host, pdns->Data.SRV.pNameTarget, pdns->Data.SRV.wPort, error)) { return false; } _mongoc_host_list_upsert (&rr_data->hosts, &new_host); @@ -136,10 +127,7 @@ srv_callback (const char *hostname, /* rr_data is unused, but here to match srv_callback signature */ static bool -txt_callback (const char *hostname, - PDNS_RECORD pdns, - mongoc_rr_data_t *rr_data, - bson_error_t *error) +txt_callback (const char *hostname, PDNS_RECORD pdns, mongoc_rr_data_t *rr_data, bson_error_t *error) { DWORD i; bson_string_t *txt; @@ -182,10 +170,7 @@ txt_callback (const char *hostname, */ static bool -_mongoc_get_rr_dnsapi (const char *hostname, - mongoc_rr_type_t rr_type, - mongoc_rr_data_t *rr_data, - bson_error_t *error) +_mongoc_get_rr_dnsapi (const char *hostname, mongoc_rr_type_t rr_type, mongoc_rr_data_t *rr_data, bson_error_t *error) { const char *rr_type_name; WORD nst; @@ -213,33 +198,16 @@ _mongoc_get_rr_dnsapi (const char *hostname, callback = txt_callback; } - res = DnsQuery_UTF8 (hostname, - nst, - DNS_QUERY_BYPASS_CACHE, - NULL /* IP Address */, - &pdns, - 0 /* reserved */); + res = DnsQuery_UTF8 (hostname, nst, DNS_QUERY_BYPASS_CACHE, NULL /* IP Address */, &pdns, 0 /* reserved */); if (res) { - DWORD flags = FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS; - - if (FormatMessage (flags, - 0, - res, - MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT), - (LPTSTR) &lpMsgBuf, - 0, - 0)) { - DNS_ERROR ("Failed to look up %s record \"%s\": %s", - rr_type_name, - hostname, - (char *) lpMsgBuf); + DWORD flags = FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS; + + if (FormatMessage (flags, 0, res, MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &lpMsgBuf, 0, 0)) { + DNS_ERROR ("Failed to look up %s record \"%s\": %s", rr_type_name, hostname, (char *) lpMsgBuf); } - DNS_ERROR ("Failed to look up %s record \"%s\": Unknown error", - rr_type_name, - hostname); + DNS_ERROR ("Failed to look up %s record \"%s\": Unknown error", rr_type_name, hostname); } if (!pdns) { @@ -295,15 +263,10 @@ _mongoc_get_rr_dnsapi (const char *hostname, RETURN (dns_success && callback_success); } -#elif ( \ - defined(MONGOC_HAVE_RES_NSEARCH) || \ - defined(MONGOC_HAVE_RES_SEARCH)) // ↑↑↑↑↑↑↑ Win32 Dnsapi / resolv ↓↓↓↓↓↓↓↓ +#elif (defined(MONGOC_HAVE_RES_NSEARCH) || defined(MONGOC_HAVE_RES_SEARCH)) // ↑↑↑↑↑↑↑ Win32 Dnsapi / resolv ↓↓↓↓↓↓↓↓ -typedef bool (*mongoc_rr_callback_t) (const char *hostname, - ns_msg *ns_answer, - ns_rr *rr, - mongoc_rr_data_t *rr_data, - bson_error_t *error); +typedef bool (*mongoc_rr_callback_t) ( + const char *hostname, ns_msg *ns_answer, ns_rr *rr, mongoc_rr_data_t *rr_data, bson_error_t *error); static const char * _mongoc_hstrerror (int code) @@ -324,11 +287,7 @@ _mongoc_hstrerror (int code) } static bool -srv_callback (const char *hostname, - ns_msg *ns_answer, - ns_rr *rr, - mongoc_rr_data_t *rr_data, - bson_error_t *error) +srv_callback (const char *hostname, ns_msg *ns_answer, ns_rr *rr, mongoc_rr_data_t *rr_data, bson_error_t *error) { const uint8_t *data; char name[1024]; @@ -343,20 +302,13 @@ srv_callback (const char *hostname, * 2-byte boundary. */ memcpy (&port, data + 4, sizeof (port)); port = ntohs (port); - size = dn_expand (ns_msg_base (*ns_answer), - ns_msg_end (*ns_answer), - data + 6, - name, - sizeof (name)); + size = dn_expand (ns_msg_base (*ns_answer), ns_msg_end (*ns_answer), data + 6, name, sizeof (name)); if (size < 1) { - DNS_ERROR ("Invalid record in SRV answer for \"%s\": \"%s\"", - hostname, - _mongoc_hstrerror (h_errno)); + DNS_ERROR ("Invalid record in SRV answer for \"%s\": \"%s\"", hostname, _mongoc_hstrerror (h_errno)); } - if (!_mongoc_host_list_from_hostport_with_err ( - &new_host, name, port, error)) { + if (!_mongoc_host_list_from_hostport_with_err (&new_host, name, port, error)) { GOTO (done); } _mongoc_host_list_upsert (&rr_data->hosts, &new_host); @@ -366,11 +318,7 @@ srv_callback (const char *hostname, } static bool -txt_callback (const char *hostname, - ns_msg *ns_answer, - ns_rr *rr, - mongoc_rr_data_t *rr_data, - bson_error_t *error) +txt_callback (const char *hostname, ns_msg *ns_answer, ns_rr *rr, mongoc_rr_data_t *rr_data, bson_error_t *error) { char s[256]; const uint8_t *data; @@ -490,17 +438,13 @@ _mongoc_get_rr_search (const char *hostname, #ifdef MONGOC_HAVE_RES_NSEARCH /* thread-safe */ res_ninit (&state); - size = - res_nsearch (&state, hostname, ns_c_in, nst, search_buf, buffer_size); + size = res_nsearch (&state, hostname, ns_c_in, nst, search_buf, buffer_size); #elif defined(MONGOC_HAVE_RES_SEARCH) size = res_search (hostname, ns_c_in, nst, search_buf, buffer_size); #endif if (size < 0) { - DNS_ERROR ("Failed to look up %s record \"%s\": %s", - rr_type_name, - hostname, - _mongoc_hstrerror (h_errno)); + DNS_ERROR ("Failed to look up %s record \"%s\": %s", rr_type_name, hostname, _mongoc_hstrerror (h_errno)); } } while (size >= buffer_size); @@ -621,8 +565,7 @@ _mongoc_client_get_rr (const char *hostname, #elif defined(MONGOC_HAVE_DNSAPI) return _mongoc_get_rr_dnsapi (hostname, rr_type, rr_data, error); #elif (defined(MONGOC_HAVE_RES_NSEARCH) || defined(MONGOC_HAVE_RES_SEARCH)) - return _mongoc_get_rr_search ( - hostname, rr_type, rr_data, initial_buffer_size, error); + return _mongoc_get_rr_search (hostname, rr_type, rr_data, initial_buffer_size, error); #else #error No SRV library is available, but ENABLE_SRV is true! #endif @@ -651,9 +594,7 @@ _mongoc_client_get_rr (const char *hostname, */ mongoc_stream_t * -mongoc_client_connect_tcp (int32_t connecttimeoutms, - const mongoc_host_list_t *host, - bson_error_t *error) +mongoc_client_connect_tcp (int32_t connecttimeoutms, const mongoc_host_list_t *host, bson_error_t *error) { mongoc_socket_t *sock = NULL; struct addrinfo hints; @@ -681,11 +622,8 @@ mongoc_client_connect_tcp (int32_t connecttimeoutms, if (s != 0) { mongoc_counter_dns_failure_inc (); TRACE ("Failed to resolve %s", host->host); - bson_set_error (error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_NAME_RESOLUTION, - "Failed to resolve %s", - host->host); + bson_set_error ( + error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_NAME_RESOLUTION, "Failed to resolve %s", host->host); RETURN (NULL); } @@ -695,8 +633,7 @@ mongoc_client_connect_tcp (int32_t connecttimeoutms, /* * Create a new non-blocking socket. */ - if (!(sock = mongoc_socket_new ( - rp->ai_family, rp->ai_socktype, rp->ai_protocol))) { + if (!(sock = mongoc_socket_new (rp->ai_family, rp->ai_socktype, rp->ai_protocol))) { continue; } @@ -704,9 +641,7 @@ mongoc_client_connect_tcp (int32_t connecttimeoutms, * Try to connect to the peer. */ expire_at = bson_get_monotonic_time () + (connecttimeoutms * 1000L); - if (0 != - mongoc_socket_connect ( - sock, rp->ai_addr, (mongoc_socklen_t) rp->ai_addrlen, expire_at)) { + if (0 != mongoc_socket_connect (sock, rp->ai_addr, (mongoc_socklen_t) rp->ai_addrlen, expire_at)) { mongoc_socket_destroy (sock); sock = NULL; continue; @@ -753,10 +688,8 @@ mongoc_client_connect_unix (const mongoc_host_list_t *host, bson_error_t *error) { #ifdef _WIN32 ENTRY; - bson_set_error (error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_CONNECT, - "UNIX domain sockets not supported on win32."); + bson_set_error ( + error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_CONNECT, "UNIX domain sockets not supported on win32."); RETURN (NULL); #else struct sockaddr_un saddr; @@ -774,20 +707,14 @@ mongoc_client_connect_unix (const mongoc_host_list_t *host, bson_error_t *error) sock = mongoc_socket_new (AF_UNIX, SOCK_STREAM, 0); if (sock == NULL) { - bson_set_error (error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_SOCKET, - "Failed to create socket."); + bson_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "Failed to create socket."); RETURN (NULL); } - if (-1 == mongoc_socket_connect ( - sock, (struct sockaddr *) &saddr, sizeof saddr, -1)) { + if (-1 == mongoc_socket_connect (sock, (struct sockaddr *) &saddr, sizeof saddr, -1)) { mongoc_socket_destroy (sock); - bson_set_error (error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_CONNECT, - "Failed to connect to UNIX domain socket."); + bson_set_error ( + error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_CONNECT, "Failed to connect to UNIX domain socket."); RETURN (NULL); } @@ -821,8 +748,8 @@ mongoc_client_connect (bool buffered, } #endif - connecttimeoutms = mongoc_uri_get_option_as_int32 ( - uri, MONGOC_URI_CONNECTTIMEOUTMS, MONGOC_DEFAULT_CONNECTTIMEOUTMS); + connecttimeoutms = + mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_CONNECTTIMEOUTMS, MONGOC_DEFAULT_CONNECTTIMEOUTMS); switch (host->family) { case AF_UNSPEC: @@ -836,11 +763,8 @@ mongoc_client_connect (bool buffered, base_stream = mongoc_client_connect_unix (host, error); break; default: - bson_set_error (error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_INVALID_TYPE, - "Invalid address family: 0x%02x", - host->family); + bson_set_error ( + error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_INVALID_TYPE, "Invalid address family: 0x%02x", host->family); break; } @@ -855,20 +779,15 @@ mongoc_client_connect (bool buffered, if (use_ssl || (mechanism && (0 == strcmp (mechanism, "MONGODB-X509")))) { mongoc_stream_t *original = base_stream; - base_stream = mongoc_stream_tls_new_with_hostname ( - base_stream, host->host, ssl_opts, true); + base_stream = mongoc_stream_tls_new_with_hostname (base_stream, host->host, ssl_opts, true); if (!base_stream) { mongoc_stream_destroy (original); - bson_set_error (error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_SOCKET, - "Failed initialize TLS state."); + bson_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "Failed initialize TLS state."); return NULL; } - if (!mongoc_stream_tls_handshake_block ( - base_stream, host->host, connecttimeoutms, error)) { + if (!mongoc_stream_tls_handshake_block (base_stream, host->host, connecttimeoutms, error)) { mongoc_stream_destroy (base_stream); return NULL; } @@ -921,8 +840,7 @@ mongoc_client_default_stream_initiator (const mongoc_uri_t *uri, #endif - return mongoc_client_connect ( - true, use_ssl, ssl_opts_void, uri, host, error); + return mongoc_client_connect (true, use_ssl, ssl_opts_void, uri, host, error); } /* @@ -949,9 +867,7 @@ mongoc_client_default_stream_initiator (const mongoc_uri_t *uri, */ mongoc_stream_t * -_mongoc_client_create_stream (mongoc_client_t *client, - const mongoc_host_list_t *host, - bson_error_t *error) +_mongoc_client_create_stream (mongoc_client_t *client, const mongoc_host_list_t *host, bson_error_t *error) { BSON_ASSERT_PARAM (client); BSON_ASSERT (host); @@ -973,8 +889,7 @@ _mongoc_client_recv (mongoc_client_t *client, BSON_ASSERT (server_stream); BSON_ASSERT_PARAM (error); - return mongoc_cluster_try_recv ( - &client->cluster, rpc, buffer, server_stream, error); + return mongoc_cluster_try_recv (&client->cluster, rpc, buffer, server_stream, error); } @@ -1024,37 +939,29 @@ mongoc_client_new (const char *uri_string) #ifdef MONGOC_ENABLE_SSL /* Only called internally. Caller must ensure opts->internal is valid. */ void -_mongoc_client_set_internal_tls_opts (mongoc_client_t *client, - _mongoc_internal_tls_opts_t *internal) +_mongoc_client_set_internal_tls_opts (mongoc_client_t *client, _mongoc_internal_tls_opts_t *internal) { BSON_ASSERT_PARAM (client); if (!client->use_ssl) { return; } - client->ssl_opts.internal = - bson_malloc (sizeof (_mongoc_internal_tls_opts_t)); - memcpy (client->ssl_opts.internal, - internal, - sizeof (_mongoc_internal_tls_opts_t)); + client->ssl_opts.internal = bson_malloc (sizeof (_mongoc_internal_tls_opts_t)); + memcpy (client->ssl_opts.internal, internal, sizeof (_mongoc_internal_tls_opts_t)); } void -mongoc_client_set_ssl_opts (mongoc_client_t *client, - const mongoc_ssl_opt_t *opts) +mongoc_client_set_ssl_opts (mongoc_client_t *client, const mongoc_ssl_opt_t *opts) { BSON_ASSERT_PARAM (client); BSON_ASSERT (opts); - _mongoc_ssl_opts_cleanup (&client->ssl_opts, - false /* don't free internal opts */); + _mongoc_ssl_opts_cleanup (&client->ssl_opts, false /* don't free internal opts */); client->use_ssl = true; - _mongoc_ssl_opts_copy_to ( - opts, &client->ssl_opts, false /* don't overwrite internal opts */); + _mongoc_ssl_opts_copy_to (opts, &client->ssl_opts, false /* don't overwrite internal opts */); if (client->topology->single_threaded) { - mongoc_topology_scanner_set_ssl_opts (client->topology->scanner, - &client->ssl_opts); + mongoc_topology_scanner_set_ssl_opts (client->topology->scanner, &client->ssl_opts); } } #endif @@ -1075,8 +982,7 @@ mongoc_client_new_from_uri (const mongoc_uri_t *uri) mongoc_client_t * -mongoc_client_new_from_uri_with_error (const mongoc_uri_t *uri, - bson_error_t *error) +mongoc_client_new_from_uri_with_error (const mongoc_uri_t *uri, bson_error_t *error) { mongoc_client_t *client; mongoc_topology_t *topology; @@ -1088,11 +994,10 @@ mongoc_client_new_from_uri_with_error (const mongoc_uri_t *uri, #ifndef MONGOC_ENABLE_SSL if (mongoc_uri_get_tls (uri)) { - bson_set_error ( - error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Can't create SSL client, SSL not enabled in this build."); + bson_set_error (error, + MONGOC_ERROR_COMMAND, + MONGOC_ERROR_COMMAND_INVALID_ARG, + "Can't create SSL client, SSL not enabled in this build."); RETURN (NULL); } #endif @@ -1148,8 +1053,7 @@ _mongoc_client_new_from_topology (mongoc_topology_t *topology) read_prefs = mongoc_uri_get_read_prefs_t (client->uri); client->read_prefs = mongoc_read_prefs_copy (read_prefs); - appname = - mongoc_uri_get_option_as_utf8 (client->uri, MONGOC_URI_APPNAME, NULL); + appname = mongoc_uri_get_option_as_utf8 (client->uri, MONGOC_URI_APPNAME, NULL); if (appname && client->topology->single_threaded) { /* the appname should have already been validated */ BSON_ASSERT (mongoc_client_set_appname (client, appname)); @@ -1265,9 +1169,7 @@ mongoc_client_get_uri (const mongoc_client_t *client) */ mongoc_client_session_t * -mongoc_client_start_session (mongoc_client_t *client, - const mongoc_session_opt_t *opts, - bson_error_t *error) +mongoc_client_start_session (mongoc_client_t *client, const mongoc_session_opt_t *opts, bson_error_t *error) { BSON_ASSERT_PARAM (client); @@ -1288,13 +1190,11 @@ mongoc_client_start_session (mongoc_client_t *client, } while (mongoc_set_get (client->client_sessions, csid)); /* causal consistency and snapshot cannot both be set. */ - if (opts && mongoc_session_opts_get_causal_consistency (opts) && - mongoc_session_opts_get_snapshot (opts)) { - bson_set_error ( - error, - MONGOC_ERROR_CLIENT, - MONGOC_ERROR_CLIENT_SESSION_FAILURE, - "Only one of causal consistency and snapshot can be enabled."); + if (opts && mongoc_session_opts_get_causal_consistency (opts) && mongoc_session_opts_get_snapshot (opts)) { + bson_set_error (error, + MONGOC_ERROR_CLIENT, + MONGOC_ERROR_CLIENT_SESSION_FAILURE, + "Only one of causal consistency and snapshot can be enabled."); _mongoc_client_push_server_session (client, ss); RETURN (NULL); } @@ -1336,11 +1236,7 @@ mongoc_client_get_database (mongoc_client_t *client, const char *name) BSON_ASSERT_PARAM (client); BSON_ASSERT (name); - return _mongoc_database_new (client, - name, - client->read_prefs, - client->read_concern, - client->write_concern); + return _mongoc_database_new (client, name, client->read_prefs, client->read_concern, client->write_concern); } @@ -1406,20 +1302,14 @@ mongoc_client_get_default_database (mongoc_client_t *client) */ mongoc_collection_t * -mongoc_client_get_collection (mongoc_client_t *client, - const char *db, - const char *collection) +mongoc_client_get_collection (mongoc_client_t *client, const char *db, const char *collection) { BSON_ASSERT_PARAM (client); BSON_ASSERT (db); BSON_ASSERT (collection); - return _mongoc_collection_new (client, - db, - collection, - client->read_prefs, - client->read_concern, - client->write_concern); + return _mongoc_collection_new ( + client, db, collection, client->read_prefs, client->read_concern, client->write_concern); } @@ -1447,10 +1337,7 @@ mongoc_client_get_collection (mongoc_client_t *client, */ mongoc_gridfs_t * -mongoc_client_get_gridfs (mongoc_client_t *client, - const char *db, - const char *prefix, - bson_error_t *error) +mongoc_client_get_gridfs (mongoc_client_t *client, const char *db, const char *prefix, bson_error_t *error) { BSON_ASSERT_PARAM (client); BSON_ASSERT (db); @@ -1505,8 +1392,7 @@ mongoc_client_get_write_concern (const mongoc_client_t *client) */ void -mongoc_client_set_write_concern (mongoc_client_t *client, - const mongoc_write_concern_t *write_concern) +mongoc_client_set_write_concern (mongoc_client_t *client, const mongoc_write_concern_t *write_concern) { BSON_ASSERT_PARAM (client); @@ -1514,9 +1400,7 @@ mongoc_client_set_write_concern (mongoc_client_t *client, if (client->write_concern) { mongoc_write_concern_destroy (client->write_concern); } - client->write_concern = write_concern - ? mongoc_write_concern_copy (write_concern) - : mongoc_write_concern_new (); + client->write_concern = write_concern ? mongoc_write_concern_copy (write_concern) : mongoc_write_concern_new (); } } @@ -1563,8 +1447,7 @@ mongoc_client_get_read_concern (const mongoc_client_t *client) */ void -mongoc_client_set_read_concern (mongoc_client_t *client, - const mongoc_read_concern_t *read_concern) +mongoc_client_set_read_concern (mongoc_client_t *client, const mongoc_read_concern_t *read_concern) { BSON_ASSERT_PARAM (client); @@ -1572,9 +1455,7 @@ mongoc_client_set_read_concern (mongoc_client_t *client, if (client->read_concern) { mongoc_read_concern_destroy (client->read_concern); } - client->read_concern = read_concern - ? mongoc_read_concern_copy (read_concern) - : mongoc_read_concern_new (); + client->read_concern = read_concern ? mongoc_read_concern_copy (read_concern) : mongoc_read_concern_new (); } } @@ -1621,8 +1502,7 @@ mongoc_client_get_read_prefs (const mongoc_client_t *client) */ void -mongoc_client_set_read_prefs (mongoc_client_t *client, - const mongoc_read_prefs_t *read_prefs) +mongoc_client_set_read_prefs (mongoc_client_t *client, const mongoc_read_prefs_t *read_prefs) { BSON_ASSERT_PARAM (client); @@ -1630,9 +1510,8 @@ mongoc_client_set_read_prefs (mongoc_client_t *client, if (client->read_prefs) { mongoc_read_prefs_destroy (client->read_prefs); } - client->read_prefs = read_prefs - ? mongoc_read_prefs_copy (read_prefs) - : mongoc_read_prefs_new (MONGOC_READ_PRIMARY); + client->read_prefs = + read_prefs ? mongoc_read_prefs_copy (read_prefs) : mongoc_read_prefs_new (MONGOC_READ_PRIMARY); } } @@ -1668,8 +1547,7 @@ mongoc_client_command (mongoc_client_t *client, db_name = ns; } - cursor = - _mongoc_cursor_cmd_deprecated_new (client, db_name, query, read_prefs); + cursor = _mongoc_cursor_cmd_deprecated_new (client, db_name, query, read_prefs); bson_free (ns); return cursor; @@ -1677,12 +1555,11 @@ mongoc_client_command (mongoc_client_t *client, static bool -_mongoc_client_retryable_write_command_with_stream ( - mongoc_client_t *client, - mongoc_cmd_parts_t *parts, - mongoc_server_stream_t *server_stream, - bson_t *reply, - bson_error_t *error) +_mongoc_client_retryable_write_command_with_stream (mongoc_client_t *client, + mongoc_cmd_parts_t *parts, + mongoc_server_stream_t *server_stream, + bson_t *reply, + bson_error_t *error) { mongoc_server_stream_t *retry_server_stream = NULL; bson_iter_t txn_number_iter; @@ -1696,10 +1573,8 @@ _mongoc_client_retryable_write_command_with_stream ( /* increment the transaction number for the first attempt of each retryable * write command */ - BSON_ASSERT (bson_iter_init_find ( - &txn_number_iter, parts->assembled.command, "txnNumber")); - bson_iter_overwrite_int64 ( - &txn_number_iter, ++parts->assembled.session->server_session->txn_number); + BSON_ASSERT (bson_iter_init_find (&txn_number_iter, parts->assembled.command, "txnNumber")); + bson_iter_overwrite_int64 (&txn_number_iter, ++parts->assembled.session->server_session->txn_number); // Store the original error and reply if needed. struct { @@ -1709,41 +1584,32 @@ _mongoc_client_retryable_write_command_with_stream ( } original_error = {.reply = {0}, .error = {0}, false}; retry: - ret = mongoc_cluster_run_command_monitored ( - &client->cluster, &parts->assembled, reply, error); + ret = mongoc_cluster_run_command_monitored (&client->cluster, &parts->assembled, reply, error); _mongoc_write_error_handle_labels (ret, error, reply, server_stream->sd); if (is_retryable) { - _mongoc_write_error_update_if_unsupported_storage_engine ( - ret, error, reply); + _mongoc_write_error_update_if_unsupported_storage_engine (ret, error, reply); } /* If a retryable error is encountered and the write is retryable, select * a new writable stream and retry. If server selection fails or the selected * server does not support retryable writes, fall through and allow the * original error to be reported. */ - if (is_retryable && - _mongoc_write_error_get_type (reply) == MONGOC_WRITE_ERR_RETRY) { + if (is_retryable && _mongoc_write_error_get_type (reply) == MONGOC_WRITE_ERR_RETRY) { bson_error_t ignored_error; // The write command may be retried at most once. is_retryable = false; { - mongoc_deprioritized_servers_t *const ds = - mongoc_deprioritized_servers_new (); + mongoc_deprioritized_servers_t *const ds = mongoc_deprioritized_servers_new (); - mongoc_deprioritized_servers_add_if_sharded ( - ds, server_stream->topology_type, server_stream->sd); + mongoc_deprioritized_servers_add_if_sharded (ds, server_stream->topology_type, server_stream->sd); BSON_ASSERT (!retry_server_stream); retry_server_stream = - mongoc_cluster_stream_for_writes (&client->cluster, - parts->assembled.session, - ds, - NULL, - &ignored_error); + mongoc_cluster_stream_for_writes (&client->cluster, parts->assembled.session, ds, NULL, &ignored_error); mongoc_deprioritized_servers_destroy (ds); } @@ -1770,8 +1636,7 @@ _mongoc_client_retryable_write_command_with_stream ( // If a retry attempt fails with an error labeled NoWritesPerformed, // drivers MUST return the original error. - if (original_error.set && - mongoc_error_has_label (reply, "NoWritesPerformed")) { + if (original_error.set && mongoc_error_has_label (reply, "NoWritesPerformed")) { if (error) { *error = original_error.error; } @@ -1793,12 +1658,11 @@ _mongoc_client_retryable_write_command_with_stream ( static bool -_mongoc_client_retryable_read_command_with_stream ( - mongoc_client_t *client, - mongoc_cmd_parts_t *parts, - mongoc_server_stream_t *server_stream, - bson_t *reply, - bson_error_t *error) +_mongoc_client_retryable_read_command_with_stream (mongoc_client_t *client, + mongoc_cmd_parts_t *parts, + mongoc_server_stream_t *server_stream, + bson_t *reply, + bson_error_t *error) { mongoc_server_stream_t *retry_server_stream = NULL; bool is_retryable = true; @@ -1817,40 +1681,31 @@ _mongoc_client_retryable_read_command_with_stream ( BSON_ASSERT (parts->is_retryable_read); retry: - ret = mongoc_cluster_run_command_monitored ( - &client->cluster, &parts->assembled, reply, error); + ret = mongoc_cluster_run_command_monitored (&client->cluster, &parts->assembled, reply, error); /* If a retryable error is encountered and the read is retryable, select * a new readable stream and retry. If server selection fails or the selected * server does not support retryable reads, fall through and allow the * original error to be reported. */ - if (is_retryable && _mongoc_read_error_get_type (ret, error, reply) == - MONGOC_READ_ERR_RETRY) { + if (is_retryable && _mongoc_read_error_get_type (ret, error, reply) == MONGOC_READ_ERR_RETRY) { bson_error_t ignored_error; /* each read command may be retried at most once */ is_retryable = false; { - mongoc_deprioritized_servers_t *const ds = - mongoc_deprioritized_servers_new (); + mongoc_deprioritized_servers_t *const ds = mongoc_deprioritized_servers_new (); if (retry_server_stream) { mongoc_deprioritized_servers_add_if_sharded ( ds, retry_server_stream->topology_type, retry_server_stream->sd); mongoc_server_stream_cleanup (retry_server_stream); } else { - mongoc_deprioritized_servers_add_if_sharded ( - ds, server_stream->topology_type, server_stream->sd); + mongoc_deprioritized_servers_add_if_sharded (ds, server_stream->topology_type, server_stream->sd); } - retry_server_stream = - mongoc_cluster_stream_for_reads (&client->cluster, - parts->read_prefs, - parts->assembled.session, - ds, - NULL, - &ignored_error); + retry_server_stream = mongoc_cluster_stream_for_reads ( + &client->cluster, parts->read_prefs, parts->assembled.session, ds, NULL, &ignored_error); mongoc_deprioritized_servers_destroy (ds); } @@ -1895,17 +1750,14 @@ _mongoc_client_command_with_stream (mongoc_client_t *client, } if (parts->is_retryable_write) { - RETURN (_mongoc_client_retryable_write_command_with_stream ( - client, parts, server_stream, reply, error)); + RETURN (_mongoc_client_retryable_write_command_with_stream (client, parts, server_stream, reply, error)); } if (parts->is_retryable_read) { - RETURN (_mongoc_client_retryable_read_command_with_stream ( - client, parts, server_stream, reply, error)); + RETURN (_mongoc_client_retryable_read_command_with_stream (client, parts, server_stream, reply, error)); } - RETURN (mongoc_cluster_run_command_monitored ( - &client->cluster, &parts->assembled, reply, error)); + RETURN (mongoc_cluster_run_command_monitored (&client->cluster, &parts->assembled, reply, error)); } @@ -1942,12 +1794,10 @@ mongoc_client_command_simple (mongoc_client_t *client, * configuration. The generic command method SHOULD allow an optional read * preference argument." */ - server_stream = mongoc_cluster_stream_for_reads ( - cluster, read_prefs, NULL, NULL, reply, error); + server_stream = mongoc_cluster_stream_for_reads (cluster, read_prefs, NULL, NULL, reply, error); if (server_stream) { - ret = _mongoc_client_command_with_stream ( - client, &parts, read_prefs, server_stream, reply, error); + ret = _mongoc_client_command_with_stream (client, &parts, read_prefs, server_stream, reply, error); } else { /* reply initialized by mongoc_cluster_stream_for_reads */ ret = false; @@ -2035,16 +1885,12 @@ _mongoc_client_command_with_opts (mongoc_client_t *client, cs = read_write_opts.client_session; if (!command_name) { - bson_set_error (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Empty command document"); + bson_set_error (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Empty command document"); GOTO (done); } if (_mongoc_client_session_in_txn (read_write_opts.client_session)) { - if ((mode == MONGOC_CMD_READ || mode == MONGOC_CMD_RAW) && - !IS_PREF_PRIMARY (user_prefs)) { + if ((mode == MONGOC_CMD_READ || mode == MONGOC_CMD_RAW) && !IS_PREF_PRIMARY (user_prefs)) { bson_set_error (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, @@ -2060,8 +1906,7 @@ _mongoc_client_command_with_opts (mongoc_client_t *client, GOTO (done); } - if (read_write_opts.writeConcern && - strcmp (command_name, "commitTransaction") != 0 && + if (read_write_opts.writeConcern && strcmp (command_name, "commitTransaction") != 0 && strcmp (command_name, "abortTransaction") != 0) { bson_set_error (error, MONGOC_ERROR_COMMAND, @@ -2085,23 +1930,16 @@ _mongoc_client_command_with_opts (mongoc_client_t *client, if (read_write_opts.serverId) { /* "serverId" passed in opts */ - server_stream = - mongoc_cluster_stream_for_server (cluster, - read_write_opts.serverId, - true /* reconnect ok */, - cs, - reply_ptr, - error); + server_stream = mongoc_cluster_stream_for_server ( + cluster, read_write_opts.serverId, true /* reconnect ok */, cs, reply_ptr, error); if (server_stream && server_stream->sd->type != MONGOC_SERVER_MONGOS) { parts.user_query_flags |= MONGOC_QUERY_SECONDARY_OK; } } else if (parts.is_write_command) { - server_stream = - mongoc_cluster_stream_for_writes (cluster, cs, NULL, reply_ptr, error); + server_stream = mongoc_cluster_stream_for_writes (cluster, cs, NULL, reply_ptr, error); } else { - server_stream = mongoc_cluster_stream_for_reads ( - cluster, prefs, cs, NULL, reply_ptr, error); + server_stream = mongoc_cluster_stream_for_reads (cluster, prefs, cs, NULL, reply_ptr, error); } if (!server_stream) { @@ -2116,8 +1954,7 @@ _mongoc_client_command_with_opts (mongoc_client_t *client, if (mode & MONGOC_CMD_WRITE) { /* use default write concern unless it's in opts */ - if (!mongoc_write_concern_is_default (default_wc) && - !read_write_opts.write_concern_owned) { + if (!mongoc_write_concern_is_default (default_wc) && !read_write_opts.write_concern_owned) { if (!mongoc_cmd_parts_set_write_concern (&parts, default_wc, error)) { GOTO (done); } @@ -2131,8 +1968,7 @@ _mongoc_client_command_with_opts (mongoc_client_t *client, } } - ret = _mongoc_client_command_with_stream ( - client, &parts, user_prefs, server_stream, reply_ptr, error); + ret = _mongoc_client_command_with_stream (client, &parts, user_prefs, server_stream, reply_ptr, error); reply_initialized = true; @@ -2208,14 +2044,13 @@ mongoc_client_write_command_with_opts (mongoc_client_t *client, bool -mongoc_client_read_write_command_with_opts ( - mongoc_client_t *client, - const char *db_name, - const bson_t *command, - const mongoc_read_prefs_t *read_prefs /* IGNORED */, - const bson_t *opts, - bson_t *reply, - bson_error_t *error) +mongoc_client_read_write_command_with_opts (mongoc_client_t *client, + const char *db_name, + const bson_t *command, + const mongoc_read_prefs_t *read_prefs /* IGNORED */, + const bson_t *opts, + bson_t *reply, + bson_error_t *error) { return _mongoc_client_command_with_opts (client, db_name, @@ -2257,14 +2092,13 @@ mongoc_client_command_with_opts (mongoc_client_t *client, bool -mongoc_client_command_simple_with_server_id ( - mongoc_client_t *client, - const char *db_name, - const bson_t *command, - const mongoc_read_prefs_t *read_prefs, - uint32_t server_id, - bson_t *reply, - bson_error_t *error) +mongoc_client_command_simple_with_server_id (mongoc_client_t *client, + const char *db_name, + const bson_t *command, + const mongoc_read_prefs_t *read_prefs, + uint32_t server_id, + bson_t *reply, + bson_error_t *error) { mongoc_server_stream_t *server_stream; mongoc_cmd_parts_t parts; @@ -2280,16 +2114,14 @@ mongoc_client_command_simple_with_server_id ( RETURN (false); } - server_stream = mongoc_cluster_stream_for_server ( - &client->cluster, server_id, true /* reconnect ok */, NULL, reply, error); + server_stream = + mongoc_cluster_stream_for_server (&client->cluster, server_id, true /* reconnect ok */, NULL, reply, error); if (server_stream) { - mongoc_cmd_parts_init ( - &parts, client, db_name, MONGOC_QUERY_NONE, command); + mongoc_cmd_parts_init (&parts, client, db_name, MONGOC_QUERY_NONE, command); parts.read_prefs = read_prefs; - ret = _mongoc_client_command_with_stream ( - client, &parts, read_prefs, server_stream, reply, error); + ret = _mongoc_client_command_with_stream (client, &parts, read_prefs, server_stream, reply, error); mongoc_cmd_parts_cleanup (&parts); mongoc_server_stream_cleanup (server_stream); @@ -2302,9 +2134,7 @@ mongoc_client_command_simple_with_server_id ( static void -_mongoc_client_prepare_killcursors_command (int64_t cursor_id, - const char *collection, - bson_t *command) +_mongoc_client_prepare_killcursors_command (int64_t cursor_id, const char *collection, bson_t *command) { bson_array_builder_t *child; @@ -2332,23 +2162,17 @@ _mongoc_client_kill_cursor (mongoc_client_t *client, BSON_ASSERT (cursor_id); /* don't attempt reconnect if server unavailable, and ignore errors */ - server_stream = mongoc_cluster_stream_for_server ( - &client->cluster, server_id, false /* reconnect_ok */, NULL, NULL, NULL); + server_stream = + mongoc_cluster_stream_for_server (&client->cluster, server_id, false /* reconnect_ok */, NULL, NULL, NULL); if (!server_stream) { return; } if (db && collection) { - _mongoc_client_killcursors_command ( - &client->cluster, server_stream, cursor_id, db, collection, cs); + _mongoc_client_killcursors_command (&client->cluster, server_stream, cursor_id, db, collection, cs); } else { - _mongoc_client_op_killcursors (&client->cluster, - server_stream, - cursor_id, - operation_id, - db, - collection); + _mongoc_client_op_killcursors (&client->cluster, server_stream, cursor_id, operation_id, db, collection); } mongoc_server_stream_cleanup (server_stream); @@ -2401,12 +2225,11 @@ _mongoc_client_monitor_op_killcursors (mongoc_cluster_t *cluster, static void -_mongoc_client_monitor_op_killcursors_succeeded ( - mongoc_cluster_t *cluster, - int64_t duration, - mongoc_server_stream_t *server_stream, - int64_t cursor_id, - int64_t operation_id) +_mongoc_client_monitor_op_killcursors_succeeded (mongoc_cluster_t *cluster, + int64_t duration, + mongoc_server_stream_t *server_stream, + int64_t cursor_id, + int64_t operation_id) { mongoc_client_t *client; bson_t doc; @@ -2424,8 +2247,7 @@ _mongoc_client_monitor_op_killcursors_succeeded ( /* fake server reply to killCursors command: {ok: 1, cursorsUnknown: [42]} */ bson_init (&doc); bson_append_int32 (&doc, "ok", 2, 1); - bson_append_array_builder_begin ( - &doc, "cursorsUnknown", 14, &cursors_unknown); + bson_append_array_builder_begin (&doc, "cursorsUnknown", 14, &cursors_unknown); bson_array_builder_append_int64 (cursors_unknown, cursor_id); bson_append_array_builder_end (&doc, cursors_unknown); @@ -2450,12 +2272,11 @@ _mongoc_client_monitor_op_killcursors_succeeded ( static void -_mongoc_client_monitor_op_killcursors_failed ( - mongoc_cluster_t *cluster, - int64_t duration, - mongoc_server_stream_t *server_stream, - const bson_error_t *error, - int64_t operation_id) +_mongoc_client_monitor_op_killcursors_failed (mongoc_cluster_t *cluster, + int64_t duration, + mongoc_server_stream_t *server_stream, + const bson_error_t *error, + int64_t operation_id) { mongoc_client_t *client; bson_t doc; @@ -2516,43 +2337,30 @@ _mongoc_client_op_killcursors (mongoc_cluster_t *cluster, int32_t message_length = 0; message_length += mcd_rpc_header_set_message_length (rpc, 0); - message_length += - mcd_rpc_header_set_request_id (rpc, ++cluster->request_id); + message_length += mcd_rpc_header_set_request_id (rpc, ++cluster->request_id); message_length += mcd_rpc_header_set_response_to (rpc, 0); - message_length += - mcd_rpc_header_set_op_code (rpc, MONGOC_OP_CODE_KILL_CURSORS); + message_length += mcd_rpc_header_set_op_code (rpc, MONGOC_OP_CODE_KILL_CURSORS); message_length += sizeof (int32_t); // ZERO - message_length += - mcd_rpc_op_kill_cursors_set_cursor_ids (rpc, &cursor_id, 1); + message_length += mcd_rpc_op_kill_cursors_set_cursor_ids (rpc, &cursor_id, 1); mcd_rpc_message_set_length (rpc, message_length); } if (has_ns) { - _mongoc_client_monitor_op_killcursors ( - cluster, server_stream, cursor_id, operation_id, db, collection); + _mongoc_client_monitor_op_killcursors (cluster, server_stream, cursor_id, operation_id, db, collection); } bson_error_t error; - const bool res = mongoc_cluster_legacy_rpc_sendv_to_server ( - cluster, rpc, server_stream, &error); + const bool res = mongoc_cluster_legacy_rpc_sendv_to_server (cluster, rpc, server_stream, &error); if (has_ns) { if (res) { _mongoc_client_monitor_op_killcursors_succeeded ( - cluster, - bson_get_monotonic_time () - started, - server_stream, - cursor_id, - operation_id); + cluster, bson_get_monotonic_time () - started, server_stream, cursor_id, operation_id); } else { _mongoc_client_monitor_op_killcursors_failed ( - cluster, - bson_get_monotonic_time () - started, - server_stream, - &error, - operation_id); + cluster, bson_get_monotonic_time () - started, server_stream, &error, operation_id); } } @@ -2574,8 +2382,7 @@ _mongoc_client_killcursors_command (mongoc_cluster_t *cluster, ENTRY; _mongoc_client_prepare_killcursors_command (cursor_id, collection, &command); - mongoc_cmd_parts_init ( - &parts, cluster->client, db, MONGOC_QUERY_SECONDARY_OK, &command); + mongoc_cmd_parts_init (&parts, cluster->client, db, MONGOC_QUERY_SECONDARY_OK, &command); parts.assembled.operation_id = ++cluster->operation_id; mongoc_cmd_parts_set_session (&parts, cs); @@ -2583,8 +2390,7 @@ _mongoc_client_killcursors_command (mongoc_cluster_t *cluster, /* Find, getMore And killCursors Commands Spec: "The result from the * killCursors command MAY be safely ignored." */ - (void) mongoc_cluster_run_command_monitored ( - cluster, &parts.assembled, NULL, NULL); + (void) mongoc_cluster_run_command_monitored (cluster, &parts.assembled, NULL, NULL); } mongoc_cmd_parts_cleanup (&parts); @@ -2623,8 +2429,7 @@ mongoc_client_kill_cursor (mongoc_client_t *client, int64_t cursor_id) { BSON_ASSERT_PARAM (client); - mongoc_topology_t *const topology = - BSON_ASSERT_PTR_INLINE (client)->topology; + mongoc_topology_t *const topology = BSON_ASSERT_PTR_INLINE (client)->topology; mongoc_server_description_t const *selected_server; mongoc_read_prefs_t *read_prefs; bson_error_t error; @@ -2641,26 +2446,20 @@ mongoc_client_kill_cursor (mongoc_client_t *client, int64_t cursor_id) } /* see if there's a known writable server - do no I/O or retries */ - selected_server = - mongoc_topology_description_select (td.ptr, - MONGOC_SS_WRITE, - read_prefs, - NULL /* chosen read mode */, - NULL /* deprioritized servers */, - topology->local_threshold_msec); + selected_server = mongoc_topology_description_select (td.ptr, + MONGOC_SS_WRITE, + read_prefs, + NULL /* chosen read mode */, + NULL /* deprioritized servers */, + topology->local_threshold_msec); if (selected_server) { server_id = selected_server->id; } if (server_id) { - _mongoc_client_kill_cursor (client, - server_id, - cursor_id, - 0 /* operation_id */, - NULL /* db */, - NULL /* collection */, - NULL /* session */); + _mongoc_client_kill_cursor ( + client, server_id, cursor_id, 0 /* operation_id */, NULL /* db */, NULL /* collection */, NULL /* session */); } else { MONGOC_INFO ("No server available for mongoc_client_kill_cursor"); } @@ -2678,9 +2477,7 @@ mongoc_client_get_database_names (mongoc_client_t *client, bson_error_t *error) char ** -mongoc_client_get_database_names_with_opts (mongoc_client_t *client, - const bson_t *opts, - bson_error_t *error) +mongoc_client_get_database_names_with_opts (mongoc_client_t *client, const bson_t *opts, bson_error_t *error) { bson_iter_t iter; const char *name; @@ -2699,8 +2496,7 @@ mongoc_client_get_database_names_with_opts (mongoc_client_t *client, bson_destroy (&cmd); while (mongoc_cursor_next (cursor, &doc)) { - if (bson_iter_init (&iter, doc) && bson_iter_find (&iter, "name") && - BSON_ITER_HOLDS_UTF8 (&iter) && + if (bson_iter_init (&iter, doc) && bson_iter_find (&iter, "name") && BSON_ITER_HOLDS_UTF8 (&iter) && (name = bson_iter_utf8 (&iter, NULL))) { ret = (char **) bson_realloc (ret, sizeof (char *) * (i + 2)); ret[i] = bson_strdup (name); @@ -2730,8 +2526,7 @@ mongoc_client_find_databases (mongoc_client_t *client, bson_error_t *error) mongoc_cursor_t * -mongoc_client_find_databases_with_opts (mongoc_client_t *client, - const bson_t *opts) +mongoc_client_find_databases_with_opts (mongoc_client_t *client, const bson_t *opts) { bson_t cmd = BSON_INITIALIZER; mongoc_cursor_t *cursor; @@ -2774,8 +2569,7 @@ mongoc_client_get_server_status (mongoc_client_t *client, /* IN */ BSON_ASSERT_PARAM (client); BSON_APPEND_INT32 (&cmd, "serverStatus", 1); - ret = mongoc_client_command_simple ( - client, "admin", &cmd, read_prefs, reply, error); + ret = mongoc_client_command_simple (client, "admin", &cmd, read_prefs, reply, error); bson_destroy (&cmd); return ret; @@ -2783,9 +2577,7 @@ mongoc_client_get_server_status (mongoc_client_t *client, /* IN */ void -mongoc_client_set_stream_initiator (mongoc_client_t *client, - mongoc_stream_initiator_t initiator, - void *user_data) +mongoc_client_set_stream_initiator (mongoc_client_t *client, mongoc_stream_initiator_t initiator, void *user_data) { BSON_ASSERT_PARAM (client); @@ -2800,22 +2592,18 @@ mongoc_client_set_stream_initiator (mongoc_client_t *client, client->initiator_data = user_data; if (client->topology->single_threaded) { - mongoc_topology_scanner_set_stream_initiator ( - client->topology->scanner, initiator, user_data); + mongoc_topology_scanner_set_stream_initiator (client->topology->scanner, initiator, user_data); } } bool -_mongoc_client_set_apm_callbacks_private (mongoc_client_t *client, - mongoc_apm_callbacks_t *callbacks, - void *context) +_mongoc_client_set_apm_callbacks_private (mongoc_client_t *client, mongoc_apm_callbacks_t *callbacks, void *context) { BSON_ASSERT_PARAM (client); if (callbacks) { - memcpy ( - &client->apm_callbacks, callbacks, sizeof (mongoc_apm_callbacks_t)); + memcpy (&client->apm_callbacks, callbacks, sizeof (mongoc_apm_callbacks_t)); } else { memset (&client->apm_callbacks, 0, sizeof (mongoc_apm_callbacks_t)); } @@ -2824,13 +2612,12 @@ _mongoc_client_set_apm_callbacks_private (mongoc_client_t *client, /* A client pool sets APM callbacks for the entire pool. */ if (client->topology->single_threaded) { - mongoc_topology_set_apm_callbacks ( - client->topology, - /* We are safe to modify the shared_descr directly, since we are - * single-threaded */ - mc_tpld_unsafe_get_mutable (client->topology), - callbacks, - context); + mongoc_topology_set_apm_callbacks (client->topology, + /* We are safe to modify the shared_descr directly, since we are + * single-threaded */ + mc_tpld_unsafe_get_mutable (client->topology), + callbacks, + context); } return true; @@ -2838,9 +2625,7 @@ _mongoc_client_set_apm_callbacks_private (mongoc_client_t *client, bool -mongoc_client_set_apm_callbacks (mongoc_client_t *client, - mongoc_apm_callbacks_t *callbacks, - void *context) +mongoc_client_set_apm_callbacks (mongoc_client_t *client, mongoc_apm_callbacks_t *callbacks, void *context) { BSON_ASSERT_PARAM (client); @@ -2854,16 +2639,14 @@ mongoc_client_set_apm_callbacks (mongoc_client_t *client, } mongoc_server_description_t * -mongoc_client_get_server_description (mongoc_client_t *client, - uint32_t server_id) +mongoc_client_get_server_description (mongoc_client_t *client, uint32_t server_id) { BSON_ASSERT_PARAM (client); mongoc_server_description_t *ret; mc_shared_tpld td = mc_tpld_take_ref (client->topology); mongoc_server_description_t const *sd = - mongoc_topology_description_server_by_id_const ( - td.ptr, server_id, NULL /* <- the error info isn't useful */); + mongoc_topology_description_server_by_id_const (td.ptr, server_id, NULL /* <- the error info isn't useful */); ret = mongoc_server_description_new_copy (sd); mc_tpld_drop_ref (&td); return ret; @@ -2871,24 +2654,20 @@ mongoc_client_get_server_description (mongoc_client_t *client, mongoc_server_description_t ** -mongoc_client_get_server_descriptions (const mongoc_client_t *client, - size_t *n /* OUT */) +mongoc_client_get_server_descriptions (const mongoc_client_t *client, size_t *n /* OUT */) { BSON_ASSERT_PARAM (client); - mc_shared_tpld td = - mc_tpld_take_ref (BSON_ASSERT_PTR_INLINE (client)->topology); + mc_shared_tpld td = mc_tpld_take_ref (BSON_ASSERT_PTR_INLINE (client)->topology); mongoc_server_description_t **const sds = - mongoc_topology_description_get_servers (td.ptr, - BSON_ASSERT_PTR_INLINE (n)); + mongoc_topology_description_get_servers (td.ptr, BSON_ASSERT_PTR_INLINE (n)); mc_tpld_drop_ref (&td); return sds; } void -mongoc_server_descriptions_destroy_all (mongoc_server_description_t **sds, - size_t n) +mongoc_server_descriptions_destroy_all (mongoc_server_description_t **sds, size_t n) { size_t i; @@ -2923,8 +2702,7 @@ mongoc_client_select_server (mongoc_client_t *client, return NULL; } - sd = mongoc_topology_select ( - client->topology, optype, prefs, NULL /* chosen read mode */, error); + sd = mongoc_topology_select (client->topology, optype, prefs, NULL /* chosen read mode */, error); if (!sd) { return NULL; } @@ -2936,8 +2714,7 @@ mongoc_client_select_server (mongoc_client_t *client, /* check failed, retry once */ mongoc_server_description_destroy (sd); - sd = mongoc_topology_select ( - client->topology, optype, prefs, NULL /* chosen read mode */, error); + sd = mongoc_topology_select (client->topology, optype, prefs, NULL /* chosen read mode */, error); if (sd) { return sd; } @@ -2956,8 +2733,7 @@ mongoc_client_set_error_api (mongoc_client_t *client, int32_t version) return false; } - if (version != MONGOC_ERROR_API_VERSION_LEGACY && - version != MONGOC_ERROR_API_VERSION_2) { + if (version != MONGOC_ERROR_API_VERSION_LEGACY && version != MONGOC_ERROR_API_VERSION_2) { MONGOC_ERROR ("Unsupported Error API Version: %" PRId32, version); return false; } @@ -3028,17 +2804,13 @@ _mongoc_client_lookup_session (const mongoc_client_t *client, RETURN (true); } - bson_set_error (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Invalid sessionId"); + bson_set_error (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid sessionId"); RETURN (false); } void -_mongoc_client_unregister_session (mongoc_client_t *client, - mongoc_client_session_t *session) +_mongoc_client_unregister_session (mongoc_client_t *client, mongoc_client_session_t *session) { BSON_ASSERT_PARAM (client); @@ -3046,8 +2818,7 @@ _mongoc_client_unregister_session (mongoc_client_t *client, } void -_mongoc_client_push_server_session (mongoc_client_t *client, - mongoc_server_session_t *server_session) +_mongoc_client_push_server_session (mongoc_client_t *client, mongoc_server_session_t *server_session) { BSON_ASSERT_PARAM (client); @@ -3085,13 +2856,8 @@ _mongoc_client_end_sessions (mongoc_client_t *client) while (!mongoc_server_session_pool_is_empty (t->session_pool)) { prefs = mongoc_read_prefs_new (MONGOC_READ_PRIMARY_PREFERRED); - server_id = - mongoc_topology_select_server_id (t, - MONGOC_SS_READ, - prefs, - NULL /* chosen read mode */, - NULL /* deprioritized servers */, - &error); + server_id = mongoc_topology_select_server_id ( + t, MONGOC_SS_READ, prefs, NULL /* chosen read mode */, NULL /* deprioritized servers */, &error); mongoc_read_prefs_destroy (prefs); if (!server_id) { @@ -3099,8 +2865,7 @@ _mongoc_client_end_sessions (mongoc_client_t *client) return; } - stream = mongoc_cluster_stream_for_server ( - cluster, server_id, false /* reconnect_ok */, NULL, NULL, &error); + stream = mongoc_cluster_stream_for_server (cluster, server_id, false /* reconnect_ok */, NULL, NULL, &error); if (!stream) { MONGOC_WARNING ("Couldn't send \"endSessions\": %s", error.message); @@ -3109,22 +2874,18 @@ _mongoc_client_end_sessions (mongoc_client_t *client) /* end sessions in chunks */ while (_mongoc_topology_end_sessions_cmd (t, &cmd)) { - mongoc_cmd_parts_init ( - &parts, client, "admin", MONGOC_QUERY_SECONDARY_OK, &cmd); + mongoc_cmd_parts_init (&parts, client, "admin", MONGOC_QUERY_SECONDARY_OK, &cmd); parts.assembled.operation_id = ++cluster->operation_id; parts.prohibit_lsid = true; r = mongoc_cmd_parts_assemble (&parts, stream, &error); if (!r) { - MONGOC_WARNING ("Couldn't construct \"endSessions\" command: %s", - error.message); + MONGOC_WARNING ("Couldn't construct \"endSessions\" command: %s", error.message); } else { - r = mongoc_cluster_run_command_monitored ( - cluster, &parts.assembled, NULL, &error); + r = mongoc_cluster_run_command_monitored (cluster, &parts.assembled, NULL, &error); if (!r) { - MONGOC_WARNING ("Couldn't send \"endSessions\": %s", - error.message); + MONGOC_WARNING ("Couldn't send \"endSessions\": %s", error.message); } } @@ -3166,17 +2927,13 @@ mongoc_client_reset (mongoc_client_t *client) } mongoc_change_stream_t * -mongoc_client_watch (mongoc_client_t *client, - const bson_t *pipeline, - const bson_t *opts) +mongoc_client_watch (mongoc_client_t *client, const bson_t *pipeline, const bson_t *opts) { return _mongoc_change_stream_new_from_client (client, pipeline, opts); } bool -mongoc_client_enable_auto_encryption (mongoc_client_t *client, - mongoc_auto_encryption_opts_t *opts, - bson_error_t *error) +mongoc_client_enable_auto_encryption (mongoc_client_t *client, mongoc_auto_encryption_opts_t *opts, bson_error_t *error) { BSON_ASSERT_PARAM (client); @@ -3192,19 +2949,16 @@ mongoc_client_enable_auto_encryption (mongoc_client_t *client, } bool -mongoc_client_set_server_api (mongoc_client_t *client, - const mongoc_server_api_t *api, - bson_error_t *error) +mongoc_client_set_server_api (mongoc_client_t *client, const mongoc_server_api_t *api, bson_error_t *error) { BSON_ASSERT_PARAM (client); BSON_ASSERT_PARAM (api); if (client->is_pooled) { - bson_set_error ( - error, - MONGOC_ERROR_CLIENT, - MONGOC_ERROR_CLIENT_API_FROM_POOL, - "Cannot set server api on a client checked out from a pool"); + bson_set_error (error, + MONGOC_ERROR_CLIENT, + MONGOC_ERROR_CLIENT_API_FROM_POOL, + "Cannot set server api on a client checked out from a pool"); return false; } @@ -3222,10 +2976,7 @@ mongoc_client_set_server_api (mongoc_client_t *client, } mongoc_server_description_t * -mongoc_client_get_handshake_description (mongoc_client_t *client, - uint32_t server_id, - bson_t *opts, - bson_error_t *error) +mongoc_client_get_handshake_description (mongoc_client_t *client, uint32_t server_id, bson_t *opts, bson_error_t *error) { mongoc_server_stream_t *server_stream; mongoc_server_description_t *sd; @@ -3233,12 +2984,8 @@ mongoc_client_get_handshake_description (mongoc_client_t *client, BSON_ASSERT_PARAM (client); BSON_UNUSED (opts); - server_stream = mongoc_cluster_stream_for_server (&client->cluster, - server_id, - true /* reconnect */, - NULL /* client session */, - NULL /* reply */, - error); + server_stream = mongoc_cluster_stream_for_server ( + &client->cluster, server_id, true /* reconnect */, NULL /* client session */, NULL /* reply */, error); if (!server_stream) { return NULL; } diff --git a/src/libmongoc/src/mongoc/mongoc-client.h b/src/libmongoc/src/mongoc/mongoc-client.h index cff520fe33..49a2a1abbf 100644 --- a/src/libmongoc/src/mongoc/mongoc-client.h +++ b/src/libmongoc/src/mongoc/mongoc-client.h @@ -95,27 +95,22 @@ typedef struct _mongoc_transaction_opt_t mongoc_transaction_opt_t; * * Returns: A newly allocated mongoc_stream_t or NULL on failure. */ -typedef mongoc_stream_t *(*mongoc_stream_initiator_t) ( - const mongoc_uri_t *uri, - const mongoc_host_list_t *host, - void *user_data, - bson_error_t *error); +typedef mongoc_stream_t *(*mongoc_stream_initiator_t) (const mongoc_uri_t *uri, + const mongoc_host_list_t *host, + void *user_data, + bson_error_t *error); MONGOC_EXPORT (mongoc_client_t *) mongoc_client_new (const char *uri_string) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (mongoc_client_t *) -mongoc_client_new_from_uri (const mongoc_uri_t *uri) - BSON_GNUC_WARN_UNUSED_RESULT; +mongoc_client_new_from_uri (const mongoc_uri_t *uri) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (mongoc_client_t *) -mongoc_client_new_from_uri_with_error ( - const mongoc_uri_t *uri, bson_error_t *error) BSON_GNUC_WARN_UNUSED_RESULT; +mongoc_client_new_from_uri_with_error (const mongoc_uri_t *uri, bson_error_t *error) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (const mongoc_uri_t *) mongoc_client_get_uri (const mongoc_client_t *client); MONGOC_EXPORT (void) -mongoc_client_set_stream_initiator (mongoc_client_t *client, - mongoc_stream_initiator_t initiator, - void *user_data); +mongoc_client_set_stream_initiator (mongoc_client_t *client, mongoc_stream_initiator_t initiator, void *user_data); MONGOC_EXPORT (mongoc_cursor_t *) mongoc_client_command (mongoc_client_t *client, const char *db_name, @@ -125,11 +120,9 @@ mongoc_client_command (mongoc_client_t *client, uint32_t batch_size, const bson_t *query, const bson_t *fields, - const mongoc_read_prefs_t *read_prefs) - BSON_GNUC_WARN_UNUSED_RESULT; + const mongoc_read_prefs_t *read_prefs) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (void) -mongoc_client_kill_cursor (mongoc_client_t *client, - int64_t cursor_id) BSON_GNUC_DEPRECATED; +mongoc_client_kill_cursor (mongoc_client_t *client, int64_t cursor_id) BSON_GNUC_DEPRECATED; MONGOC_EXPORT (bool) mongoc_client_command_simple (mongoc_client_t *client, const char *db_name, @@ -153,14 +146,13 @@ mongoc_client_write_command_with_opts (mongoc_client_t *client, bson_t *reply, bson_error_t *error); MONGOC_EXPORT (bool) -mongoc_client_read_write_command_with_opts ( - mongoc_client_t *client, - const char *db_name, - const bson_t *command, - const mongoc_read_prefs_t *read_prefs /* IGNORED */, - const bson_t *opts, - bson_t *reply, - bson_error_t *error); +mongoc_client_read_write_command_with_opts (mongoc_client_t *client, + const char *db_name, + const bson_t *command, + const mongoc_read_prefs_t *read_prefs /* IGNORED */, + const bson_t *opts, + bson_t *reply, + bson_error_t *error); MONGOC_EXPORT (bool) mongoc_client_command_with_opts (mongoc_client_t *client, const char *db_name, @@ -170,14 +162,13 @@ mongoc_client_command_with_opts (mongoc_client_t *client, bson_t *reply, bson_error_t *error); MONGOC_EXPORT (bool) -mongoc_client_command_simple_with_server_id ( - mongoc_client_t *client, - const char *db_name, - const bson_t *command, - const mongoc_read_prefs_t *read_prefs, - uint32_t server_id, - bson_t *reply, - bson_error_t *error); +mongoc_client_command_simple_with_server_id (mongoc_client_t *client, + const char *db_name, + const bson_t *command, + const mongoc_read_prefs_t *read_prefs, + uint32_t server_id, + bson_t *reply, + bson_error_t *error); MONGOC_EXPORT (void) mongoc_client_destroy (mongoc_client_t *client); MONGOC_EXPORT (mongoc_client_session_t *) @@ -185,80 +176,61 @@ mongoc_client_start_session (mongoc_client_t *client, const mongoc_session_opt_t *opts, bson_error_t *error) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (mongoc_database_t *) -mongoc_client_get_database (mongoc_client_t *client, - const char *name) BSON_GNUC_WARN_UNUSED_RESULT; +mongoc_client_get_database (mongoc_client_t *client, const char *name) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (mongoc_database_t *) -mongoc_client_get_default_database (mongoc_client_t *client) - BSON_GNUC_WARN_UNUSED_RESULT; +mongoc_client_get_default_database (mongoc_client_t *client) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (mongoc_gridfs_t *) -mongoc_client_get_gridfs (mongoc_client_t *client, - const char *db, - const char *prefix, - bson_error_t *error) BSON_GNUC_WARN_UNUSED_RESULT; +mongoc_client_get_gridfs (mongoc_client_t *client, const char *db, const char *prefix, bson_error_t *error) + BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (mongoc_collection_t *) mongoc_client_get_collection (mongoc_client_t *client, const char *db, - const char *collection) - BSON_GNUC_WARN_UNUSED_RESULT; + const char *collection) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (char **) -mongoc_client_get_database_names (mongoc_client_t *client, bson_error_t *error) - BSON_GNUC_WARN_UNUSED_RESULT +mongoc_client_get_database_names (mongoc_client_t *client, bson_error_t *error) BSON_GNUC_WARN_UNUSED_RESULT BSON_GNUC_DEPRECATED_FOR (mongoc_client_get_database_names_with_opts); MONGOC_EXPORT (char **) mongoc_client_get_database_names_with_opts (mongoc_client_t *client, const bson_t *opts, - bson_error_t *error) - BSON_GNUC_WARN_UNUSED_RESULT; + bson_error_t *error) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (mongoc_cursor_t *) -mongoc_client_find_databases (mongoc_client_t *client, - bson_error_t *error) BSON_GNUC_WARN_UNUSED_RESULT +mongoc_client_find_databases (mongoc_client_t *client, bson_error_t *error) BSON_GNUC_WARN_UNUSED_RESULT BSON_GNUC_DEPRECATED_FOR (mongoc_client_find_databases_with_opts); MONGOC_EXPORT (mongoc_cursor_t *) -mongoc_client_find_databases_with_opts ( - mongoc_client_t *client, const bson_t *opts) BSON_GNUC_WARN_UNUSED_RESULT; +mongoc_client_find_databases_with_opts (mongoc_client_t *client, const bson_t *opts) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (bool) mongoc_client_get_server_status (mongoc_client_t *client, mongoc_read_prefs_t *read_prefs, bson_t *reply, bson_error_t *error) BSON_GNUC_DEPRECATED; MONGOC_EXPORT (int32_t) -mongoc_client_get_max_message_size (mongoc_client_t *client) - BSON_GNUC_DEPRECATED; +mongoc_client_get_max_message_size (mongoc_client_t *client) BSON_GNUC_DEPRECATED; MONGOC_EXPORT (int32_t) mongoc_client_get_max_bson_size (mongoc_client_t *client) BSON_GNUC_DEPRECATED; MONGOC_EXPORT (const mongoc_write_concern_t *) mongoc_client_get_write_concern (const mongoc_client_t *client); MONGOC_EXPORT (void) -mongoc_client_set_write_concern (mongoc_client_t *client, - const mongoc_write_concern_t *write_concern); +mongoc_client_set_write_concern (mongoc_client_t *client, const mongoc_write_concern_t *write_concern); MONGOC_EXPORT (const mongoc_read_concern_t *) mongoc_client_get_read_concern (const mongoc_client_t *client); MONGOC_EXPORT (void) -mongoc_client_set_read_concern (mongoc_client_t *client, - const mongoc_read_concern_t *read_concern); +mongoc_client_set_read_concern (mongoc_client_t *client, const mongoc_read_concern_t *read_concern); MONGOC_EXPORT (const mongoc_read_prefs_t *) mongoc_client_get_read_prefs (const mongoc_client_t *client); MONGOC_EXPORT (void) -mongoc_client_set_read_prefs (mongoc_client_t *client, - const mongoc_read_prefs_t *read_prefs); +mongoc_client_set_read_prefs (mongoc_client_t *client, const mongoc_read_prefs_t *read_prefs); #ifdef MONGOC_ENABLE_SSL MONGOC_EXPORT (void) -mongoc_client_set_ssl_opts (mongoc_client_t *client, - const mongoc_ssl_opt_t *opts); +mongoc_client_set_ssl_opts (mongoc_client_t *client, const mongoc_ssl_opt_t *opts); #endif MONGOC_EXPORT (bool) -mongoc_client_set_apm_callbacks (mongoc_client_t *client, - mongoc_apm_callbacks_t *callbacks, - void *context); +mongoc_client_set_apm_callbacks (mongoc_client_t *client, mongoc_apm_callbacks_t *callbacks, void *context); MONGOC_EXPORT (mongoc_server_description_t *) -mongoc_client_get_server_description ( - mongoc_client_t *client, uint32_t server_id) BSON_GNUC_WARN_UNUSED_RESULT; +mongoc_client_get_server_description (mongoc_client_t *client, uint32_t server_id) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (mongoc_server_description_t **) -mongoc_client_get_server_descriptions (const mongoc_client_t *client, - size_t *n) BSON_GNUC_WARN_UNUSED_RESULT; +mongoc_client_get_server_descriptions (const mongoc_client_t *client, size_t *n) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (void) -mongoc_server_descriptions_destroy_all (mongoc_server_description_t **sds, - size_t n); +mongoc_server_descriptions_destroy_all (mongoc_server_description_t **sds, size_t n); MONGOC_EXPORT (mongoc_server_description_t *) mongoc_client_select_server (mongoc_client_t *client, bool for_writes, @@ -269,9 +241,7 @@ mongoc_client_set_error_api (mongoc_client_t *client, int32_t version); MONGOC_EXPORT (bool) mongoc_client_set_appname (mongoc_client_t *client, const char *appname); MONGOC_EXPORT (mongoc_change_stream_t *) -mongoc_client_watch (mongoc_client_t *client, - const bson_t *pipeline, - const bson_t *opts) BSON_GNUC_WARN_UNUSED_RESULT; +mongoc_client_watch (mongoc_client_t *client, const bson_t *pipeline, const bson_t *opts) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (void) mongoc_client_reset (mongoc_client_t *client); @@ -281,19 +251,13 @@ mongoc_client_enable_auto_encryption (mongoc_client_t *client, bson_error_t *error); MONGOC_EXPORT (const char *) -mongoc_client_get_crypt_shared_version (const mongoc_client_t *client) - BSON_GNUC_WARN_UNUSED_RESULT; +mongoc_client_get_crypt_shared_version (const mongoc_client_t *client) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (bool) -mongoc_client_set_server_api (mongoc_client_t *client, - const mongoc_server_api_t *api, - bson_error_t *error); +mongoc_client_set_server_api (mongoc_client_t *client, const mongoc_server_api_t *api, bson_error_t *error); MONGOC_EXPORT (mongoc_server_description_t *) -mongoc_client_get_handshake_description (mongoc_client_t *client, - uint32_t server_id, - bson_t *opts, - bson_error_t *error) +mongoc_client_get_handshake_description (mongoc_client_t *client, uint32_t server_id, bson_t *opts, bson_error_t *error) BSON_GNUC_WARN_UNUSED_RESULT; BSON_END_DECLS diff --git a/src/libmongoc/src/mongoc/mongoc-cluster-aws-private.h b/src/libmongoc/src/mongoc/mongoc-cluster-aws-private.h index 1989ae2226..963ab45454 100644 --- a/src/libmongoc/src/mongoc/mongoc-cluster-aws-private.h +++ b/src/libmongoc/src/mongoc/mongoc-cluster-aws-private.h @@ -82,8 +82,7 @@ _mongoc_aws_credentials_cache_unlock (void); // _mongoc_aws_credentials_cache_put_nolock is a non-locking variant of // _mongoc_aws_credentials_cache_put. void -_mongoc_aws_credentials_cache_put_nolock ( - const _mongoc_aws_credentials_t *creds); +_mongoc_aws_credentials_cache_put_nolock (const _mongoc_aws_credentials_t *creds); // _mongoc_aws_credentials_cache_put adds credentials into the global cache. void @@ -121,21 +120,15 @@ _mongoc_aws_credentials_cache_cleanup (void); bool -_mongoc_aws_credentials_obtain (mongoc_uri_t *uri, - _mongoc_aws_credentials_t *creds, - bson_error_t *error); +_mongoc_aws_credentials_obtain (mongoc_uri_t *uri, _mongoc_aws_credentials_t *creds, bson_error_t *error); void -_mongoc_aws_credentials_copy_to (const _mongoc_aws_credentials_t *src, - _mongoc_aws_credentials_t *dst); +_mongoc_aws_credentials_copy_to (const _mongoc_aws_credentials_t *src, _mongoc_aws_credentials_t *dst); void _mongoc_aws_credentials_cleanup (_mongoc_aws_credentials_t *creds); bool -_mongoc_validate_and_derive_region (char *sts_fqdn, - size_t sts_fqdn_len, - char **region, - bson_error_t *error); +_mongoc_validate_and_derive_region (char *sts_fqdn, size_t sts_fqdn_len, char **region, bson_error_t *error); #endif /* MONGOC_CLUSTER_AWS_PRIVATE_H */ diff --git a/src/libmongoc/src/mongoc/mongoc-cluster-aws.c b/src/libmongoc/src/mongoc/mongoc-cluster-aws.c index 1e41d0344b..f624aa062d 100644 --- a/src/libmongoc/src/mongoc/mongoc-cluster-aws.c +++ b/src/libmongoc/src/mongoc/mongoc-cluster-aws.c @@ -33,13 +33,10 @@ #undef MONGOC_LOG_DOMAIN #define MONGOC_LOG_DOMAIN "aws_auth" -#define AUTH_ERROR_AND_FAIL(...) \ - do { \ - bson_set_error (error, \ - MONGOC_ERROR_CLIENT, \ - MONGOC_ERROR_CLIENT_AUTHENTICATE, \ - __VA_ARGS__); \ - goto fail; \ +#define AUTH_ERROR_AND_FAIL(...) \ + do { \ + bson_set_error (error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_AUTHENTICATE, __VA_ARGS__); \ + goto fail; \ } while (0) @@ -64,20 +61,14 @@ _run_command (mongoc_cluster_t *cluster, mongoc_cmd_parts_t parts; mongoc_server_stream_t *server_stream; bool ret; - mc_shared_tpld td = - mc_tpld_take_ref (BSON_ASSERT_PTR_INLINE (cluster)->client->topology); - - mongoc_cmd_parts_init (&parts, - cluster->client, - "$external", - MONGOC_QUERY_NONE /* unused for OP_MSG */, - command); + mc_shared_tpld td = mc_tpld_take_ref (BSON_ASSERT_PTR_INLINE (cluster)->client->topology); + + mongoc_cmd_parts_init (&parts, cluster->client, "$external", MONGOC_QUERY_NONE /* unused for OP_MSG */, command); /* Drivers must not append session ids to auth commands per sessions spec. */ parts.prohibit_lsid = true; server_stream = _mongoc_cluster_create_server_stream (td.ptr, sd, stream); mc_tpld_drop_ref (&td); - ret = mongoc_cluster_run_command_parts ( - cluster, server_stream, &parts, reply, error); + ret = mongoc_cluster_run_command_parts (cluster, server_stream, &parts, reply, error); mongoc_server_stream_cleanup (server_stream); return ret; } @@ -92,9 +83,7 @@ _run_command (mongoc_cluster_t *cluster, * payload is always initialized. */ static bool -_sasl_reply_parse_payload_as_bson (const bson_t *reply, - bson_t *payload, - bson_error_t *error) +_sasl_reply_parse_payload_as_bson (const bson_t *reply, bson_t *payload, bson_error_t *error) { bson_iter_t iter; bson_subtype_t payload_subtype; @@ -104,8 +93,7 @@ _sasl_reply_parse_payload_as_bson (const bson_t *reply, bson_init (payload); - if (!bson_iter_init_find (&iter, reply, "payload") || - !BSON_ITER_HOLDS_BINARY (&iter)) { + if (!bson_iter_init_find (&iter, reply, "payload") || !BSON_ITER_HOLDS_BINARY (&iter)) { AUTH_ERROR_AND_FAIL ("server reply did not contain binary payload"); } @@ -164,15 +152,9 @@ _send_http_request (bool use_tls, req.path = path; req.extra_headers = headers; if (use_tls) { - _mongoc_ssl_opts_copy_to ( - mongoc_ssl_opt_get_default (), &ssl_opt, true /* copy_internal */); + _mongoc_ssl_opts_copy_to (mongoc_ssl_opt_get_default (), &ssl_opt, true /* copy_internal */); } - ret = _mongoc_http_send (&req, - socket_timeout_ms, - use_tls /* use_tls */, - use_tls ? &ssl_opt : NULL, - &res, - error); + ret = _mongoc_http_send (&req, socket_timeout_ms, use_tls /* use_tls */, use_tls ? &ssl_opt : NULL, &res, error); if (ret) { *http_response_headers = bson_strndup (res.headers, res.headers_len); @@ -189,8 +171,7 @@ _send_http_request (bool use_tls, static bool _creds_empty (_mongoc_aws_credentials_t *creds) { - return creds->access_key_id == NULL && creds->secret_access_key == NULL && - creds->session_token == NULL; + return creds->access_key_id == NULL && creds->secret_access_key == NULL && creds->session_token == NULL; } /* @@ -209,20 +190,17 @@ _validate_and_set_creds (const char *access_key_id, bson_error_t *error) { bool has_access_key_id = access_key_id && strlen (access_key_id) != 0; - bool has_secret_access_key = - secret_access_key && strlen (secret_access_key) != 0; + bool has_secret_access_key = secret_access_key && strlen (secret_access_key) != 0; bool has_session_token = session_token && strlen (session_token) != 0; bool ret = false; /* Check for invalid combinations of URI parameters. */ if (has_access_key_id && !has_secret_access_key) { - AUTH_ERROR_AND_FAIL ( - "ACCESS_KEY_ID is set, but SECRET_ACCESS_KEY is missing"); + AUTH_ERROR_AND_FAIL ("ACCESS_KEY_ID is set, but SECRET_ACCESS_KEY is missing"); } if (!has_access_key_id && has_secret_access_key) { - AUTH_ERROR_AND_FAIL ( - "SECRET_ACCESS_KEY is set, but ACCESS_KEY_ID is missing"); + AUTH_ERROR_AND_FAIL ("SECRET_ACCESS_KEY is set, but ACCESS_KEY_ID is missing"); } if (!has_access_key_id && !has_secret_access_key && has_session_token) { @@ -248,9 +226,7 @@ _validate_and_set_creds (const char *access_key_id, * set. */ static bool -_obtain_creds_from_uri (_mongoc_aws_credentials_t *creds, - mongoc_uri_t *uri, - bson_error_t *error) +_obtain_creds_from_uri (_mongoc_aws_credentials_t *creds, mongoc_uri_t *uri, bson_error_t *error) { bool ret = false; bson_t auth_mechanism_props; @@ -258,18 +234,14 @@ _obtain_creds_from_uri (_mongoc_aws_credentials_t *creds, if (mongoc_uri_get_mechanism_properties (uri, &auth_mechanism_props)) { bson_iter_t iter; - if (bson_iter_init_find_case ( - &iter, &auth_mechanism_props, "AWS_SESSION_TOKEN") && + if (bson_iter_init_find_case (&iter, &auth_mechanism_props, "AWS_SESSION_TOKEN") && BSON_ITER_HOLDS_UTF8 (&iter)) { uri_session_token = bson_iter_utf8 (&iter, NULL); } } - if (!_validate_and_set_creds (mongoc_uri_get_username (uri), - mongoc_uri_get_password (uri), - uri_session_token, - creds, - error)) { + if (!_validate_and_set_creds ( + mongoc_uri_get_username (uri), mongoc_uri_get_password (uri), uri_session_token, creds, error)) { goto fail; } @@ -291,11 +263,7 @@ _obtain_creds_from_env (_mongoc_aws_credentials_t *creds, bson_error_t *error) env_secret_access_key = _mongoc_getenv ("AWS_SECRET_ACCESS_KEY"); env_session_token = _mongoc_getenv ("AWS_SESSION_TOKEN"); - if (!_validate_and_set_creds (env_access_key_id, - env_secret_access_key, - env_session_token, - creds, - error)) { + if (!_validate_and_set_creds (env_access_key_id, env_secret_access_key, env_session_token, creds, error)) { goto fail; } ret = true; @@ -309,9 +277,7 @@ _obtain_creds_from_env (_mongoc_aws_credentials_t *creds, bson_error_t *error) // expiration_ms_to_timer converts milliseconds since Unix Epoch into the // mcd_timer `expiration_timer`. static bool -expiration_ms_to_timer (int64_t expiration_ms, - mcd_timer *expiration_timer, - bson_error_t *error) +expiration_ms_to_timer (int64_t expiration_ms, mcd_timer *expiration_timer, bson_error_t *error) { bool ret = false; @@ -327,8 +293,8 @@ expiration_ms_to_timer (int64_t expiration_ms, } } - *expiration_timer = mcd_timer_expire_after (mcd_milliseconds ( - expiration_ms - now_ms - MONGOC_AWS_CREDENTIALS_EXPIRATION_WINDOW_MS)); + *expiration_timer = + mcd_timer_expire_after (mcd_milliseconds (expiration_ms - now_ms - MONGOC_AWS_CREDENTIALS_EXPIRATION_WINDOW_MS)); ret = true; fail: return ret; @@ -339,9 +305,7 @@ expiration_ms_to_timer (int64_t expiration_ms, // string. Example: "2023-02-07T20:04:27Z". On success, `expiration_timer` is // set to the expiration time. static bool -expiration_iso8601_to_timer (const char *expiration_str, - mcd_timer *expiration_timer, - bson_error_t *error) +expiration_iso8601_to_timer (const char *expiration_str, mcd_timer *expiration_timer, bson_error_t *error) { bool ret = false; @@ -355,13 +319,11 @@ expiration_iso8601_to_timer (const char *expiration_str, // libbson has private API `_bson_iso8601_date_parse` to parse ISO-8601 // strings. The private API is inaccessible to libmongoc. // Create a temporary bson document with a $date to parse. - date_doc_str = bson_strdup_printf ( - "{\"Expiration\" : {\"$date\" : \"%s\"}}", expiration_str); + date_doc_str = bson_strdup_printf ("{\"Expiration\" : {\"$date\" : \"%s\"}}", expiration_str); if (!bson_init_from_json (&date_doc, date_doc_str, -1, &json_err)) { bson_free (date_doc_str); - AUTH_ERROR_AND_FAIL ("failed to parse Expiration: %s", - json_err.message); + AUTH_ERROR_AND_FAIL ("failed to parse Expiration: %s", json_err.message); } BSON_ASSERT (bson_iter_init_find (&date_iter, &date_doc, "Expiration")); expiration_ms = bson_iter_date_time (&date_iter); @@ -387,8 +349,7 @@ generate_AWS_ROLE_SESSION_NAME (bson_error_t *error) uint8_t data[NUM_BYTES]; char *out = bson_malloc (NUM_BYTES * 2 + 1); if (!_mongoc_rand_bytes (data, NUM_BYTES)) { - AUTH_ERROR_AND_FAIL ( - "unable to generate random bytes for AWS_ROLE_SESSION_NAME"); + AUTH_ERROR_AND_FAIL ("unable to generate random bytes for AWS_ROLE_SESSION_NAME"); } size_t i; @@ -436,46 +397,34 @@ _obtain_creds_from_ecs (_mongoc_aws_credentials_t *creds, bson_error_t *error) &http_response_body, &http_response_headers, &http_error)) { - AUTH_ERROR_AND_FAIL ("failed to contact ECS link local server: %s", - http_error.message); + AUTH_ERROR_AND_FAIL ("failed to contact ECS link local server: %s", http_error.message); } - response_json = bson_new_from_json ( - (const uint8_t *) http_response_body, strlen (http_response_body), error); + response_json = bson_new_from_json ((const uint8_t *) http_response_body, strlen (http_response_body), error); if (!response_json) { - AUTH_ERROR_AND_FAIL ("invalid JSON in ECS response. Response headers: %s", - http_response_headers); + AUTH_ERROR_AND_FAIL ("invalid JSON in ECS response. Response headers: %s", http_response_headers); } - if (bson_iter_init_find_case (&iter, response_json, "AccessKeyId") && - BSON_ITER_HOLDS_UTF8 (&iter)) { + if (bson_iter_init_find_case (&iter, response_json, "AccessKeyId") && BSON_ITER_HOLDS_UTF8 (&iter)) { ecs_access_key_id = bson_iter_utf8 (&iter, NULL); } - if (bson_iter_init_find_case (&iter, response_json, "SecretAccessKey") && - BSON_ITER_HOLDS_UTF8 (&iter)) { + if (bson_iter_init_find_case (&iter, response_json, "SecretAccessKey") && BSON_ITER_HOLDS_UTF8 (&iter)) { ecs_secret_access_key = bson_iter_utf8 (&iter, NULL); } - if (bson_iter_init_find_case (&iter, response_json, "Token") && - BSON_ITER_HOLDS_UTF8 (&iter)) { + if (bson_iter_init_find_case (&iter, response_json, "Token") && BSON_ITER_HOLDS_UTF8 (&iter)) { ecs_session_token = bson_iter_utf8 (&iter, NULL); } - if (bson_iter_init_find_case (&iter, response_json, "Expiration") && - BSON_ITER_HOLDS_UTF8 (&iter)) { - if (!expiration_iso8601_to_timer ( - bson_iter_utf8 (&iter, NULL), &creds->expiration.value, error)) { + if (bson_iter_init_find_case (&iter, response_json, "Expiration") && BSON_ITER_HOLDS_UTF8 (&iter)) { + if (!expiration_iso8601_to_timer (bson_iter_utf8 (&iter, NULL), &creds->expiration.value, error)) { goto fail; } creds->expiration.set = true; } - if (!_validate_and_set_creds (ecs_access_key_id, - ecs_secret_access_key, - ecs_session_token, - creds, - error)) { + if (!_validate_and_set_creds (ecs_access_key_id, ecs_secret_access_key, ecs_session_token, creds, error)) { goto fail; } @@ -489,8 +438,7 @@ _obtain_creds_from_ecs (_mongoc_aws_credentials_t *creds, bson_error_t *error) } static bool -_obtain_creds_from_assumerolewithwebidentity (_mongoc_aws_credentials_t *creds, - bson_error_t *error) +_obtain_creds_from_assumerolewithwebidentity (_mongoc_aws_credentials_t *creds, bson_error_t *error) { bool ret = false; char *http_response_headers = NULL; @@ -510,8 +458,7 @@ _obtain_creds_from_assumerolewithwebidentity (_mongoc_aws_credentials_t *creds, aws_web_identity_token_file = _mongoc_getenv ("AWS_WEB_IDENTITY_TOKEN_FILE"); aws_role_arn = _mongoc_getenv ("AWS_ROLE_ARN"); - if (!aws_web_identity_token_file || - strlen (aws_web_identity_token_file) == 0 || !aws_role_arn || + if (!aws_web_identity_token_file || strlen (aws_web_identity_token_file) == 0 || !aws_role_arn || strlen (aws_role_arn) == 0) { bson_free (aws_role_arn); bson_free (aws_web_identity_token_file); @@ -529,25 +476,22 @@ _obtain_creds_from_assumerolewithwebidentity (_mongoc_aws_credentials_t *creds, // Read the contents of the file given by ``AWS_WEB_IDENTITY_TOKEN_FILE``. { - fstream = mongoc_stream_file_new_for_path ( - aws_web_identity_token_file, O_RDONLY, 0); + fstream = mongoc_stream_file_new_for_path (aws_web_identity_token_file, O_RDONLY, 0); if (!fstream) { - AUTH_ERROR_AND_FAIL ( - "failed to open AWS_WEB_IDENTITY_TOKEN_FILE: %s. Reason: %s", - aws_web_identity_token_file, - strerror (errno)); + AUTH_ERROR_AND_FAIL ("failed to open AWS_WEB_IDENTITY_TOKEN_FILE: %s. Reason: %s", + aws_web_identity_token_file, + strerror (errno)); } token_file_contents = bson_string_new (NULL); for (;;) { char buf[128]; - ssize_t got = mongoc_stream_read ( - fstream, - buf, - sizeof (buf) - 1 /* leave space for null terminator */, - 0 /* min_bytes */, - 0 /* timeout_msec. Unused for file stream. */); + ssize_t got = mongoc_stream_read (fstream, + buf, + sizeof (buf) - 1 /* leave space for null terminator */, + 0 /* min_bytes */, + 0 /* timeout_msec. Unused for file stream. */); if (got > 0) { // add null terminator. @@ -557,22 +501,20 @@ _obtain_creds_from_assumerolewithwebidentity (_mongoc_aws_credentials_t *creds, // EOF. break; } else { - AUTH_ERROR_AND_FAIL ( - "failed to read AWS_WEB_IDENTITY_TOKEN_FILE: %s. Reason: %s", - aws_web_identity_token_file, - strerror (errno)); + AUTH_ERROR_AND_FAIL ("failed to read AWS_WEB_IDENTITY_TOKEN_FILE: %s. Reason: %s", + aws_web_identity_token_file, + strerror (errno)); } } } - path_and_query = - bson_strdup_printf ("/?Action=AssumeRoleWithWebIdentity" - "&RoleSessionName=%s" - "&RoleArn=%s" - "&WebIdentityToken=%s&Version=2011-06-15", - aws_role_session_name, - aws_role_arn, - token_file_contents->str); + path_and_query = bson_strdup_printf ("/?Action=AssumeRoleWithWebIdentity" + "&RoleSessionName=%s" + "&RoleArn=%s" + "&WebIdentityToken=%s&Version=2011-06-15", + aws_role_session_name, + aws_role_arn, + token_file_contents->str); // send an HTTP request to sts.amazonaws.com. if (!_send_http_request (true /* use_tls */, @@ -584,12 +526,10 @@ _obtain_creds_from_assumerolewithwebidentity (_mongoc_aws_credentials_t *creds, &http_response_body, &http_response_headers, &http_error)) { - AUTH_ERROR_AND_FAIL ("failed to contact sts.amazonaws.com: %s", - http_error.message); + AUTH_ERROR_AND_FAIL ("failed to contact sts.amazonaws.com: %s", http_error.message); } - response_bson = bson_new_from_json ( - (const uint8_t *) http_response_body, strlen (http_response_body), error); + response_bson = bson_new_from_json ((const uint8_t *) http_response_body, strlen (http_response_body), error); if (!response_bson) { AUTH_ERROR_AND_FAIL ("invalid JSON in response from sts.amazonaws.com. " "Response headers: %s", @@ -597,8 +537,7 @@ _obtain_creds_from_assumerolewithwebidentity (_mongoc_aws_credentials_t *creds, } if (!bson_iter_init (&iter, response_bson)) { - AUTH_ERROR_AND_FAIL ("failed to initialize BSON iterator to response: %s", - http_response_body); + AUTH_ERROR_AND_FAIL ("failed to initialize BSON iterator to response: %s", http_response_body); } // If the response contains "Error", return only the "Error" document. @@ -611,56 +550,48 @@ _obtain_creds_from_assumerolewithwebidentity (_mongoc_aws_credentials_t *creds, goto fail; } char *Error_json = bson_as_json (&Error_bson, NULL); - bson_set_error ( - error, - MONGOC_ERROR_CLIENT, - MONGOC_ERROR_CLIENT_AUTHENTICATE, - "Response to AssumeRoleWithWebIdentity contains 'Error': %s", - Error_json); + bson_set_error (error, + MONGOC_ERROR_CLIENT, + MONGOC_ERROR_CLIENT_AUTHENTICATE, + "Response to AssumeRoleWithWebIdentity contains 'Error': %s", + Error_json); bson_free (Error_json); goto fail; } bson_iter_t Credentials_iter; - if (!bson_iter_find_descendant ( - &iter, - "AssumeRoleWithWebIdentityResponse.AssumeRoleWithWebIdentityResult." - "Credentials", - &iter)) { - AUTH_ERROR_AND_FAIL ( - "did not find " - "AssumeRoleWithWebIdentityResponse.AssumeRoleWithWebIdentityResult." - "Credentials in response from sts.amazonaws.com."); + if (!bson_iter_find_descendant (&iter, + "AssumeRoleWithWebIdentityResponse.AssumeRoleWithWebIdentityResult." + "Credentials", + &iter)) { + AUTH_ERROR_AND_FAIL ("did not find " + "AssumeRoleWithWebIdentityResponse.AssumeRoleWithWebIdentityResult." + "Credentials in response from sts.amazonaws.com."); } if (!bson_iter_recurse (&iter, &Credentials_iter)) { - AUTH_ERROR_AND_FAIL ( - "Unable to recurse in Credentials in response from sts.amazonaws.com"); + AUTH_ERROR_AND_FAIL ("Unable to recurse in Credentials in response from sts.amazonaws.com"); } iter = Credentials_iter; if (bson_iter_find (&iter, "AccessKeyId") && BSON_ITER_HOLDS_UTF8 (&iter)) { access_key_id = bson_iter_utf8 (&iter, NULL); } else { - AUTH_ERROR_AND_FAIL ( - "did not find AccessKeyId in response from sts.amazonaws.com"); + AUTH_ERROR_AND_FAIL ("did not find AccessKeyId in response from sts.amazonaws.com"); } iter = Credentials_iter; - if (bson_iter_find (&iter, "SecretAccessKey") && - BSON_ITER_HOLDS_UTF8 (&iter)) { + if (bson_iter_find (&iter, "SecretAccessKey") && BSON_ITER_HOLDS_UTF8 (&iter)) { secret_access_key = bson_iter_utf8 (&iter, NULL); } else { - AUTH_ERROR_AND_FAIL ( - "did not find SecretAccessKey in response from sts.amazonaws.com"); + AUTH_ERROR_AND_FAIL ("did not find SecretAccessKey in response from sts.amazonaws.com"); } iter = Credentials_iter; if (bson_iter_find (&iter, "SessionToken") && BSON_ITER_HOLDS_UTF8 (&iter)) { session_token = bson_iter_utf8 (&iter, NULL); } else { - AUTH_ERROR_AND_FAIL ( - "did not find SessionToken in response from sts.amazonaws.com"); + AUTH_ERROR_AND_FAIL ("did not find SessionToken in response from sts.amazonaws.com"); } iter = Credentials_iter; @@ -669,18 +600,15 @@ _obtain_creds_from_assumerolewithwebidentity (_mongoc_aws_credentials_t *creds, // since Unix Epoch. This differs from the ISO-8601 string returned in EC2 // and ECS responses. int64_t expiration_ms = (int64_t) (1000.0 * bson_iter_double (&iter)); - if (!expiration_ms_to_timer ( - expiration_ms, &creds->expiration.value, error)) { + if (!expiration_ms_to_timer (expiration_ms, &creds->expiration.value, error)) { goto fail; } creds->expiration.set = true; } else { - AUTH_ERROR_AND_FAIL ( - "did not find Expiration in response from sts.amazonaws.com"); + AUTH_ERROR_AND_FAIL ("did not find Expiration in response from sts.amazonaws.com"); } - if (!_validate_and_set_creds ( - access_key_id, secret_access_key, session_token, creds, error)) { + if (!_validate_and_set_creds (access_key_id, secret_access_key, session_token, creds, error)) { goto fail; } @@ -727,20 +655,16 @@ _obtain_creds_from_ec2 (_mongoc_aws_credentials_t *creds, bson_error_t *error) &token, &http_response_headers, &http_error)) { - AUTH_ERROR_AND_FAIL ("failed to contact EC2 link local server: %s", - http_error.message); + AUTH_ERROR_AND_FAIL ("failed to contact EC2 link local server: %s", http_error.message); } if (0 == strlen (token)) { - AUTH_ERROR_AND_FAIL ( - "unable to retrieve token from EC2 metadata. Headers: %s", - http_response_headers); + AUTH_ERROR_AND_FAIL ("unable to retrieve token from EC2 metadata. Headers: %s", http_response_headers); } bson_free (http_response_headers); http_response_headers = NULL; - token_header = - bson_strdup_printf ("X-aws-ec2-metadata-token: %s\r\n", token); + token_header = bson_strdup_printf ("X-aws-ec2-metadata-token: %s\r\n", token); /* Get the role name. */ if (!_send_http_request (false /* use_tls */, @@ -752,19 +676,15 @@ _obtain_creds_from_ec2 (_mongoc_aws_credentials_t *creds, bson_error_t *error) &role_name, &http_response_headers, &http_error)) { - AUTH_ERROR_AND_FAIL ("failed to contact EC2 link local server: %s", - http_error.message); + AUTH_ERROR_AND_FAIL ("failed to contact EC2 link local server: %s", http_error.message); } if (0 == strlen (role_name)) { - AUTH_ERROR_AND_FAIL ( - "unable to retrieve role_name from EC2 metadata. Headers: %s", - http_response_headers); + AUTH_ERROR_AND_FAIL ("unable to retrieve role_name from EC2 metadata. Headers: %s", http_response_headers); } /* Get the creds. */ - path_with_role = bson_strdup_printf ( - "/latest/meta-data/iam/security-credentials/%s", role_name); + path_with_role = bson_strdup_printf ("/latest/meta-data/iam/security-credentials/%s", role_name); bson_free (http_response_headers); http_response_headers = NULL; if (!_send_http_request (false /* use_tls */, @@ -776,46 +696,34 @@ _obtain_creds_from_ec2 (_mongoc_aws_credentials_t *creds, bson_error_t *error) &http_response_body, &http_response_headers, &http_error)) { - AUTH_ERROR_AND_FAIL ("failed to contact EC2 link local server: %s", - http_error.message); + AUTH_ERROR_AND_FAIL ("failed to contact EC2 link local server: %s", http_error.message); } - response_json = bson_new_from_json ( - (const uint8_t *) http_response_body, strlen (http_response_body), error); + response_json = bson_new_from_json ((const uint8_t *) http_response_body, strlen (http_response_body), error); if (!response_json) { - AUTH_ERROR_AND_FAIL ("invalid JSON in EC2 response. Response headers: %s", - http_response_headers); + AUTH_ERROR_AND_FAIL ("invalid JSON in EC2 response. Response headers: %s", http_response_headers); } - if (bson_iter_init_find_case (&iter, response_json, "AccessKeyId") && - BSON_ITER_HOLDS_UTF8 (&iter)) { + if (bson_iter_init_find_case (&iter, response_json, "AccessKeyId") && BSON_ITER_HOLDS_UTF8 (&iter)) { ec2_access_key_id = bson_iter_utf8 (&iter, NULL); } - if (bson_iter_init_find_case (&iter, response_json, "SecretAccessKey") && - BSON_ITER_HOLDS_UTF8 (&iter)) { + if (bson_iter_init_find_case (&iter, response_json, "SecretAccessKey") && BSON_ITER_HOLDS_UTF8 (&iter)) { ec2_secret_access_key = bson_iter_utf8 (&iter, NULL); } - if (bson_iter_init_find_case (&iter, response_json, "Token") && - BSON_ITER_HOLDS_UTF8 (&iter)) { + if (bson_iter_init_find_case (&iter, response_json, "Token") && BSON_ITER_HOLDS_UTF8 (&iter)) { ec2_session_token = bson_iter_utf8 (&iter, NULL); } - if (bson_iter_init_find_case (&iter, response_json, "Expiration") && - BSON_ITER_HOLDS_UTF8 (&iter)) { - if (!expiration_iso8601_to_timer ( - bson_iter_utf8 (&iter, NULL), &creds->expiration.value, error)) { + if (bson_iter_init_find_case (&iter, response_json, "Expiration") && BSON_ITER_HOLDS_UTF8 (&iter)) { + if (!expiration_iso8601_to_timer (bson_iter_utf8 (&iter, NULL), &creds->expiration.value, error)) { goto fail; } creds->expiration.set = true; } - if (!_validate_and_set_creds (ec2_access_key_id, - ec2_secret_access_key, - ec2_session_token, - creds, - error)) { + if (!_validate_and_set_creds (ec2_access_key_id, ec2_secret_access_key, ec2_session_token, creds, error)) { goto fail; } @@ -845,9 +753,7 @@ _obtain_creds_from_ec2 (_mongoc_aws_credentials_t *creds, bson_error_t *error) * On failure, returns false and sets error. */ bool -_mongoc_aws_credentials_obtain (mongoc_uri_t *uri, - _mongoc_aws_credentials_t *creds, - bson_error_t *error) +_mongoc_aws_credentials_obtain (mongoc_uri_t *uri, _mongoc_aws_credentials_t *creds, bson_error_t *error) { bool ret = false; @@ -953,10 +859,7 @@ _mongoc_aws_credentials_obtain (mongoc_uri_t *uri, * region is always set and must be freed by caller. */ bool -_mongoc_validate_and_derive_region (char *sts_fqdn, - size_t sts_fqdn_len, - char **region, - bson_error_t *error) +_mongoc_validate_and_derive_region (char *sts_fqdn, size_t sts_fqdn_len, char **region, bson_error_t *error) { bool ret = false; char *ptr; @@ -1080,11 +983,7 @@ _client_first (mongoc_cluster_t *cluster, "Common Crypto, or cng) to support MONGODB-AWS"); #endif - BCON_APPEND (&client_payload, - "r", - BCON_BIN (BSON_SUBTYPE_BINARY, client_nonce, 32), - "p", - BCON_INT32 (110)); + BCON_APPEND (&client_payload, "r", BCON_BIN (BSON_SUBTYPE_BINARY, client_nonce, 32), "p", BCON_INT32 (110)); BCON_APPEND (&client_command, "saslStart", @@ -1092,13 +991,10 @@ _client_first (mongoc_cluster_t *cluster, "mechanism", "MONGODB-AWS", "payload", - BCON_BIN (BSON_SUBTYPE_BINARY, - bson_get_data (&client_payload), - client_payload.len)); + BCON_BIN (BSON_SUBTYPE_BINARY, bson_get_data (&client_payload), client_payload.len)); bson_destroy (&server_reply); - if (!_run_command ( - cluster, stream, sd, &client_command, &server_reply, error)) { + if (!_run_command (cluster, stream, sd, &client_command, &server_reply, error)) { goto fail; } @@ -1108,36 +1004,30 @@ _client_first (mongoc_cluster_t *cluster, } bson_destroy (&server_payload); - if (!_sasl_reply_parse_payload_as_bson ( - &server_reply, &server_payload, error)) { + if (!_sasl_reply_parse_payload_as_bson (&server_reply, &server_payload, error)) { goto fail; } - if (!bson_iter_init_find (&iter, &server_payload, "h") || - !BSON_ITER_HOLDS_UTF8 (&iter)) { + if (!bson_iter_init_find (&iter, &server_payload, "h") || !BSON_ITER_HOLDS_UTF8 (&iter)) { AUTH_ERROR_AND_FAIL ("server payload did not contain string STS FQDN"); } *sts_fqdn = bson_strdup (bson_iter_utf8 (&iter, &sts_fqdn_len)); - if (!_mongoc_validate_and_derive_region ( - *sts_fqdn, sts_fqdn_len, region, error)) { + if (!_mongoc_validate_and_derive_region (*sts_fqdn, sts_fqdn_len, region, error)) { goto fail; } - if (!bson_iter_init_find (&iter, &server_payload, "s") || - !BSON_ITER_HOLDS_BINARY (&iter)) { + if (!bson_iter_init_find (&iter, &server_payload, "s") || !BSON_ITER_HOLDS_BINARY (&iter)) { AUTH_ERROR_AND_FAIL ("server payload did not contain nonce"); } - bson_iter_binary ( - &iter, &reply_nonce_subtype, &reply_nonce_len, &reply_nonce_data); + bson_iter_binary (&iter, &reply_nonce_subtype, &reply_nonce_len, &reply_nonce_data); if (reply_nonce_len != 64) { AUTH_ERROR_AND_FAIL ("server reply nonce was not 64 bytes"); } if (0 != memcmp (reply_nonce_data, client_nonce, 32)) { - AUTH_ERROR_AND_FAIL ( - "server reply nonce prefix did not match client nonce"); + AUTH_ERROR_AND_FAIL ("server reply nonce prefix did not match client nonce"); } /* Drivers MUST error on any additional fields */ @@ -1211,8 +1101,7 @@ _client_second (mongoc_cluster_t *cluster, kms_request_t *request = NULL; char *signature = NULL; const char *date = NULL; - const size_t server_nonce_str_len = - mcommon_b64_ntop_calculate_target_size (64); + const size_t server_nonce_str_len = mcommon_b64_ntop_calculate_target_size (64); char *server_nonce_str = NULL; const char *body = "Action=GetCallerIdentity&Version=2011-06-15"; bson_t client_payload = BSON_INITIALIZER; @@ -1233,12 +1122,10 @@ _client_second (mongoc_cluster_t *cluster, request = kms_request_new ("POST", "/", NULL); if (kms_request_get_error (request)) { - AUTH_ERROR_AND_FAIL ("Failed to create new KMS request: %s", - kms_request_get_error (request)); + AUTH_ERROR_AND_FAIL ("Failed to create new KMS request: %s", kms_request_get_error (request)); } - if (mcommon_b64_ntop ( - server_nonce, 64, server_nonce_str, server_nonce_str_len) == -1) { + if (mcommon_b64_ntop (server_nonce, 64, server_nonce_str, server_nonce_str_len) == -1) { AUTH_ERROR_AND_FAIL ("Failed to parse server nonce"); } @@ -1246,10 +1133,8 @@ _client_second (mongoc_cluster_t *cluster, AUTH_ERROR_AND_FAIL ("Failed to append payload"); } - KMS_REQUEST_SET ( - kms_request_set_access_key_id, "access key ID", creds->access_key_id); - KMS_REQUEST_SET ( - kms_request_set_secret_key, "secret key", creds->secret_access_key); + KMS_REQUEST_SET (kms_request_set_access_key_id, "access key ID", creds->access_key_id); + KMS_REQUEST_SET (kms_request_set_secret_key, "secret key", creds->secret_access_key); KMS_REQUEST_SET (kms_request_set_date, "date", NULL /* use current time */); KMS_REQUEST_SET (kms_request_set_region, "region", region); KMS_REQUEST_SET (kms_request_set_service, "service", "sts"); @@ -1264,18 +1149,15 @@ _client_second (mongoc_cluster_t *cluster, signature = kms_request_get_signature (request); if (kms_request_get_error (request)) { - AUTH_ERROR_AND_FAIL ("Failed to get signature: %s", - kms_request_get_error (request)); + AUTH_ERROR_AND_FAIL ("Failed to get signature: %s", kms_request_get_error (request)); } date = kms_request_get_canonical_header (request, "X-Amz-Date"); if (kms_request_get_error (request)) { - AUTH_ERROR_AND_FAIL ("Failed to get canonical header: %s", - kms_request_get_error (request)); + AUTH_ERROR_AND_FAIL ("Failed to get canonical header: %s", kms_request_get_error (request)); } - BCON_APPEND ( - &client_payload, "a", BCON_UTF8 (signature), "d", BCON_UTF8 (date)); + BCON_APPEND (&client_payload, "a", BCON_UTF8 (signature), "d", BCON_UTF8 (date)); if (creds->session_token) { BCON_APPEND (&client_payload, "t", BCON_UTF8 (creds->session_token)); } @@ -1286,13 +1168,10 @@ _client_second (mongoc_cluster_t *cluster, "conversationId", BCON_INT32 (conv_id), "payload", - BCON_BIN (BSON_SUBTYPE_BINARY, - bson_get_data (&client_payload), - client_payload.len)); + BCON_BIN (BSON_SUBTYPE_BINARY, bson_get_data (&client_payload), client_payload.len)); bson_destroy (&server_reply); - if (!_run_command ( - cluster, stream, sd, &client_command, &server_reply, error)) { + if (!_run_command (cluster, stream, sd, &client_command, &server_reply, error)) { goto fail; } @@ -1324,26 +1203,11 @@ _mongoc_cluster_auth_node_aws (mongoc_cluster_t *cluster, goto fail; } - if (!_client_first (cluster, - stream, - sd, - server_nonce, - &sts_fqdn, - ®ion, - &conv_id, - error)) { + if (!_client_first (cluster, stream, sd, server_nonce, &sts_fqdn, ®ion, &conv_id, error)) { goto fail; } - if (!_client_second (cluster, - stream, - sd, - &creds, - server_nonce, - sts_fqdn, - region, - conv_id, - error)) { + if (!_client_second (cluster, stream, sd, &creds, server_nonce, sts_fqdn, region, conv_id, error)) { goto fail; } @@ -1374,9 +1238,7 @@ _mongoc_cluster_auth_node_aws (mongoc_cluster_t *cluster, bool -_mongoc_aws_credentials_obtain (mongoc_uri_t *uri, - _mongoc_aws_credentials_t *creds, - bson_error_t *error) +_mongoc_aws_credentials_obtain (mongoc_uri_t *uri, _mongoc_aws_credentials_t *creds, bson_error_t *error) { AUTH_ERROR_AND_FAIL ("AWS auth not supported, configure libmongoc with " "ENABLE_MONGODB_AWS_AUTH=ON"); @@ -1385,10 +1247,7 @@ _mongoc_aws_credentials_obtain (mongoc_uri_t *uri, } bool -_mongoc_validate_and_derive_region (char *sts_fqdn, - size_t sts_fqdn_len, - char **region, - bson_error_t *error) +_mongoc_validate_and_derive_region (char *sts_fqdn, size_t sts_fqdn_len, char **region, bson_error_t *error) { AUTH_ERROR_AND_FAIL ("AWS auth not supported, configure libmongoc with " "ENABLE_MONGODB_AWS_AUTH=ON"); @@ -1407,8 +1266,7 @@ _mongoc_aws_credentials_cleanup (_mongoc_aws_credentials_t *creds) } void -_mongoc_aws_credentials_copy_to (const _mongoc_aws_credentials_t *src, - _mongoc_aws_credentials_t *dst) +_mongoc_aws_credentials_copy_to (const _mongoc_aws_credentials_t *src, _mongoc_aws_credentials_t *dst) { BSON_ASSERT_PARAM (src); BSON_ASSERT_PARAM (dst); @@ -1434,8 +1292,7 @@ check_expired (const _mongoc_aws_credentials_t *creds) if (!creds->expiration.set) { return true; } - return mcd_get_milliseconds ( - mcd_timer_remaining (creds->expiration.value)) == 0; + return mcd_get_milliseconds (mcd_timer_remaining (creds->expiration.value)) == 0; } void @@ -1453,8 +1310,7 @@ _mongoc_aws_credentials_cache_unlock (void) } void -_mongoc_aws_credentials_cache_put_nolock ( - const _mongoc_aws_credentials_t *creds) +_mongoc_aws_credentials_cache_put_nolock (const _mongoc_aws_credentials_t *creds) { _mongoc_aws_credentials_cache_t *cache = &mongoc_aws_credentials_cache; BSON_ASSERT_PARAM (creds); diff --git a/src/libmongoc/src/mongoc/mongoc-cluster-cyrus.c b/src/libmongoc/src/mongoc/mongoc-cluster-cyrus.c index 4825010b5b..9fe56848e3 100644 --- a/src/libmongoc/src/mongoc/mongoc-cluster-cyrus.c +++ b/src/libmongoc/src/mongoc/mongoc-cluster-cyrus.c @@ -50,35 +50,28 @@ _mongoc_cluster_auth_node_cyrus (mongoc_cluster_t *cluster, BSON_ASSERT (cluster); BSON_ASSERT (stream); - if (!_mongoc_cyrus_new_from_cluster ( - &sasl, cluster, stream, sd->host.host, error)) { + if (!_mongoc_cyrus_new_from_cluster (&sasl, cluster, stream, sd->host.host, error)) { return false; } for (;;) { - mongoc_cmd_parts_init ( - &parts, cluster->client, "$external", MONGOC_QUERY_SECONDARY_OK, &cmd); + mongoc_cmd_parts_init (&parts, cluster->client, "$external", MONGOC_QUERY_SECONDARY_OK, &cmd); parts.prohibit_lsid = true; /* If this is the first step, input buffer is NULL. */ bson_free (outbuf); outbuf = NULL; outbuf_len = 0; - if (!_mongoc_cyrus_step ( - &sasl, inbuf, inbuf_len, &outbuf, &outbuf_len, error)) { + if (!_mongoc_cyrus_step (&sasl, inbuf, inbuf_len, &outbuf, &outbuf_len, error)) { goto failure; } bson_init (&cmd); if (sasl.step == 1) { - _mongoc_cluster_build_sasl_start (&cmd, - sasl.credentials.mechanism, - (const char *) outbuf, - outbuf_len); + _mongoc_cluster_build_sasl_start (&cmd, sasl.credentials.mechanism, (const char *) outbuf, outbuf_len); } else { - _mongoc_cluster_build_sasl_continue ( - &cmd, conv_id, (const char *) outbuf, outbuf_len); + _mongoc_cluster_build_sasl_continue (&cmd, conv_id, (const char *) outbuf, outbuf_len); } TRACE ("SASL: authenticating (step %d)", sasl.step); @@ -92,8 +85,7 @@ _mongoc_cluster_auth_node_cyrus (mongoc_cluster_t *cluster, goto failure; } - if (!mongoc_cluster_run_command_private ( - cluster, &parts.assembled, &reply, error)) { + if (!mongoc_cluster_run_command_private (cluster, &parts.assembled, &reply, error)) { mongoc_server_stream_cleanup (server_stream); bson_destroy (&cmd); bson_destroy (&reply); @@ -103,16 +95,14 @@ _mongoc_cluster_auth_node_cyrus (mongoc_cluster_t *cluster, bson_destroy (&cmd); - if (bson_iter_init_find (&iter, &reply, "done") && - bson_iter_as_bool (&iter)) { + if (bson_iter_init_find (&iter, &reply, "done") && bson_iter_as_bool (&iter)) { bson_destroy (&reply); break; } conv_id = _mongoc_cluster_get_conversation_id (&reply); - if (!bson_iter_init_find (&iter, &reply, "payload") || - !BSON_ITER_HOLDS_UTF8 (&iter)) { + if (!bson_iter_init_find (&iter, &reply, "payload") || !BSON_ITER_HOLDS_UTF8 (&iter)) { MONGOC_DEBUG ("SASL: authentication failed"); bson_destroy (&reply); bson_set_error (error, diff --git a/src/libmongoc/src/mongoc/mongoc-cluster-private.h b/src/libmongoc/src/mongoc/mongoc-cluster-private.h index 7af22850aa..1815def3cd 100644 --- a/src/libmongoc/src/mongoc/mongoc-cluster-private.h +++ b/src/libmongoc/src/mongoc/mongoc-cluster-private.h @@ -67,9 +67,7 @@ typedef struct _mongoc_cluster_t { void -mongoc_cluster_init (mongoc_cluster_t *cluster, - const mongoc_uri_t *uri, - void *client); +mongoc_cluster_init (mongoc_cluster_t *cluster, const mongoc_uri_t *uri, void *client); void mongoc_cluster_destroy (mongoc_cluster_t *cluster); @@ -84,20 +82,16 @@ int32_t mongoc_cluster_get_max_msg_size (mongoc_cluster_t *cluster); size_t -_mongoc_cluster_buffer_iovec (mongoc_iovec_t *iov, - size_t iovcnt, - int skip, - char *buffer); +_mongoc_cluster_buffer_iovec (mongoc_iovec_t *iov, size_t iovcnt, int skip, char *buffer); bool mongoc_cluster_check_interval (mongoc_cluster_t *cluster, uint32_t server_id); bool -mongoc_cluster_legacy_rpc_sendv_to_server ( - mongoc_cluster_t *cluster, - mcd_rpc_message *rpc, - mongoc_server_stream_t *server_stream, - bson_error_t *error); +mongoc_cluster_legacy_rpc_sendv_to_server (mongoc_cluster_t *cluster, + mcd_rpc_message *rpc, + mongoc_server_stream_t *server_stream, + bson_error_t *error); bool mongoc_cluster_try_recv (mongoc_cluster_t *cluster, @@ -157,12 +151,11 @@ mongoc_cluster_stream_for_writes (mongoc_cluster_t *cluster, * @note May add nodes and/or update the cluster's topology. */ mongoc_server_stream_t * -mongoc_cluster_stream_for_aggr_with_write ( - mongoc_cluster_t *cluster, - const mongoc_read_prefs_t *read_prefs, - mongoc_client_session_t *cs, - bson_t *reply, - bson_error_t *error); +mongoc_cluster_stream_for_aggr_with_write (mongoc_cluster_t *cluster, + const mongoc_read_prefs_t *read_prefs, + mongoc_client_session_t *cs, + bson_t *reply, + bson_error_t *error); /** * @brief Obtain a server stream associated with the cluster node associated @@ -188,14 +181,10 @@ mongoc_cluster_stream_for_server (mongoc_cluster_t *cluster, bson_error_t *error); bool -mongoc_cluster_stream_valid (mongoc_cluster_t *cluster, - mongoc_server_stream_t *server_stream); +mongoc_cluster_stream_valid (mongoc_cluster_t *cluster, mongoc_server_stream_t *server_stream); bool -mongoc_cluster_run_command_monitored (mongoc_cluster_t *cluster, - mongoc_cmd_t *cmd, - bson_t *reply, - bson_error_t *error); +mongoc_cluster_run_command_monitored (mongoc_cluster_t *cluster, mongoc_cmd_t *cmd, bson_t *reply, bson_error_t *error); bool mongoc_cluster_run_command_parts (mongoc_cluster_t *cluster, @@ -205,22 +194,13 @@ mongoc_cluster_run_command_parts (mongoc_cluster_t *cluster, bson_error_t *error); bool -mongoc_cluster_run_command_private (mongoc_cluster_t *cluster, - mongoc_cmd_t *cmd, - bson_t *reply, - bson_error_t *error); +mongoc_cluster_run_command_private (mongoc_cluster_t *cluster, mongoc_cmd_t *cmd, bson_t *reply, bson_error_t *error); void -_mongoc_cluster_build_sasl_start (bson_t *cmd, - const char *mechanism, - const char *buf, - uint32_t buflen); +_mongoc_cluster_build_sasl_start (bson_t *cmd, const char *mechanism, const char *buf, uint32_t buflen); void -_mongoc_cluster_build_sasl_continue (bson_t *cmd, - int conv_id, - const char *buf, - uint32_t buflen); +_mongoc_cluster_build_sasl_continue (bson_t *cmd, int conv_id, const char *buf, uint32_t buflen); int _mongoc_cluster_get_conversation_id (const bson_t *reply); @@ -268,14 +248,10 @@ mcd_rpc_message_compress (mcd_rpc_message *rpc, bson_error_t *error); bool -mcd_rpc_message_decompress (mcd_rpc_message *rpc, - void **data, - size_t *data_len); +mcd_rpc_message_decompress (mcd_rpc_message *rpc, void **data, size_t *data_len); bool -mcd_rpc_message_decompress_if_necessary (mcd_rpc_message *rpc, - void **data, - size_t *data_len); +mcd_rpc_message_decompress_if_necessary (mcd_rpc_message *rpc, void **data, size_t *data_len); BSON_END_DECLS diff --git a/src/libmongoc/src/mongoc/mongoc-cluster-sasl.c b/src/libmongoc/src/mongoc/mongoc-cluster-sasl.c index fd9f3acba9..98adb1057e 100644 --- a/src/libmongoc/src/mongoc/mongoc-cluster-sasl.c +++ b/src/libmongoc/src/mongoc/mongoc-cluster-sasl.c @@ -38,10 +38,7 @@ #endif void -_mongoc_cluster_build_sasl_start (bson_t *cmd, - const char *mechanism, - const char *buf, - uint32_t buflen) +_mongoc_cluster_build_sasl_start (bson_t *cmd, const char *mechanism, const char *buf, uint32_t buflen) { BSON_APPEND_INT32 (cmd, "saslStart", 1); BSON_APPEND_UTF8 (cmd, "mechanism", mechanism); @@ -49,10 +46,7 @@ _mongoc_cluster_build_sasl_start (bson_t *cmd, BSON_APPEND_INT32 (cmd, "autoAuthorize", 1); } void -_mongoc_cluster_build_sasl_continue (bson_t *cmd, - int conv_id, - const char *buf, - uint32_t buflen) +_mongoc_cluster_build_sasl_continue (bson_t *cmd, int conv_id, const char *buf, uint32_t buflen) { BSON_APPEND_INT32 (cmd, "saslContinue", 1); BSON_APPEND_INT32 (cmd, "conversationId", conv_id); @@ -63,8 +57,7 @@ _mongoc_cluster_get_conversation_id (const bson_t *reply) { bson_iter_t iter; - if (bson_iter_init_find (&iter, reply, "conversationId") && - BSON_ITER_HOLDS_INT32 (&iter)) { + if (bson_iter_init_find (&iter, reply, "conversationId") && BSON_ITER_HOLDS_INT32 (&iter)) { return bson_iter_int32 (&iter); } diff --git a/src/libmongoc/src/mongoc/mongoc-cluster-sspi.c b/src/libmongoc/src/mongoc/mongoc-cluster-sspi.c index 13cf8c52a5..8fac3e24c9 100644 --- a/src/libmongoc/src/mongoc/mongoc-cluster-sspi.c +++ b/src/libmongoc/src/mongoc/mongoc-cluster-sspi.c @@ -27,9 +27,7 @@ static mongoc_sspi_client_state_t * -_mongoc_cluster_sspi_new (mongoc_uri_t *uri, - mongoc_stream_t *stream, - const char *hostname) +_mongoc_cluster_sspi_new (mongoc_uri_t *uri, mongoc_stream_t *stream, const char *hostname) { WCHAR *service; /* L"serviceName@hostname@REALM" */ const char *service_name = "mongodb"; @@ -53,18 +51,15 @@ _mongoc_cluster_sspi_new (mongoc_uri_t *uri, _mongoc_sasl_set_properties (&state->sasl, uri); if (state->sasl.canonicalize_host_name && - _mongoc_sasl_get_canonicalized_name ( - stream, real_name, sizeof real_name)) { + _mongoc_sasl_get_canonicalized_name (stream, real_name, sizeof real_name)) { hostname = real_name; } /* service realm is an SSPI-specific feature */ if (mongoc_uri_get_mechanism_properties (uri, &properties) && - bson_iter_init_find_case (&iter, &properties, "SERVICE_REALM") && - BSON_ITER_HOLDS_UTF8 (&iter)) { + bson_iter_init_find_case (&iter, &properties, "SERVICE_REALM") && BSON_ITER_HOLDS_UTF8 (&iter)) { service_realm = bson_iter_utf8 (&iter, NULL); - service_ascii = - bson_strdup_printf ("%s@%s@%s", service_name, hostname, service_realm); + service_ascii = bson_strdup_printf ("%s@%s@%s", service_name, hostname, service_realm); } else { service_ascii = bson_strdup_printf ("%s@%s", service_name, hostname); } @@ -72,12 +67,8 @@ _mongoc_cluster_sspi_new (mongoc_uri_t *uri, /* this is donated to the sspi */ service = bson_malloc0 ((service_ascii_len + 1) * sizeof (WCHAR)); - service_len = MultiByteToWideChar (CP_UTF8, - 0, - service_ascii, - (int) service_ascii_len, - service, - (int) service_ascii_len); + service_len = + MultiByteToWideChar (CP_UTF8, 0, service_ascii, (int) service_ascii_len, service, (int) service_ascii_len); service[service_len] = L'\0'; bson_free (service_ascii); @@ -86,12 +77,7 @@ _mongoc_cluster_sspi_new (mongoc_uri_t *uri, /* this is donated to the sspi */ pass = bson_malloc0 ((tmp_creds_len + 1) * sizeof (WCHAR)); - pass_len = MultiByteToWideChar (CP_UTF8, - 0, - state->sasl.pass, - (int) tmp_creds_len, - pass, - (int) tmp_creds_len); + pass_len = MultiByteToWideChar (CP_UTF8, 0, state->sasl.pass, (int) tmp_creds_len, pass, (int) tmp_creds_len); pass[pass_len] = L'\0'; } @@ -100,24 +86,12 @@ _mongoc_cluster_sspi_new (mongoc_uri_t *uri, /* this is donated to the sspi */ user = bson_malloc0 ((tmp_creds_len + 1) * sizeof (WCHAR)); - user_len = MultiByteToWideChar (CP_UTF8, - 0, - state->sasl.user, - (int) tmp_creds_len, - user, - (int) tmp_creds_len); + user_len = MultiByteToWideChar (CP_UTF8, 0, state->sasl.user, (int) tmp_creds_len, user, (int) tmp_creds_len); user[user_len] = L'\0'; } - res = _mongoc_sspi_auth_sspi_client_init (service, - flags, - user, - (ULONG) user_len, - NULL, - 0, - pass, - (ULONG) pass_len, - state); + res = _mongoc_sspi_auth_sspi_client_init ( + service, flags, user, (ULONG) user_len, NULL, 0, pass, (ULONG) pass_len, state); if (res != MONGOC_SSPI_AUTH_GSS_ERROR) { return state; @@ -166,16 +140,13 @@ _mongoc_cluster_auth_node_sspi (mongoc_cluster_t *cluster, state = _mongoc_cluster_sspi_new (cluster->uri, stream, sd->host.host); if (!state) { - bson_set_error (error, - MONGOC_ERROR_CLIENT, - MONGOC_ERROR_CLIENT_AUTHENTICATE, - "Couldn't initialize SSPI service."); + bson_set_error ( + error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_AUTHENTICATE, "Couldn't initialize SSPI service."); goto failure; } for (step = 0;; step++) { - mongoc_cmd_parts_init ( - &parts, cluster->client, "$external", MONGOC_QUERY_SECONDARY_OK, &cmd); + mongoc_cmd_parts_init (&parts, cluster->client, "$external", MONGOC_QUERY_SECONDARY_OK, &cmd); parts.prohibit_lsid = true; bson_init (&cmd); @@ -187,19 +158,12 @@ _mongoc_cluster_auth_node_sspi (mongoc_cluster_t *cluster, res = _mongoc_sspi_auth_sspi_client_unwrap (state, buf); response = bson_strdup (state->response); - _mongoc_sspi_auth_sspi_client_wrap (state, - response, - (SEC_CHAR *) state->sasl.user, - (ULONG) tmp_creds_len, - 0); + _mongoc_sspi_auth_sspi_client_wrap (state, response, (SEC_CHAR *) state->sasl.user, (ULONG) tmp_creds_len, 0); bson_free (response); } if (res == MONGOC_SSPI_AUTH_GSS_ERROR) { - bson_set_error (error, - MONGOC_ERROR_CLIENT, - MONGOC_ERROR_CLIENT_AUTHENTICATE, - "Received invalid SSPI data."); + bson_set_error (error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_AUTHENTICATE, "Received invalid SSPI data."); mongoc_cmd_parts_cleanup (&parts); bson_destroy (&cmd); @@ -207,17 +171,10 @@ _mongoc_cluster_auth_node_sspi (mongoc_cluster_t *cluster, } if (step == 0) { - _mongoc_cluster_build_sasl_start (&cmd, - "GSSAPI", - state->response, - (uint32_t) strlen (state->response)); + _mongoc_cluster_build_sasl_start (&cmd, "GSSAPI", state->response, (uint32_t) strlen (state->response)); } else { if (state->response) { - _mongoc_cluster_build_sasl_continue ( - &cmd, - conv_id, - state->response, - (uint32_t) strlen (state->response)); + _mongoc_cluster_build_sasl_continue (&cmd, conv_id, state->response, (uint32_t) strlen (state->response)); } else { _mongoc_cluster_build_sasl_continue (&cmd, conv_id, "", 0); } @@ -233,8 +190,7 @@ _mongoc_cluster_auth_node_sspi (mongoc_cluster_t *cluster, goto failure; } - if (!mongoc_cluster_run_command_private ( - cluster, &parts.assembled, &reply, error)) { + if (!mongoc_cluster_run_command_private (cluster, &parts.assembled, &reply, error)) { mongoc_server_stream_cleanup (server_stream); mongoc_cmd_parts_cleanup (&parts); bson_destroy (&cmd); @@ -246,16 +202,14 @@ _mongoc_cluster_auth_node_sspi (mongoc_cluster_t *cluster, mongoc_cmd_parts_cleanup (&parts); bson_destroy (&cmd); - if (bson_iter_init_find (&iter, &reply, "done") && - bson_iter_as_bool (&iter)) { + if (bson_iter_init_find (&iter, &reply, "done") && bson_iter_as_bool (&iter)) { bson_destroy (&reply); break; } conv_id = _mongoc_cluster_get_conversation_id (&reply); - if (!bson_iter_init_find (&iter, &reply, "payload") || - !BSON_ITER_HOLDS_UTF8 (&iter)) { + if (!bson_iter_init_find (&iter, &reply, "payload") || !BSON_ITER_HOLDS_UTF8 (&iter)) { bson_destroy (&reply); bson_set_error (error, MONGOC_ERROR_CLIENT, diff --git a/src/libmongoc/src/mongoc/mongoc-cluster.c b/src/libmongoc/src/mongoc/mongoc-cluster.c index 343528bfce..7421d4afe0 100644 --- a/src/libmongoc/src/mongoc/mongoc-cluster.c +++ b/src/libmongoc/src/mongoc/mongoc-cluster.c @@ -84,19 +84,13 @@ _cluster_fetch_stream_pooled (mongoc_cluster_t *cluster, bson_error_t *error); static bool -mongoc_cluster_run_opmsg (mongoc_cluster_t *cluster, - mongoc_cmd_t *cmd, - bson_t *reply, - bson_error_t *error); +mongoc_cluster_run_opmsg (mongoc_cluster_t *cluster, mongoc_cmd_t *cmd, bson_t *reply, bson_error_t *error); static void -_bson_error_message_printf (bson_error_t *error, const char *format, ...) - BSON_GNUC_PRINTF (2, 3); +_bson_error_message_printf (bson_error_t *error, const char *format, ...) BSON_GNUC_PRINTF (2, 3); static void -_handle_not_primary_error (mongoc_cluster_t *cluster, - const mongoc_server_stream_t *server_stream, - const bson_t *reply) +_handle_not_primary_error (mongoc_cluster_t *cluster, const mongoc_server_stream_t *server_stream, const bson_t *reply) { uint32_t server_id; @@ -117,9 +111,7 @@ _handle_not_primary_error (mongoc_cluster_t *cluster, /* Called when a network error occurs on an application socket. */ static void -_handle_network_error (mongoc_cluster_t *cluster, - mongoc_server_stream_t *server_stream, - const bson_error_t *why) +_handle_network_error (mongoc_cluster_t *cluster, mongoc_server_stream_t *server_stream, const bson_error_t *why) { mongoc_topology_t *topology; uint32_t server_id; @@ -163,8 +155,7 @@ static int32_t _compression_level_from_uri (int32_t compressor_id, const mongoc_uri_t *uri) { if (compressor_id == MONGOC_COMPRESSOR_ZLIB_ID) { - return mongoc_uri_get_option_as_int32 ( - uri, MONGOC_URI_ZLIBCOMPRESSIONLEVEL, -1); + return mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_ZLIBCOMPRESSIONLEVEL, -1); } return -1; @@ -172,10 +163,7 @@ _compression_level_from_uri (int32_t compressor_id, const mongoc_uri_t *uri) size_t -_mongoc_cluster_buffer_iovec (mongoc_iovec_t *iov, - size_t iovcnt, - int skip, - char *buffer) +_mongoc_cluster_buffer_iovec (mongoc_iovec_t *iov, size_t iovcnt, int skip, char *buffer) { size_t buffer_offset = 0; int total_iov_len = 0; @@ -201,9 +189,7 @@ _mongoc_cluster_buffer_iovec (mongoc_iovec_t *iov, difference = 0u; } - memcpy (buffer + buffer_offset, - ((char *) iov[n].iov_base) + difference, - iov[n].iov_len - difference); + memcpy (buffer + buffer_offset, ((char *) iov[n].iov_base) + difference, iov[n].iov_len - difference); buffer_offset += iov[n].iov_len - difference; } @@ -227,14 +213,13 @@ _bson_error_message_printf (bson_error_t *error, const char *format, ...) } } -#define RUN_CMD_ERR_DECORATE \ - do { \ - _bson_error_message_printf ( \ - error, \ - "Failed to send \"%s\" command with database \"%s\": %s", \ - cmd->command_name, \ - cmd->db_name, \ - error->message); \ +#define RUN_CMD_ERR_DECORATE \ + do { \ + _bson_error_message_printf (error, \ + "Failed to send \"%s\" command with database \"%s\": %s", \ + cmd->command_name, \ + cmd->db_name, \ + error->message); \ } while (0) #define RUN_CMD_ERR(_domain, _code, ...) \ @@ -249,11 +234,8 @@ static const int32_t message_header_length = 4u * sizeof (int32_t); static bool -_mongoc_cluster_run_command_opquery_send (mongoc_cluster_t *cluster, - mongoc_cmd_t *cmd, - int32_t compressor_id, - mcd_rpc_message *rpc, - bson_error_t *error) +_mongoc_cluster_run_command_opquery_send ( + mongoc_cluster_t *cluster, mongoc_cmd_t *cmd, int32_t compressor_id, mcd_rpc_message *rpc, bson_error_t *error) { BSON_ASSERT_PARAM (cluster); BSON_ASSERT_PARAM (cmd); @@ -272,8 +254,7 @@ _mongoc_cluster_run_command_opquery_send (mongoc_cluster_t *cluster, // For other cursor-typed commands like aggregate, only secondaryOk can be // set. Clear bits except secondaryOk; leave secondaryOk set only if it is // already. - const int32_t flags = - (int32_t) cmd->query_flags & MONGOC_OP_QUERY_FLAG_SECONDARY_OK; + const int32_t flags = (int32_t) cmd->query_flags & MONGOC_OP_QUERY_FLAG_SECONDARY_OK; { int32_t message_length = 0; @@ -287,8 +268,7 @@ _mongoc_cluster_run_command_opquery_send (mongoc_cluster_t *cluster, message_length += mcd_rpc_op_query_set_full_collection_name (rpc, ns); message_length += mcd_rpc_op_query_set_number_to_skip (rpc, 0); message_length += mcd_rpc_op_query_set_number_to_return (rpc, -1); - message_length += - mcd_rpc_op_query_set_query (rpc, bson_get_data (cmd->command)); + message_length += mcd_rpc_op_query_set_query (rpc, bson_get_data (cmd->command)); mcd_rpc_message_set_length (rpc, message_length); } @@ -298,37 +278,30 @@ _mongoc_cluster_run_command_opquery_send (mongoc_cluster_t *cluster, BSON_ASSERT (iovecs); const bool is_compressible = - compressor_id != -1 && IS_NOT_COMMAND (HANDSHAKE_CMD_LEGACY_HELLO) && - IS_NOT_COMMAND ("hello") && IS_NOT_COMMAND ("saslstart") && - IS_NOT_COMMAND ("saslcontinue") && IS_NOT_COMMAND ("getnonce") && - IS_NOT_COMMAND ("authenticate") && IS_NOT_COMMAND ("createuser") && - IS_NOT_COMMAND ("updateuser"); + compressor_id != -1 && IS_NOT_COMMAND (HANDSHAKE_CMD_LEGACY_HELLO) && IS_NOT_COMMAND ("hello") && + IS_NOT_COMMAND ("saslstart") && IS_NOT_COMMAND ("saslcontinue") && IS_NOT_COMMAND ("getnonce") && + IS_NOT_COMMAND ("authenticate") && IS_NOT_COMMAND ("createuser") && IS_NOT_COMMAND ("updateuser"); void *compressed_data = NULL; size_t compressed_data_len = 0u; - if (is_compressible && - !mcd_rpc_message_compress ( - rpc, - compressor_id, - _compression_level_from_uri (compressor_id, cluster->uri), - &compressed_data, - &compressed_data_len, - error)) { + if (is_compressible && !mcd_rpc_message_compress (rpc, + compressor_id, + _compression_level_from_uri (compressor_id, cluster->uri), + &compressed_data, + &compressed_data_len, + error)) { goto done; } if (cluster->client->in_exhaust) { - bson_set_error (error, - MONGOC_ERROR_CLIENT, - MONGOC_ERROR_CLIENT_IN_EXHAUST, - "a cursor derived from this client is in exhaust"); + bson_set_error ( + error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_IN_EXHAUST, "a cursor derived from this client is in exhaust"); goto done; } mcd_rpc_message_egress (rpc); - if (!_mongoc_stream_writev_full ( - stream, iovecs, num_iovecs, cluster->sockettimeoutms, error)) { + if (!_mongoc_stream_writev_full (stream, iovecs, num_iovecs, cluster->sockettimeoutms, error)) { RUN_CMD_ERR_DECORATE; _handle_network_error (cluster, cmd->server_stream, error); goto done; @@ -345,11 +318,8 @@ _mongoc_cluster_run_command_opquery_send (mongoc_cluster_t *cluster, } static bool -_mongoc_cluster_run_command_opquery_recv (mongoc_cluster_t *cluster, - mongoc_cmd_t *cmd, - mcd_rpc_message *rpc, - bson_t *reply, - bson_error_t *error) +_mongoc_cluster_run_command_opquery_recv ( + mongoc_cluster_t *cluster, mongoc_cmd_t *cmd, mcd_rpc_message *rpc, bson_t *reply, bson_error_t *error) { BSON_ASSERT_PARAM (cluster); BSON_ASSERT_PARAM (cmd); @@ -367,52 +337,37 @@ _mongoc_cluster_run_command_opquery_recv (mongoc_cluster_t *cluster, void *decompressed_data = NULL; size_t decompressed_data_len = 0u; - if (!_mongoc_buffer_append_from_stream ( - &buffer, stream, sizeof (int32_t), cluster->sockettimeoutms, error)) { - RUN_CMD_ERR (MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_SOCKET, - "socket error or timeout"); + if (!_mongoc_buffer_append_from_stream (&buffer, stream, sizeof (int32_t), cluster->sockettimeoutms, error)) { + RUN_CMD_ERR (MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "socket error or timeout"); _handle_network_error (cluster, cmd->server_stream, error); goto done; } const int32_t message_length = _int32_from_le (buffer.data); - if (message_length < message_header_length || - message_length > MONGOC_DEFAULT_MAX_MSG_SIZE) { - RUN_CMD_ERR (MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_SOCKET, - "invalid message length"); + if (message_length < message_header_length || message_length > MONGOC_DEFAULT_MAX_MSG_SIZE) { + RUN_CMD_ERR (MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "invalid message length"); _handle_network_error (cluster, cmd->server_stream, error); goto done; } const size_t remaining_bytes = (size_t) message_length - sizeof (int32_t); - if (!_mongoc_buffer_append_from_stream ( - &buffer, stream, remaining_bytes, cluster->sockettimeoutms, error)) { - RUN_CMD_ERR (MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_SOCKET, - "socket error or timeout"); + if (!_mongoc_buffer_append_from_stream (&buffer, stream, remaining_bytes, cluster->sockettimeoutms, error)) { + RUN_CMD_ERR (MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "socket error or timeout"); _handle_network_error (cluster, cmd->server_stream, error); goto done; } - if (!mcd_rpc_message_from_data_in_place ( - rpc, buffer.data, buffer.len, NULL)) { - RUN_CMD_ERR (MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_SOCKET, - "malformed reply from server"); + if (!mcd_rpc_message_from_data_in_place (rpc, buffer.data, buffer.len, NULL)) { + RUN_CMD_ERR (MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "malformed reply from server"); goto done; } mcd_rpc_message_ingress (rpc); - if (!mcd_rpc_message_decompress_if_necessary ( - rpc, &decompressed_data, &decompressed_data_len)) { - RUN_CMD_ERR (MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_SOCKET, - "could not decompress server reply"); + if (!mcd_rpc_message_decompress_if_necessary (rpc, &decompressed_data, &decompressed_data_len)) { + RUN_CMD_ERR (MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "could not decompress server reply"); goto done; } @@ -420,9 +375,7 @@ _mongoc_cluster_run_command_opquery_recv (mongoc_cluster_t *cluster, bson_t body; if (!mcd_rpc_message_get_body (rpc, &body)) { - RUN_CMD_ERR (MONGOC_ERROR_PROTOCOL, - MONGOC_ERROR_PROTOCOL_INVALID_REPLY, - "malformed reply from server"); + RUN_CMD_ERR (MONGOC_ERROR_PROTOCOL, MONGOC_ERROR_PROTOCOL_INVALID_REPLY, "malformed reply from server"); goto done; } @@ -430,8 +383,7 @@ _mongoc_cluster_run_command_opquery_recv (mongoc_cluster_t *cluster, bson_destroy (&body); } - if (!_mongoc_cmd_check_ok ( - reply, cluster->client->error_api_version, error)) { + if (!_mongoc_cmd_check_ok (reply, cluster->client->error_api_version, error)) { goto done; } @@ -445,11 +397,8 @@ _mongoc_cluster_run_command_opquery_recv (mongoc_cluster_t *cluster, } static bool -mongoc_cluster_run_command_opquery (mongoc_cluster_t *cluster, - mongoc_cmd_t *cmd, - int32_t compressor_id, - bson_t *reply, - bson_error_t *error) +mongoc_cluster_run_command_opquery ( + mongoc_cluster_t *cluster, mongoc_cmd_t *cmd, int32_t compressor_id, bson_t *reply, bson_error_t *error) { BSON_ASSERT_PARAM (cluster); BSON_ASSERT_PARAM (cmd); @@ -466,15 +415,13 @@ mongoc_cluster_run_command_opquery (mongoc_cluster_t *cluster, mcd_rpc_message *const rpc = mcd_rpc_message_new (); - if (!_mongoc_cluster_run_command_opquery_send ( - cluster, cmd, compressor_id, rpc, error)) { + if (!_mongoc_cluster_run_command_opquery_send (cluster, cmd, compressor_id, rpc, error)) { GOTO (done); } mcd_rpc_message_reset (rpc); - if (!_mongoc_cluster_run_command_opquery_recv ( - cluster, cmd, rpc, reply, error)) { + if (!_mongoc_cluster_run_command_opquery_recv (cluster, cmd, rpc, reply, error)) { GOTO (done); } @@ -483,9 +430,7 @@ mongoc_cluster_run_command_opquery (mongoc_cluster_t *cluster, done: if (!ret && error->code == 0) { /* generic error */ - RUN_CMD_ERR (MONGOC_ERROR_PROTOCOL, - MONGOC_ERROR_PROTOCOL_INVALID_REPLY, - "invalid reply from server"); + RUN_CMD_ERR (MONGOC_ERROR_PROTOCOL, MONGOC_ERROR_PROTOCOL_INVALID_REPLY, "invalid reply from server"); } mcd_rpc_message_destroy (rpc); @@ -497,8 +442,7 @@ static bool _in_sharded_txn (const mongoc_client_session_t *session) { return session && _mongoc_client_session_in_txn_or_ending (session) && - _mongoc_topology_get_type (session->client->topology) == - MONGOC_TOPOLOGY_SHARDED; + _mongoc_topology_get_type (session->client->topology) == MONGOC_TOPOLOGY_SHARDED; } static bool @@ -512,25 +456,19 @@ _in_sharded_or_loadbalanced_txn (const mongoc_client_session_t *session) return false; } - mongoc_topology_description_type_t type = - _mongoc_topology_get_type (session->client->topology); + mongoc_topology_description_type_t type = _mongoc_topology_get_type (session->client->topology); - return (type == MONGOC_TOPOLOGY_SHARDED) || - (type == MONGOC_TOPOLOGY_LOAD_BALANCED); + return (type == MONGOC_TOPOLOGY_SHARDED) || (type == MONGOC_TOPOLOGY_LOAD_BALANCED); } static void -_handle_txn_error_labels (bool cmd_ret, - const bson_error_t *cmd_err, - const mongoc_cmd_t *cmd, - bson_t *reply) +_handle_txn_error_labels (bool cmd_ret, const bson_error_t *cmd_err, const mongoc_cmd_t *cmd, bson_t *reply) { if (!cmd->is_txn_finish) { return; } - _mongoc_write_error_handle_labels ( - cmd_ret, cmd_err, reply, cmd->server_stream->sd); + _mongoc_write_error_handle_labels (cmd_ret, cmd_err, reply, cmd->server_stream->sd); } /* @@ -552,10 +490,7 @@ _handle_txn_error_labels (bool cmd_ret, */ bool -mongoc_cluster_run_command_monitored (mongoc_cluster_t *cluster, - mongoc_cmd_t *cmd, - bson_t *reply, - bson_error_t *error) +mongoc_cluster_run_command_monitored (mongoc_cluster_t *cluster, mongoc_cmd_t *cmd, bson_t *reply, bson_error_t *error) { bool retval; const int32_t request_id = ++cluster->request_id; @@ -588,8 +523,7 @@ mongoc_cluster_run_command_monitored (mongoc_cluster_t *cluster, if (_mongoc_cse_is_enabled (cluster->client)) { bson_destroy (&encrypted); - retval = _mongoc_cse_auto_encrypt ( - cluster->client, cmd, &encrypted_cmd, &encrypted, error); + retval = _mongoc_cse_auto_encrypt (cluster->client, cmd, &encrypted_cmd, &encrypted, error); cmd = &encrypted_cmd; if (!retval) { bson_init (reply); @@ -598,11 +532,8 @@ mongoc_cluster_run_command_monitored (mongoc_cluster_t *cluster, } if (callbacks->started) { - mongoc_apm_command_started_init_with_cmd (&started_event, - cmd, - request_id, - &is_redacted, - cluster->client->apm_context); + mongoc_apm_command_started_init_with_cmd ( + &started_event, cmd, request_id, &is_redacted, cluster->client->apm_context); callbacks->started (&started_event); mongoc_apm_command_started_cleanup (&started_event); @@ -620,19 +551,18 @@ mongoc_cluster_run_command_monitored (mongoc_cluster_t *cluster, if (!cmd->is_acknowledged) { bson_append_int32 (&fake_reply, "ok", 2, 1); } - mongoc_apm_command_succeeded_init ( - &succeeded_event, - bson_get_monotonic_time () - started, - cmd->is_acknowledged ? reply : &fake_reply, - cmd->command_name, - request_id, - cmd->operation_id, - &server_stream->sd->host, - server_id, - &server_stream->sd->service_id, - server_stream->sd->server_connection_id, - is_redacted, - cluster->client->apm_context); + mongoc_apm_command_succeeded_init (&succeeded_event, + bson_get_monotonic_time () - started, + cmd->is_acknowledged ? reply : &fake_reply, + cmd->command_name, + request_id, + cmd->operation_id, + &server_stream->sd->host, + server_id, + &server_stream->sd->service_id, + server_stream->sd->server_connection_id, + is_redacted, + cluster->client->apm_context); callbacks->succeeded (&succeeded_event); mongoc_apm_command_succeeded_cleanup (&succeeded_event); @@ -659,8 +589,7 @@ mongoc_cluster_run_command_monitored (mongoc_cluster_t *cluster, if (retval && _mongoc_cse_is_enabled (cluster->client)) { bson_destroy (&decrypted); - retval = _mongoc_cse_auto_decrypt ( - cluster->client, cmd->db_name, reply, &decrypted, error); + retval = _mongoc_cse_auto_decrypt (cluster->client, cmd->db_name, reply, &decrypted, error); bson_destroy (reply); bson_steal (reply, &decrypted); bson_init (&decrypted); @@ -677,9 +606,8 @@ mongoc_cluster_run_command_monitored (mongoc_cluster_t *cluster, bson_iter_init_find (&iter, reply, "recoveryToken")) { bson_destroy (cmd->session->recovery_token); if (BSON_ITER_HOLDS_DOCUMENT (&iter)) { - cmd->session->recovery_token = - bson_new_from_data (bson_iter_value (&iter)->value.v_doc.data, - bson_iter_value (&iter)->value.v_doc.data_len); + cmd->session->recovery_token = bson_new_from_data (bson_iter_value (&iter)->value.v_doc.data, + bson_iter_value (&iter)->value.v_doc.data_len); } else { MONGOC_ERROR ("Malformed recovery token from server"); cmd->session->recovery_token = NULL; @@ -703,8 +631,7 @@ mongoc_cluster_run_command_monitored (mongoc_cluster_t *cluster, static bool _should_use_op_msg (const mongoc_cluster_t *cluster) { - return mongoc_cluster_uses_server_api (cluster) || - mongoc_cluster_uses_loadbalanced (cluster); + return mongoc_cluster_uses_server_api (cluster) || mongoc_cluster_uses_loadbalanced (cluster); } @@ -728,10 +655,7 @@ _should_use_op_msg (const mongoc_cluster_t *cluster) */ bool -mongoc_cluster_run_command_private (mongoc_cluster_t *cluster, - mongoc_cmd_t *cmd, - bson_t *reply, - bson_error_t *error) +mongoc_cluster_run_command_private (mongoc_cluster_t *cluster, mongoc_cmd_t *cmd, bson_t *reply, bson_error_t *error) { bool retval; const mongoc_server_stream_t *server_stream; @@ -749,12 +673,10 @@ mongoc_cluster_run_command_private (mongoc_cluster_t *cluster, server_stream = cmd->server_stream; - if (_should_use_op_msg (cluster) || - server_stream->sd->max_wire_version >= WIRE_VERSION_MIN) { + if (_should_use_op_msg (cluster) || server_stream->sd->max_wire_version >= WIRE_VERSION_MIN) { retval = mongoc_cluster_run_opmsg (cluster, cmd, reply, error); } else { - retval = - mongoc_cluster_run_command_opquery (cluster, cmd, -1, reply, error); + retval = mongoc_cluster_run_command_opquery (cluster, cmd, -1, reply, error); } _handle_not_primary_error (cluster, server_stream, reply); @@ -763,8 +685,7 @@ mongoc_cluster_run_command_private (mongoc_cluster_t *cluster, bson_destroy (&reply_local); } - _mongoc_topology_update_last_used (cluster->client->topology, - server_stream->sd->id); + _mongoc_topology_update_last_used (cluster->client->topology, server_stream->sd->id); return retval; } @@ -804,8 +725,7 @@ mongoc_cluster_run_command_parts (mongoc_cluster_t *cluster, return false; } - ret = mongoc_cluster_run_command_private ( - cluster, &parts->assembled, reply, error); + ret = mongoc_cluster_run_command_private (cluster, &parts->assembled, reply, error); mongoc_cmd_parts_cleanup (parts); return ret; } @@ -845,28 +765,24 @@ _stream_run_hello (mongoc_cluster_t *cluster, mongoc_server_stream_t *server_stream; bool r; mongoc_ssl_opt_t *ssl_opts = NULL; - mc_shared_tpld td = - mc_tpld_take_ref (BSON_ASSERT_PTR_INLINE (cluster)->client->topology); + mc_shared_tpld td = mc_tpld_take_ref (BSON_ASSERT_PTR_INLINE (cluster)->client->topology); ENTRY; BSON_ASSERT (stream); - _mongoc_topology_dup_handshake_cmd (cluster->client->topology, - &handshake_command); + _mongoc_topology_dup_handshake_cmd (cluster->client->topology, &handshake_command); if (cluster->requires_auth && speculative_auth_response) { #ifdef MONGOC_ENABLE_SSL ssl_opts = &cluster->client->ssl_opts; #endif - _mongoc_topology_scanner_add_speculative_authentication ( - &handshake_command, cluster->uri, ssl_opts, scram); + _mongoc_topology_scanner_add_speculative_authentication (&handshake_command, cluster->uri, ssl_opts, scram); } if (negotiate_sasl_supported_mechs) { - _mongoc_handshake_append_sasl_supported_mechs (cluster->uri, - &handshake_command); + _mongoc_handshake_append_sasl_supported_mechs (cluster->uri, &handshake_command); } start = bson_get_monotonic_time (); @@ -881,8 +797,7 @@ _stream_run_hello (mongoc_cluster_t *cluster, * invalidates again. */ mongoc_server_description_init (&empty_sd, address, server_id); - server_stream = - _mongoc_cluster_create_server_stream (td.ptr, &empty_sd, stream); + server_stream = _mongoc_cluster_create_server_stream (td.ptr, &empty_sd, stream); mongoc_server_description_cleanup (&empty_sd); @@ -906,8 +821,7 @@ _stream_run_hello (mongoc_cluster_t *cluster, hello_cmd.server_stream = server_stream; hello_cmd.is_acknowledged = true; - if (!mongoc_cluster_run_command_private ( - cluster, &hello_cmd, &reply, error)) { + if (!mongoc_cluster_run_command_private (cluster, &hello_cmd, &reply, error)) { if (negotiate_sasl_supported_mechs) { bsonParse (reply, find (allOf (key ("ok"), isFalse), // @@ -932,18 +846,15 @@ _stream_run_hello (mongoc_cluster_t *cluster, mongoc_server_description_init (ret_handshake_sd, address, server_id); /* send the error from run_command IN to handle_hello */ - mongoc_server_description_handle_hello ( - ret_handshake_sd, &reply, rtt_msec, error); + mongoc_server_description_handle_hello (ret_handshake_sd, &reply, rtt_msec, error); if (cluster->requires_auth && speculative_auth_response) { - _mongoc_topology_scanner_parse_speculative_authentication ( - &reply, speculative_auth_response); + _mongoc_topology_scanner_parse_speculative_authentication (&reply, speculative_auth_response); } /* Note: This call will render our copy of the topology description to be * stale */ - r = _mongoc_topology_update_from_handshake (cluster->client->topology, - ret_handshake_sd); + r = _mongoc_topology_update_from_handshake (cluster->client->topology, ret_handshake_sd); if (!r) { mongoc_server_description_reset (ret_handshake_sd); bson_set_error (&ret_handshake_sd->error, @@ -1040,8 +951,7 @@ _cluster_run_hello (mongoc_cluster_t *cluster, */ static char * -_mongoc_cluster_build_basic_auth_digest (mongoc_cluster_t *cluster, - const char *nonce) +_mongoc_cluster_build_basic_auth_digest (mongoc_cluster_t *cluster, const char *nonce) { const char *username; const char *password; @@ -1120,8 +1030,7 @@ _mongoc_cluster_auth_node_cr (mongoc_cluster_t *cluster, BSON_ASSERT (cluster); BSON_ASSERT (stream); - if (!(auth_source = mongoc_uri_get_auth_source (cluster->uri)) || - (*auth_source == '\0')) { + if (!(auth_source = mongoc_uri_get_auth_source (cluster->uri)) || (*auth_source == '\0')) { auth_source = "admin"; } @@ -1138,19 +1047,14 @@ _mongoc_cluster_auth_node_cr (mongoc_cluster_t *cluster, */ bson_init (&command); bson_append_int32 (&command, "getnonce", 8, 1); - mongoc_cmd_parts_init (&parts, - cluster->client, - auth_source, - MONGOC_QUERY_SECONDARY_OK, - &command); + mongoc_cmd_parts_init (&parts, cluster->client, auth_source, MONGOC_QUERY_SECONDARY_OK, &command); parts.prohibit_lsid = true; td = mc_tpld_take_ref (cluster->client->topology); server_stream = _mongoc_cluster_create_server_stream (td.ptr, sd, stream); mc_tpld_drop_ref (&td); - if (!mongoc_cluster_run_command_parts ( - cluster, server_stream, &parts, &reply, error)) { + if (!mongoc_cluster_run_command_parts (cluster, server_stream, &parts, &reply, error)) { mongoc_server_stream_cleanup (server_stream); bson_destroy (&command); bson_destroy (&reply); @@ -1158,10 +1062,7 @@ _mongoc_cluster_auth_node_cr (mongoc_cluster_t *cluster, } bson_destroy (&command); if (!bson_iter_init_find_case (&iter, &reply, "nonce")) { - bson_set_error (error, - MONGOC_ERROR_CLIENT, - MONGOC_ERROR_CLIENT_GETNONCE, - "Invalid reply from getnonce"); + bson_set_error (error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_GETNONCE, "Invalid reply from getnonce"); bson_destroy (&reply); RETURN (false); } @@ -1173,8 +1074,7 @@ _mongoc_cluster_auth_node_cr (mongoc_cluster_t *cluster, digest = _mongoc_cluster_build_basic_auth_digest (cluster, nonce); bson_init (&command); bson_append_int32 (&command, "authenticate", 12, 1); - bson_append_utf8 ( - &command, "user", 4, mongoc_uri_get_username (cluster->uri), -1); + bson_append_utf8 (&command, "user", 4, mongoc_uri_get_username (cluster->uri), -1); bson_append_utf8 (&command, "nonce", 5, nonce, -1); bson_append_utf8 (&command, "key", 3, digest, -1); bson_destroy (&reply); @@ -1185,14 +1085,9 @@ _mongoc_cluster_auth_node_cr (mongoc_cluster_t *cluster, * Execute the authenticate command. mongoc_cluster_run_command_private * checks for {ok: 1} in the response. */ - mongoc_cmd_parts_init (&parts, - cluster->client, - auth_source, - MONGOC_QUERY_SECONDARY_OK, - &command); + mongoc_cmd_parts_init (&parts, cluster->client, auth_source, MONGOC_QUERY_SECONDARY_OK, &command); parts.prohibit_lsid = true; - ret = mongoc_cluster_run_command_parts ( - cluster, server_stream, &parts, &reply, error); + ret = mongoc_cluster_run_command_parts (cluster, server_stream, &parts, &reply, error); if (!ret) { /* error->message is already set */ @@ -1263,10 +1158,7 @@ _mongoc_cluster_auth_node_plain (mongoc_cluster_t *cluster, bson_free (str); if (buflen == -1) { - bson_set_error (error, - MONGOC_ERROR_CLIENT, - MONGOC_ERROR_CLIENT_AUTHENTICATE, - "failed base64 encoding message"); + bson_set_error (error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_AUTHENTICATE, "failed base64 encoding message"); return false; } @@ -1275,16 +1167,14 @@ _mongoc_cluster_auth_node_plain (mongoc_cluster_t *cluster, bson_append_utf8 (&b, "payload", 7, (const char *) buf, buflen); BSON_APPEND_INT32 (&b, "autoAuthorize", 1); - mongoc_cmd_parts_init ( - &parts, cluster->client, "$external", MONGOC_QUERY_SECONDARY_OK, &b); + mongoc_cmd_parts_init (&parts, cluster->client, "$external", MONGOC_QUERY_SECONDARY_OK, &b); parts.prohibit_lsid = true; td = mc_tpld_take_ref (cluster->client->topology); server_stream = _mongoc_cluster_create_server_stream (td.ptr, sd, stream); mc_tpld_drop_ref (&td); - ret = mongoc_cluster_run_command_parts ( - cluster, server_stream, &parts, &reply, error); + ret = mongoc_cluster_run_command_parts (cluster, server_stream, &parts, &reply, error); mongoc_server_stream_cleanup (server_stream); if (!ret) { /* error->message is already set */ @@ -1330,8 +1220,7 @@ _mongoc_cluster_get_auth_cmd_x509 (const mongoc_uri_t *uri, return false; } - username_from_subject = - mongoc_ssl_extract_subject (ssl_opts->pem_file, ssl_opts->pem_pwd); + username_from_subject = mongoc_ssl_extract_subject (ssl_opts->pem_file, ssl_opts->pem_pwd); if (!username_from_subject) { bson_set_error (error, MONGOC_ERROR_CLIENT, @@ -1346,10 +1235,7 @@ _mongoc_cluster_get_auth_cmd_x509 (const mongoc_uri_t *uri, bson_init (cmd); BSON_APPEND_INT32 (cmd, "authenticate", 1); BSON_APPEND_UTF8 (cmd, "mechanism", "MONGODB-X509"); - BSON_APPEND_UTF8 (cmd, - "user", - username_from_uri ? username_from_uri - : username_from_subject); + BSON_APPEND_UTF8 (cmd, "user", username_from_uri ? username_from_uri : username_from_subject); bson_free (username_from_subject); @@ -1382,20 +1268,17 @@ _mongoc_cluster_auth_node_x509 (mongoc_cluster_t *cluster, BSON_ASSERT (cluster); BSON_ASSERT (stream); - if (!_mongoc_cluster_get_auth_cmd_x509 ( - cluster->uri, &cluster->client->ssl_opts, &cmd, error)) { + if (!_mongoc_cluster_get_auth_cmd_x509 (cluster->uri, &cluster->client->ssl_opts, &cmd, error)) { return false; } - mongoc_cmd_parts_init ( - &parts, cluster->client, "$external", MONGOC_QUERY_SECONDARY_OK, &cmd); + mongoc_cmd_parts_init (&parts, cluster->client, "$external", MONGOC_QUERY_SECONDARY_OK, &cmd); parts.prohibit_lsid = true; td = mc_tpld_take_ref (cluster->client->topology); server_stream = _mongoc_cluster_create_server_stream (td.ptr, sd, stream); mc_tpld_drop_ref (&td); - ret = mongoc_cluster_run_command_parts ( - cluster, server_stream, &parts, &reply, error); + ret = mongoc_cluster_run_command_parts (cluster, server_stream, &parts, &reply, error); mongoc_server_stream_cleanup (server_stream); if (!ret) { /* error->message is already set */ @@ -1426,9 +1309,7 @@ mongoc_cluster_uses_loadbalanced (const mongoc_cluster_t *cluster) #ifdef MONGOC_ENABLE_CRYPTO void -_mongoc_cluster_init_scram (const mongoc_cluster_t *cluster, - mongoc_scram_t *scram, - mongoc_crypto_hash_algorithm_t algo) +_mongoc_cluster_init_scram (const mongoc_cluster_t *cluster, mongoc_scram_t *scram, mongoc_crypto_hash_algorithm_t algo) { _mongoc_uri_init_scram (cluster->uri, scram, algo); } @@ -1462,8 +1343,7 @@ _mongoc_cluster_get_auth_cmd_scram (mongoc_crypto_hash_algorithm_t algo, uint32_t buflen = 0; bson_t options; - if (!_mongoc_scram_step ( - scram, buf, buflen, buf, sizeof buf, &buflen, error)) { + if (!_mongoc_scram_step (scram, buf, buflen, buf, sizeof buf, &buflen, error)) { return false; } @@ -1510,34 +1390,28 @@ _mongoc_cluster_get_auth_cmd_scram (mongoc_crypto_hash_algorithm_t algo, */ static bool -_mongoc_cluster_run_scram_command ( - mongoc_cluster_t *cluster, - mongoc_stream_t *stream, - const mongoc_server_description_t *handshake_sd, - const bson_t *cmd, - bson_t *reply, - bson_error_t *error) +_mongoc_cluster_run_scram_command (mongoc_cluster_t *cluster, + mongoc_stream_t *stream, + const mongoc_server_description_t *handshake_sd, + const bson_t *cmd, + bson_t *reply, + bson_error_t *error) { mongoc_cmd_parts_t parts; mongoc_server_stream_t *server_stream; const char *auth_source; - mc_shared_tpld td = - mc_tpld_take_ref (BSON_ASSERT_PTR_INLINE (cluster)->client->topology); + mc_shared_tpld td = mc_tpld_take_ref (BSON_ASSERT_PTR_INLINE (cluster)->client->topology); - if (!(auth_source = mongoc_uri_get_auth_source (cluster->uri)) || - (*auth_source == '\0')) { + if (!(auth_source = mongoc_uri_get_auth_source (cluster->uri)) || (*auth_source == '\0')) { auth_source = "admin"; } - mongoc_cmd_parts_init ( - &parts, cluster->client, auth_source, MONGOC_QUERY_SECONDARY_OK, cmd); + mongoc_cmd_parts_init (&parts, cluster->client, auth_source, MONGOC_QUERY_SECONDARY_OK, cmd); parts.prohibit_lsid = true; - server_stream = - _mongoc_cluster_create_server_stream (td.ptr, handshake_sd, stream); + server_stream = _mongoc_cluster_create_server_stream (td.ptr, handshake_sd, stream); mc_tpld_drop_ref (&td); - if (!mongoc_cluster_run_command_parts ( - cluster, server_stream, &parts, reply, error)) { + if (!mongoc_cluster_run_command_parts (cluster, server_stream, &parts, reply, error)) { mongoc_server_stream_cleanup (server_stream); bson_destroy (reply); @@ -1573,14 +1447,13 @@ _mongoc_cluster_run_scram_command ( */ static bool -_mongoc_cluster_auth_scram_start ( - mongoc_cluster_t *cluster, - mongoc_stream_t *stream, - const mongoc_server_description_t *handshake_sd, - mongoc_crypto_hash_algorithm_t algo, - mongoc_scram_t *scram, - bson_t *reply, - bson_error_t *error) +_mongoc_cluster_auth_scram_start (mongoc_cluster_t *cluster, + mongoc_stream_t *stream, + const mongoc_server_description_t *handshake_sd, + mongoc_crypto_hash_algorithm_t algo, + mongoc_scram_t *scram, + bson_t *reply, + bson_error_t *error) { bson_t cmd; @@ -1594,8 +1467,7 @@ _mongoc_cluster_auth_scram_start ( return false; } - if (!_mongoc_cluster_run_scram_command ( - cluster, stream, handshake_sd, &cmd, reply, error)) { + if (!_mongoc_cluster_run_scram_command (cluster, stream, handshake_sd, &cmd, reply, error)) { bson_destroy (&cmd); return false; @@ -1650,10 +1522,7 @@ _mongoc_cluster_scram_handle_reply (mongoc_scram_t *scram, if (is_done) { if (scram->step < 2) { /* Prior to step 2, we haven't even received server proof. */ - bson_set_error (error, - MONGOC_ERROR_CLIENT, - MONGOC_ERROR_CLIENT_AUTHENTICATE, - "Incorrect step for 'done'"); + bson_set_error (error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_AUTHENTICATE, "Incorrect step for 'done'"); return false; } *done = true; @@ -1662,35 +1531,26 @@ _mongoc_cluster_scram_handle_reply (mongoc_scram_t *scram, } } - if (!bson_iter_init_find (&iter, reply, "conversationId") || - !BSON_ITER_HOLDS_INT32 (&iter) || - !(*conv_id = bson_iter_int32 (&iter)) || - !bson_iter_init_find (&iter, reply, "payload") || + if (!bson_iter_init_find (&iter, reply, "conversationId") || !BSON_ITER_HOLDS_INT32 (&iter) || + !(*conv_id = bson_iter_int32 (&iter)) || !bson_iter_init_find (&iter, reply, "payload") || !BSON_ITER_HOLDS_BINARY (&iter)) { const char *errmsg = "Received invalid SCRAM reply from MongoDB server."; MONGOC_DEBUG ("SCRAM: authentication failed"); - if (bson_iter_init_find (&iter, reply, "errmsg") && - BSON_ITER_HOLDS_UTF8 (&iter)) { + if (bson_iter_init_find (&iter, reply, "errmsg") && BSON_ITER_HOLDS_UTF8 (&iter)) { errmsg = bson_iter_utf8 (&iter, NULL); } - bson_set_error (error, - MONGOC_ERROR_CLIENT, - MONGOC_ERROR_CLIENT_AUTHENTICATE, - "%s", - errmsg); + bson_set_error (error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_AUTHENTICATE, "%s", errmsg); return false; } bson_iter_binary (&iter, &btype, buflen, (const uint8_t **) &tmpstr); if (*buflen > bufmax) { - bson_set_error (error, - MONGOC_ERROR_CLIENT, - MONGOC_ERROR_CLIENT_AUTHENTICATE, - "SCRAM reply from MongoDB is too large."); + bson_set_error ( + error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_AUTHENTICATE, "SCRAM reply from MongoDB is too large."); return false; } @@ -1719,13 +1579,12 @@ _mongoc_cluster_scram_handle_reply (mongoc_scram_t *scram, */ static bool -_mongoc_cluster_auth_scram_continue ( - mongoc_cluster_t *cluster, - mongoc_stream_t *stream, - const mongoc_server_description_t *handshake_sd, - mongoc_scram_t *scram, - const bson_t *sasl_start_reply, - bson_error_t *error) +_mongoc_cluster_auth_scram_continue (mongoc_cluster_t *cluster, + mongoc_stream_t *stream, + const mongoc_server_description_t *handshake_sd, + mongoc_scram_t *scram, + const bson_t *sasl_start_reply, + bson_error_t *error) { bson_t cmd; uint8_t buf[4096] = {0}; @@ -1734,20 +1593,13 @@ _mongoc_cluster_auth_scram_continue ( bool done = false; bson_t reply_local; - if (!_mongoc_cluster_scram_handle_reply (scram, - sasl_start_reply, - &done, - &conv_id, - buf, - sizeof buf, - &buflen, - error)) { + if (!_mongoc_cluster_scram_handle_reply ( + scram, sasl_start_reply, &done, &conv_id, buf, sizeof buf, &buflen, error)) { return false; } for (;;) { - if (!_mongoc_scram_step ( - scram, buf, buflen, buf, sizeof buf, &buflen, error)) { + if (!_mongoc_scram_step (scram, buf, buflen, buf, sizeof buf, &buflen, error)) { return false; } @@ -1763,22 +1615,14 @@ _mongoc_cluster_auth_scram_continue ( TRACE ("SCRAM: authenticating (step %d)", scram->step); - if (!_mongoc_cluster_run_scram_command ( - cluster, stream, handshake_sd, &cmd, &reply_local, error)) { + if (!_mongoc_cluster_run_scram_command (cluster, stream, handshake_sd, &cmd, &reply_local, error)) { bson_destroy (&cmd); return false; } bson_destroy (&cmd); - if (!_mongoc_cluster_scram_handle_reply (scram, - &reply_local, - &done, - &conv_id, - buf, - sizeof buf, - &buflen, - error)) { + if (!_mongoc_cluster_scram_handle_reply (scram, &reply_local, &done, &conv_id, buf, sizeof buf, &buflen, error)) { bson_destroy (&reply_local); return false; } @@ -1828,13 +1672,11 @@ _mongoc_cluster_auth_node_scram (mongoc_cluster_t *cluster, _mongoc_cluster_init_scram (cluster, &scram, algo); - if (!_mongoc_cluster_auth_scram_start ( - cluster, stream, handshake_sd, algo, &scram, &reply, error)) { + if (!_mongoc_cluster_auth_scram_start (cluster, stream, handshake_sd, algo, &scram, &reply, error)) { goto failure; } - if (!_mongoc_cluster_auth_scram_continue ( - cluster, stream, handshake_sd, &scram, &reply, error)) { + if (!_mongoc_cluster_auth_scram_continue (cluster, stream, handshake_sd, &scram, &reply, error)) { bson_destroy (&reply); goto failure; @@ -1867,8 +1709,7 @@ _mongoc_cluster_auth_node_scram_sha_1 (mongoc_cluster_t *cluster, "libmongoc built with ENABLE_SSL"); return false; #else - return _mongoc_cluster_auth_node_scram ( - cluster, stream, sd, MONGOC_CRYPTO_ALGORITHM_SHA_1, error); + return _mongoc_cluster_auth_node_scram (cluster, stream, sd, MONGOC_CRYPTO_ALGORITHM_SHA_1, error); #endif } @@ -1886,8 +1727,7 @@ _mongoc_cluster_auth_node_scram_sha_256 (mongoc_cluster_t *cluster, "libmongoc built with ENABLE_SSL"); return false; #else - return _mongoc_cluster_auth_node_scram ( - cluster, stream, sd, MONGOC_CRYPTO_ALGORITHM_SHA_256, error); + return _mongoc_cluster_auth_node_scram (cluster, stream, sd, MONGOC_CRYPTO_ALGORITHM_SHA_256, error); #endif } @@ -1908,12 +1748,11 @@ _mongoc_cluster_auth_node_scram_sha_256 (mongoc_cluster_t *cluster, */ static bool -_mongoc_cluster_auth_node ( - mongoc_cluster_t *cluster, - mongoc_stream_t *stream, - mongoc_server_description_t *sd, - const mongoc_handshake_sasl_supported_mechs_t *sasl_supported_mechs, - bson_error_t *error) +_mongoc_cluster_auth_node (mongoc_cluster_t *cluster, + mongoc_stream_t *stream, + mongoc_server_description_t *sd, + const mongoc_handshake_sasl_supported_mechs_t *sasl_supported_mechs, + bson_error_t *error) { bool ret = false; const char *mechanism; @@ -1946,8 +1785,7 @@ _mongoc_cluster_auth_node ( } else if (0 == strcasecmp (mechanism, "SCRAM-SHA-1")) { ret = _mongoc_cluster_auth_node_scram_sha_1 (cluster, stream, sd, error); } else if (0 == strcasecmp (mechanism, "SCRAM-SHA-256")) { - ret = - _mongoc_cluster_auth_node_scram_sha_256 (cluster, stream, sd, error); + ret = _mongoc_cluster_auth_node_scram_sha_256 (cluster, stream, sd, error); } else if (0 == strcasecmp (mechanism, "GSSAPI")) { ret = _mongoc_cluster_auth_node_sasl (cluster, stream, sd, error); } else if (0 == strcasecmp (mechanism, "PLAIN")) { @@ -1994,8 +1832,7 @@ mongoc_cluster_disconnect_node (mongoc_cluster_t *cluster, uint32_t server_id) if (topology->single_threaded) { mongoc_topology_scanner_node_t *scanner_node; - scanner_node = - mongoc_topology_scanner_get_node (topology->scanner, server_id); + scanner_node = mongoc_topology_scanner_get_node (topology->scanner, server_id); /* might never actually have connected */ if (scanner_node && scanner_node->stream) { @@ -2030,8 +1867,7 @@ _mongoc_cluster_node_dtor (void *data_, void *ctx_) } static mongoc_cluster_node_t * -_mongoc_cluster_node_new (mongoc_stream_t *stream, - const char *connection_address) +_mongoc_cluster_node_new (mongoc_stream_t *stream, const char *connection_address) { mongoc_cluster_node_t *node; @@ -2051,16 +1887,14 @@ _mongoc_cluster_node_new (mongoc_stream_t *stream, } static bool -_mongoc_cluster_finish_speculative_auth ( - mongoc_cluster_t *cluster, - mongoc_stream_t *stream, - mongoc_server_description_t *handshake_sd, - bson_t *speculative_auth_response, - mongoc_scram_t *scram, - bson_error_t *error) -{ - const char *mechanism = - _mongoc_topology_scanner_get_speculative_auth_mechanism (cluster->uri); +_mongoc_cluster_finish_speculative_auth (mongoc_cluster_t *cluster, + mongoc_stream_t *stream, + mongoc_server_description_t *handshake_sd, + bson_t *speculative_auth_response, + mongoc_scram_t *scram, + bson_error_t *error) +{ + const char *mechanism = _mongoc_topology_scanner_get_speculative_auth_mechanism (cluster->uri); bool ret = false; bool auth_handled = false; @@ -2085,8 +1919,7 @@ _mongoc_cluster_finish_speculative_auth ( #endif #ifdef MONGOC_ENABLE_CRYPTO - if (strcasecmp (mechanism, "SCRAM-SHA-1") == 0 || - strcasecmp (mechanism, "SCRAM-SHA-256") == 0) { + if (strcasecmp (mechanism, "SCRAM-SHA-1") == 0 || strcasecmp (mechanism, "SCRAM-SHA-256") == 0) { /* Don't attempt authentication if scram objects have advanced past * saslStart */ if (scram->step != 1) { @@ -2095,12 +1928,8 @@ _mongoc_cluster_finish_speculative_auth ( auth_handled = true; - ret = _mongoc_cluster_auth_scram_continue (cluster, - stream, - handshake_sd, - scram, - speculative_auth_response, - error); + ret = + _mongoc_cluster_auth_scram_continue (cluster, stream, handshake_sd, scram, speculative_auth_response, error); } #endif @@ -2165,8 +1994,7 @@ _cluster_add_node (mongoc_cluster_t *cluster, stream = _mongoc_client_create_stream (cluster->client, host, error); if (!stream) { - MONGOC_WARNING ( - "Failed connection to %s (%s)", host->host_and_port, error->message); + MONGOC_WARNING ("Failed connection to %s (%s)", host->host_and_port, error->message); GOTO (error); /* TODO CDRIVER-3654: if this is a non-timeout network error and the * generation is not stale, mark the server unknown and increment the @@ -2176,37 +2004,21 @@ _cluster_add_node (mongoc_cluster_t *cluster, /* take critical fields from a fresh hello */ cluster_node = _mongoc_cluster_node_new (stream, host->host_and_port); - handshake_sd = _cluster_run_hello (cluster, - cluster_node, - server_id, - &scram, - &speculative_auth_response, - error); + handshake_sd = _cluster_run_hello (cluster, cluster_node, server_id, &scram, &speculative_auth_response, error); if (!handshake_sd) { GOTO (error); } - _mongoc_handshake_parse_sasl_supported_mechs ( - &handshake_sd->last_hello_response, &sasl_supported_mechs); + _mongoc_handshake_parse_sasl_supported_mechs (&handshake_sd->last_hello_response, &sasl_supported_mechs); if (cluster->requires_auth) { /* Complete speculative authentication */ - bool is_auth = - _mongoc_cluster_finish_speculative_auth (cluster, - stream, - handshake_sd, - &speculative_auth_response, - &scram, - error); - - if (!is_auth && !_mongoc_cluster_auth_node (cluster, - cluster_node->stream, - handshake_sd, - &sasl_supported_mechs, - error)) { - MONGOC_WARNING ("Failed authentication to %s (%s)", - host->host_and_port, - error->message); + bool is_auth = _mongoc_cluster_finish_speculative_auth ( + cluster, stream, handshake_sd, &speculative_auth_response, &scram, error); + + if (!is_auth && + !_mongoc_cluster_auth_node (cluster, cluster_node->stream, handshake_sd, &sasl_supported_mechs, error)) { + MONGOC_WARNING ("Failed authentication to %s (%s)", host->host_and_port, error->message); mongoc_server_description_destroy (handshake_sd); GOTO (error); } @@ -2217,8 +2029,8 @@ _cluster_add_node (mongoc_cluster_t *cluster, /* Copy the latest connection pool generation. * TODO (CDRIVER-4078) do not store the generation counter on the server * description */ - handshake_sd->generation = _mongoc_topology_get_connection_pool_generation ( - td, server_id, &handshake_sd->service_id); + handshake_sd->generation = + _mongoc_topology_get_connection_pool_generation (td, server_id, &handshake_sd->service_id); bson_destroy (&speculative_auth_response); mongoc_set_add (cluster->nodes, server_id, cluster_node); @@ -2246,9 +2058,7 @@ _cluster_add_node (mongoc_cluster_t *cluster, } static void -node_not_found (const mongoc_topology_description_t *td, - uint32_t server_id, - bson_error_t *error /* OUT */) +node_not_found (const mongoc_topology_description_t *td, uint32_t server_id, bson_error_t *error /* OUT */) { mongoc_server_description_t const *sd; @@ -2306,11 +2116,9 @@ _try_get_server_stream (mongoc_cluster_t *cluster, { if (cluster->client->topology->single_threaded) { /* in the single-threaded use case we share topology's streams */ - return _cluster_fetch_stream_single ( - cluster, td, server_id, reconnect_ok, error); + return _cluster_fetch_stream_single (cluster, td, server_id, reconnect_ok, error); } else { - return _cluster_fetch_stream_pooled ( - cluster, td, server_id, reconnect_ok, error); + return _cluster_fetch_stream_pooled (cluster, td, server_id, reconnect_ok, error); } } @@ -2322,8 +2130,7 @@ _mongoc_cluster_stream_for_server (mongoc_cluster_t *cluster, bson_t *reply, bson_error_t *error /* OUT */) { - mongoc_topology_t *const topology = - BSON_ASSERT_PTR_INLINE (cluster)->client->topology; + mongoc_topology_t *const topology = BSON_ASSERT_PTR_INLINE (cluster)->client->topology; mongoc_server_stream_t *ret_server_stream; bson_error_t err_local; /* if fetch_stream fails we need a place to receive error details and pass @@ -2336,8 +2143,7 @@ _mongoc_cluster_stream_for_server (mongoc_cluster_t *cluster, td = mc_tpld_take_ref (topology); - ret_server_stream = _try_get_server_stream ( - cluster, td.ptr, server_id, reconnect_ok, err_ptr); + ret_server_stream = _try_get_server_stream (cluster, td.ptr, server_id, reconnect_ok, err_ptr); if (!ret_server_stream) { /* TODO CDRIVER-3654. A null server stream could be due to: @@ -2368,18 +2174,15 @@ _mongoc_cluster_stream_for_server (mongoc_cluster_t *cluster, goto done; } - mongoc_topology_description_invalidate_server ( - tdmod.new_td, server_id, err_ptr); + mongoc_topology_description_invalidate_server (tdmod.new_td, server_id, err_ptr); mongoc_cluster_disconnect_node (cluster, server_id); /* This is not load balanced mode, so there are no service IDs associated * with connections. Pass kZeroServiceId to clear the entire connection * pool to this server. */ - _mongoc_topology_description_clear_connection_pool ( - tdmod.new_td, server_id, &kZeroServiceId); + _mongoc_topology_description_clear_connection_pool (tdmod.new_td, server_id, &kZeroServiceId); if (!topology->single_threaded) { - _mongoc_topology_background_monitoring_cancel_check (topology, - server_id); + _mongoc_topology_background_monitoring_cancel_check (topology, server_id); } mc_tpld_modify_commit (tdmod); ret_server_stream = NULL; @@ -2437,8 +2240,7 @@ mongoc_cluster_stream_for_server (mongoc_cluster_t *cluster, mongoc_server_stream_t *const server_stream = - _mongoc_cluster_stream_for_server ( - cluster, server_id, reconnect_ok, cs, reply, error); + _mongoc_cluster_stream_for_server (cluster, server_id, reconnect_ok, cs, reply, error); if (_in_sharded_txn (cs)) { _mongoc_client_session_pin (cs, server_id); @@ -2466,15 +2268,11 @@ _cluster_fetch_stream_single (mongoc_cluster_t *cluster, mongoc_topology_scanner_node_t *scanner_node; char *address; - scanner_node = mongoc_topology_scanner_get_node ( - cluster->client->topology->scanner, server_id); + scanner_node = mongoc_topology_scanner_get_node (cluster->client->topology->scanner, server_id); /* This could happen if a user explicitly passes a bad server id. */ if (!scanner_node) { - bson_set_error (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Could not find server with id: %d", - server_id); + bson_set_error ( + error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Could not find server with id: %d", server_id); return NULL; } @@ -2490,12 +2288,10 @@ _cluster_fetch_stream_single (mongoc_cluster_t *cluster, } if (scanner_node->stream) { - handshake_sd = - mongoc_server_description_new_copy (scanner_node->handshake_sd); + handshake_sd = mongoc_server_description_new_copy (scanner_node->handshake_sd); } else { if (!reconnect_ok) { - stream_not_found ( - td, server_id, scanner_node->host.host_and_port, error); + stream_not_found (td, server_id, scanner_node->host.host_and_port, error); return NULL; } @@ -2507,8 +2303,7 @@ _cluster_fetch_stream_single (mongoc_cluster_t *cluster, return NULL; } - scanner_node = mongoc_topology_scanner_get_node ( - cluster->client->topology->scanner, server_id); + scanner_node = mongoc_topology_scanner_get_node (cluster->client->topology->scanner, server_id); if (!scanner_node || !scanner_node->stream) { stream_not_found (td, server_id, address, error); @@ -2517,8 +2312,7 @@ _cluster_fetch_stream_single (mongoc_cluster_t *cluster, } bson_free (address); - handshake_sd = - mongoc_server_description_new_copy (scanner_node->handshake_sd); + handshake_sd = mongoc_server_description_new_copy (scanner_node->handshake_sd); } if (handshake_sd->type == MONGOC_SERVER_UNKNOWN) { @@ -2530,13 +2324,12 @@ _cluster_fetch_stream_single (mongoc_cluster_t *cluster, /* stream open but not auth'ed: first use since connect or reconnect */ if (cluster->requires_auth && !scanner_node->has_auth) { /* Complete speculative authentication */ - bool has_speculative_auth = _mongoc_cluster_finish_speculative_auth ( - cluster, - scanner_node->stream, - handshake_sd, - &scanner_node->speculative_auth_response, - &scanner_node->scram, - &handshake_sd->error); + bool has_speculative_auth = _mongoc_cluster_finish_speculative_auth (cluster, + scanner_node->stream, + handshake_sd, + &scanner_node->speculative_auth_response, + &scanner_node->scram, + &handshake_sd->error); #ifdef MONGOC_ENABLE_CRYPTO _mongoc_scram_destroy (&scanner_node->scram); @@ -2549,11 +2342,8 @@ _cluster_fetch_stream_single (mongoc_cluster_t *cluster, } if (!has_speculative_auth && - !_mongoc_cluster_auth_node (cluster, - scanner_node->stream, - handshake_sd, - &scanner_node->sasl_supported_mechs, - &handshake_sd->error)) { + !_mongoc_cluster_auth_node ( + cluster, scanner_node->stream, handshake_sd, &scanner_node->sasl_supported_mechs, &handshake_sd->error)) { *error = handshake_sd->error; mongoc_server_description_destroy (handshake_sd); return NULL; @@ -2565,8 +2355,8 @@ _cluster_fetch_stream_single (mongoc_cluster_t *cluster, /* Copy the latest connection pool generation. * TODO (CDRIVER-4078) do not store the generation counter on the server * description */ - handshake_sd->generation = _mongoc_topology_get_connection_pool_generation ( - td, server_id, &handshake_sd->service_id); + handshake_sd->generation = + _mongoc_topology_get_connection_pool_generation (td, server_id, &handshake_sd->service_id); return mongoc_server_stream_new (td, handshake_sd, scanner_node->stream); } @@ -2587,12 +2377,10 @@ _cluster_fetch_stream_single (mongoc_cluster_t *cluster, */ bool -mongoc_cluster_stream_valid (mongoc_cluster_t *cluster, - mongoc_server_stream_t *server_stream) +mongoc_cluster_stream_valid (mongoc_cluster_t *cluster, mongoc_server_stream_t *server_stream) { mongoc_server_stream_t *tmp_stream = NULL; - mongoc_topology_t *topology = - BSON_ASSERT_PTR_INLINE (cluster)->client->topology; + mongoc_topology_t *topology = BSON_ASSERT_PTR_INLINE (cluster)->client->topology; const mongoc_server_description_t *sd; bool ret = false; bson_error_t error; @@ -2602,8 +2390,7 @@ mongoc_cluster_stream_valid (mongoc_cluster_t *cluster, goto done; } - tmp_stream = mongoc_cluster_stream_for_server ( - cluster, server_stream->sd->id, false, NULL, NULL, NULL); + tmp_stream = mongoc_cluster_stream_for_server (cluster, server_stream->sd->id, false, NULL, NULL, NULL); if (!tmp_stream || tmp_stream->stream != server_stream->stream) { /* stream was freed, or has changed. */ goto done; @@ -2611,12 +2398,9 @@ mongoc_cluster_stream_valid (mongoc_cluster_t *cluster, /* Check that the server stream is still valid for the given server, and that * the server is still registered. */ - sd = mongoc_topology_description_server_by_id_const ( - td.ptr, server_stream->sd->id, &error); - if (!sd || - server_stream->sd->generation < - _mongoc_topology_get_connection_pool_generation ( - td.ptr, server_stream->sd->id, &server_stream->sd->service_id)) { + sd = mongoc_topology_description_server_by_id_const (td.ptr, server_stream->sd->id, &error); + if (!sd || server_stream->sd->generation < _mongoc_topology_get_connection_pool_generation ( + td.ptr, server_stream->sd->id, &server_stream->sd->service_id)) { /* No server description, or the pool has been cleared. */ goto done; } @@ -2629,13 +2413,11 @@ mongoc_cluster_stream_valid (mongoc_cluster_t *cluster, } mongoc_server_stream_t * -_mongoc_cluster_create_server_stream ( - mongoc_topology_description_t const *td, - const mongoc_server_description_t *handshake_sd, - mongoc_stream_t *stream) +_mongoc_cluster_create_server_stream (mongoc_topology_description_t const *td, + const mongoc_server_description_t *handshake_sd, + mongoc_stream_t *stream) { - mongoc_server_description_t *const sd = - mongoc_server_description_new_copy (handshake_sd); + mongoc_server_description_t *const sd = mongoc_server_description_new_copy (handshake_sd); /* can't just use mongoc_topology_server_by_id(), since we must hold the * lock while copying topology->shared_descr.ptr->logical_time below */ return mongoc_server_stream_new (td, sd, stream); @@ -2653,8 +2435,7 @@ _cluster_fetch_stream_pooled (mongoc_cluster_t *cluster, mongoc_server_description_t const *sd; bool has_server_description = false; - cluster_node = - (mongoc_cluster_node_t *) mongoc_set_get (cluster->nodes, server_id); + cluster_node = (mongoc_cluster_node_t *) mongoc_set_get (cluster->nodes, server_id); sd = mongoc_topology_description_server_by_id_const (td, server_id, error); if (sd) { @@ -2666,11 +2447,9 @@ _cluster_fetch_stream_pooled (mongoc_cluster_t *cluster, BSON_ASSERT (cluster_node->stream); connection_pool_generation = - _mongoc_topology_get_connection_pool_generation ( - td, server_id, &cluster_node->handshake_sd->service_id); + _mongoc_topology_get_connection_pool_generation (td, server_id, &cluster_node->handshake_sd->service_id); - if (!has_server_description || - cluster_node->handshake_sd->generation < connection_pool_generation) { + if (!has_server_description || cluster_node->handshake_sd->generation < connection_pool_generation) { /* Since the stream was created, connections to this server were * invalidated. * This may have happened if: @@ -2681,8 +2460,7 @@ _cluster_fetch_stream_pooled (mongoc_cluster_t *cluster, */ mongoc_cluster_disconnect_node (cluster, server_id); } else { - return _mongoc_cluster_create_server_stream ( - td, cluster_node->handshake_sd, cluster_node->stream); + return _mongoc_cluster_create_server_stream (td, cluster_node->handshake_sd, cluster_node->stream); } } @@ -2694,8 +2472,7 @@ _cluster_fetch_stream_pooled (mongoc_cluster_t *cluster, cluster_node = _cluster_add_node (cluster, td, server_id, error); if (cluster_node) { - return _mongoc_cluster_create_server_stream ( - td, cluster_node->handshake_sd, cluster_node->stream); + return _mongoc_cluster_create_server_stream (td, cluster_node->handshake_sd, cluster_node->stream); } else { return NULL; } @@ -2721,9 +2498,7 @@ _cluster_fetch_stream_pooled (mongoc_cluster_t *cluster, */ void -mongoc_cluster_init (mongoc_cluster_t *cluster, - const mongoc_uri_t *uri, - void *client) +mongoc_cluster_init (mongoc_cluster_t *cluster, const mongoc_uri_t *uri, void *client) { ENTRY; @@ -2734,16 +2509,13 @@ mongoc_cluster_init (mongoc_cluster_t *cluster, cluster->uri = mongoc_uri_copy (uri); cluster->client = (mongoc_client_t *) client; - cluster->requires_auth = - (mongoc_uri_get_username (uri) || mongoc_uri_get_auth_mechanism (uri)); + cluster->requires_auth = (mongoc_uri_get_username (uri) || mongoc_uri_get_auth_mechanism (uri)); - cluster->sockettimeoutms = mongoc_uri_get_option_as_int32 ( - uri, MONGOC_URI_SOCKETTIMEOUTMS, MONGOC_DEFAULT_SOCKETTIMEOUTMS); + cluster->sockettimeoutms = + mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_SOCKETTIMEOUTMS, MONGOC_DEFAULT_SOCKETTIMEOUTMS); cluster->socketcheckintervalms = - mongoc_uri_get_option_as_int32 (uri, - MONGOC_URI_SOCKETCHECKINTERVALMS, - MONGOC_TOPOLOGY_SOCKET_CHECK_INTERVAL_MS); + mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_SOCKETCHECKINTERVALMS, MONGOC_TOPOLOGY_SOCKET_CHECK_INTERVAL_MS); /* TODO for single-threaded case we don't need this */ cluster->nodes = mongoc_set_new (8, _mongoc_cluster_node_dtor, NULL); @@ -2808,15 +2580,13 @@ _mongoc_cluster_select_server_id (mongoc_client_session_t *cs, if (_in_sharded_txn (cs)) { server_id = cs->server_id; if (!server_id) { - server_id = mongoc_topology_select_server_id ( - topology, optype, read_prefs, must_use_primary, ds, error); + server_id = mongoc_topology_select_server_id (topology, optype, read_prefs, must_use_primary, ds, error); if (server_id) { _mongoc_client_session_pin (cs, server_id); } } } else { - server_id = mongoc_topology_select_server_id ( - topology, optype, read_prefs, must_use_primary, ds, error); + server_id = mongoc_topology_select_server_id (topology, optype, read_prefs, must_use_primary, ds, error); /* Transactions Spec: Additionally, any non-transaction operation using a * pinned ClientSession MUST unpin the session and the operation MUST * perform normal server selection. */ @@ -2871,8 +2641,7 @@ _mongoc_cluster_stream_for_optype (mongoc_cluster_t *cluster, BSON_ASSERT (cluster); - server_id = _mongoc_cluster_select_server_id ( - cs, topology, optype, read_prefs, &must_use_primary, ds, error); + server_id = _mongoc_cluster_select_server_id (cs, topology, optype, read_prefs, &must_use_primary, ds, error); if (!server_id) { if (reply) { @@ -2884,8 +2653,7 @@ _mongoc_cluster_stream_for_optype (mongoc_cluster_t *cluster, if (!mongoc_cluster_check_interval (cluster, server_id)) { /* Server Selection Spec: try once more */ - server_id = _mongoc_cluster_select_server_id ( - cs, topology, optype, read_prefs, &must_use_primary, ds, error); + server_id = _mongoc_cluster_select_server_id (cs, topology, optype, read_prefs, &must_use_primary, ds, error); if (!server_id) { if (reply) { @@ -2899,12 +2667,8 @@ _mongoc_cluster_stream_for_optype (mongoc_cluster_t *cluster, bson_t first_reply; bson_error_t first_error = {0}; - server_stream = _mongoc_cluster_stream_for_server (cluster, - server_id, - true /* reconnect_ok */, - cs, - &first_reply, - &first_error); + server_stream = + _mongoc_cluster_stream_for_server (cluster, server_id, true /* reconnect_ok */, cs, &first_reply, &first_error); if (server_stream) { server_stream->must_use_primary = must_use_primary; @@ -2913,20 +2677,14 @@ _mongoc_cluster_stream_for_optype (mongoc_cluster_t *cluster, // Important: authentication errors are also considered retryable even if // they not considered a network error. - const bool retryable_error = _mongoc_error_is_network (&first_error) || - _mongoc_error_is_auth (&first_error); + const bool retryable_error = _mongoc_error_is_network (&first_error) || _mongoc_error_is_auth (&first_error); if (is_retryable && retryable_error) { bson_t retry_reply; bson_error_t retry_error = {0}; - server_stream = - _mongoc_cluster_stream_for_server (cluster, - server_id, - true /* reconnect_ok */, - cs, - &retry_reply, - &retry_error); + server_stream = _mongoc_cluster_stream_for_server ( + cluster, server_id, true /* reconnect_ok */, cs, &retry_reply, &retry_error); if (server_stream) { server_stream->must_use_primary = must_use_primary; @@ -2979,17 +2737,11 @@ mongoc_cluster_stream_for_reads (mongoc_cluster_t *cluster, // Retryable Reads Spec: This boolean option determines whether retryable // behavior will be applied to all read operations executed within the // MongoClient. - const bool is_retryable = mongoc_uri_get_option_as_bool ( - cluster->uri, MONGOC_URI_RETRYREADS, MONGOC_DEFAULT_RETRYREADS); + const bool is_retryable = + mongoc_uri_get_option_as_bool (cluster->uri, MONGOC_URI_RETRYREADS, MONGOC_DEFAULT_RETRYREADS); - return _mongoc_cluster_stream_for_optype (cluster, - MONGOC_SS_READ, - prefs_override, - cs, - is_retryable, - ds, - reply, - error); + return _mongoc_cluster_stream_for_optype ( + cluster, MONGOC_SS_READ, prefs_override, cs, is_retryable, ds, reply, error); } mongoc_server_stream_t * @@ -2999,35 +2751,27 @@ mongoc_cluster_stream_for_writes (mongoc_cluster_t *cluster, bson_t *reply, bson_error_t *error) { - const bool is_retryable = mongoc_uri_get_option_as_bool ( - cluster->uri, MONGOC_URI_RETRYWRITES, MONGOC_DEFAULT_RETRYWRITES); + const bool is_retryable = + mongoc_uri_get_option_as_bool (cluster->uri, MONGOC_URI_RETRYWRITES, MONGOC_DEFAULT_RETRYWRITES); - return _mongoc_cluster_stream_for_optype ( - cluster, MONGOC_SS_WRITE, NULL, cs, is_retryable, ds, reply, error); + return _mongoc_cluster_stream_for_optype (cluster, MONGOC_SS_WRITE, NULL, cs, is_retryable, ds, reply, error); } mongoc_server_stream_t * -mongoc_cluster_stream_for_aggr_with_write ( - mongoc_cluster_t *cluster, - const mongoc_read_prefs_t *read_prefs, - mongoc_client_session_t *cs, - bson_t *reply, - bson_error_t *error) +mongoc_cluster_stream_for_aggr_with_write (mongoc_cluster_t *cluster, + const mongoc_read_prefs_t *read_prefs, + mongoc_client_session_t *cs, + bson_t *reply, + bson_error_t *error) { const mongoc_read_prefs_t *const prefs_override = _mongoc_client_session_in_txn (cs) ? cs->txn.opts.read_prefs : read_prefs; - const bool is_retryable = mongoc_uri_get_option_as_bool ( - cluster->uri, MONGOC_URI_RETRYWRITES, MONGOC_DEFAULT_RETRYWRITES); + const bool is_retryable = + mongoc_uri_get_option_as_bool (cluster->uri, MONGOC_URI_RETRYWRITES, MONGOC_DEFAULT_RETRYWRITES); - return _mongoc_cluster_stream_for_optype (cluster, - MONGOC_SS_AGGREGATE_WITH_WRITE, - prefs_override, - cs, - is_retryable, - NULL, - reply, - error); + return _mongoc_cluster_stream_for_optype ( + cluster, MONGOC_SS_AGGREGATE_WITH_WRITE, prefs_override, cs, is_retryable, NULL, reply, error); } static bool @@ -3101,15 +2845,11 @@ mongoc_cluster_get_max_bson_obj_size (mongoc_cluster_t *cluster) max_bson_obj_size = MONGOC_DEFAULT_BSON_OBJ_SIZE; if (!cluster->client->topology->single_threaded) { - mongoc_set_for_each (cluster->nodes, - _mongoc_cluster_min_of_max_obj_size_nodes, - &max_bson_obj_size); + mongoc_set_for_each (cluster->nodes, _mongoc_cluster_min_of_max_obj_size_nodes, &max_bson_obj_size); } else { - mc_shared_tpld td = - mc_tpld_take_ref (BSON_ASSERT_PTR_INLINE (cluster)->client->topology); - mongoc_set_for_each_const (mc_tpld_servers_const (td.ptr), - _mongoc_cluster_min_of_max_obj_size_sds, - &max_bson_obj_size); + mc_shared_tpld td = mc_tpld_take_ref (BSON_ASSERT_PTR_INLINE (cluster)->client->topology); + mongoc_set_for_each_const ( + mc_tpld_servers_const (td.ptr), _mongoc_cluster_min_of_max_obj_size_sds, &max_bson_obj_size); mc_tpld_drop_ref (&td); } @@ -3138,15 +2878,11 @@ mongoc_cluster_get_max_msg_size (mongoc_cluster_t *cluster) int32_t max_msg_size = MONGOC_DEFAULT_MAX_MSG_SIZE; if (!cluster->client->topology->single_threaded) { - mongoc_set_for_each (cluster->nodes, - _mongoc_cluster_min_of_max_msg_size_nodes, - &max_msg_size); + mongoc_set_for_each (cluster->nodes, _mongoc_cluster_min_of_max_msg_size_nodes, &max_msg_size); } else { - mc_shared_tpld td = - mc_tpld_take_ref (BSON_ASSERT_PTR_INLINE (cluster)->client->topology); - mongoc_set_for_each_const (mc_tpld_servers_const (td.ptr), - _mongoc_cluster_min_of_max_msg_size_sds, - &max_msg_size); + mc_shared_tpld td = mc_tpld_take_ref (BSON_ASSERT_PTR_INLINE (cluster)->client->topology); + mongoc_set_for_each_const ( + mc_tpld_servers_const (td.ptr), _mongoc_cluster_min_of_max_msg_size_sds, &max_msg_size); mc_tpld_drop_ref (&td); } @@ -3200,8 +2936,7 @@ mongoc_cluster_check_interval (mongoc_cluster_t *cluster, uint32_t server_id) return true; } - scanner_node = - mongoc_topology_scanner_get_node (topology->scanner, server_id); + scanner_node = mongoc_topology_scanner_get_node (topology->scanner, server_id); if (!scanner_node) { return false; @@ -3223,41 +2958,33 @@ mongoc_cluster_check_interval (mongoc_cluster_t *cluster, uint32_t server_id) if (scanner_node->last_used + (1000 * CHECK_CLOSED_DURATION_MSEC) < now) { if (mongoc_stream_check_closed (stream)) { mc_tpld_modification tdmod; - bson_set_error (&error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_SOCKET, - "connection closed"); + bson_set_error (&error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "connection closed"); mongoc_cluster_disconnect_node (cluster, server_id); tdmod = mc_tpld_modify_begin (topology); /* invalidate_server() is okay if 'server_id' was already removed. */ - mongoc_topology_description_invalidate_server ( - tdmod.new_td, server_id, &error); + mongoc_topology_description_invalidate_server (tdmod.new_td, server_id, &error); mc_tpld_modify_commit (tdmod); return false; } } - if (scanner_node->last_used + (1000 * cluster->socketcheckintervalms) < - now) { + if (scanner_node->last_used + (1000 * cluster->socketcheckintervalms) < now) { mc_shared_tpld td; bson_init (&command); BSON_APPEND_INT32 (&command, "ping", 1); - mongoc_cmd_parts_init ( - &parts, cluster->client, "admin", MONGOC_QUERY_SECONDARY_OK, &command); + mongoc_cmd_parts_init (&parts, cluster->client, "admin", MONGOC_QUERY_SECONDARY_OK, &command); parts.prohibit_lsid = true; td = mc_tpld_take_ref (cluster->client->topology); - server_stream = - _mongoc_cluster_create_server_stream (td.ptr, handshake_sd, stream); + server_stream = _mongoc_cluster_create_server_stream (td.ptr, handshake_sd, stream); mc_tpld_drop_ref (&td); if (!server_stream) { bson_destroy (&command); return false; } - r = mongoc_cluster_run_command_parts ( - cluster, server_stream, &parts, NULL, &error); + r = mongoc_cluster_run_command_parts (cluster, server_stream, &parts, NULL, &error); mongoc_server_stream_cleanup (server_stream); bson_destroy (&command); @@ -3267,8 +2994,7 @@ mongoc_cluster_check_interval (mongoc_cluster_t *cluster, uint32_t server_id) mongoc_cluster_disconnect_node (cluster, server_id); tdmod = mc_tpld_modify_begin (cluster->client->topology); /* invalidate_server() is okay if 'server_id' was already removed. */ - mongoc_topology_description_invalidate_server ( - tdmod.new_td, server_id, &error); + mongoc_topology_description_invalidate_server (tdmod.new_td, server_id, &error); mc_tpld_modify_commit (tdmod); } } @@ -3278,11 +3004,10 @@ mongoc_cluster_check_interval (mongoc_cluster_t *cluster, uint32_t server_id) bool -mongoc_cluster_legacy_rpc_sendv_to_server ( - mongoc_cluster_t *cluster, - mcd_rpc_message *rpc, - mongoc_server_stream_t *server_stream, - bson_error_t *error) +mongoc_cluster_legacy_rpc_sendv_to_server (mongoc_cluster_t *cluster, + mcd_rpc_message *rpc, + mongoc_server_stream_t *server_stream, + bson_error_t *error) { BSON_ASSERT_PARAM (cluster); BSON_ASSERT_PARAM (rpc); @@ -3299,30 +3024,24 @@ mongoc_cluster_legacy_rpc_sendv_to_server ( size_t num_iovecs = 0u; if (cluster->client->in_exhaust) { - bson_set_error (error, - MONGOC_ERROR_CLIENT, - MONGOC_ERROR_CLIENT_IN_EXHAUST, - "a cursor derived from this client is in exhaust"); + bson_set_error ( + error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_IN_EXHAUST, "a cursor derived from this client is in exhaust"); GOTO (done); } - const int32_t compressor_id = - mongoc_server_description_compressor_id (server_stream->sd); + const int32_t compressor_id = mongoc_server_description_compressor_id (server_stream->sd); - if (compressor_id != -1 && - !mcd_rpc_message_compress ( - rpc, - compressor_id, - _compression_level_from_uri (compressor_id, cluster->uri), - &compressed_data, - &compressed_data_len, - error)) { + if (compressor_id != -1 && !mcd_rpc_message_compress (rpc, + compressor_id, + _compression_level_from_uri (compressor_id, cluster->uri), + &compressed_data, + &compressed_data_len, + error)) { GOTO (done); } const uint32_t server_id = server_stream->sd->id; - const int32_t max_msg_size = - mongoc_server_stream_max_msg_size (server_stream); + const int32_t max_msg_size = mongoc_server_stream_max_msg_size (server_stream); const int32_t message_length = mcd_rpc_header_get_message_length (rpc); @@ -3341,11 +3060,7 @@ mongoc_cluster_legacy_rpc_sendv_to_server ( BSON_ASSERT (iovecs); mcd_rpc_message_egress (rpc); - if (!_mongoc_stream_writev_full (server_stream->stream, - iovecs, - num_iovecs, - cluster->sockettimeoutms, - error)) { + if (!_mongoc_stream_writev_full (server_stream->stream, iovecs, num_iovecs, cluster->sockettimeoutms, error)) { GOTO (done); } @@ -3381,13 +3096,9 @@ mongoc_cluster_try_recv (mongoc_cluster_t *cluster, const size_t offset = buffer->len; - if (!_mongoc_buffer_append_from_stream (buffer, - server_stream->stream, - sizeof (int32_t), - cluster->sockettimeoutms, - error)) { - MONGOC_DEBUG ( - "could not read message length, stream probably closed or timed out"); + if (!_mongoc_buffer_append_from_stream ( + buffer, server_stream->stream, sizeof (int32_t), cluster->sockettimeoutms, error)) { + MONGOC_DEBUG ("could not read message length, stream probably closed or timed out"); mongoc_counter_protocol_ingress_error_inc (); _handle_network_error (cluster, server_stream, error); GOTO (done); @@ -3395,17 +3106,13 @@ mongoc_cluster_try_recv (mongoc_cluster_t *cluster, const int32_t message_length = _int32_from_le (buffer->data + offset); - const int32_t max_msg_size = - mongoc_server_stream_max_msg_size (server_stream); + const int32_t max_msg_size = mongoc_server_stream_max_msg_size (server_stream); - if (message_length < message_header_length || - message_length > max_msg_size) { + if (message_length < message_header_length || message_length > max_msg_size) { bson_set_error (error, MONGOC_ERROR_PROTOCOL, MONGOC_ERROR_PROTOCOL_INVALID_REPLY, - "message length %" PRId32 - " is not within valid range of %" PRId32 "-%" PRId32 - " bytes", + "message length %" PRId32 " is not within valid range of %" PRId32 "-%" PRId32 " bytes", message_header_length, message_length, server_stream->sd->max_msg_size); @@ -3416,22 +3123,16 @@ mongoc_cluster_try_recv (mongoc_cluster_t *cluster, const size_t remaining_bytes = (size_t) message_length - sizeof (int32_t); - if (!_mongoc_buffer_append_from_stream (buffer, - server_stream->stream, - remaining_bytes, - cluster->sockettimeoutms, - error)) { + if (!_mongoc_buffer_append_from_stream ( + buffer, server_stream->stream, remaining_bytes, cluster->sockettimeoutms, error)) { _handle_network_error (cluster, server_stream, error); mongoc_counter_protocol_ingress_error_inc (); GOTO (done); } - if (!mcd_rpc_message_from_data_in_place ( - rpc, buffer->data + offset, (size_t) message_length, NULL)) { - bson_set_error (error, - MONGOC_ERROR_PROTOCOL, - MONGOC_ERROR_PROTOCOL_INVALID_REPLY, - "failed to decode reply from server"); + if (!mcd_rpc_message_from_data_in_place (rpc, buffer->data + offset, (size_t) message_length, NULL)) { + bson_set_error ( + error, MONGOC_ERROR_PROTOCOL, MONGOC_ERROR_PROTOCOL_INVALID_REPLY, "failed to decode reply from server"); _handle_network_error (cluster, server_stream, error); mongoc_counter_protocol_ingress_error_inc (); GOTO (done); @@ -3442,19 +3143,15 @@ mongoc_cluster_try_recv (mongoc_cluster_t *cluster, void *decompressed_data = NULL; size_t decompressed_data_len = 0u; - if (!mcd_rpc_message_decompress_if_necessary ( - rpc, &decompressed_data, &decompressed_data_len)) { - bson_set_error (error, - MONGOC_ERROR_PROTOCOL, - MONGOC_ERROR_PROTOCOL_INVALID_REPLY, - "could not decompress server reply"); + if (!mcd_rpc_message_decompress_if_necessary (rpc, &decompressed_data, &decompressed_data_len)) { + bson_set_error ( + error, MONGOC_ERROR_PROTOCOL, MONGOC_ERROR_PROTOCOL_INVALID_REPLY, "could not decompress server reply"); GOTO (done); } if (decompressed_data) { _mongoc_buffer_destroy (buffer); - _mongoc_buffer_init ( - buffer, decompressed_data, decompressed_data_len, NULL, NULL); + _mongoc_buffer_init (buffer, decompressed_data, decompressed_data_len, NULL, NULL); } ret = true; @@ -3506,11 +3203,8 @@ network_error_reply (bson_t *reply, mongoc_cmd_t *cmd) static bool -_mongoc_cluster_run_opmsg_send (mongoc_cluster_t *cluster, - mongoc_cmd_t *cmd, - mcd_rpc_message *rpc, - bson_t *reply, - bson_error_t *error) +_mongoc_cluster_run_opmsg_send ( + mongoc_cluster_t *cluster, mongoc_cmd_t *cmd, mcd_rpc_message *rpc, bson_t *reply, bson_error_t *error) { BSON_ASSERT_PARAM (cluster); BSON_ASSERT_PARAM (cmd); @@ -3520,18 +3214,14 @@ _mongoc_cluster_run_opmsg_send (mongoc_cluster_t *cluster, mongoc_server_stream_t *const server_stream = cmd->server_stream; - const uint32_t flags = - (cmd->is_acknowledged ? MONGOC_OP_MSG_FLAG_NONE - : MONGOC_OP_MSG_FLAG_MORE_TO_COME) | - (cmd->op_msg_is_exhaust ? MONGOC_OP_MSG_FLAG_EXHAUST_ALLOWED - : MONGOC_OP_MSG_FLAG_NONE); + const uint32_t flags = (cmd->is_acknowledged ? MONGOC_OP_MSG_FLAG_NONE : MONGOC_OP_MSG_FLAG_MORE_TO_COME) | + (cmd->op_msg_is_exhaust ? MONGOC_OP_MSG_FLAG_EXHAUST_ALLOWED : MONGOC_OP_MSG_FLAG_NONE); { int32_t message_length = 0; message_length += mcd_rpc_header_set_message_length (rpc, 0); - message_length += - mcd_rpc_header_set_request_id (rpc, ++cluster->request_id); + message_length += mcd_rpc_header_set_request_id (rpc, ++cluster->request_id); message_length += mcd_rpc_header_set_response_to (rpc, 0); message_length += mcd_rpc_header_set_op_code (rpc, MONGOC_OP_CODE_MSG); @@ -3539,24 +3229,20 @@ _mongoc_cluster_run_opmsg_send (mongoc_cluster_t *cluster, message_length += mcd_rpc_op_msg_set_flag_bits (rpc, flags); message_length += mcd_rpc_op_msg_section_set_kind (rpc, 0u, 0); - message_length += mcd_rpc_op_msg_section_set_body ( - rpc, 0u, bson_get_data (cmd->command)); + message_length += mcd_rpc_op_msg_section_set_body (rpc, 0u, bson_get_data (cmd->command)); if (cmd->payload) { BSON_ASSERT (bson_in_range_signed (size_t, cmd->payload_size)); - const size_t section_length = sizeof (int32_t) + - strlen (cmd->payload_identifier) + 1u + - (size_t) cmd->payload_size; + const size_t section_length = + sizeof (int32_t) + strlen (cmd->payload_identifier) + 1u + (size_t) cmd->payload_size; BSON_ASSERT (bson_in_range_unsigned (int32_t, section_length)); message_length += mcd_rpc_op_msg_section_set_kind (rpc, 1u, 1); - message_length += mcd_rpc_op_msg_section_set_length ( - rpc, 1u, (int32_t) section_length); - message_length += mcd_rpc_op_msg_section_set_identifier ( - rpc, 1u, cmd->payload_identifier); - message_length += mcd_rpc_op_msg_section_set_document_sequence ( - rpc, 1u, cmd->payload, (size_t) cmd->payload_size); + message_length += mcd_rpc_op_msg_section_set_length (rpc, 1u, (int32_t) section_length); + message_length += mcd_rpc_op_msg_section_set_identifier (rpc, 1u, cmd->payload_identifier); + message_length += + mcd_rpc_op_msg_section_set_document_sequence (rpc, 1u, cmd->payload, (size_t) cmd->payload_size); } mcd_rpc_message_set_length (rpc, message_length); @@ -3566,20 +3252,16 @@ _mongoc_cluster_run_opmsg_send (mongoc_cluster_t *cluster, size_t compressed_data_len = 0u; if (mongoc_cmd_is_compressible (cmd)) { - const int32_t compressor_id = - mongoc_server_description_compressor_id (server_stream->sd); - - TRACE ( - "Function '%s' is compressible: %d", cmd->command_name, compressor_id); - - if (compressor_id != -1 && - !mcd_rpc_message_compress ( - rpc, - compressor_id, - _compression_level_from_uri (compressor_id, cluster->uri), - &compressed_data, - &compressed_data_len, - error)) { + const int32_t compressor_id = mongoc_server_description_compressor_id (server_stream->sd); + + TRACE ("Function '%s' is compressible: %d", cmd->command_name, compressor_id); + + if (compressor_id != -1 && !mcd_rpc_message_compress (rpc, + compressor_id, + _compression_level_from_uri (compressor_id, cluster->uri), + &compressed_data, + &compressed_data_len, + error)) { RUN_CMD_ERR_DECORATE; _handle_network_error (cluster, server_stream, error); server_stream->stream = NULL; @@ -3593,11 +3275,8 @@ _mongoc_cluster_run_opmsg_send (mongoc_cluster_t *cluster, BSON_ASSERT (iovecs); mcd_rpc_message_egress (rpc); - const bool res = _mongoc_stream_writev_full (server_stream->stream, - iovecs, - num_iovecs, - cluster->sockettimeoutms, - error); + const bool res = + _mongoc_stream_writev_full (server_stream->stream, iovecs, num_iovecs, cluster->sockettimeoutms, error); if (!res) { RUN_CMD_ERR_DECORATE; @@ -3613,11 +3292,8 @@ _mongoc_cluster_run_opmsg_send (mongoc_cluster_t *cluster, } static bool -_mongoc_cluster_run_opmsg_recv (mongoc_cluster_t *cluster, - mongoc_cmd_t *cmd, - mcd_rpc_message *rpc, - bson_t *reply, - bson_error_t *error) +_mongoc_cluster_run_opmsg_recv ( + mongoc_cluster_t *cluster, mongoc_cmd_t *cmd, mcd_rpc_message *rpc, bson_t *reply, bson_error_t *error) { BSON_ASSERT_PARAM (cluster); BSON_ASSERT_PARAM (cmd); @@ -3632,13 +3308,9 @@ _mongoc_cluster_run_opmsg_recv (mongoc_cluster_t *cluster, mongoc_buffer_t buffer; _mongoc_buffer_init (&buffer, NULL, 0, NULL, NULL); - if (!_mongoc_buffer_append_from_stream (&buffer, - server_stream->stream, - sizeof (int32_t), - cluster->sockettimeoutms, - error)) { - MONGOC_DEBUG ( - "could not read message length, stream probably closed or timed out"); + if (!_mongoc_buffer_append_from_stream ( + &buffer, server_stream->stream, sizeof (int32_t), cluster->sockettimeoutms, error)) { + MONGOC_DEBUG ("could not read message length, stream probably closed or timed out"); RUN_CMD_ERR_DECORATE; _handle_network_error (cluster, server_stream, error); server_stream->stream = NULL; @@ -3648,13 +3320,10 @@ _mongoc_cluster_run_opmsg_recv (mongoc_cluster_t *cluster, const int32_t message_length = _int32_from_le (buffer.data); - if (message_length < message_header_length || - message_length > server_stream->sd->max_msg_size) { + if (message_length < message_header_length || message_length > server_stream->sd->max_msg_size) { RUN_CMD_ERR (MONGOC_ERROR_PROTOCOL, MONGOC_ERROR_PROTOCOL_INVALID_REPLY, - "message length %" PRId32 - " is not within valid range of %" PRId32 "-%" PRId32 - " bytes", + "message length %" PRId32 " is not within valid range of %" PRId32 "-%" PRId32 " bytes", message_header_length, message_length, server_stream->sd->max_msg_size); @@ -3666,11 +3335,8 @@ _mongoc_cluster_run_opmsg_recv (mongoc_cluster_t *cluster, const size_t remaining_bytes = (size_t) message_length - sizeof (int32_t); - if (!_mongoc_buffer_append_from_stream (&buffer, - server_stream->stream, - remaining_bytes, - cluster->sockettimeoutms, - error)) { + if (!_mongoc_buffer_append_from_stream ( + &buffer, server_stream->stream, remaining_bytes, cluster->sockettimeoutms, error)) { RUN_CMD_ERR_DECORATE; _handle_network_error (cluster, server_stream, error); server_stream->stream = NULL; @@ -3678,11 +3344,8 @@ _mongoc_cluster_run_opmsg_recv (mongoc_cluster_t *cluster, goto done; } - if (!mcd_rpc_message_from_data_in_place ( - rpc, buffer.data, buffer.len, NULL)) { - RUN_CMD_ERR (MONGOC_ERROR_PROTOCOL, - MONGOC_ERROR_PROTOCOL_INVALID_REPLY, - "malformed server message"); + if (!mcd_rpc_message_from_data_in_place (rpc, buffer.data, buffer.len, NULL)) { + RUN_CMD_ERR (MONGOC_ERROR_PROTOCOL, MONGOC_ERROR_PROTOCOL_INVALID_REPLY, "malformed server message"); _handle_network_error (cluster, server_stream, error); server_stream->stream = NULL; network_error_reply (reply, cmd); @@ -3693,12 +3356,9 @@ _mongoc_cluster_run_opmsg_recv (mongoc_cluster_t *cluster, void *decompressed_data = NULL; size_t decompressed_data_len = 0u; - if (!mcd_rpc_message_decompress_if_necessary ( - rpc, &decompressed_data, &decompressed_data_len)) { - bson_set_error (error, - MONGOC_ERROR_PROTOCOL, - MONGOC_ERROR_PROTOCOL_INVALID_REPLY, - "could not decompress message from server"); + if (!mcd_rpc_message_decompress_if_necessary (rpc, &decompressed_data, &decompressed_data_len)) { + bson_set_error ( + error, MONGOC_ERROR_PROTOCOL, MONGOC_ERROR_PROTOCOL_INVALID_REPLY, "could not decompress message from server"); _handle_network_error (cluster, server_stream, error); server_stream->stream = NULL; network_error_reply (reply, cmd); @@ -3707,8 +3367,7 @@ _mongoc_cluster_run_opmsg_recv (mongoc_cluster_t *cluster, if (decompressed_data) { _mongoc_buffer_destroy (&buffer); - _mongoc_buffer_init ( - &buffer, decompressed_data, decompressed_data_len, NULL, NULL); + _mongoc_buffer_init (&buffer, decompressed_data, decompressed_data_len, NULL, NULL); } bson_t body; @@ -3717,9 +3376,7 @@ _mongoc_cluster_run_opmsg_recv (mongoc_cluster_t *cluster, cluster->client->in_exhaust = op_msg_flags & MONGOC_OP_MSG_FLAG_MORE_TO_COME; if (!mcd_rpc_message_get_body (rpc, &body)) { - RUN_CMD_ERR (MONGOC_ERROR_PROTOCOL, - MONGOC_ERROR_PROTOCOL_INVALID_REPLY, - "malformed message from server"); + RUN_CMD_ERR (MONGOC_ERROR_PROTOCOL, MONGOC_ERROR_PROTOCOL_INVALID_REPLY, "malformed message from server"); _handle_network_error (cluster, server_stream, error); server_stream->stream = NULL; network_error_reply (reply, cmd); @@ -3728,12 +3385,10 @@ _mongoc_cluster_run_opmsg_recv (mongoc_cluster_t *cluster, _mongoc_topology_update_cluster_time (cluster->client->topology, &body); - ret = - _mongoc_cmd_check_ok (&body, cluster->client->error_api_version, error); + ret = _mongoc_cmd_check_ok (&body, cluster->client->error_api_version, error); if (cmd->session) { - _mongoc_client_session_handle_reply ( - cmd->session, cmd->is_acknowledged, cmd->command_name, &body); + _mongoc_client_session_handle_reply (cmd->session, cmd->is_acknowledged, cmd->command_name, &body); } bson_copy_to (&body, reply); @@ -3746,10 +3401,7 @@ _mongoc_cluster_run_opmsg_recv (mongoc_cluster_t *cluster, } static bool -mongoc_cluster_run_opmsg (mongoc_cluster_t *cluster, - mongoc_cmd_t *cmd, - bson_t *reply, - bson_error_t *error) +mongoc_cluster_run_opmsg (mongoc_cluster_t *cluster, mongoc_cmd_t *cmd, bson_t *reply, bson_error_t *error) { BSON_ASSERT_PARAM (cluster); BSON_ASSERT_PARAM (cmd); @@ -3757,10 +3409,7 @@ mongoc_cluster_run_opmsg (mongoc_cluster_t *cluster, BSON_ASSERT_PARAM (error); if (!cmd->command_name) { - bson_set_error (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "empty command document"); + bson_set_error (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "empty command document"); bson_init (reply); return false; } @@ -3778,8 +3427,7 @@ mongoc_cluster_run_opmsg (mongoc_cluster_t *cluster, mcd_rpc_message *const rpc = mcd_rpc_message_new (); - if (!cluster->client->in_exhaust && - !_mongoc_cluster_run_opmsg_send (cluster, cmd, rpc, reply, error)) { + if (!cluster->client->in_exhaust && !_mongoc_cluster_run_opmsg_send (cluster, cmd, rpc, reply, error)) { goto done; } @@ -3823,21 +3471,17 @@ mcd_rpc_message_compress (mcd_rpc_message *rpc, char *compressed_message = NULL; mongoc_iovec_t *iovecs = NULL; - const int32_t original_message_length = - mcd_rpc_header_get_message_length (rpc); + const int32_t original_message_length = mcd_rpc_header_get_message_length (rpc); // msgHeader consists of four int32 fields. const int32_t message_header_length = 4u * sizeof (int32_t); // compressedMessage does not include msgHeader fields. BSON_ASSERT (original_message_length >= message_header_length); - const size_t uncompressed_size = - (size_t) (original_message_length - message_header_length); + const size_t uncompressed_size = (size_t) (original_message_length - message_header_length); BSON_ASSERT (bson_in_range_unsigned (int32_t, uncompressed_size)); - const size_t estimated_compressed_size = - mongoc_compressor_max_compressed_length (compressor_id, - uncompressed_size); + const size_t estimated_compressed_size = mongoc_compressor_max_compressed_length (compressor_id, uncompressed_size); if (estimated_compressed_size == 0u) { bson_set_error (error, @@ -3858,10 +3502,8 @@ mcd_rpc_message_compress (mcd_rpc_message *rpc, BSON_ASSERT (iovecs); uncompressed_message = bson_malloc (uncompressed_size); - BSON_ASSERT ( - _mongoc_cluster_buffer_iovec ( - iovecs, num_iovecs, message_header_length, uncompressed_message) == - uncompressed_size); + BSON_ASSERT (_mongoc_cluster_buffer_iovec (iovecs, num_iovecs, message_header_length, uncompressed_message) == + uncompressed_size); compressed_message = bson_malloc (estimated_compressed_size); @@ -3875,8 +3517,7 @@ mcd_rpc_message_compress (mcd_rpc_message *rpc, uncompressed_size, compressed_message, &compressed_size)) { - MONGOC_WARNING ("Could not compress data with %s", - mongoc_compressor_id_to_name (compressor_id)); + MONGOC_WARNING ("Could not compress data with %s", mongoc_compressor_id_to_name (compressor_id)); goto fail; } @@ -3888,15 +3529,11 @@ mcd_rpc_message_compress (mcd_rpc_message *rpc, message_len += mcd_rpc_header_set_message_length (rpc, 0); message_len += mcd_rpc_header_set_request_id (rpc, request_id); message_len += mcd_rpc_header_set_response_to (rpc, response_to); - message_len += - mcd_rpc_header_set_op_code (rpc, MONGOC_OP_CODE_COMPRESSED); + message_len += mcd_rpc_header_set_op_code (rpc, MONGOC_OP_CODE_COMPRESSED); message_len += mcd_rpc_op_compressed_set_original_opcode (rpc, op_code); - message_len += mcd_rpc_op_compressed_set_uncompressed_size ( - rpc, (int32_t) uncompressed_size); - message_len += - mcd_rpc_op_compressed_set_compressor_id (rpc, (uint8_t) compressor_id); - message_len += mcd_rpc_op_compressed_set_compressed_message ( - rpc, compressed_message, compressed_size); + message_len += mcd_rpc_op_compressed_set_uncompressed_size (rpc, (int32_t) uncompressed_size); + message_len += mcd_rpc_op_compressed_set_compressor_id (rpc, (uint8_t) compressor_id); + message_len += mcd_rpc_op_compressed_set_compressed_message (rpc, compressed_message, compressed_size); mcd_rpc_message_set_length (rpc, message_len); } @@ -3927,12 +3564,10 @@ mcd_rpc_message_decompress (mcd_rpc_message *rpc, void **data, size_t *data_len) // msgHeader consists of four int32 fields. const size_t message_header_length = 4u * sizeof (int32_t); - const size_t uncompressed_size = - (size_t) mcd_rpc_op_compressed_get_uncompressed_size (rpc); + const size_t uncompressed_size = (size_t) mcd_rpc_op_compressed_get_uncompressed_size (rpc); // uncompressedSize does not include msgHeader fields. - const size_t original_message_length = - message_header_length + uncompressed_size; + const size_t original_message_length = message_header_length + uncompressed_size; uint8_t *const ptr = bson_malloc (original_message_length); const int32_t message_length = original_message_length; @@ -3966,12 +3601,11 @@ mcd_rpc_message_decompress (mcd_rpc_message *rpc, void **data, size_t *data_len) size_t actual_uncompressed_size = uncompressed_size; // Populate the rest of the uncompressed message. - if (!mongoc_uncompress ( - mcd_rpc_op_compressed_get_compressor_id (rpc), - mcd_rpc_op_compressed_get_compressed_message (rpc), - mcd_rpc_op_compressed_get_compressed_message_length (rpc), - ptr + message_header_length, - &actual_uncompressed_size)) { + if (!mongoc_uncompress (mcd_rpc_op_compressed_get_compressor_id (rpc), + mcd_rpc_op_compressed_get_compressed_message (rpc), + mcd_rpc_op_compressed_get_compressed_message_length (rpc), + ptr + message_header_length, + &actual_uncompressed_size)) { bson_free (ptr); return false; } @@ -3987,9 +3621,7 @@ mcd_rpc_message_decompress (mcd_rpc_message *rpc, void **data, size_t *data_len) } bool -mcd_rpc_message_decompress_if_necessary (mcd_rpc_message *rpc, - void **data, - size_t *data_len) +mcd_rpc_message_decompress_if_necessary (mcd_rpc_message *rpc, void **data, size_t *data_len) { BSON_ASSERT_PARAM (rpc); BSON_ASSERT_PARAM (data); diff --git a/src/libmongoc/src/mongoc/mongoc-cmd-private.h b/src/libmongoc/src/mongoc/mongoc-cmd-private.h index 602528f56f..0bb4bf1e67 100644 --- a/src/libmongoc/src/mongoc/mongoc-cmd-private.h +++ b/src/libmongoc/src/mongoc/mongoc-cmd-private.h @@ -98,37 +98,25 @@ mongoc_cmd_parts_init (mongoc_cmd_parts_t *op, const bson_t *command_body); void -mongoc_cmd_parts_set_session (mongoc_cmd_parts_t *parts, - mongoc_client_session_t *cs); +mongoc_cmd_parts_set_session (mongoc_cmd_parts_t *parts, mongoc_client_session_t *cs); void -mongoc_cmd_parts_set_server_api (mongoc_cmd_parts_t *parts, - mongoc_server_api_t *api); +mongoc_cmd_parts_set_server_api (mongoc_cmd_parts_t *parts, mongoc_server_api_t *api); bool -mongoc_cmd_parts_append_opts (mongoc_cmd_parts_t *parts, - bson_iter_t *iter, - bson_error_t *error); +mongoc_cmd_parts_append_opts (mongoc_cmd_parts_t *parts, bson_iter_t *iter, bson_error_t *error); bool -mongoc_cmd_parts_set_read_concern (mongoc_cmd_parts_t *parts, - const mongoc_read_concern_t *rc, - bson_error_t *error); +mongoc_cmd_parts_set_read_concern (mongoc_cmd_parts_t *parts, const mongoc_read_concern_t *rc, bson_error_t *error); bool -mongoc_cmd_parts_set_write_concern (mongoc_cmd_parts_t *parts, - const mongoc_write_concern_t *wc, - bson_error_t *error); +mongoc_cmd_parts_set_write_concern (mongoc_cmd_parts_t *parts, const mongoc_write_concern_t *wc, bson_error_t *error); bool -mongoc_cmd_parts_append_read_write (mongoc_cmd_parts_t *parts, - mongoc_read_write_opts_t *rw_opts, - bson_error_t *error); +mongoc_cmd_parts_append_read_write (mongoc_cmd_parts_t *parts, mongoc_read_write_opts_t *rw_opts, bson_error_t *error); bool -mongoc_cmd_parts_assemble (mongoc_cmd_parts_t *parts, - mongoc_server_stream_t *server_stream, - bson_error_t *error); +mongoc_cmd_parts_assemble (mongoc_cmd_parts_t *parts, mongoc_server_stream_t *server_stream, bson_error_t *error); bool mongoc_cmd_is_compressible (mongoc_cmd_t *cmd); @@ -137,15 +125,13 @@ void mongoc_cmd_parts_cleanup (mongoc_cmd_parts_t *op); bool -_is_retryable_read (const mongoc_cmd_parts_t *parts, - const mongoc_server_stream_t *server_stream); +_is_retryable_read (const mongoc_cmd_parts_t *parts, const mongoc_server_stream_t *server_stream); void _mongoc_cmd_append_payload_as_array (const mongoc_cmd_t *cmd, bson_t *out); void -_mongoc_cmd_append_server_api (bson_t *command_body, - const mongoc_server_api_t *api); +_mongoc_cmd_append_server_api (bson_t *command_body, const mongoc_server_api_t *api); BSON_END_DECLS diff --git a/src/libmongoc/src/mongoc/mongoc-cmd.c b/src/libmongoc/src/mongoc/mongoc-cmd.c index 6ad74c43a4..f3d2fbc17a 100644 --- a/src/libmongoc/src/mongoc/mongoc-cmd.c +++ b/src/libmongoc/src/mongoc/mongoc-cmd.c @@ -78,8 +78,7 @@ mongoc_cmd_parts_init (mongoc_cmd_parts_t *parts, */ void -mongoc_cmd_parts_set_session (mongoc_cmd_parts_t *parts, - mongoc_client_session_t *cs) +mongoc_cmd_parts_set_session (mongoc_cmd_parts_t *parts, mongoc_client_session_t *cs) { BSON_ASSERT (parts); BSON_ASSERT (!parts->assembled.command); @@ -109,9 +108,7 @@ mongoc_cmd_parts_set_session (mongoc_cmd_parts_t *parts, */ bool -mongoc_cmd_parts_append_opts (mongoc_cmd_parts_t *parts, - bson_iter_t *iter, - bson_error_t *error) +mongoc_cmd_parts_append_opts (mongoc_cmd_parts_t *parts, bson_iter_t *iter, bson_error_t *error) { mongoc_client_session_t *cs = NULL; mongoc_write_concern_t *wc; @@ -141,10 +138,7 @@ mongoc_cmd_parts_append_opts (mongoc_cmd_parts_t *parts, continue; } else if (BSON_ITER_IS_KEY (iter, "readConcern")) { if (!BSON_ITER_HOLDS_DOCUMENT (iter)) { - bson_set_error (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION, - "Invalid readConcern"); + bson_set_error (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION, "Invalid readConcern"); RETURN (false); } @@ -157,15 +151,13 @@ mongoc_cmd_parts_append_opts (mongoc_cmd_parts_t *parts, } else if (BSON_ITER_IS_KEY (iter, "sessionId")) { BSON_ASSERT (!parts->assembled.session); - if (!_mongoc_client_session_from_iter ( - parts->client, iter, &cs, error)) { + if (!_mongoc_client_session_from_iter (parts->client, iter, &cs, error)) { RETURN (false); } parts->assembled.session = cs; continue; - } else if (BSON_ITER_IS_KEY (iter, "serverId") || - BSON_ITER_IS_KEY (iter, "maxAwaitTimeMS") || + } else if (BSON_ITER_IS_KEY (iter, "serverId") || BSON_ITER_IS_KEY (iter, "maxAwaitTimeMS") || BSON_ITER_IS_KEY (iter, "exhaust")) { continue; } @@ -185,19 +177,16 @@ mongoc_cmd_parts_append_opts (mongoc_cmd_parts_t *parts, } -#define OPTS_ERR(_code, ...) \ - do { \ - bson_set_error ( \ - error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_##_code, __VA_ARGS__); \ - RETURN (false); \ +#define OPTS_ERR(_code, ...) \ + do { \ + bson_set_error (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_##_code, __VA_ARGS__); \ + RETURN (false); \ } while (0) /* set readConcern if allowed, otherwise error */ bool -mongoc_cmd_parts_set_read_concern (mongoc_cmd_parts_t *parts, - const mongoc_read_concern_t *rc, - bson_error_t *error) +mongoc_cmd_parts_set_read_concern (mongoc_cmd_parts_t *parts, const mongoc_read_concern_t *rc, bson_error_t *error) { const char *command_name; @@ -222,8 +211,7 @@ mongoc_cmd_parts_set_read_concern (mongoc_cmd_parts_t *parts, } bson_destroy (&parts->read_concern_document); - bson_copy_to (_mongoc_read_concern_get_bson ((mongoc_read_concern_t *) rc), - &parts->read_concern_document); + bson_copy_to (_mongoc_read_concern_get_bson ((mongoc_read_concern_t *) rc), &parts->read_concern_document); RETURN (true); } @@ -232,9 +220,7 @@ mongoc_cmd_parts_set_read_concern (mongoc_cmd_parts_t *parts, /* set writeConcern if allowed, otherwise ignore - unlike set_read_concern, it's * the caller's responsibility to check if writeConcern is supported */ bool -mongoc_cmd_parts_set_write_concern (mongoc_cmd_parts_t *parts, - const mongoc_write_concern_t *wc, - bson_error_t *error) +mongoc_cmd_parts_set_write_concern (mongoc_cmd_parts_t *parts, const mongoc_write_concern_t *wc, bson_error_t *error) { ENTRY; @@ -250,8 +236,7 @@ mongoc_cmd_parts_set_write_concern (mongoc_cmd_parts_t *parts, parts->assembled.is_acknowledged = mongoc_write_concern_is_acknowledged (wc); bson_destroy (&parts->write_concern_document); - bson_copy_to (_mongoc_write_concern_get_bson ((mongoc_write_concern_t *) wc), - &parts->write_concern_document); + bson_copy_to (_mongoc_write_concern_get_bson ((mongoc_write_concern_t *) wc), &parts->write_concern_document); RETURN (true); } @@ -277,9 +262,7 @@ mongoc_cmd_parts_set_write_concern (mongoc_cmd_parts_t *parts, */ bool -mongoc_cmd_parts_append_read_write (mongoc_cmd_parts_t *parts, - mongoc_read_write_opts_t *rw_opts, - bson_error_t *error) +mongoc_cmd_parts_append_read_write (mongoc_cmd_parts_t *parts, mongoc_read_write_opts_t *rw_opts, bson_error_t *error) { ENTRY; @@ -287,14 +270,12 @@ mongoc_cmd_parts_append_read_write (mongoc_cmd_parts_t *parts, BSON_ASSERT (!parts->assembled.command); if (!bson_empty (&rw_opts->collation)) { - if (!bson_append_document ( - &parts->extra, "collation", 9, &rw_opts->collation)) { + if (!bson_append_document (&parts->extra, "collation", 9, &rw_opts->collation)) { OPTS_ERR (COMMAND_INVALID_ARG, "'opts' with 'collation' is too large"); } } - if (!mongoc_cmd_parts_set_write_concern ( - parts, rw_opts->writeConcern, error)) { + if (!mongoc_cmd_parts_set_write_concern (parts, rw_opts->writeConcern, error)) { RETURN (false); } @@ -335,18 +316,14 @@ _mongoc_cmd_parts_add_write_concern (mongoc_cmd_parts_t *parts) { if (!bson_empty (&parts->write_concern_document)) { _mongoc_cmd_parts_ensure_copied (parts); - bson_append_document (&parts->assembled_body, - "writeConcern", - 12, - &parts->write_concern_document); + bson_append_document (&parts->assembled_body, "writeConcern", 12, &parts->write_concern_document); } } /* The server type must be mongos, or message must be OP_MSG. */ static void -_mongoc_cmd_parts_add_read_prefs (bson_t *query, - const mongoc_read_prefs_t *prefs) +_mongoc_cmd_parts_add_read_prefs (bson_t *query, const mongoc_read_prefs_t *prefs) { bson_t child; const char *mode_str; @@ -393,8 +370,7 @@ _iter_concat (bson_t *dst, bson_iter_t *iter) /* Update result with the read prefs. Server must be mongos. */ static void -_mongoc_cmd_parts_assemble_mongos (mongoc_cmd_parts_t *parts, - const mongoc_server_stream_t *server_stream) +_mongoc_cmd_parts_assemble_mongos (mongoc_cmd_parts_t *parts, const mongoc_server_stream_t *server_stream) { mongoc_read_mode_t mode; const bson_t *tags = NULL; @@ -411,8 +387,7 @@ _mongoc_cmd_parts_assemble_mongos (mongoc_cmd_parts_t *parts, mode = mongoc_read_prefs_get_mode (parts->read_prefs); if (parts->read_prefs) { - max_staleness_seconds = - mongoc_read_prefs_get_max_staleness_seconds (parts->read_prefs); + max_staleness_seconds = mongoc_read_prefs_get_max_staleness_seconds (parts->read_prefs); tags = mongoc_read_prefs_get_tags (parts->read_prefs); hedge = mongoc_read_prefs_get_hedge (parts->read_prefs); @@ -449,8 +424,7 @@ _mongoc_cmd_parts_assemble_mongos (mongoc_cmd_parts_t *parts, case MONGOC_READ_PRIMARY: break; case MONGOC_READ_SECONDARY_PREFERRED: - if (!bson_empty0 (tags) || max_staleness_seconds > 0 || - !bson_empty0 (hedge)) { + if (!bson_empty0 (tags) || max_staleness_seconds > 0 || !bson_empty0 (hedge)) { add_read_prefs = true; } parts->assembled.query_flags |= MONGOC_QUERY_SECONDARY_OK; @@ -464,8 +438,7 @@ _mongoc_cmd_parts_assemble_mongos (mongoc_cmd_parts_t *parts, } requires_read_concern = - !bson_empty (&parts->read_concern_document) && - strcmp (parts->assembled.command_name, "getMore") != 0; + !bson_empty (&parts->read_concern_document) && strcmp (parts->assembled.command_name, "getMore") != 0; requires_write_concern = !bson_empty (&parts->write_concern_document); @@ -483,23 +456,19 @@ _mongoc_cmd_parts_assemble_mongos (mongoc_cmd_parts_t *parts, bson_concat (&query, &parts->extra); if (requires_read_concern) { - bson_append_document ( - &query, "readConcern", 11, &parts->read_concern_document); + bson_append_document (&query, "readConcern", 11, &parts->read_concern_document); } if (requires_write_concern) { - bson_append_document ( - &query, "writeConcern", 12, &parts->write_concern_document); + bson_append_document (&query, "writeConcern", 12, &parts->write_concern_document); } bson_append_document_end (&parts->assembled_body, &query); - _mongoc_cmd_parts_add_read_prefs (&parts->assembled_body, - parts->read_prefs); + _mongoc_cmd_parts_add_read_prefs (&parts->assembled_body, parts->read_prefs); if (has_dollar_query) { /* copy anything that isn't in user's $query */ - bson_copy_to_excluding_noinit ( - parts->body, &parts->assembled_body, "$query", NULL); + bson_copy_to_excluding_noinit (parts->body, &parts->assembled_body, "$query", NULL); } parts->assembled.command = &parts->assembled_body; @@ -509,28 +478,22 @@ _mongoc_cmd_parts_assemble_mongos (mongoc_cmd_parts_t *parts, _iter_concat (&query, &dollar_query); bson_concat (&query, &parts->extra); if (requires_read_concern) { - bson_append_document ( - &query, "readConcern", 11, &parts->read_concern_document); + bson_append_document (&query, "readConcern", 11, &parts->read_concern_document); } if (requires_write_concern) { - bson_append_document ( - &query, "writeConcern", 12, &parts->write_concern_document); + bson_append_document (&query, "writeConcern", 12, &parts->write_concern_document); } bson_append_document_end (&parts->assembled_body, &query); /* copy anything that isn't in user's $query */ - bson_copy_to_excluding_noinit ( - parts->body, &parts->assembled_body, "$query", NULL); + bson_copy_to_excluding_noinit (parts->body, &parts->assembled_body, "$query", NULL); parts->assembled.command = &parts->assembled_body; } else { if (requires_read_concern) { _mongoc_cmd_parts_ensure_copied (parts); - bson_append_document (&parts->assembled_body, - "readConcern", - 11, - &parts->read_concern_document); + bson_append_document (&parts->assembled_body, "readConcern", 11, &parts->read_concern_document); } _mongoc_cmd_parts_add_write_concern (parts); @@ -546,8 +509,7 @@ _mongoc_cmd_parts_assemble_mongos (mongoc_cmd_parts_t *parts, static void -_mongoc_cmd_parts_assemble_mongod (mongoc_cmd_parts_t *parts, - const mongoc_server_stream_t *server_stream) +_mongoc_cmd_parts_assemble_mongod (mongoc_cmd_parts_t *parts, const mongoc_server_stream_t *server_stream) { ENTRY; @@ -570,8 +532,7 @@ _mongoc_cmd_parts_assemble_mongod (mongoc_cmd_parts_t *parts, * request. Clients MUST NOT set the secondaryOk wire protocol flag if * the read preference mode is primary. */ - if (parts->read_prefs && - parts->read_prefs->mode != MONGOC_READ_PRIMARY) { + if (parts->read_prefs && parts->read_prefs->mode != MONGOC_READ_PRIMARY) { parts->assembled.query_flags |= MONGOC_QUERY_SECONDARY_OK; } @@ -591,13 +552,9 @@ _mongoc_cmd_parts_assemble_mongod (mongoc_cmd_parts_t *parts, _mongoc_cmd_parts_ensure_copied (parts); } - if (!bson_empty (&parts->read_concern_document) && - strcmp (parts->assembled.command_name, "getMore") != 0) { + if (!bson_empty (&parts->read_concern_document) && strcmp (parts->assembled.command_name, "getMore") != 0) { _mongoc_cmd_parts_ensure_copied (parts); - bson_append_document (&parts->assembled_body, - "readConcern", - 11, - &parts->read_concern_document); + bson_append_document (&parts->assembled_body, "readConcern", 11, &parts->read_concern_document); } _mongoc_cmd_parts_add_write_concern (parts); @@ -640,12 +597,10 @@ _largest_cluster_time (const bson_t *a, const bson_t *b) * documentation already instructs users not to use that for basic writes. */ static bool -_allow_txn_number (const mongoc_cmd_parts_t *parts, - const mongoc_server_stream_t *server_stream) +_allow_txn_number (const mongoc_cmd_parts_t *parts, const mongoc_server_stream_t *server_stream) { /* There is no reason to call this function if allow_txn_number is set */ - BSON_ASSERT (parts->allow_txn_number == - MONGOC_CMD_PARTS_ALLOW_TXN_NUMBER_UNKNOWN); + BSON_ASSERT (parts->allow_txn_number == MONGOC_CMD_PARTS_ALLOW_TXN_NUMBER_UNKNOWN); if (!parts->is_write_command) { return false; @@ -669,8 +624,7 @@ _allow_txn_number (const mongoc_cmd_parts_t *parts, /* Check if the write command should support retryable behavior. */ static bool -_is_retryable_write (const mongoc_cmd_parts_t *parts, - const mongoc_server_stream_t *server_stream) +_is_retryable_write (const mongoc_cmd_parts_t *parts, const mongoc_server_stream_t *server_stream) { if (!parts->assembled.session) { return false; @@ -696,9 +650,7 @@ _is_retryable_write (const mongoc_cmd_parts_t *parts, return false; } - if (!mongoc_uri_get_option_as_bool (parts->client->uri, - MONGOC_URI_RETRYWRITES, - MONGOC_DEFAULT_RETRYWRITES)) { + if (!mongoc_uri_get_option_as_bool (parts->client->uri, MONGOC_URI_RETRYWRITES, MONGOC_DEFAULT_RETRYWRITES)) { return false; } @@ -708,8 +660,7 @@ _is_retryable_write (const mongoc_cmd_parts_t *parts, /* Check if the read command should support retryable behavior. */ bool -_is_retryable_read (const mongoc_cmd_parts_t *parts, - const mongoc_server_stream_t *server_stream) +_is_retryable_read (const mongoc_cmd_parts_t *parts, const mongoc_server_stream_t *server_stream) { if (!parts->is_read_command) { return false; @@ -729,9 +680,7 @@ _is_retryable_read (const mongoc_cmd_parts_t *parts, return false; } - if (!mongoc_uri_get_option_as_bool (parts->client->uri, - MONGOC_URI_RETRYREADS, - MONGOC_DEFAULT_RETRYREADS)) { + if (!mongoc_uri_get_option_as_bool (parts->client->uri, MONGOC_URI_RETRYREADS, MONGOC_DEFAULT_RETRYREADS)) { return false; } @@ -760,9 +709,7 @@ _is_retryable_read (const mongoc_cmd_parts_t *parts, */ bool -mongoc_cmd_parts_assemble (mongoc_cmd_parts_t *parts, - mongoc_server_stream_t *server_stream, - bson_error_t *error) +mongoc_cmd_parts_assemble (mongoc_cmd_parts_t *parts, mongoc_server_stream_t *server_stream, bson_error_t *error) { mongoc_server_description_type_t server_type; mongoc_client_session_t *cs; @@ -805,26 +752,20 @@ mongoc_cmd_parts_assemble (mongoc_cmd_parts_t *parts, /* unused in OP_MSG: */ parts->assembled.query_flags = parts->user_query_flags; parts->assembled.server_stream = server_stream; - cmd_name = parts->assembled.command_name = - _mongoc_get_command_name (parts->assembled.command); + cmd_name = parts->assembled.command_name = _mongoc_get_command_name (parts->assembled.command); if (!parts->assembled.command_name) { - bson_set_error (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Empty command document"); + bson_set_error (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Empty command document"); GOTO (done); } TRACE ("Preparing '%s'", cmd_name); is_get_more = !strcmp (cmd_name, "getMore"); - parts->assembled.is_txn_finish = !strcmp (cmd_name, "commitTransaction") || - !strcmp (cmd_name, "abortTransaction"); + parts->assembled.is_txn_finish = !strcmp (cmd_name, "commitTransaction") || !strcmp (cmd_name, "abortTransaction"); if (!parts->is_write_command && IS_PREF_PRIMARY (parts->read_prefs) && - server_stream->topology_type == MONGOC_TOPOLOGY_SINGLE && - server_type != MONGOC_SERVER_MONGOS) { + server_stream->topology_type == MONGOC_TOPOLOGY_SINGLE && server_type != MONGOC_SERVER_MONGOS) { prefs = mongoc_read_prefs_new (MONGOC_READ_PRIMARY_PREFERRED); prefs_ptr = prefs; } else { @@ -839,24 +780,21 @@ mongoc_cmd_parts_assemble (mongoc_cmd_parts_t *parts, mode = MONGOC_READ_PRIMARY; } - if (mongoc_client_uses_server_api (parts->client) || - mongoc_client_uses_loadbalanced (parts->client) || + if (mongoc_client_uses_server_api (parts->client) || mongoc_client_uses_loadbalanced (parts->client) || server_stream->sd->max_wire_version >= WIRE_VERSION_MIN) { if (!bson_has_field (parts->body, "$db")) { BSON_APPEND_UTF8 (&parts->extra, "$db", parts->assembled.db_name); } if (cs && _mongoc_client_session_in_txn (cs)) { - if (!IS_PREF_PRIMARY (cs->txn.opts.read_prefs) && - !parts->is_write_command) { + if (!IS_PREF_PRIMARY (cs->txn.opts.read_prefs) && !parts->is_write_command) { bson_set_error (error, MONGOC_ERROR_TRANSACTION, MONGOC_ERROR_TRANSACTION_INVALID_STATE, "Read preference in a transaction must be primary"); GOTO (done); } - } else if (mode != MONGOC_READ_PRIMARY && - server_type != MONGOC_SERVER_STANDALONE) { + } else if (mode != MONGOC_READ_PRIMARY && server_type != MONGOC_SERVER_STANDALONE) { /* "Type Standalone: clients MUST NOT send the read preference to the * server" */ _mongoc_cmd_parts_add_read_prefs (&parts->extra, prefs_ptr); @@ -886,32 +824,25 @@ mongoc_cmd_parts_assemble (mongoc_cmd_parts_t *parts, */ if (cs) { if (!parts->assembled.is_acknowledged) { - bson_set_error ( - error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Cannot use client session with unacknowledged command"); + bson_set_error (error, + MONGOC_ERROR_COMMAND, + MONGOC_ERROR_COMMAND_INVALID_ARG, + "Cannot use client session with unacknowledged command"); GOTO (done); } _mongoc_cmd_parts_ensure_copied (parts); - bson_append_document (&parts->assembled_body, - "lsid", - 4, - mongoc_client_session_get_lsid (cs)); + bson_append_document (&parts->assembled_body, "lsid", 4, mongoc_client_session_get_lsid (cs)); cs->server_session->last_used_usec = bson_get_monotonic_time (); cluster_time = mongoc_client_session_get_cluster_time (cs); } /* Ensure we know if the write command allows a transaction number */ - if (!_mongoc_client_session_txn_in_progress (cs) && - parts->is_write_command && - parts->allow_txn_number == - MONGOC_CMD_PARTS_ALLOW_TXN_NUMBER_UNKNOWN) { - parts->allow_txn_number = _allow_txn_number (parts, server_stream) - ? MONGOC_CMD_PARTS_ALLOW_TXN_NUMBER_YES - : MONGOC_CMD_PARTS_ALLOW_TXN_NUMBER_NO; + if (!_mongoc_client_session_txn_in_progress (cs) && parts->is_write_command && + parts->allow_txn_number == MONGOC_CMD_PARTS_ALLOW_TXN_NUMBER_UNKNOWN) { + parts->allow_txn_number = _allow_txn_number (parts, server_stream) ? MONGOC_CMD_PARTS_ALLOW_TXN_NUMBER_YES + : MONGOC_CMD_PARTS_ALLOW_TXN_NUMBER_NO; } /* Determine if the command is retryable. If so, append txnNumber now @@ -928,20 +859,17 @@ mongoc_cmd_parts_assemble (mongoc_cmd_parts_t *parts, } if (!bson_empty (&server_stream->cluster_time)) { - cluster_time = - _largest_cluster_time (&server_stream->cluster_time, cluster_time); + cluster_time = _largest_cluster_time (&server_stream->cluster_time, cluster_time); } if (cluster_time && server_type != MONGOC_SERVER_STANDALONE) { _mongoc_cmd_parts_ensure_copied (parts); - bson_append_document ( - &parts->assembled_body, "$clusterTime", 12, cluster_time); + bson_append_document (&parts->assembled_body, "$clusterTime", 12, cluster_time); } /* Add versioned server api, if it is set. */ if (mongoc_client_uses_server_api (parts->client)) { - _mongoc_cmd_append_server_api (&parts->assembled_body, - parts->client->api); + _mongoc_cmd_append_server_api (&parts->assembled_body, parts->client->api); } if (!is_get_more) { @@ -950,8 +878,7 @@ mongoc_cmd_parts_assemble (mongoc_cmd_parts_t *parts, * Throw an error if snapshot is enabled and wire version is less * than 13 before potentially appending "snapshot" read concern. */ if (mongoc_session_opts_get_snapshot (&cs->opts) && - server_stream->sd->max_wire_version < - WIRE_VERSION_SNAPSHOT_READS) { + server_stream->sd->max_wire_version < WIRE_VERSION_SNAPSHOT_READS) { bson_set_error (error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_SESSION_FAILURE, @@ -961,34 +888,25 @@ mongoc_cmd_parts_assemble (mongoc_cmd_parts_t *parts, _mongoc_cmd_parts_ensure_copied (parts); _mongoc_client_session_append_read_concern ( - cs, - &parts->read_concern_document, - parts->is_read_command, - &parts->assembled_body); + cs, &parts->read_concern_document, parts->is_read_command, &parts->assembled_body); } else if (!bson_empty (&parts->read_concern_document)) { _mongoc_cmd_parts_ensure_copied (parts); - bson_append_document (&parts->assembled_body, - "readConcern", - 11, - &parts->read_concern_document); + bson_append_document (&parts->assembled_body, "readConcern", 11, &parts->read_concern_document); } } /* if transaction is in progress do not inherit write concern */ - if (parts->assembled.is_txn_finish || - !_mongoc_client_session_in_txn (cs)) { + if (parts->assembled.is_txn_finish || !_mongoc_client_session_in_txn (cs)) { _mongoc_cmd_parts_add_write_concern (parts); } _mongoc_cmd_parts_ensure_copied (parts); - if (!_mongoc_client_session_append_txn ( - cs, &parts->assembled_body, error)) { + if (!_mongoc_client_session_append_txn (cs, &parts->assembled_body, error)) { GOTO (done); } ret = true; - } else if (server_type == MONGOC_SERVER_MONGOS || - server_stream->topology_type == MONGOC_TOPOLOGY_LOAD_BALANCED) { + } else if (server_type == MONGOC_SERVER_MONGOS || server_stream->topology_type == MONGOC_TOPOLOGY_LOAD_BALANCED) { /* TODO (CDRIVER-4117) remove the check of the topology description type. */ _mongoc_cmd_parts_assemble_mongos (parts, server_stream); @@ -1036,14 +954,10 @@ mongoc_cmd_is_compressible (mongoc_cmd_t *cmd) BSON_ASSERT (cmd); BSON_ASSERT (cmd->command_name); - return !!strcasecmp (cmd->command_name, "hello") && - !!strcasecmp (cmd->command_name, HANDSHAKE_CMD_LEGACY_HELLO) && - !!strcasecmp (cmd->command_name, "authenticate") && - !!strcasecmp (cmd->command_name, "getnonce") && - !!strcasecmp (cmd->command_name, "saslstart") && - !!strcasecmp (cmd->command_name, "saslcontinue") && - !!strcasecmp (cmd->command_name, "createuser") && - !!strcasecmp (cmd->command_name, "updateuser"); + return !!strcasecmp (cmd->command_name, "hello") && !!strcasecmp (cmd->command_name, HANDSHAKE_CMD_LEGACY_HELLO) && + !!strcasecmp (cmd->command_name, "authenticate") && !!strcasecmp (cmd->command_name, "getnonce") && + !!strcasecmp (cmd->command_name, "saslstart") && !!strcasecmp (cmd->command_name, "saslcontinue") && + !!strcasecmp (cmd->command_name, "createuser") && !!strcasecmp (cmd->command_name, "updateuser"); } /*-------------------------------------------------------------------------- @@ -1113,8 +1027,7 @@ _mongoc_cmd_append_payload_as_array (const mongoc_cmd_t *cmd, bson_t *out) *-------------------------------------------------------------------------- */ void -_mongoc_cmd_append_server_api (bson_t *command_body, - const mongoc_server_api_t *api) +_mongoc_cmd_append_server_api (bson_t *command_body, const mongoc_server_api_t *api) { const char *string_version; @@ -1132,9 +1045,6 @@ _mongoc_cmd_append_server_api (bson_t *command_body, } if (api->deprecation_errors.is_set) { - bson_append_bool (command_body, - "apiDeprecationErrors", - -1, - api->deprecation_errors.value); + bson_append_bool (command_body, "apiDeprecationErrors", -1, api->deprecation_errors.value); } } diff --git a/src/libmongoc/src/mongoc/mongoc-collection.c b/src/libmongoc/src/mongoc/mongoc-collection.c index 5dc87be4ef..a1adc64525 100644 --- a/src/libmongoc/src/mongoc/mongoc-collection.c +++ b/src/libmongoc/src/mongoc/mongoc-collection.c @@ -47,19 +47,17 @@ #define MONGOC_LOG_DOMAIN "collection" static void -_mongoc_collection_write_command_execute ( - mongoc_write_command_t *command, - const mongoc_collection_t *collection, - const mongoc_write_concern_t *write_concern, - mongoc_client_session_t *cs, - mongoc_write_result_t *result) +_mongoc_collection_write_command_execute (mongoc_write_command_t *command, + const mongoc_collection_t *collection, + const mongoc_write_concern_t *write_concern, + mongoc_client_session_t *cs, + mongoc_write_result_t *result) { mongoc_server_stream_t *server_stream; ENTRY; - server_stream = mongoc_cluster_stream_for_writes ( - &collection->client->cluster, cs, NULL, NULL, &result->error); + server_stream = mongoc_cluster_stream_for_writes (&collection->client->cluster, cs, NULL, NULL, &result->error); if (!server_stream) { /* result->error has been filled out */ @@ -83,23 +81,18 @@ _mongoc_collection_write_command_execute ( static void -_mongoc_collection_write_command_execute_idl ( - mongoc_write_command_t *command, - const mongoc_collection_t *collection, - mongoc_crud_opts_t *crud, - mongoc_write_result_t *result) +_mongoc_collection_write_command_execute_idl (mongoc_write_command_t *command, + const mongoc_collection_t *collection, + mongoc_crud_opts_t *crud, + mongoc_write_result_t *result) { mongoc_server_stream_t *server_stream; bson_t reply; ENTRY; - server_stream = - mongoc_cluster_stream_for_writes (&collection->client->cluster, - crud->client_session, - NULL, - &reply, - &result->error); + server_stream = mongoc_cluster_stream_for_writes ( + &collection->client->cluster, crud->client_session, NULL, &reply, &result->error); if (!server_stream) { /* result->error and reply have been filled out */ @@ -108,8 +101,7 @@ _mongoc_collection_write_command_execute_idl ( EXIT; } - if (_mongoc_client_session_in_txn (crud->client_session) && - crud->writeConcern) { + if (_mongoc_client_session_in_txn (crud->client_session) && crud->writeConcern) { bson_set_error (&result->error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, @@ -118,20 +110,13 @@ _mongoc_collection_write_command_execute_idl ( EXIT; } - if (!crud->writeConcern && - !_mongoc_client_session_in_txn (crud->client_session)) { + if (!crud->writeConcern && !_mongoc_client_session_in_txn (crud->client_session)) { crud->writeConcern = collection->write_concern; crud->write_concern_owned = false; } - _mongoc_write_command_execute_idl (command, - collection->client, - server_stream, - collection->db, - collection->collection, - 0 /* offset */, - crud, - result); + _mongoc_write_command_execute_idl ( + command, collection->client, server_stream, collection->db, collection->collection, 0 /* offset */, crud, result); mongoc_server_stream_cleanup (server_stream); @@ -182,13 +167,9 @@ _mongoc_collection_new (mongoc_client_t *client, col = (mongoc_collection_t *) bson_malloc0 (sizeof *col); col->client = client; - col->write_concern = write_concern - ? mongoc_write_concern_copy (write_concern) - : mongoc_write_concern_new (); - col->read_concern = read_concern ? mongoc_read_concern_copy (read_concern) - : mongoc_read_concern_new (); - col->read_prefs = read_prefs ? mongoc_read_prefs_copy (read_prefs) - : mongoc_read_prefs_new (MONGOC_READ_PRIMARY); + col->write_concern = write_concern ? mongoc_write_concern_copy (write_concern) : mongoc_write_concern_new (); + col->read_concern = read_concern ? mongoc_read_concern_copy (read_concern) : mongoc_read_concern_new (); + col->read_prefs = read_prefs ? mongoc_read_prefs_copy (read_prefs) : mongoc_read_prefs_new (MONGOC_READ_PRIMARY); col->ns = bson_strdup_printf ("%s.%s", db, collection); col->db = bson_strdup (db); @@ -376,11 +357,9 @@ mongoc_collection_find (mongoc_collection_t *collection, /* IN */ bson_init (&opts); _mongoc_cursor_flags_to_opts (flags, &opts, &secondary_ok); /* check if the query is wrapped in $query */ - has_unwrapped = _mongoc_cursor_translate_dollar_query_opts ( - query, &opts, &unwrapped, &error); + has_unwrapped = _mongoc_cursor_translate_dollar_query_opts (query, &opts, &unwrapped, &error); if (!bson_empty0 (fields)) { - bson_append_document ( - &opts, MONGOC_CURSOR_PROJECTION, MONGOC_CURSOR_PROJECTION_LEN, fields); + bson_append_document (&opts, MONGOC_CURSOR_PROJECTION, MONGOC_CURSOR_PROJECTION_LEN, fields); } cursor = _mongoc_cursor_find_new (collection->client, collection->ns, @@ -451,13 +430,8 @@ mongoc_collection_find_with_opts (mongoc_collection_t *collection, bson_clear (&collection->gle); - return _mongoc_cursor_find_new (collection->client, - collection->ns, - filter, - opts, - read_prefs, - collection->read_prefs, - collection->read_concern); + return _mongoc_cursor_find_new ( + collection->client, collection->ns, filter, opts, read_prefs, collection->read_prefs, collection->read_concern); } @@ -532,8 +506,7 @@ mongoc_collection_command (mongoc_collection_t *collection, */ /* flags, skip, limit, batch_size, fields are unused */ - cursor = _mongoc_cursor_cmd_deprecated_new ( - collection->client, ns, query, read_prefs); + cursor = _mongoc_cursor_cmd_deprecated_new (collection->client, ns, query, read_prefs); bson_free (ns); return cursor; } @@ -565,11 +538,8 @@ mongoc_collection_read_command_with_opts (mongoc_collection_t *collection, bool -mongoc_collection_write_command_with_opts (mongoc_collection_t *collection, - const bson_t *command, - const bson_t *opts, - bson_t *reply, - bson_error_t *error) +mongoc_collection_write_command_with_opts ( + mongoc_collection_t *collection, const bson_t *command, const bson_t *opts, bson_t *reply, bson_error_t *error) { BSON_ASSERT_PARAM (collection); @@ -589,13 +559,12 @@ mongoc_collection_write_command_with_opts (mongoc_collection_t *collection, bool -mongoc_collection_read_write_command_with_opts ( - mongoc_collection_t *collection, - const bson_t *command, - const mongoc_read_prefs_t *read_prefs /* IGNORED */, - const bson_t *opts, - bson_t *reply, - bson_error_t *error) +mongoc_collection_read_write_command_with_opts (mongoc_collection_t *collection, + const bson_t *command, + const mongoc_read_prefs_t *read_prefs /* IGNORED */, + const bson_t *opts, + bson_t *reply, + bson_error_t *error) { BSON_ASSERT_PARAM (collection); @@ -719,8 +688,7 @@ mongoc_collection_count (mongoc_collection_t *collection, /* IN */ if (collection->read_concern->level != NULL) { const bson_t *read_concern_bson; - read_concern_bson = - _mongoc_read_concern_get_bson (collection->read_concern); + read_concern_bson = _mongoc_read_concern_get_bson (collection->read_concern); BSON_APPEND_DOCUMENT (&opts, "readConcern", read_concern_bson); } @@ -728,8 +696,7 @@ mongoc_collection_count (mongoc_collection_t *collection, /* IN */ * preference argument and otherwise MUST use the default read preference * from client, database or collection configuration. */ BEGIN_IGNORE_DEPRECATIONS - ret = mongoc_collection_count_with_opts ( - collection, flags, query, skip, limit, &opts, read_prefs, error); + ret = mongoc_collection_count_with_opts (collection, flags, query, skip, limit, &opts, read_prefs, error); END_IGNORE_DEPRECATIONS bson_destroy (&opts); @@ -738,15 +705,14 @@ mongoc_collection_count (mongoc_collection_t *collection, /* IN */ int64_t -mongoc_collection_count_with_opts ( - mongoc_collection_t *collection, /* IN */ - mongoc_query_flags_t flags, /* IN */ - const bson_t *query, /* IN */ - int64_t skip, /* IN */ - int64_t limit, /* IN */ - const bson_t *opts, /* IN */ - const mongoc_read_prefs_t *read_prefs, /* IN */ - bson_error_t *error) /* OUT */ +mongoc_collection_count_with_opts (mongoc_collection_t *collection, /* IN */ + mongoc_query_flags_t flags, /* IN */ + const bson_t *query, /* IN */ + int64_t skip, /* IN */ + int64_t limit, /* IN */ + const bson_t *opts, /* IN */ + const mongoc_read_prefs_t *read_prefs, /* IN */ + bson_error_t *error) /* OUT */ { bson_iter_t iter; int64_t ret = -1; @@ -758,16 +724,14 @@ mongoc_collection_count_with_opts ( BSON_ASSERT_PARAM (collection); - bsonBuildAppend ( - cmd, - kv ("count", - utf8_w_len (collection->collection, collection->collectionlen)), - kv ("query", - if (query, // If we have a query, - then (bson (*query)), // Copy it - else (doc ()))), // Otherwise, add an empty doc - if (limit, then (kv ("limit", int64 (limit)))), - if (skip, then (kv ("skip", int64 (skip))))); + bsonBuildAppend (cmd, + kv ("count", utf8_w_len (collection->collection, collection->collectionlen)), + kv ("query", + if (query, // If we have a query, + then (bson (*query)), // Copy it + else (doc ()))), // Otherwise, add an empty doc + if (limit, then (kv ("limit", int64 (limit)))), + if (skip, then (kv ("skip", int64 (skip))))); success = _mongoc_client_command_with_opts (collection->client, @@ -796,12 +760,11 @@ mongoc_collection_count_with_opts ( } int64_t -mongoc_collection_estimated_document_count ( - mongoc_collection_t *coll, - const bson_t *opts, - const mongoc_read_prefs_t *read_prefs, - bson_t *reply, - bson_error_t *error) +mongoc_collection_estimated_document_count (mongoc_collection_t *coll, + const bson_t *opts, + const mongoc_read_prefs_t *read_prefs, + bson_t *reply, + bson_error_t *error) { bson_iter_t iter; int64_t count = -1; @@ -815,8 +778,7 @@ mongoc_collection_estimated_document_count ( BSON_ASSERT_PARAM (coll); - server_stream = mongoc_cluster_stream_for_reads ( - &coll->client->cluster, read_prefs, NULL, NULL, reply, error); + server_stream = mongoc_cluster_stream_for_reads (&coll->client->cluster, read_prefs, NULL, NULL, reply, error); if (opts && bson_has_field (opts, "sessionId")) { bson_set_error (error, @@ -887,8 +849,7 @@ _make_aggregate_for_count (const mongoc_collection_t *coll, bson_t empty; bson_init (out); - bson_append_utf8 ( - out, "aggregate", 9, coll->collection, coll->collectionlen); + bson_append_utf8 (out, "aggregate", 9, coll->collection, coll->collectionlen); bson_append_document_begin (out, "cursor", 6, &empty); bson_append_document_end (out, &empty); bson_append_array_builder_begin (out, "pipeline", 8, &pipeline); @@ -946,20 +907,18 @@ mongoc_collection_count_documents (mongoc_collection_t *coll, // Parse options to validate. mongoc_count_document_opts_t cd_opts; - if (!_mongoc_count_document_opts_parse ( - coll->client, opts, &cd_opts, error)) { + if (!_mongoc_count_document_opts_parse (coll->client, opts, &cd_opts, error)) { GOTO (done); } _make_aggregate_for_count (coll, filter, &cd_opts, &aggregate_cmd); bson_init (&aggregate_opts); if (opts) { - bsonBuildAppend (aggregate_opts, - insert (*opts, not(key ("skip", "limit")))); + bsonBuildAppend (aggregate_opts, insert (*opts, not(key ("skip", "limit")))); } - ret = mongoc_collection_read_command_with_opts ( - coll, &aggregate_cmd, read_prefs, &aggregate_opts, &cmd_reply, error); + ret = + mongoc_collection_read_command_with_opts (coll, &aggregate_cmd, read_prefs, &aggregate_opts, &cmd_reply, error); bson_destroy (&aggregate_cmd); bson_destroy (&aggregate_opts); if (reply) { @@ -972,8 +931,7 @@ mongoc_collection_count_documents (mongoc_collection_t *coll, } /* steals reply */ - cursor = mongoc_cursor_new_from_command_reply_with_opts ( - coll->client, &cmd_reply, NULL); + cursor = mongoc_cursor_new_from_command_reply_with_opts (coll->client, &cmd_reply, NULL); BSON_ASSERT (mongoc_cursor_get_id (cursor) == 0); ret = mongoc_cursor_next (cursor, &result); if (!ret) { @@ -985,8 +943,7 @@ mongoc_collection_count_documents (mongoc_collection_t *coll, } } - if (bson_iter_init_find (&iter, result, "n") && - BSON_ITER_HOLDS_INT (&iter)) { + if (bson_iter_init_find (&iter, result, "n") && BSON_ITER_HOLDS_INT (&iter)) { count = bson_iter_as_int64 (&iter); } @@ -1024,9 +981,7 @@ mongoc_collection_drop (mongoc_collection_t *collection, /* IN */ static bool -drop_with_opts (mongoc_collection_t *collection, - const bson_t *opts, - bson_error_t *error) +drop_with_opts (mongoc_collection_t *collection, const bson_t *opts, bson_error_t *error) { bool ret; bson_t cmd; @@ -1034,8 +989,7 @@ drop_with_opts (mongoc_collection_t *collection, BSON_ASSERT_PARAM (collection); bson_init (&cmd); - bson_append_utf8 ( - &cmd, "drop", 4, collection->collection, collection->collectionlen); + bson_append_utf8 (&cmd, "drop", 4, collection->collection, collection->collectionlen); ret = _mongoc_client_command_with_opts (collection->client, collection->db, @@ -1075,14 +1029,12 @@ drop_with_opts_with_encryptedFields (mongoc_collection_t *collection, } /* Drop ESC collection. */ - escName = _mongoc_get_encryptedField_state_collection ( - encryptedFields, name, "esc", error); + escName = _mongoc_get_encryptedField_state_collection (encryptedFields, name, "esc", error); if (!escName) { goto fail; } - escCollection = mongoc_client_get_collection ( - collection->client, collection->db, escName); + escCollection = mongoc_client_get_collection (collection->client, collection->db, escName); if (!drop_with_opts (escCollection, NULL /* opts */, error)) { if (error->code == MONGOC_SERVER_ERR_NS_NOT_FOUND) { memset (error, 0, sizeof (bson_error_t)); @@ -1092,14 +1044,12 @@ drop_with_opts_with_encryptedFields (mongoc_collection_t *collection, } /* Drop ECOC collection. */ - ecocName = _mongoc_get_encryptedField_state_collection ( - encryptedFields, name, "ecoc", error); + ecocName = _mongoc_get_encryptedField_state_collection (encryptedFields, name, "ecoc", error); if (!ecocName) { goto fail; } - ecocCollection = mongoc_client_get_collection ( - collection->client, collection->db, ecocName); + ecocCollection = mongoc_client_get_collection (collection->client, collection->db, ecocName); if (!drop_with_opts (ecocCollection, NULL /* opts */, error)) { if (error->code == MONGOC_SERVER_ERR_NS_NOT_FOUND) { memset (error, 0, sizeof (bson_error_t)); @@ -1127,9 +1077,7 @@ drop_with_opts_with_encryptedFields (mongoc_collection_t *collection, } bool -mongoc_collection_drop_with_opts (mongoc_collection_t *collection, - const bson_t *opts, - bson_error_t *error) +mongoc_collection_drop_with_opts (mongoc_collection_t *collection, const bson_t *opts, bson_error_t *error) { // The encryptedFields for the collection. bson_t encryptedFields = BSON_INITIALIZER; @@ -1138,14 +1086,13 @@ mongoc_collection_drop_with_opts (mongoc_collection_t *collection, // Try to find the encryptedFields from the collection options or from the // encryptedFieldsMap. - if (!_mongoc_get_collection_encryptedFields ( - collection->client, - collection->db, - mongoc_collection_get_name (collection), - opts, - true /* checkEncryptedFieldsMap */, - &encryptedFields, - error)) { + if (!_mongoc_get_collection_encryptedFields (collection->client, + collection->db, + mongoc_collection_get_name (collection), + opts, + true /* checkEncryptedFieldsMap */, + &encryptedFields, + error)) { goto done; } @@ -1154,11 +1101,7 @@ mongoc_collection_drop_with_opts (mongoc_collection_t *collection, if (collection->client->topology->encrypted_fields_map != NULL) { // but we can ask the server for them: if (!_mongoc_get_encryptedFields_from_server ( - collection->client, - collection->db, - mongoc_collection_get_name (collection), - &encryptedFields, - error)) { + collection->client, collection->db, mongoc_collection_get_name (collection), &encryptedFields, error)) { goto done; } } @@ -1173,20 +1116,14 @@ mongoc_collection_drop_with_opts (mongoc_collection_t *collection, // We've found the encryptedFields, so we need to do something different // to drop this collection: - bsonBuildAppend ( - opts_without_encryptedFields, - if (opts, then (insert (*opts, not(key ("encryptedFields")))))); + bsonBuildAppend (opts_without_encryptedFields, if (opts, then (insert (*opts, not(key ("encryptedFields")))))); if (bsonBuildError) { - bson_set_error (error, - MONGOC_ERROR_BSON, - MONGOC_ERROR_BSON_INVALID, - "Error while updating drop options: %s", - bsonBuildError); + bson_set_error ( + error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "Error while updating drop options: %s", bsonBuildError); goto done; } - okay = drop_with_opts_with_encryptedFields ( - collection, &opts_without_encryptedFields, &encryptedFields, error); + okay = drop_with_opts_with_encryptedFields (collection, &opts_without_encryptedFields, &encryptedFields, error); done: bson_destroy (&opts_without_encryptedFields); @@ -1216,8 +1153,7 @@ mongoc_collection_drop_index (mongoc_collection_t *collection, /* IN */ const char *index_name, /* IN */ bson_error_t *error) /* OUT */ { - return mongoc_collection_drop_index_with_opts ( - collection, index_name, NULL, error); + return mongoc_collection_drop_index_with_opts (collection, index_name, NULL, error); } @@ -1234,11 +1170,7 @@ mongoc_collection_drop_index_with_opts (mongoc_collection_t *collection, BSON_ASSERT_PARAM (index_name); bson_init (&cmd); - bson_append_utf8 (&cmd, - "dropIndexes", - -1, - collection->collection, - collection->collectionlen); + bson_append_utf8 (&cmd, "dropIndexes", -1, collection->collection, collection->collectionlen); bson_append_utf8 (&cmd, "index", -1, index_name, -1); ret = _mongoc_client_command_with_opts (collection->client, @@ -1280,20 +1212,12 @@ mongoc_collection_keys_to_index_string (const bson_t *keys) * representing direction */ type = bson_iter_type (&iter); if (type == BSON_TYPE_UTF8) { - bson_string_append_printf (s, - (i++ ? "_%s_%s" : "%s_%s"), - bson_iter_key (&iter), - bson_iter_utf8 (&iter, NULL)); + bson_string_append_printf (s, (i++ ? "_%s_%s" : "%s_%s"), bson_iter_key (&iter), bson_iter_utf8 (&iter, NULL)); } else if (type == BSON_TYPE_INT32) { - bson_string_append_printf (s, - (i++ ? "_%s_%d" : "%s_%d"), - bson_iter_key (&iter), - bson_iter_int32 (&iter)); + bson_string_append_printf (s, (i++ ? "_%s_%d" : "%s_%d"), bson_iter_key (&iter), bson_iter_int32 (&iter)); } else if (type == BSON_TYPE_INT64) { - bson_string_append_printf (s, - (i++ ? "_%s_%" PRId64 : "%s_%" PRId64), - bson_iter_key (&iter), - bson_iter_int64 (&iter)); + bson_string_append_printf ( + s, (i++ ? "_%s_%" PRId64 : "%s_%" PRId64), bson_iter_key (&iter), bson_iter_int64 (&iter)); } else { bson_string_free (s, true); return NULL; @@ -1314,8 +1238,7 @@ mongoc_collection_create_index (mongoc_collection_t *collection, BEGIN_IGNORE_DEPRECATIONS - ret = mongoc_collection_create_index_with_opts ( - collection, keys, opt, NULL, &reply, error); + ret = mongoc_collection_create_index_with_opts (collection, keys, opt, NULL, &reply, error); END_IGNORE_DEPRECATIONS @@ -1324,8 +1247,7 @@ mongoc_collection_create_index (mongoc_collection_t *collection, } static bool -_mongoc_collection_index_keys_equal (const bson_t *expected, - const bson_t *actual) +_mongoc_collection_index_keys_equal (const bson_t *expected, const bson_t *actual) { bson_iter_t iter_expected; bson_iter_t iter_actual; @@ -1341,21 +1263,16 @@ _mongoc_collection_index_keys_equal (const bson_t *expected, } /* If key order does not match, indexes are unequal */ - if (strcmp (bson_iter_key (&iter_expected), - bson_iter_key (&iter_actual)) != 0) { + if (strcmp (bson_iter_key (&iter_expected), bson_iter_key (&iter_actual)) != 0) { return false; } - if (BSON_ITER_HOLDS_NUMBER (&iter_expected) && - BSON_ITER_HOLDS_NUMBER (&iter_actual)) { - if (bson_iter_as_int64 (&iter_expected) != - bson_iter_as_int64 (&iter_actual)) { + if (BSON_ITER_HOLDS_NUMBER (&iter_expected) && BSON_ITER_HOLDS_NUMBER (&iter_actual)) { + if (bson_iter_as_int64 (&iter_expected) != bson_iter_as_int64 (&iter_actual)) { return false; } - } else if (BSON_ITER_HOLDS_UTF8 (&iter_expected) && - BSON_ITER_HOLDS_UTF8 (&iter_actual)) { - if (strcmp (bson_iter_utf8 (&iter_expected, NULL), - bson_iter_utf8 (&iter_actual, NULL)) != 0) { + } else if (BSON_ITER_HOLDS_UTF8 (&iter_expected) && BSON_ITER_HOLDS_UTF8 (&iter_actual)) { + if (strcmp (bson_iter_utf8 (&iter_expected, NULL), bson_iter_utf8 (&iter_actual, NULL)) != 0) { return false; } } else { @@ -1435,11 +1352,10 @@ _mongoc_collection_create_index_if_not_exists (mongoc_collection_t *collection, char *alloc_name = mongoc_collection_keys_to_index_string (keys); if (!alloc_name) { - bson_set_error ( - error, - MONGOC_ERROR_BSON, - MONGOC_ERROR_BSON_INVALID, - "Cannot generate index name from invalid `keys` argument"); + bson_set_error (error, + MONGOC_ERROR_BSON, + MONGOC_ERROR_BSON_INVALID, + "Cannot generate index name from invalid `keys` argument"); GOTO (done); } @@ -1457,8 +1373,7 @@ _mongoc_collection_create_index_if_not_exists (mongoc_collection_t *collection, BCON_DOCUMENT (&index), "]"); - r = mongoc_collection_write_command_with_opts ( - collection, &command, NULL, NULL, error); + r = mongoc_collection_write_command_with_opts (collection, &command, NULL, NULL, error); done: bson_destroy (&index); @@ -1502,12 +1417,10 @@ mongoc_collection_create_index_with_opts (mongoc_collection_t *collection, def_opt = mongoc_index_opt_get_default (); opt = opt ? opt : def_opt; - mongoc_cmd_parts_init ( - &parts, collection->client, collection->db, MONGOC_QUERY_NONE, &cmd); + mongoc_cmd_parts_init (&parts, collection->client, collection->db, MONGOC_QUERY_NONE, &cmd); parts.is_write_command = true; - if (!_mongoc_create_index_opts_parse ( - collection->client, opts, &parsed, error)) { + if (!_mongoc_create_index_opts_parse (collection->client, opts, &parsed, error)) { GOTO (done); } @@ -1525,11 +1438,10 @@ mongoc_collection_create_index_with_opts (mongoc_collection_t *collection, if (alloc_name) { name = alloc_name; } else { - bson_set_error ( - error, - MONGOC_ERROR_BSON, - MONGOC_ERROR_BSON_INVALID, - "Cannot generate index name from invalid `keys` argument"); + bson_set_error (error, + MONGOC_ERROR_BSON, + MONGOC_ERROR_BSON_INVALID, + "Cannot generate index name from invalid `keys` argument"); GOTO (done); } } @@ -1537,8 +1449,7 @@ mongoc_collection_create_index_with_opts (mongoc_collection_t *collection, /* * Build our createIndexes command to send to the server. */ - BSON_ASSERT ( - BSON_APPEND_UTF8 (&cmd, "createIndexes", collection->collection)); + BSON_ASSERT (BSON_APPEND_UTF8 (&cmd, "createIndexes", collection->collection)); bson_append_array_builder_begin (&cmd, "indexes", 7, &ar); bson_array_builder_append_document_begin (ar, &doc); BSON_ASSERT (BSON_APPEND_DOCUMENT (&doc, "key", keys)); @@ -1556,8 +1467,7 @@ mongoc_collection_create_index_with_opts (mongoc_collection_t *collection, BSON_ASSERT (BSON_APPEND_BOOL (&doc, "sparse", true)); } if (opt->expire_after_seconds != def_opt->expire_after_seconds) { - BSON_ASSERT (BSON_APPEND_INT32 ( - &doc, "expireAfterSeconds", opt->expire_after_seconds)); + BSON_ASSERT (BSON_APPEND_INT32 (&doc, "expireAfterSeconds", opt->expire_after_seconds)); } if (opt->v != def_opt->v) { BSON_ASSERT (BSON_APPEND_INT32 (&doc, "v", opt->v)); @@ -1566,16 +1476,13 @@ mongoc_collection_create_index_with_opts (mongoc_collection_t *collection, BSON_ASSERT (BSON_APPEND_DOCUMENT (&doc, "weights", opt->weights)); } if (opt->default_language != def_opt->default_language) { - BSON_ASSERT ( - BSON_APPEND_UTF8 (&doc, "default_language", opt->default_language)); + BSON_ASSERT (BSON_APPEND_UTF8 (&doc, "default_language", opt->default_language)); } if (opt->language_override != def_opt->language_override) { - BSON_ASSERT ( - BSON_APPEND_UTF8 (&doc, "language_override", opt->language_override)); + BSON_ASSERT (BSON_APPEND_UTF8 (&doc, "language_override", opt->language_override)); } if (opt->partial_filter_expression) { - BSON_ASSERT (BSON_APPEND_DOCUMENT ( - &doc, "partialFilterExpression", opt->partial_filter_expression)); + BSON_ASSERT (BSON_APPEND_DOCUMENT (&doc, "partialFilterExpression", opt->partial_filter_expression)); } if (opt->collation) { BSON_ASSERT (BSON_APPEND_DOCUMENT (&doc, "collation", opt->collation)); @@ -1584,24 +1491,19 @@ mongoc_collection_create_index_with_opts (mongoc_collection_t *collection, geo_opt = opt->geo_options; def_geo = mongoc_index_opt_geo_get_default (); if (geo_opt->twod_sphere_version != def_geo->twod_sphere_version) { - BSON_ASSERT (BSON_APPEND_INT32 ( - &doc, "2dsphereIndexVersion", geo_opt->twod_sphere_version)); + BSON_ASSERT (BSON_APPEND_INT32 (&doc, "2dsphereIndexVersion", geo_opt->twod_sphere_version)); } if (geo_opt->twod_bits_precision != def_geo->twod_bits_precision) { - BSON_ASSERT ( - BSON_APPEND_INT32 (&doc, "bits", geo_opt->twod_bits_precision)); + BSON_ASSERT (BSON_APPEND_INT32 (&doc, "bits", geo_opt->twod_bits_precision)); } if (geo_opt->twod_location_min != def_geo->twod_location_min) { - BSON_ASSERT ( - BSON_APPEND_DOUBLE (&doc, "min", geo_opt->twod_location_min)); + BSON_ASSERT (BSON_APPEND_DOUBLE (&doc, "min", geo_opt->twod_location_min)); } if (geo_opt->twod_location_max != def_geo->twod_location_max) { - BSON_ASSERT ( - BSON_APPEND_DOUBLE (&doc, "max", geo_opt->twod_location_max)); + BSON_ASSERT (BSON_APPEND_DOUBLE (&doc, "max", geo_opt->twod_location_max)); } if (geo_opt->haystack_bucket_size != def_geo->haystack_bucket_size) { - BSON_ASSERT (BSON_APPEND_DOUBLE ( - &doc, "bucketSize", geo_opt->haystack_bucket_size)); + BSON_ASSERT (BSON_APPEND_DOUBLE (&doc, "bucketSize", geo_opt->haystack_bucket_size)); } } @@ -1612,8 +1514,7 @@ mongoc_collection_create_index_with_opts (mongoc_collection_t *collection, wt_opt = (mongoc_index_opt_wt_t *) storage_opt; BSON_APPEND_DOCUMENT_BEGIN (&doc, "storageEngine", &storage_doc); BSON_APPEND_DOCUMENT_BEGIN (&storage_doc, "wiredTiger", &wt_doc); - BSON_ASSERT ( - BSON_APPEND_UTF8 (&wt_doc, "configString", wt_opt->config_str)); + BSON_ASSERT (BSON_APPEND_UTF8 (&wt_doc, "configString", wt_opt->config_str)); bson_append_document_end (&storage_doc, &wt_doc); bson_append_document_end (&doc, &storage_doc); break; @@ -1625,32 +1526,27 @@ mongoc_collection_create_index_with_opts (mongoc_collection_t *collection, bson_array_builder_append_document_end (ar, &doc); bson_append_array_builder_end (&cmd, ar); - server_stream = mongoc_cluster_stream_for_writes ( - &collection->client->cluster, parsed.client_session, NULL, reply, error); + server_stream = + mongoc_cluster_stream_for_writes (&collection->client->cluster, parsed.client_session, NULL, reply, error); if (!server_stream) { reply_initialized = true; GOTO (done); } - if (!mongoc_cmd_parts_set_write_concern ( - &parts, parsed.writeConcern, error)) { + if (!mongoc_cmd_parts_set_write_concern (&parts, parsed.writeConcern, error)) { GOTO (done); } parts.assembled.session = parsed.client_session; if (!bson_concat (&parts.extra, &parsed.extra)) { - bson_set_error (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "'opts' is too large"); + bson_set_error (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "'opts' is too large"); GOTO (done); } cluster = &collection->client->cluster; if (mongoc_cmd_parts_assemble (&parts, server_stream, error)) { - ret = mongoc_cluster_run_command_monitored ( - cluster, &parts.assembled, reply, error); + ret = mongoc_cluster_run_command_monitored (cluster, &parts.assembled, reply, error); } else { _mongoc_bson_init_if_set (reply); } @@ -1690,8 +1586,7 @@ mongoc_collection_ensure_index (mongoc_collection_t *collection, mongoc_cursor_t * -mongoc_collection_find_indexes (mongoc_collection_t *collection, - bson_error_t *error) +mongoc_collection_find_indexes (mongoc_collection_t *collection, bson_error_t *error) { mongoc_cursor_t *cursor; @@ -1704,8 +1599,7 @@ mongoc_collection_find_indexes (mongoc_collection_t *collection, mongoc_cursor_t * -mongoc_collection_find_indexes_with_opts (mongoc_collection_t *collection, - const bson_t *opts) +mongoc_collection_find_indexes_with_opts (mongoc_collection_t *collection, const bson_t *opts) { mongoc_cursor_t *cursor; bson_t cmd = BSON_INITIALIZER; @@ -1714,26 +1608,20 @@ mongoc_collection_find_indexes_with_opts (mongoc_collection_t *collection, BSON_ASSERT_PARAM (collection); - bson_append_utf8 (&cmd, - "listIndexes", - -1, - collection->collection, - collection->collectionlen); + bson_append_utf8 (&cmd, "listIndexes", -1, collection->collection, collection->collectionlen); BSON_APPEND_DOCUMENT_BEGIN (&cmd, "cursor", &child); bson_append_document_end (&cmd, &child); /* No read preference. Index Enumeration Spec: "run listIndexes on the * primary node in replicaSet mode". */ - cursor = _mongoc_cursor_cmd_new ( - collection->client, collection->ns, &cmd, opts, NULL, NULL, NULL); + cursor = _mongoc_cursor_cmd_new (collection->client, collection->ns, &cmd, opts, NULL, NULL, NULL); if (!mongoc_cursor_error (cursor, &error)) { _mongoc_cursor_prime (cursor); } - if (mongoc_cursor_error (cursor, &error) && - error.code == MONGOC_ERROR_COLLECTION_DOES_NOT_EXIST) { + if (mongoc_cursor_error (cursor, &error) && error.code == MONGOC_ERROR_COLLECTION_DOES_NOT_EXIST) { /* collection does not exist. from spec: return no documents but no err: * https://github.com/mongodb/specifications/blob/master/source/enumerate-indexes.rst#enumeration-getting-index-information */ @@ -1797,8 +1685,7 @@ mongoc_collection_insert_bulk (mongoc_collection_t *collection, if (!(flags & MONGOC_INSERT_NO_VALIDATE)) { for (i = 0; i < n_documents; i++) { - if (!_mongoc_validate_new_document ( - documents[i], _mongoc_default_insert_vflags, error)) { + if (!_mongoc_validate_new_document (documents[i], _mongoc_default_insert_vflags, error)) { RETURN (false); } } @@ -1810,19 +1697,13 @@ mongoc_collection_insert_bulk (mongoc_collection_t *collection, write_flags.ordered = !(flags & MONGOC_INSERT_CONTINUE_ON_ERROR); - _mongoc_write_command_init_insert ( - &command, - NULL, - NULL, - write_flags, - ++collection->client->cluster.operation_id); + _mongoc_write_command_init_insert (&command, NULL, NULL, write_flags, ++collection->client->cluster.operation_id); for (i = 0; i < n_documents; i++) { _mongoc_write_command_insert_append (&command, documents[i]); } - _mongoc_collection_write_command_execute ( - &command, collection, write_concern, NULL, &result); + _mongoc_collection_write_command_execute (&command, collection, write_concern, NULL, &result); collection->gle = bson_new (); ret = MONGOC_WRITE_RESULT_COMPLETE (&result, @@ -1858,12 +1739,10 @@ mongoc_collection_insert (mongoc_collection_t *collection, } if (write_concern) { - mongoc_write_concern_append ((mongoc_write_concern_t *) write_concern, - &opts); + mongoc_write_concern_append ((mongoc_write_concern_t *) write_concern, &opts); } - r = - mongoc_collection_insert_one (collection, document, &opts, &reply, error); + r = mongoc_collection_insert_one (collection, document, &opts, &reply, error); collection->gle = bson_copy (&reply); bson_destroy (&reply); @@ -1898,11 +1777,8 @@ mongoc_collection_insert (mongoc_collection_t *collection, */ bool -mongoc_collection_insert_one (mongoc_collection_t *collection, - const bson_t *document, - const bson_t *opts, - bson_t *reply, - bson_error_t *error) +mongoc_collection_insert_one ( + mongoc_collection_t *collection, const bson_t *document, const bson_t *opts, bson_t *reply, bson_error_t *error) { mongoc_insert_one_opts_t insert_one_opts; mongoc_write_command_t command; @@ -1917,8 +1793,7 @@ mongoc_collection_insert_one (mongoc_collection_t *collection, _mongoc_bson_init_if_set (reply); - if (!_mongoc_insert_one_opts_parse ( - collection->client, opts, &insert_one_opts, error)) { + if (!_mongoc_insert_one_opts_parse (collection->client, opts, &insert_one_opts, error)) { GOTO (done); } @@ -1927,25 +1802,18 @@ mongoc_collection_insert_one (mongoc_collection_t *collection, } if (insert_one_opts.crud.comment.value_type != BSON_TYPE_EOD) { - bson_append_value ( - &cmd_opts, "comment", 7, &insert_one_opts.crud.comment); + bson_append_value (&cmd_opts, "comment", 7, &insert_one_opts.crud.comment); } - if (!_mongoc_validate_new_document ( - document, insert_one_opts.crud.validate, error)) { + if (!_mongoc_validate_new_document (document, insert_one_opts.crud.validate, error)) { GOTO (done); } _mongoc_write_result_init (&result); - _mongoc_write_command_init_insert_idl ( - &command, - document, - &cmd_opts, - ++collection->client->cluster.operation_id); + _mongoc_write_command_init_insert_idl (&command, document, &cmd_opts, ++collection->client->cluster.operation_id); command.flags.bypass_document_validation = insert_one_opts.bypass; - _mongoc_collection_write_command_execute_idl ( - &command, collection, &insert_one_opts.crud, &result); + _mongoc_collection_write_command_execute_idl (&command, collection, &insert_one_opts.crud, &result); ret = MONGOC_WRITE_RESULT_COMPLETE (&result, collection->client->error_api_version, @@ -2015,15 +1883,13 @@ mongoc_collection_insert_many (mongoc_collection_t *collection, _mongoc_bson_init_if_set (reply); - if (!_mongoc_insert_many_opts_parse ( - collection->client, opts, &insert_many_opts, error)) { + if (!_mongoc_insert_many_opts_parse (collection->client, opts, &insert_many_opts, error)) { _mongoc_insert_many_opts_cleanup (&insert_many_opts); return false; } if (insert_many_opts.crud.comment.value_type != BSON_TYPE_EOD) { - bson_append_value ( - &cmd_opts, "comment", 7, &insert_many_opts.crud.comment); + bson_append_value (&cmd_opts, "comment", 7, &insert_many_opts.crud.comment); } if (!bson_empty (&insert_many_opts.extra)) { @@ -2031,15 +1897,13 @@ mongoc_collection_insert_many (mongoc_collection_t *collection, } _mongoc_write_result_init (&result); - _mongoc_write_command_init_insert_idl ( - &command, NULL, &cmd_opts, ++collection->client->cluster.operation_id); + _mongoc_write_command_init_insert_idl (&command, NULL, &cmd_opts, ++collection->client->cluster.operation_id); command.flags.ordered = insert_many_opts.ordered; command.flags.bypass_document_validation = insert_many_opts.bypass; for (i = 0; i < n_documents; i++) { - if (!_mongoc_validate_new_document ( - documents[i], insert_many_opts.crud.validate, error)) { + if (!_mongoc_validate_new_document (documents[i], insert_many_opts.crud.validate, error)) { ret = false; GOTO (done); } @@ -2047,8 +1911,7 @@ mongoc_collection_insert_many (mongoc_collection_t *collection, _mongoc_write_command_insert_append (&command, documents[i]); } - _mongoc_collection_write_command_execute_idl ( - &command, collection, &insert_many_opts.crud, &result); + _mongoc_collection_write_command_execute_idl (&command, collection, &insert_many_opts.crud, &result); ret = MONGOC_WRITE_RESULT_COMPLETE (&result, collection->client->error_api_version, @@ -2121,17 +1984,14 @@ mongoc_collection_update (mongoc_collection_t *collection, write_concern = collection->write_concern; } - if (!((uint32_t) flags & MONGOC_UPDATE_NO_VALIDATE) && - bson_iter_init (&iter, update) && bson_iter_next (&iter)) { + if (!((uint32_t) flags & MONGOC_UPDATE_NO_VALIDATE) && bson_iter_init (&iter, update) && bson_iter_next (&iter)) { if (bson_iter_key (&iter)[0] == '$') { /* update document, all keys must be $-operators */ - if (!_mongoc_validate_update ( - update, _mongoc_default_update_vflags, error)) { + if (!_mongoc_validate_update (update, _mongoc_default_update_vflags, error)) { return false; } } else { - if (!_mongoc_validate_replace ( - update, _mongoc_default_replace_vflags, error)) { + if (!_mongoc_validate_replace (update, _mongoc_default_replace_vflags, error)) { return false; } } @@ -2142,20 +2002,18 @@ mongoc_collection_update (mongoc_collection_t *collection, BSON_APPEND_BOOL (&opts, "multi", !!(flags & MONGOC_UPDATE_MULTI_UPDATE)); _mongoc_write_result_init (&result); - _mongoc_write_command_init_update ( - &command, - selector, - update, - NULL, /* cmd_opts */ - &opts, - write_flags, - ++collection->client->cluster.operation_id); + _mongoc_write_command_init_update (&command, + selector, + update, + NULL, /* cmd_opts */ + &opts, + write_flags, + ++collection->client->cluster.operation_id); bson_destroy (&opts); command.flags.has_multi_write = !!(flags & MONGOC_UPDATE_MULTI_UPDATE); - _mongoc_collection_write_command_execute ( - &command, collection, write_concern, NULL, &result); + _mongoc_collection_write_command_execute (&command, collection, write_concern, NULL, &result); collection->gle = bson_new (); ret = MONGOC_WRITE_RESULT_COMPLETE (&result, @@ -2227,12 +2085,7 @@ _mongoc_collection_update_or_replace (mongoc_collection_t *collection, _mongoc_write_result_init (&result); _mongoc_write_command_init_update_idl ( - &command, - selector, - update, - &cmd_opts, - extra, - ++collection->client->cluster.operation_id); + &command, selector, update, &cmd_opts, extra, ++collection->client->cluster.operation_id); command.flags.has_multi_write = multi; command.flags.bypass_document_validation = bypass; @@ -2243,12 +2096,8 @@ _mongoc_collection_update_or_replace (mongoc_collection_t *collection, command.flags.has_update_hint = true; } - server_stream = - mongoc_cluster_stream_for_writes (&collection->client->cluster, - update_opts->crud.client_session, - NULL, - reply, - error); + server_stream = mongoc_cluster_stream_for_writes ( + &collection->client->cluster, update_opts->crud.client_session, NULL, reply, error); if (!server_stream) { /* mongoc_cluster_stream_for_writes inits reply on error */ @@ -2257,8 +2106,7 @@ _mongoc_collection_update_or_replace (mongoc_collection_t *collection, } if (!bson_empty0 (array_filters)) { - if (!mongoc_write_concern_is_acknowledged ( - update_opts->crud.writeConcern)) { + if (!mongoc_write_concern_is_acknowledged (update_opts->crud.writeConcern)) { bson_set_error (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION, @@ -2267,8 +2115,7 @@ _mongoc_collection_update_or_replace (mongoc_collection_t *collection, } } - if (_mongoc_client_session_in_txn (update_opts->crud.client_session) && - update_opts->crud.writeConcern) { + if (_mongoc_client_session_in_txn (update_opts->crud.client_session) && update_opts->crud.writeConcern) { bson_set_error (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, @@ -2276,8 +2123,7 @@ _mongoc_collection_update_or_replace (mongoc_collection_t *collection, GOTO (done); } - if (!update_opts->crud.writeConcern && - !_mongoc_client_session_in_txn (update_opts->crud.client_session)) { + if (!update_opts->crud.writeConcern && !_mongoc_client_session_in_txn (update_opts->crud.client_session)) { update_opts->crud.writeConcern = collection->write_concern; update_opts->crud.write_concern_owned = false; } @@ -2336,15 +2182,13 @@ mongoc_collection_update_one (mongoc_collection_t *collection, BSON_ASSERT_PARAM (collection); BSON_ASSERT_PARAM (update); - if (!_mongoc_update_one_opts_parse ( - collection->client, opts, &update_one_opts, error)) { + if (!_mongoc_update_one_opts_parse (collection->client, opts, &update_one_opts, error)) { _mongoc_update_one_opts_cleanup (&update_one_opts); _mongoc_bson_init_if_set (reply); return false; } - if (!_mongoc_validate_update ( - update, update_one_opts.update.crud.validate, error)) { + if (!_mongoc_validate_update (update, update_one_opts.update.crud.validate, error)) { _mongoc_update_one_opts_cleanup (&update_one_opts); _mongoc_bson_init_if_set (reply); return false; @@ -2382,15 +2226,13 @@ mongoc_collection_update_many (mongoc_collection_t *collection, BSON_ASSERT_PARAM (collection); BSON_ASSERT_PARAM (update); - if (!_mongoc_update_many_opts_parse ( - collection->client, opts, &update_many_opts, error)) { + if (!_mongoc_update_many_opts_parse (collection->client, opts, &update_many_opts, error)) { _mongoc_update_many_opts_cleanup (&update_many_opts); _mongoc_bson_init_if_set (reply); return false; } - if (!_mongoc_validate_update ( - update, update_many_opts.update.crud.validate, error)) { + if (!_mongoc_validate_update (update, update_many_opts.update.crud.validate, error)) { _mongoc_update_many_opts_cleanup (&update_many_opts); _mongoc_bson_init_if_set (reply); return false; @@ -2428,15 +2270,13 @@ mongoc_collection_replace_one (mongoc_collection_t *collection, BSON_ASSERT_PARAM (collection); BSON_ASSERT_PARAM (replacement); - if (!_mongoc_replace_one_opts_parse ( - collection->client, opts, &replace_one_opts, error)) { + if (!_mongoc_replace_one_opts_parse (collection->client, opts, &replace_one_opts, error)) { _mongoc_replace_one_opts_cleanup (&replace_one_opts); _mongoc_bson_init_if_set (reply); return false; } - if (!_mongoc_validate_replace ( - replacement, replace_one_opts.update.crud.validate, error)) { + if (!_mongoc_validate_replace (replacement, replace_one_opts.update.crud.validate, error)) { _mongoc_replace_one_opts_cleanup (&replace_one_opts); _mongoc_bson_init_if_set (reply); return false; @@ -2493,33 +2333,24 @@ mongoc_collection_save (mongoc_collection_t *collection, BEGIN_IGNORE_DEPRECATIONS if (!bson_iter_init_find (&iter, document, "_id")) { - return mongoc_collection_insert ( - collection, MONGOC_INSERT_NONE, document, write_concern, error); + return mongoc_collection_insert (collection, MONGOC_INSERT_NONE, document, write_concern, error); } bson_init (&selector); if (!bson_append_iter (&selector, NULL, 0, &iter)) { - bson_set_error (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Failed to append bson to create update."); + bson_set_error ( + error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Failed to append bson to create update."); bson_destroy (&selector); return false; } /* this document will be inserted, validate same as for inserts */ - if (!_mongoc_validate_new_document ( - document, _mongoc_default_insert_vflags, error)) { + if (!_mongoc_validate_new_document (document, _mongoc_default_insert_vflags, error)) { return false; } - ret = mongoc_collection_update (collection, - MONGOC_UPDATE_UPSERT | - MONGOC_UPDATE_NO_VALIDATE, - &selector, - document, - write_concern, - error); + ret = mongoc_collection_update ( + collection, MONGOC_UPDATE_UPSERT | MONGOC_UPDATE_NO_VALIDATE, &selector, document, write_concern, error); END_IGNORE_DEPRECATIONS bson_destroy (&selector); @@ -2585,22 +2416,16 @@ mongoc_collection_remove (mongoc_collection_t *collection, } bson_init (&opts); - BSON_APPEND_INT32 ( - &opts, "limit", flags & MONGOC_REMOVE_SINGLE_REMOVE ? 1 : 0); + BSON_APPEND_INT32 (&opts, "limit", flags & MONGOC_REMOVE_SINGLE_REMOVE ? 1 : 0); _mongoc_write_result_init (&result); ++collection->client->cluster.operation_id; - _mongoc_write_command_init_delete (&command, - selector, - NULL, - &opts, - write_flags, - collection->client->cluster.operation_id); + _mongoc_write_command_init_delete ( + &command, selector, NULL, &opts, write_flags, collection->client->cluster.operation_id); bson_destroy (&opts); command.flags.has_multi_write = !(flags & MONGOC_REMOVE_SINGLE_REMOVE); - _mongoc_collection_write_command_execute ( - &command, collection, write_concern, NULL, &result); + _mongoc_collection_write_command_execute (&command, collection, write_concern, NULL, &result); collection->gle = bson_new (); ret = MONGOC_WRITE_RESULT_COMPLETE (&result, @@ -2624,11 +2449,7 @@ mongoc_collection_delete (mongoc_collection_t *collection, const mongoc_write_concern_t *write_concern, bson_error_t *error) { - return mongoc_collection_remove (collection, - (mongoc_remove_flags_t) flags, - selector, - write_concern, - error); + return mongoc_collection_remove (collection, (mongoc_remove_flags_t) flags, selector, write_concern, error); } @@ -2681,11 +2502,7 @@ _mongoc_delete_one_or_many (mongoc_collection_t *collection, } _mongoc_write_command_init_delete_idl ( - &command, - selector, - &cmd_opts, - &opts, - ++collection->client->cluster.operation_id); + &command, selector, &cmd_opts, &opts, ++collection->client->cluster.operation_id); command.flags.has_multi_write = multi; if (!bson_empty (&delete_opts->collation)) { @@ -2695,8 +2512,7 @@ _mongoc_delete_one_or_many (mongoc_collection_t *collection, command.flags.has_delete_hint = true; } - _mongoc_collection_write_command_execute_idl ( - &command, collection, &delete_opts->crud, &result); + _mongoc_collection_write_command_execute_idl (&command, collection, &delete_opts->crud, &result); /* set field described in CRUD spec for the DeleteResult */ ret = MONGOC_WRITE_RESULT_COMPLETE (&result, @@ -2718,11 +2534,8 @@ _mongoc_delete_one_or_many (mongoc_collection_t *collection, bool -mongoc_collection_delete_one (mongoc_collection_t *collection, - const bson_t *selector, - const bson_t *opts, - bson_t *reply, - bson_error_t *error) +mongoc_collection_delete_one ( + mongoc_collection_t *collection, const bson_t *selector, const bson_t *opts, bson_t *reply, bson_error_t *error) { mongoc_delete_one_opts_t delete_one_opts; bool ret = false; @@ -2733,18 +2546,12 @@ mongoc_collection_delete_one (mongoc_collection_t *collection, BSON_ASSERT_PARAM (selector); _mongoc_bson_init_if_set (reply); - if (!_mongoc_delete_one_opts_parse ( - collection->client, opts, &delete_one_opts, error)) { + if (!_mongoc_delete_one_opts_parse (collection->client, opts, &delete_one_opts, error)) { GOTO (done); } - ret = _mongoc_delete_one_or_many (collection, - false /* multi */, - selector, - &delete_one_opts.delete, - &delete_one_opts.extra, - reply, - error); + ret = _mongoc_delete_one_or_many ( + collection, false /* multi */, selector, &delete_one_opts.delete, &delete_one_opts.extra, reply, error); done: _mongoc_delete_one_opts_cleanup (&delete_one_opts); @@ -2753,11 +2560,8 @@ mongoc_collection_delete_one (mongoc_collection_t *collection, } bool -mongoc_collection_delete_many (mongoc_collection_t *collection, - const bson_t *selector, - const bson_t *opts, - bson_t *reply, - bson_error_t *error) +mongoc_collection_delete_many ( + mongoc_collection_t *collection, const bson_t *selector, const bson_t *opts, bson_t *reply, bson_error_t *error) { mongoc_delete_many_opts_t delete_many_opts; bool ret = false; @@ -2768,18 +2572,12 @@ mongoc_collection_delete_many (mongoc_collection_t *collection, BSON_ASSERT_PARAM (selector); _mongoc_bson_init_if_set (reply); - if (!_mongoc_delete_many_opts_parse ( - collection->client, opts, &delete_many_opts, error)) { + if (!_mongoc_delete_many_opts_parse (collection->client, opts, &delete_many_opts, error)) { GOTO (done); } - ret = _mongoc_delete_one_or_many (collection, - true /* multi */, - selector, - &delete_many_opts.delete, - &delete_many_opts.extra, - reply, - error); + ret = _mongoc_delete_one_or_many ( + collection, true /* multi */, selector, &delete_many_opts.delete, &delete_many_opts.extra, reply, error); done: _mongoc_delete_many_opts_cleanup (&delete_many_opts); @@ -2829,8 +2627,7 @@ mongoc_collection_get_read_prefs (const mongoc_collection_t *collection) */ void -mongoc_collection_set_read_prefs (mongoc_collection_t *collection, - const mongoc_read_prefs_t *read_prefs) +mongoc_collection_set_read_prefs (mongoc_collection_t *collection, const mongoc_read_prefs_t *read_prefs) { BSON_ASSERT_PARAM (collection); @@ -2887,8 +2684,7 @@ mongoc_collection_get_read_concern (const mongoc_collection_t *collection) */ void -mongoc_collection_set_read_concern (mongoc_collection_t *collection, - const mongoc_read_concern_t *read_concern) +mongoc_collection_set_read_concern (mongoc_collection_t *collection, const mongoc_read_concern_t *read_concern) { BSON_ASSERT_PARAM (collection); @@ -2945,8 +2741,7 @@ mongoc_collection_get_write_concern (const mongoc_collection_t *collection) */ void -mongoc_collection_set_write_concern ( - mongoc_collection_t *collection, const mongoc_write_concern_t *write_concern) +mongoc_collection_set_write_concern (mongoc_collection_t *collection, const mongoc_write_concern_t *write_concern) { BSON_ASSERT_PARAM (collection); @@ -3006,8 +2801,7 @@ mongoc_collection_get_name (mongoc_collection_t *collection) */ const bson_t * -mongoc_collection_get_last_error ( - const mongoc_collection_t *collection) /* IN */ +mongoc_collection_get_last_error (const mongoc_collection_t *collection) /* IN */ { BSON_ASSERT_PARAM (collection); @@ -3056,24 +2850,18 @@ mongoc_collection_validate (mongoc_collection_t *collection, /* IN */ BSON_ASSERT_PARAM (collection); - if (options && bson_iter_init_find (&iter, options, "full") && - !BSON_ITER_HOLDS_BOOL (&iter)) { - bson_set_error (error, - MONGOC_ERROR_BSON, - MONGOC_ERROR_BSON_INVALID, - "'full' must be a boolean value."); + if (options && bson_iter_init_find (&iter, options, "full") && !BSON_ITER_HOLDS_BOOL (&iter)) { + bson_set_error (error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "'full' must be a boolean value."); goto cleanup; } - bson_append_utf8 ( - &cmd, "validate", 8, collection->collection, collection->collectionlen); + bson_append_utf8 (&cmd, "validate", 8, collection->collection, collection->collectionlen); if (options) { bson_concat (&cmd, options); } - ret = - mongoc_collection_command_simple (collection, &cmd, NULL, reply, error); + ret = mongoc_collection_command_simple (collection, &cmd, NULL, reply, error); reply_initialized = true; cleanup: @@ -3116,8 +2904,7 @@ mongoc_collection_rename (mongoc_collection_t *collection, bool drop_target_before_rename, bson_error_t *error) { - return mongoc_collection_rename_with_opts ( - collection, new_db, new_name, drop_target_before_rename, NULL, error); + return mongoc_collection_rename_with_opts (collection, new_db, new_name, drop_target_before_rename, NULL, error); } @@ -3145,8 +2932,7 @@ mongoc_collection_rename_with_opts (mongoc_collection_t *collection, return false; } - newns = - bson_strdup_printf ("%s.%s", new_db ? new_db : collection->db, new_name); + newns = bson_strdup_printf ("%s.%s", new_db ? new_db : collection->db, new_name); BSON_APPEND_UTF8 (&cmd, "renameCollection", collection->ns); BSON_APPEND_UTF8 (&cmd, "to", newns); @@ -3213,10 +2999,7 @@ mongoc_collection_rename_with_opts (mongoc_collection_t *collection, */ bool -mongoc_collection_stats (mongoc_collection_t *collection, - const bson_t *options, - bson_t *stats, - bson_error_t *error) +mongoc_collection_stats (mongoc_collection_t *collection, const bson_t *options, bson_t *stats, bson_error_t *error) { bson_iter_t iter; bson_t cmd = BSON_INITIALIZER; @@ -3224,12 +3007,8 @@ mongoc_collection_stats (mongoc_collection_t *collection, BSON_ASSERT_PARAM (collection); - if (options && bson_iter_init_find (&iter, options, "scale") && - !BSON_ITER_HOLDS_INT32 (&iter)) { - bson_set_error (error, - MONGOC_ERROR_BSON, - MONGOC_ERROR_BSON_INVALID, - "'scale' must be an int32 value."); + if (options && bson_iter_init_find (&iter, options, "scale") && !BSON_ITER_HOLDS_INT32 (&iter)) { + bson_set_error (error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "'scale' must be an int32 value."); return false; } @@ -3242,8 +3021,7 @@ mongoc_collection_stats (mongoc_collection_t *collection, /* Server Selection Spec: "may-use-secondary" commands SHOULD take a read * preference argument and otherwise MUST use the default read preference * from client, database or collection configuration. */ - ret = mongoc_collection_command_simple ( - collection, &cmd, collection->read_prefs, stats, error); + ret = mongoc_collection_command_simple (collection, &cmd, collection->read_prefs, stats, error); bson_destroy (&cmd); @@ -3252,10 +3030,9 @@ mongoc_collection_stats (mongoc_collection_t *collection, mongoc_bulk_operation_t * -mongoc_collection_create_bulk_operation ( - mongoc_collection_t *collection, - bool ordered, - const mongoc_write_concern_t *write_concern) +mongoc_collection_create_bulk_operation (mongoc_collection_t *collection, + bool ordered, + const mongoc_write_concern_t *write_concern) { bson_t opts = BSON_INITIALIZER; mongoc_bulk_operation_t *bulk; @@ -3263,8 +3040,7 @@ mongoc_collection_create_bulk_operation ( bson_append_bool (&opts, "ordered", 7, ordered); if (write_concern) { - wc_ok = mongoc_write_concern_append ( - (mongoc_write_concern_t *) write_concern, &opts); + wc_ok = mongoc_write_concern_append ((mongoc_write_concern_t *) write_concern, &opts); } bulk = mongoc_collection_create_bulk_operation_with_opts (collection, &opts); @@ -3272,10 +3048,8 @@ mongoc_collection_create_bulk_operation ( bson_destroy (&opts); if (!wc_ok) { - bson_set_error (&bulk->result.error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "invalid writeConcern"); + bson_set_error ( + &bulk->result.error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "invalid writeConcern"); } return bulk; @@ -3283,8 +3057,7 @@ mongoc_collection_create_bulk_operation ( mongoc_bulk_operation_t * -mongoc_collection_create_bulk_operation_with_opts ( - mongoc_collection_t *collection, const bson_t *opts) +mongoc_collection_create_bulk_operation_with_opts (mongoc_collection_t *collection, const bson_t *opts) { mongoc_bulk_opts_t bulk_opts; mongoc_bulk_write_flags_t write_flags = MONGOC_BULK_WRITE_FLAGS_INIT; @@ -3299,11 +3072,7 @@ mongoc_collection_create_bulk_operation_with_opts ( wc = COALESCE (bulk_opts.writeConcern, collection->write_concern); } write_flags.ordered = bulk_opts.ordered; - bulk = _mongoc_bulk_operation_new (collection->client, - collection->db, - collection->collection, - write_flags, - wc); + bulk = _mongoc_bulk_operation_new (collection->client, collection->db, collection->collection, write_flags, wc); if (!bson_empty (&bulk_opts.let)) { mongoc_bulk_operation_set_let (bulk, &bulk_opts.let); @@ -3353,12 +3122,11 @@ mongoc_collection_create_bulk_operation_with_opts ( *-------------------------------------------------------------------------- */ bool -mongoc_collection_find_and_modify_with_opts ( - mongoc_collection_t *collection, - const bson_t *query, - const mongoc_find_and_modify_opts_t *opts, - bson_t *reply, - bson_error_t *error) +mongoc_collection_find_and_modify_with_opts (mongoc_collection_t *collection, + const bson_t *query, + const mongoc_find_and_modify_opts_t *opts, + bson_t *reply, + bson_error_t *error) { mongoc_cluster_t *cluster; mongoc_cmd_parts_t parts; @@ -3385,20 +3153,17 @@ mongoc_collection_find_and_modify_with_opts ( reply_ptr = reply ? reply : &reply_local; cluster = &collection->client->cluster; - mongoc_cmd_parts_init ( - &parts, collection->client, collection->db, MONGOC_QUERY_NONE, &command); + mongoc_cmd_parts_init (&parts, collection->client, collection->db, MONGOC_QUERY_NONE, &command); parts.is_read_command = true; parts.is_write_command = true; bson_init (reply_ptr); - if (!_mongoc_find_and_modify_appended_opts_parse ( - cluster->client, &opts->extra, &appended_opts, error)) { + if (!_mongoc_find_and_modify_appended_opts_parse (cluster->client, &opts->extra, &appended_opts, error)) { GOTO (done); } - server_stream = mongoc_cluster_stream_for_writes ( - cluster, appended_opts.client_session, NULL, &ss_reply, error); + server_stream = mongoc_cluster_stream_for_writes (cluster, appended_opts.client_session, NULL, &ss_reply, error); if (!server_stream) { bson_concat (reply_ptr, &ss_reply); @@ -3439,9 +3204,7 @@ mongoc_collection_find_and_modify_with_opts ( } if (opts->bypass_document_validation) { - BSON_APPEND_BOOL (&command, - "bypassDocumentValidation", - opts->bypass_document_validation); + BSON_APPEND_BOOL (&command, "bypassDocumentValidation", opts->bypass_document_validation); } if (opts->max_time_ms > 0) { @@ -3468,10 +3231,8 @@ mongoc_collection_find_and_modify_with_opts ( /* inherit write concern from collection if not in transaction */ else if (!_mongoc_client_session_in_txn (parts.assembled.session)) { if (!mongoc_write_concern_is_valid (collection->write_concern)) { - bson_set_error (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "The write concern is invalid."); + bson_set_error ( + error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "The write concern is invalid."); GOTO (done); } @@ -3479,17 +3240,15 @@ mongoc_collection_find_and_modify_with_opts ( } if (appended_opts.hint.value_type) { - int max_wire_version = - mongoc_write_concern_is_acknowledged (write_concern) - ? WIRE_VERSION_FIND_AND_MODIFY_HINT_SERVER_SIDE_ERROR - : WIRE_VERSION_FIND_AND_MODIFY_HINT; + int max_wire_version = mongoc_write_concern_is_acknowledged (write_concern) + ? WIRE_VERSION_FIND_AND_MODIFY_HINT_SERVER_SIDE_ERROR + : WIRE_VERSION_FIND_AND_MODIFY_HINT; if (server_stream->sd->max_wire_version < max_wire_version) { - bson_set_error ( - error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION, - "The selected server does not support hint for findAndModify"); + bson_set_error (error, + MONGOC_ERROR_COMMAND, + MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION, + "The selected server does not support hint for findAndModify"); GOTO (done); } @@ -3529,11 +3288,8 @@ mongoc_collection_find_and_modify_with_opts ( * write command */ if (is_retryable) { bson_iter_t txn_number_iter; - BSON_ASSERT (bson_iter_init_find ( - &txn_number_iter, parts.assembled.command, "txnNumber")); - bson_iter_overwrite_int64 ( - &txn_number_iter, - ++parts.assembled.session->server_session->txn_number); + BSON_ASSERT (bson_iter_init_find (&txn_number_iter, parts.assembled.command, "txnNumber")); + bson_iter_overwrite_int64 (&txn_number_iter, ++parts.assembled.session->server_session->txn_number); } // Store the original error and reply if needed. @@ -3545,43 +3301,33 @@ mongoc_collection_find_and_modify_with_opts ( retry: bson_destroy (reply_ptr); - ret = mongoc_cluster_run_command_monitored ( - cluster, &parts.assembled, reply_ptr, error); + ret = mongoc_cluster_run_command_monitored (cluster, &parts.assembled, reply_ptr, error); if (parts.is_retryable_write) { - _mongoc_write_error_handle_labels ( - ret, error, reply_ptr, server_stream->sd); + _mongoc_write_error_handle_labels (ret, error, reply_ptr, server_stream->sd); } if (is_retryable) { - _mongoc_write_error_update_if_unsupported_storage_engine ( - ret, error, reply_ptr); + _mongoc_write_error_update_if_unsupported_storage_engine (ret, error, reply_ptr); } /* If a retryable error is encountered and the write is retryable, select * a new writable stream and retry. If server selection fails or the selected * server does not support retryable writes, fall through and allow the * original error to be reported. */ - if (is_retryable && - _mongoc_write_error_get_type (reply_ptr) == MONGOC_WRITE_ERR_RETRY) { + if (is_retryable && _mongoc_write_error_get_type (reply_ptr) == MONGOC_WRITE_ERR_RETRY) { bson_error_t ignored_error; /* each write command may be retried at most once */ is_retryable = false; { - mongoc_deprioritized_servers_t *const ds = - mongoc_deprioritized_servers_new (); + mongoc_deprioritized_servers_t *const ds = mongoc_deprioritized_servers_new (); - mongoc_deprioritized_servers_add_if_sharded ( - ds, server_stream->topology_type, server_stream->sd); + mongoc_deprioritized_servers_add_if_sharded (ds, server_stream->topology_type, server_stream->sd); retry_server_stream = - mongoc_cluster_stream_for_writes (cluster, - parts.assembled.session, - ds, - NULL /* reply */, - &ignored_error); + mongoc_cluster_stream_for_writes (cluster, parts.assembled.session, ds, NULL /* reply */, &ignored_error); mongoc_deprioritized_servers_destroy (ds); } @@ -3603,8 +3349,7 @@ mongoc_collection_find_and_modify_with_opts ( // If a retry attempt fails with an error labeled NoWritesPerformed, // drivers MUST return the original error. - if (original_error.set && - mongoc_error_has_label (reply_ptr, "NoWritesPerformed")) { + if (original_error.set && mongoc_error_has_label (reply_ptr, "NoWritesPerformed")) { if (error) { *error = original_error.error; } @@ -3616,8 +3361,7 @@ mongoc_collection_find_and_modify_with_opts ( bson_destroy (&original_error.reply); } - if (bson_iter_init_find (&iter, reply_ptr, "writeConcernError") && - BSON_ITER_HOLDS_DOCUMENT (&iter)) { + if (bson_iter_init_find (&iter, reply_ptr, "writeConcernError") && BSON_ITER_HOLDS_DOCUMENT (&iter)) { const char *errmsg = NULL; int32_t code = 0; @@ -3629,11 +3373,7 @@ mongoc_collection_find_and_modify_with_opts ( errmsg = bson_iter_utf8 (&inner, NULL); } } - bson_set_error (error, - MONGOC_ERROR_WRITE_CONCERN, - code, - "Write Concern error: %s", - errmsg); + bson_set_error (error, MONGOC_ERROR_WRITE_CONCERN, code, "Write Concern error: %s", errmsg); ret = false; } @@ -3727,17 +3467,14 @@ mongoc_collection_find_and_modify (mongoc_collection_t *collection, mongoc_find_and_modify_opts_set_fields (opts, fields); mongoc_find_and_modify_opts_set_flags (opts, flags); - ret = mongoc_collection_find_and_modify_with_opts ( - collection, query, opts, reply, error); + ret = mongoc_collection_find_and_modify_with_opts (collection, query, opts, reply, error); mongoc_find_and_modify_opts_destroy (opts); return ret; } mongoc_change_stream_t * -mongoc_collection_watch (const mongoc_collection_t *coll, - const bson_t *pipeline, - const bson_t *opts) +mongoc_collection_watch (const mongoc_collection_t *coll, const bson_t *pipeline, const bson_t *opts) { return _mongoc_change_stream_new_from_collection (coll, pipeline, opts); } @@ -3796,28 +3533,25 @@ mongoc_collection_create_indexes_with_opts (mongoc_collection_t *collection, // Check for commitQuorum option. if (opts && bson_has_field (opts, "commitQuorum")) { - server_stream = - mongoc_cluster_stream_for_writes (&collection->client->cluster, - NULL /* mongoc_client_session_t */, - NULL /* deprioritized servers */, - reply_ptr, - error); + server_stream = mongoc_cluster_stream_for_writes (&collection->client->cluster, + NULL /* mongoc_client_session_t */, + NULL /* deprioritized servers */, + reply_ptr, + error); if (server_stream->sd->max_wire_version < WIRE_VERSION_4_4) { // Raise an error required by the specification: // "Drivers MUST manually raise an error if this option is specified // when creating an index on a pre 4.4 server." - bson_set_error ( - error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION, - "The selected server does not support the commitQuorum option"); + bson_set_error (error, + MONGOC_ERROR_COMMAND, + MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION, + "The selected server does not support the commitQuorum option"); GOTO (fail); } } // Build the createIndexes command. - BSON_ASSERT ( - BSON_APPEND_UTF8 (&cmd, "createIndexes", collection->collection)); + BSON_ASSERT (BSON_APPEND_UTF8 (&cmd, "createIndexes", collection->collection)); bson_array_builder_t *indexes; BSON_ASSERT (BSON_APPEND_ARRAY_BUILDER_BEGIN (&cmd, "indexes", &indexes)); for (uint32_t idx = 0; idx < n_models; idx++) { @@ -3840,13 +3574,11 @@ mongoc_collection_create_indexes_with_opts (mongoc_collection_t *collection, BSON_ASSERT (bson_array_builder_append_document_begin (indexes, &index)); BSON_ASSERT (BSON_APPEND_DOCUMENT (&index, "key", models[idx]->keys)); bson_iter_t name_iter; - if (models[idx]->opts && - bson_iter_init_find (&name_iter, models[idx]->opts, "name")) { + if (models[idx]->opts && bson_iter_init_find (&name_iter, models[idx]->opts, "name")) { // `name` was specified as an index option. } else { // No `name` was specified. Create index `name` from keys. - char *name = - mongoc_collection_keys_to_index_string (models[idx]->keys); + char *name = mongoc_collection_keys_to_index_string (models[idx]->keys); BSON_ASSERT (name); BSON_ASSERT (BSON_APPEND_UTF8 (&index, "name", name)); bson_free (name); @@ -3859,13 +3591,8 @@ mongoc_collection_create_indexes_with_opts (mongoc_collection_t *collection, } BSON_ASSERT (bson_append_array_builder_end (&cmd, indexes)); - ok = mongoc_client_command_with_opts (collection->client, - collection->db, - &cmd, - NULL /* read_prefs */, - opts, - reply_ptr, - error); + ok = mongoc_client_command_with_opts ( + collection->client, collection->db, &cmd, NULL /* read_prefs */, opts, reply_ptr, error); fail: mongoc_server_stream_cleanup (server_stream); diff --git a/src/libmongoc/src/mongoc/mongoc-collection.h b/src/libmongoc/src/mongoc/mongoc-collection.h index 89ff3e40e8..e4f13ec310 100644 --- a/src/libmongoc/src/mongoc/mongoc-collection.h +++ b/src/libmongoc/src/mongoc/mongoc-collection.h @@ -42,13 +42,11 @@ mongoc_collection_aggregate (mongoc_collection_t *collection, mongoc_query_flags_t flags, const bson_t *pipeline, const bson_t *opts, - const mongoc_read_prefs_t *read_prefs) - BSON_GNUC_WARN_UNUSED_RESULT; + const mongoc_read_prefs_t *read_prefs) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (void) mongoc_collection_destroy (mongoc_collection_t *collection); MONGOC_EXPORT (mongoc_collection_t *) -mongoc_collection_copy (mongoc_collection_t *collection) - BSON_GNUC_WARN_UNUSED_RESULT; +mongoc_collection_copy (mongoc_collection_t *collection) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (mongoc_cursor_t *) mongoc_collection_command (mongoc_collection_t *collection, mongoc_query_flags_t flags, @@ -57,8 +55,7 @@ mongoc_collection_command (mongoc_collection_t *collection, uint32_t batch_size, const bson_t *command, const bson_t *fields, - const mongoc_read_prefs_t *read_prefs) - BSON_GNUC_WARN_UNUSED_RESULT; + const mongoc_read_prefs_t *read_prefs) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (bool) mongoc_collection_read_command_with_opts (mongoc_collection_t *collection, const bson_t *command, @@ -67,19 +64,15 @@ mongoc_collection_read_command_with_opts (mongoc_collection_t *collection, bson_t *reply, bson_error_t *error); MONGOC_EXPORT (bool) -mongoc_collection_write_command_with_opts (mongoc_collection_t *collection, - const bson_t *command, - const bson_t *opts, - bson_t *reply, - bson_error_t *error); +mongoc_collection_write_command_with_opts ( + mongoc_collection_t *collection, const bson_t *command, const bson_t *opts, bson_t *reply, bson_error_t *error); MONGOC_EXPORT (bool) -mongoc_collection_read_write_command_with_opts ( - mongoc_collection_t *collection, - const bson_t *command, - const mongoc_read_prefs_t *read_prefs /* IGNORED */, - const bson_t *opts, - bson_t *reply, - bson_error_t *error); +mongoc_collection_read_write_command_with_opts (mongoc_collection_t *collection, + const bson_t *command, + const mongoc_read_prefs_t *read_prefs /* IGNORED */, + const bson_t *opts, + bson_t *reply, + bson_error_t *error); MONGOC_EXPORT (bool) mongoc_collection_command_with_opts (mongoc_collection_t *collection, const bson_t *command, @@ -101,8 +94,7 @@ mongoc_collection_count (mongoc_collection_t *collection, int64_t limit, const mongoc_read_prefs_t *read_prefs, bson_error_t *error) - BSON_GNUC_DEPRECATED_FOR (mongoc_collection_count_documents or - mongoc_collection_estimated_document_count); + BSON_GNUC_DEPRECATED_FOR (mongoc_collection_count_documents or mongoc_collection_estimated_document_count); MONGOC_EXPORT (int64_t) mongoc_collection_count_with_opts (mongoc_collection_t *collection, mongoc_query_flags_t flags, @@ -112,18 +104,13 @@ mongoc_collection_count_with_opts (mongoc_collection_t *collection, const bson_t *opts, const mongoc_read_prefs_t *read_prefs, bson_error_t *error) - BSON_GNUC_DEPRECATED_FOR (mongoc_collection_count_documents or - mongoc_collection_estimated_document_count); + BSON_GNUC_DEPRECATED_FOR (mongoc_collection_count_documents or mongoc_collection_estimated_document_count); MONGOC_EXPORT (bool) mongoc_collection_drop (mongoc_collection_t *collection, bson_error_t *error); MONGOC_EXPORT (bool) -mongoc_collection_drop_with_opts (mongoc_collection_t *collection, - const bson_t *opts, - bson_error_t *error); +mongoc_collection_drop_with_opts (mongoc_collection_t *collection, const bson_t *opts, bson_error_t *error); MONGOC_EXPORT (bool) -mongoc_collection_drop_index (mongoc_collection_t *collection, - const char *index_name, - bson_error_t *error); +mongoc_collection_drop_index (mongoc_collection_t *collection, const char *index_name, bson_error_t *error); MONGOC_EXPORT (bool) mongoc_collection_drop_index_with_opts (mongoc_collection_t *collection, const char *index_name, @@ -140,22 +127,18 @@ mongoc_collection_create_index_with_opts (mongoc_collection_t *collection, const mongoc_index_opt_t *opt, const bson_t *opts, bson_t *reply, - bson_error_t *error) - BSON_GNUC_DEPRECATED; + bson_error_t *error) BSON_GNUC_DEPRECATED; MONGOC_EXPORT (bool) mongoc_collection_ensure_index (mongoc_collection_t *collection, const bson_t *keys, const mongoc_index_opt_t *opt, bson_error_t *error) BSON_GNUC_DEPRECATED; MONGOC_EXPORT (mongoc_cursor_t *) -mongoc_collection_find_indexes (mongoc_collection_t *collection, - bson_error_t *error) - BSON_GNUC_WARN_UNUSED_RESULT +mongoc_collection_find_indexes (mongoc_collection_t *collection, bson_error_t *error) BSON_GNUC_WARN_UNUSED_RESULT BSON_GNUC_DEPRECATED_FOR (mongoc_collection_find_indexes_with_opts); MONGOC_EXPORT (mongoc_cursor_t *) mongoc_collection_find_indexes_with_opts (mongoc_collection_t *collection, - const bson_t *opts) - BSON_GNUC_WARN_UNUSED_RESULT; + const bson_t *opts) BSON_GNUC_WARN_UNUSED_RESULT; typedef struct _mongoc_index_model_t mongoc_index_model_t; @@ -182,14 +165,12 @@ mongoc_collection_find (mongoc_collection_t *collection, const bson_t *query, const bson_t *fields, const mongoc_read_prefs_t *read_prefs) - BSON_GNUC_DEPRECATED_FOR (mongoc_collection_find_with_opts) - BSON_GNUC_WARN_UNUSED_RESULT; + BSON_GNUC_DEPRECATED_FOR (mongoc_collection_find_with_opts) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (mongoc_cursor_t *) mongoc_collection_find_with_opts (mongoc_collection_t *collection, const bson_t *filter, const bson_t *opts, - const mongoc_read_prefs_t *read_prefs) - BSON_GNUC_WARN_UNUSED_RESULT; + const mongoc_read_prefs_t *read_prefs) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (bool) mongoc_collection_insert (mongoc_collection_t *collection, mongoc_insert_flags_t flags, @@ -197,11 +178,8 @@ mongoc_collection_insert (mongoc_collection_t *collection, const mongoc_write_concern_t *write_concern, bson_error_t *error); MONGOC_EXPORT (bool) -mongoc_collection_insert_one (mongoc_collection_t *collection, - const bson_t *document, - const bson_t *opts, - bson_t *reply, - bson_error_t *error); +mongoc_collection_insert_one ( + mongoc_collection_t *collection, const bson_t *document, const bson_t *opts, bson_t *reply, bson_error_t *error); MONGOC_EXPORT (bool) mongoc_collection_insert_many (mongoc_collection_t *collection, const bson_t **documents, @@ -215,8 +193,7 @@ mongoc_collection_insert_bulk (mongoc_collection_t *collection, const bson_t **documents, uint32_t n_documents, const mongoc_write_concern_t *write_concern, - bson_error_t *error) - BSON_GNUC_DEPRECATED_FOR (mongoc_collection_insert_many); + bson_error_t *error) BSON_GNUC_DEPRECATED_FOR (mongoc_collection_insert_many); MONGOC_EXPORT (bool) mongoc_collection_update (mongoc_collection_t *collection, mongoc_update_flags_t flags, @@ -251,15 +228,13 @@ mongoc_collection_delete (mongoc_collection_t *collection, const bson_t *selector, const mongoc_write_concern_t *write_concern, bson_error_t *error) - BSON_GNUC_DEPRECATED_FOR (mongoc_collection_delete_one or - mongoc_collection_delete_many); + BSON_GNUC_DEPRECATED_FOR (mongoc_collection_delete_one or mongoc_collection_delete_many); MONGOC_EXPORT (bool) mongoc_collection_save (mongoc_collection_t *collection, const bson_t *document, const mongoc_write_concern_t *write_concern, bson_error_t *error) - BSON_GNUC_DEPRECATED_FOR (mongoc_collection_insert_one or - mongoc_collection_replace_one); + BSON_GNUC_DEPRECATED_FOR (mongoc_collection_insert_one or mongoc_collection_replace_one); MONGOC_EXPORT (bool) mongoc_collection_remove (mongoc_collection_t *collection, mongoc_remove_flags_t flags, @@ -267,17 +242,11 @@ mongoc_collection_remove (mongoc_collection_t *collection, const mongoc_write_concern_t *write_concern, bson_error_t *error); MONGOC_EXPORT (bool) -mongoc_collection_delete_one (mongoc_collection_t *collection, - const bson_t *selector, - const bson_t *opts, - bson_t *reply, - bson_error_t *error); +mongoc_collection_delete_one ( + mongoc_collection_t *collection, const bson_t *selector, const bson_t *opts, bson_t *reply, bson_error_t *error); MONGOC_EXPORT (bool) -mongoc_collection_delete_many (mongoc_collection_t *collection, - const bson_t *selector, - const bson_t *opts, - bson_t *reply, - bson_error_t *error); +mongoc_collection_delete_many ( + mongoc_collection_t *collection, const bson_t *selector, const bson_t *opts, bson_t *reply, bson_error_t *error); MONGOC_EXPORT (bool) mongoc_collection_rename (mongoc_collection_t *collection, const char *new_db, @@ -292,12 +261,11 @@ mongoc_collection_rename_with_opts (mongoc_collection_t *collection, const bson_t *opts, bson_error_t *error); MONGOC_EXPORT (bool) -mongoc_collection_find_and_modify_with_opts ( - mongoc_collection_t *collection, - const bson_t *query, - const mongoc_find_and_modify_opts_t *opts, - bson_t *reply, - bson_error_t *error); +mongoc_collection_find_and_modify_with_opts (mongoc_collection_t *collection, + const bson_t *query, + const mongoc_find_and_modify_opts_t *opts, + bson_t *reply, + bson_error_t *error); MONGOC_EXPORT (bool) mongoc_collection_find_and_modify (mongoc_collection_t *collection, const bson_t *query, @@ -310,49 +278,37 @@ mongoc_collection_find_and_modify (mongoc_collection_t *collection, bson_t *reply, bson_error_t *error); MONGOC_EXPORT (bool) -mongoc_collection_stats (mongoc_collection_t *collection, - const bson_t *options, - bson_t *reply, - bson_error_t *error) BSON_GNUC_DEPRECATED; +mongoc_collection_stats (mongoc_collection_t *collection, const bson_t *options, bson_t *reply, bson_error_t *error) + BSON_GNUC_DEPRECATED; MONGOC_EXPORT (mongoc_bulk_operation_t *) -mongoc_collection_create_bulk_operation ( - mongoc_collection_t *collection, - bool ordered, - const mongoc_write_concern_t *write_concern) BSON_GNUC_WARN_UNUSED_RESULT +mongoc_collection_create_bulk_operation (mongoc_collection_t *collection, + bool ordered, + const mongoc_write_concern_t *write_concern) BSON_GNUC_WARN_UNUSED_RESULT BSON_GNUC_DEPRECATED_FOR (mongoc_collection_create_bulk_operation_with_opts); MONGOC_EXPORT (mongoc_bulk_operation_t *) -mongoc_collection_create_bulk_operation_with_opts ( - mongoc_collection_t *collection, - const bson_t *opts) BSON_GNUC_WARN_UNUSED_RESULT; +mongoc_collection_create_bulk_operation_with_opts (mongoc_collection_t *collection, + const bson_t *opts) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (const mongoc_read_prefs_t *) mongoc_collection_get_read_prefs (const mongoc_collection_t *collection); MONGOC_EXPORT (void) -mongoc_collection_set_read_prefs (mongoc_collection_t *collection, - const mongoc_read_prefs_t *read_prefs); +mongoc_collection_set_read_prefs (mongoc_collection_t *collection, const mongoc_read_prefs_t *read_prefs); MONGOC_EXPORT (const mongoc_read_concern_t *) mongoc_collection_get_read_concern (const mongoc_collection_t *collection); MONGOC_EXPORT (void) -mongoc_collection_set_read_concern (mongoc_collection_t *collection, - const mongoc_read_concern_t *read_concern); +mongoc_collection_set_read_concern (mongoc_collection_t *collection, const mongoc_read_concern_t *read_concern); MONGOC_EXPORT (const mongoc_write_concern_t *) mongoc_collection_get_write_concern (const mongoc_collection_t *collection); MONGOC_EXPORT (void) -mongoc_collection_set_write_concern ( - mongoc_collection_t *collection, - const mongoc_write_concern_t *write_concern); +mongoc_collection_set_write_concern (mongoc_collection_t *collection, const mongoc_write_concern_t *write_concern); MONGOC_EXPORT (const char *) mongoc_collection_get_name (mongoc_collection_t *collection); MONGOC_EXPORT (const bson_t *) -mongoc_collection_get_last_error (const mongoc_collection_t *collection) - BSON_GNUC_DEPRECATED; +mongoc_collection_get_last_error (const mongoc_collection_t *collection) BSON_GNUC_DEPRECATED; MONGOC_EXPORT (char *) -mongoc_collection_keys_to_index_string (const bson_t *keys) - BSON_GNUC_WARN_UNUSED_RESULT; +mongoc_collection_keys_to_index_string (const bson_t *keys) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (bool) -mongoc_collection_validate (mongoc_collection_t *collection, - const bson_t *options, - bson_t *reply, - bson_error_t *error) BSON_GNUC_DEPRECATED; +mongoc_collection_validate (mongoc_collection_t *collection, const bson_t *options, bson_t *reply, bson_error_t *error) + BSON_GNUC_DEPRECATED; MONGOC_EXPORT (mongoc_change_stream_t *) mongoc_collection_watch (const mongoc_collection_t *coll, const bson_t *pipeline, @@ -365,12 +321,11 @@ mongoc_collection_count_documents (mongoc_collection_t *coll, bson_t *reply, bson_error_t *error); MONGOC_EXPORT (int64_t) -mongoc_collection_estimated_document_count ( - mongoc_collection_t *coll, - const bson_t *opts, - const mongoc_read_prefs_t *read_prefs, - bson_t *reply, - bson_error_t *error); +mongoc_collection_estimated_document_count (mongoc_collection_t *coll, + const bson_t *opts, + const mongoc_read_prefs_t *read_prefs, + bson_t *reply, + bson_error_t *error); BSON_END_DECLS diff --git a/src/libmongoc/src/mongoc/mongoc-compression.c b/src/libmongoc/src/mongoc/mongoc-compression.c index 538235095b..5d946d13ef 100644 --- a/src/libmongoc/src/mongoc/mongoc-compression.c +++ b/src/libmongoc/src/mongoc/mongoc-compression.c @@ -36,9 +36,7 @@ size_t mongoc_compressor_max_compressed_length (int32_t compressor_id, size_t len) { - TRACE ("Getting compression length for '%s' (%d)", - mongoc_compressor_id_to_name (compressor_id), - compressor_id); + TRACE ("Getting compression length for '%s' (%d)", mongoc_compressor_id_to_name (compressor_id), compressor_id); switch (compressor_id) { #ifdef MONGOC_ENABLE_COMPRESSION_SNAPPY case MONGOC_COMPRESSOR_SNAPPY_ID: @@ -146,18 +144,13 @@ mongoc_uncompress (int32_t compressor_id, uint8_t *uncompressed, size_t *uncompressed_len) { - TRACE ("Uncompressing with '%s' (%d)", - mongoc_compressor_id_to_name (compressor_id), - compressor_id); + TRACE ("Uncompressing with '%s' (%d)", mongoc_compressor_id_to_name (compressor_id), compressor_id); switch (compressor_id) { case MONGOC_COMPRESSOR_SNAPPY_ID: { #ifdef MONGOC_ENABLE_COMPRESSION_SNAPPY snappy_status status; - status = snappy_uncompress ((const char *) compressed, - compressed_len, - (char *) uncompressed, - uncompressed_len); + status = snappy_uncompress ((const char *) compressed, compressed_len, (char *) uncompressed, uncompressed_len); return status == SNAPPY_OK; #else @@ -170,10 +163,8 @@ mongoc_uncompress (int32_t compressor_id, case MONGOC_COMPRESSOR_ZLIB_ID: { #ifdef MONGOC_ENABLE_COMPRESSION_ZLIB BSON_ASSERT (bson_in_range_unsigned (unsigned_long, compressed_len)); - const int ok = uncompress (uncompressed, - (unsigned long *) uncompressed_len, - compressed, - (unsigned long) compressed_len); + const int ok = + uncompress (uncompressed, (unsigned long *) uncompressed_len, compressed, (unsigned long) compressed_len); return ok == Z_OK; #else @@ -187,10 +178,7 @@ mongoc_uncompress (int32_t compressor_id, #ifdef MONGOC_ENABLE_COMPRESSION_ZSTD int ok; - ok = ZSTD_decompress ((void *) uncompressed, - *uncompressed_len, - (const void *) compressed, - compressed_len); + ok = ZSTD_decompress ((void *) uncompressed, *uncompressed_len, (const void *) compressed, compressed_len); if (!ZSTD_isError (ok)) { *uncompressed_len = ok; @@ -223,16 +211,12 @@ mongoc_compress (int32_t compressor_id, char *compressed, size_t *compressed_len) { - TRACE ("Compressing with '%s' (%d)", - mongoc_compressor_id_to_name (compressor_id), - compressor_id); + TRACE ("Compressing with '%s' (%d)", mongoc_compressor_id_to_name (compressor_id), compressor_id); switch (compressor_id) { case MONGOC_COMPRESSOR_SNAPPY_ID: #ifdef MONGOC_ENABLE_COMPRESSION_SNAPPY /* No compression_level option for snappy */ - return snappy_compress ( - uncompressed, uncompressed_len, compressed, compressed_len) == - SNAPPY_OK; + return snappy_compress (uncompressed, uncompressed_len, compressed, compressed_len) == SNAPPY_OK; #else MONGOC_ERROR ("Client attempting to use compress with snappy, but snappy " "compression is not compiled in"); @@ -257,11 +241,7 @@ mongoc_compress (int32_t compressor_id, #ifdef MONGOC_ENABLE_COMPRESSION_ZSTD int ok; - ok = ZSTD_compress ((void *) compressed, - *compressed_len, - (const void *) uncompressed, - uncompressed_len, - 0); + ok = ZSTD_compress ((void *) compressed, *compressed_len, (const void *) uncompressed, uncompressed_len, 0); if (!ZSTD_isError (ok)) { *compressed_len = ok; diff --git a/src/libmongoc/src/mongoc/mongoc-counters-private.h b/src/libmongoc/src/mongoc/mongoc-counters-private.h index 736a56ca3b..b39f668292 100644 --- a/src/libmongoc/src/mongoc/mongoc-counters-private.h +++ b/src/libmongoc/src/mongoc/mongoc-counters-private.h @@ -26,8 +26,7 @@ #ifdef __linux__ #include #include -#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__) || \ - defined(__OpenBSD__) +#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__) || defined(__OpenBSD__) #include #include #include @@ -62,8 +61,7 @@ _mongoc_get_cpu_count (void) return psd.psd_max_proc_cnt; } return 1; -#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__) || \ - defined(__OpenBSD__) +#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__) || defined(__OpenBSD__) int mib[2]; int maxproc; size_t len; @@ -138,8 +136,7 @@ typedef struct { } mongoc_counter_t; -#define COUNTER(ident, Category, Name, Description) \ - extern mongoc_counter_t __mongoc_counter_##ident; +#define COUNTER(ident, Category, Name, Description) extern mongoc_counter_t __mongoc_counter_##ident; #include "mongoc-counters.defs" #undef COUNTER @@ -152,45 +149,42 @@ enum { }; #ifdef MONGOC_ENABLE_SHM_COUNTERS -#define COUNTER(ident, Category, Name, Description) \ - static BSON_INLINE void mongoc_counter_##ident##_add (int64_t val) \ - { \ - int64_t *counter = \ - &BSON_CONCAT (__mongoc_counter_, ident) \ - .cpus[_mongoc_sched_getcpu ()] \ - .slots[BSON_CONCAT (COUNTER_, ident) % SLOTS_PER_CACHELINE]; \ - bson_atomic_int64_fetch_add (counter, val, bson_memory_order_seq_cst); \ - } \ - static BSON_INLINE void mongoc_counter_##ident##_inc (void) \ - { \ - mongoc_counter_##ident##_add (1); \ - } \ - static BSON_INLINE void mongoc_counter_##ident##_dec (void) \ - { \ - mongoc_counter_##ident##_add (-1); \ - } \ - static BSON_INLINE void mongoc_counter_##ident##_reset (void) \ - { \ - uint32_t i; \ - for (i = 0; i < _mongoc_get_cpu_count (); i++) { \ - int64_t *counter = &__mongoc_counter_##ident.cpus[i] \ - .slots[COUNTER_##ident % SLOTS_PER_CACHELINE]; \ - bson_atomic_int64_exchange (counter, 0, bson_memory_order_seq_cst); \ - } \ - bson_atomic_thread_fence (); \ - } \ - static BSON_INLINE int32_t mongoc_counter_##ident##_count (void) \ - { \ - int32_t _sum = 0; \ - uint32_t _i; \ - for (_i = 0; _i < _mongoc_get_cpu_count (); _i++) { \ - const int64_t *counter = \ - &BSON_CONCAT (__mongoc_counter_, ident) \ - .cpus[_i] \ - .slots[BSON_CONCAT (COUNTER_, ident) % SLOTS_PER_CACHELINE]; \ - _sum += bson_atomic_int64_fetch (counter, bson_memory_order_seq_cst); \ - } \ - return _sum; \ +#define COUNTER(ident, Category, Name, Description) \ + static BSON_INLINE void mongoc_counter_##ident##_add (int64_t val) \ + { \ + int64_t *counter = &BSON_CONCAT (__mongoc_counter_, ident) \ + .cpus[_mongoc_sched_getcpu ()] \ + .slots[BSON_CONCAT (COUNTER_, ident) % SLOTS_PER_CACHELINE]; \ + bson_atomic_int64_fetch_add (counter, val, bson_memory_order_seq_cst); \ + } \ + static BSON_INLINE void mongoc_counter_##ident##_inc (void) \ + { \ + mongoc_counter_##ident##_add (1); \ + } \ + static BSON_INLINE void mongoc_counter_##ident##_dec (void) \ + { \ + mongoc_counter_##ident##_add (-1); \ + } \ + static BSON_INLINE void mongoc_counter_##ident##_reset (void) \ + { \ + uint32_t i; \ + for (i = 0; i < _mongoc_get_cpu_count (); i++) { \ + int64_t *counter = &__mongoc_counter_##ident.cpus[i].slots[COUNTER_##ident % SLOTS_PER_CACHELINE]; \ + bson_atomic_int64_exchange (counter, 0, bson_memory_order_seq_cst); \ + } \ + bson_atomic_thread_fence (); \ + } \ + static BSON_INLINE int32_t mongoc_counter_##ident##_count (void) \ + { \ + int32_t _sum = 0; \ + uint32_t _i; \ + for (_i = 0; _i < _mongoc_get_cpu_count (); _i++) { \ + const int64_t *counter = &BSON_CONCAT (__mongoc_counter_, ident) \ + .cpus[_i] \ + .slots[BSON_CONCAT (COUNTER_, ident) % SLOTS_PER_CACHELINE]; \ + _sum += bson_atomic_int64_fetch (counter, bson_memory_order_seq_cst); \ + } \ + return _sum; \ } #include "mongoc-counters.defs" #undef COUNTER diff --git a/src/libmongoc/src/mongoc/mongoc-counters.c b/src/libmongoc/src/mongoc/mongoc-counters.c index f8a6bdf7a7..1f4a32c799 100644 --- a/src/libmongoc/src/mongoc/mongoc-counters.c +++ b/src/libmongoc/src/mongoc/mongoc-counters.c @@ -71,8 +71,7 @@ BSON_STATIC_ASSERT2 (counters_t, sizeof (mongoc_counters_t) == 64); * for whether or not initiating the shared memory segment succeeded. */ static void *gCounterFallback = NULL; -#define COUNTER(ident, Category, Name, Description) \ - mongoc_counter_t __mongoc_counter_##ident; +#define COUNTER(ident, Category, Name, Description) mongoc_counter_t __mongoc_counter_##ident; #include "mongoc-counters.defs" #undef COUNTER @@ -107,8 +106,7 @@ mongoc_counters_calc_size (void) n_cpu = _mongoc_get_cpu_count (); n_groups = (LAST_COUNTER / SLOTS_PER_CACHELINE) + 1; - size = (sizeof (mongoc_counters_t) + - (LAST_COUNTER * sizeof (mongoc_counter_info_t)) + + size = (sizeof (mongoc_counters_t) + (LAST_COUNTER * sizeof (mongoc_counter_info_t)) + (n_cpu * n_groups * sizeof (mongoc_counter_slots_t))); #ifdef BSON_OS_UNIX @@ -175,9 +173,7 @@ mongoc_counters_alloc (size_t size) #ifndef O_NOFOLLOW #define O_NOFOLLOW 0 #endif - if (-1 == (fd = shm_open (name, - O_CREAT | O_EXCL | O_RDWR, - S_IRUSR | S_IWUSR | O_NOFOLLOW))) { + if (-1 == (fd = shm_open (name, O_CREAT | O_EXCL | O_RDWR, S_IRUSR | S_IWUSR | O_NOFOLLOW))) { goto fail_noclean; } @@ -234,11 +230,8 @@ mongoc_counters_alloc (size_t size) * Returns: The offset to the data for the counters values. */ static size_t -mongoc_counters_register (mongoc_counters_t *counters, - uint32_t num, - const char *category, - const char *name, - const char *description) +mongoc_counters_register ( + mongoc_counters_t *counters, uint32_t num, const char *category, const char *name, const char *description) { mongoc_counter_info_t *infos; char *segment; @@ -263,9 +256,7 @@ mongoc_counters_register (mongoc_counters_t *counters, infos = (mongoc_counter_info_t *) (segment + counters->infos_offset); infos = &infos[counters->n_counters]; infos->slot = num % SLOTS_PER_CACHELINE; - infos->offset = - (counters->values_offset + - ((num / SLOTS_PER_CACHELINE) * n_cpu * sizeof (mongoc_counter_slots_t))); + infos->offset = (counters->values_offset + ((num / SLOTS_PER_CACHELINE) * n_cpu * sizeof (mongoc_counter_slots_t))); bson_strncpy (infos->category, category, sizeof infos->category); bson_strncpy (infos->name, name, sizeof infos->name); @@ -308,9 +299,8 @@ _mongoc_counters_init (void) BSON_ASSERT ((counters->values_offset % 64) == 0); -#define COUNTER(ident, Category, Name, Desc) \ - off = mongoc_counters_register ( \ - counters, COUNTER_##ident, Category, Name, Desc); \ +#define COUNTER(ident, Category, Name, Desc) \ + off = mongoc_counters_register (counters, COUNTER_##ident, Category, Name, Desc); \ __mongoc_counter_##ident.cpus = (mongoc_counter_slots_t *) (segment + off); #include "mongoc-counters.defs" #undef COUNTER diff --git a/src/libmongoc/src/mongoc/mongoc-crypt-private.h b/src/libmongoc/src/mongoc/mongoc-crypt-private.h index b9ac23b17c..13fb205bd3 100644 --- a/src/libmongoc/src/mongoc/mongoc-crypt-private.h +++ b/src/libmongoc/src/mongoc/mongoc-crypt-private.h @@ -85,36 +85,34 @@ Perform explicit encryption. Return false on error and sets `error`. */ bool -_mongoc_crypt_explicit_encrypt ( - _mongoc_crypt_t *crypt, - mongoc_collection_t *key_vault_coll, - const char *algorithm /* may be NULL */, - const bson_value_t *keyid /* may be NULL */, - const char *keyaltname /* may be NULL */, - const char *query_type /* may be NULL */, - const int64_t *contention_factor /* may be NULL */, - const bson_t *range_opts /* may be NULL */, - const bson_value_t *value_in, - bson_value_t *value_out, - bson_error_t *error); +_mongoc_crypt_explicit_encrypt (_mongoc_crypt_t *crypt, + mongoc_collection_t *key_vault_coll, + const char *algorithm /* may be NULL */, + const bson_value_t *keyid /* may be NULL */, + const char *keyaltname /* may be NULL */, + const char *query_type /* may be NULL */, + const int64_t *contention_factor /* may be NULL */, + const bson_t *range_opts /* may be NULL */, + const bson_value_t *value_in, + bson_value_t *value_out, + bson_error_t *error); /* Perform explicit encryption on an expression. Return false on error and sets `error`. */ bool -_mongoc_crypt_explicit_encrypt_expression ( - _mongoc_crypt_t *crypt, - mongoc_collection_t *key_vault_coll, - const char *algorithm /* may be NULL */, - const bson_value_t *keyid /* may be NULL */, - const char *keyaltname /* may be NULL */, - const char *query_type /* may be NULL */, - const int64_t *contention_factor /* may be NULL */, - const bson_t *range_opts /* may be NULL */, - const bson_t *expr_in, - bson_t *expr_out, - bson_error_t *error); +_mongoc_crypt_explicit_encrypt_expression (_mongoc_crypt_t *crypt, + mongoc_collection_t *key_vault_coll, + const char *algorithm /* may be NULL */, + const bson_value_t *keyid /* may be NULL */, + const char *keyaltname /* may be NULL */, + const char *query_type /* may be NULL */, + const int64_t *contention_factor /* may be NULL */, + const bson_t *range_opts /* may be NULL */, + const bson_t *expr_in, + bson_t *expr_out, + bson_error_t *error); /* Perform explicit decryption. diff --git a/src/libmongoc/src/mongoc/mongoc-crypt.c b/src/libmongoc/src/mongoc/mongoc-crypt.c index 61804e38c6..d1ca820da0 100644 --- a/src/libmongoc/src/mongoc/mongoc-crypt.c +++ b/src/libmongoc/src/mongoc/mongoc-crypt.c @@ -49,10 +49,8 @@ typedef struct { mcd_mapof_kmsid_to_tlsopts * mcd_mapof_kmsid_to_tlsopts_new (void) { - mcd_mapof_kmsid_to_tlsopts *k2t = - bson_malloc0 (sizeof (mcd_mapof_kmsid_to_tlsopts)); - _mongoc_array_init (&k2t->entries, - sizeof (mcd_mapof_kmsid_to_tlsopts_entry)); + mcd_mapof_kmsid_to_tlsopts *k2t = bson_malloc0 (sizeof (mcd_mapof_kmsid_to_tlsopts)); + _mongoc_array_init (&k2t->entries, sizeof (mcd_mapof_kmsid_to_tlsopts_entry)); return k2t; } @@ -63,8 +61,7 @@ mcd_mapof_kmsid_to_tlsopts_destroy (mcd_mapof_kmsid_to_tlsopts *k2t) return; } for (size_t i = 0; i < k2t->entries.len; i++) { - mcd_mapof_kmsid_to_tlsopts_entry *e = &_mongoc_array_index ( - &k2t->entries, mcd_mapof_kmsid_to_tlsopts_entry, i); + mcd_mapof_kmsid_to_tlsopts_entry *e = &_mongoc_array_index (&k2t->entries, mcd_mapof_kmsid_to_tlsopts_entry, i); bson_free (e->kmsid); _mongoc_ssl_opts_cleanup (&e->tlsopts, true /* free_internal */); } @@ -76,9 +73,7 @@ mcd_mapof_kmsid_to_tlsopts_destroy (mcd_mapof_kmsid_to_tlsopts *k2t) // `kmsid` and `tlsopts` are copied. // No checking is done to prohibit duplicate entries. void -mcd_mapof_kmsid_to_tlsopts_insert (mcd_mapof_kmsid_to_tlsopts *k2t, - const char *kmsid, - const mongoc_ssl_opt_t *tlsopts) +mcd_mapof_kmsid_to_tlsopts_insert (mcd_mapof_kmsid_to_tlsopts *k2t, const char *kmsid, const mongoc_ssl_opt_t *tlsopts) { BSON_ASSERT_PARAM (k2t); BSON_ASSERT_PARAM (kmsid); @@ -92,15 +87,13 @@ mcd_mapof_kmsid_to_tlsopts_insert (mcd_mapof_kmsid_to_tlsopts *k2t, // `mcd_mapof_kmsid_to_tlsopts_get` returns the TLS options for a KMS ID, or // NULL. const mongoc_ssl_opt_t * -mcd_mapof_kmsid_to_tlsopts_get (const mcd_mapof_kmsid_to_tlsopts *k2t, - const char *kmsid) +mcd_mapof_kmsid_to_tlsopts_get (const mcd_mapof_kmsid_to_tlsopts *k2t, const char *kmsid) { BSON_ASSERT_PARAM (k2t); BSON_ASSERT_PARAM (kmsid); for (size_t i = 0; i < k2t->entries.len; i++) { - mcd_mapof_kmsid_to_tlsopts_entry *e = &_mongoc_array_index ( - &k2t->entries, mcd_mapof_kmsid_to_tlsopts_entry, i); + mcd_mapof_kmsid_to_tlsopts_entry *e = &_mongoc_array_index (&k2t->entries, mcd_mapof_kmsid_to_tlsopts_entry, i); if (0 == strcmp (e->kmsid, kmsid)) { return &e->tlsopts; } @@ -110,8 +103,7 @@ mcd_mapof_kmsid_to_tlsopts_get (const mcd_mapof_kmsid_to_tlsopts *k2t, bool -mcd_mapof_kmsid_to_tlsopts_has (const mcd_mapof_kmsid_to_tlsopts *k2t, - const char *kmsid) +mcd_mapof_kmsid_to_tlsopts_has (const mcd_mapof_kmsid_to_tlsopts *k2t, const char *kmsid) { return NULL != mcd_mapof_kmsid_to_tlsopts_get (k2t, kmsid); } @@ -138,10 +130,7 @@ struct __mongoc_crypt_t { }; static void -_log_callback (mongocrypt_log_level_t mongocrypt_log_level, - const char *message, - uint32_t message_len, - void *ctx) +_log_callback (mongocrypt_log_level_t mongocrypt_log_level, const char *message, uint32_t message_len, void *ctx) { mongoc_log_level_t log_level = MONGOC_LOG_LEVEL_ERROR; @@ -208,9 +197,7 @@ _status_to_error (mongocrypt_status_t *status, bson_error_t *error) * Returns false if error, and sets @error. */ bool -_ctx_check_error (mongocrypt_ctx_t *ctx, - bson_error_t *error, - bool error_expected) +_ctx_check_error (mongocrypt_ctx_t *ctx, bson_error_t *error, bool error_expected) { mongocrypt_status_t *status; @@ -232,9 +219,7 @@ _ctx_check_error (mongocrypt_ctx_t *ctx, } bool -_kms_ctx_check_error (mongocrypt_kms_ctx_t *kms_ctx, - bson_error_t *error, - bool error_expected) +_kms_ctx_check_error (mongocrypt_kms_ctx_t *kms_ctx, bson_error_t *error, bool error_expected) { mongocrypt_status_t *status; @@ -256,9 +241,7 @@ _kms_ctx_check_error (mongocrypt_kms_ctx_t *kms_ctx, } bool -_crypt_check_error (mongocrypt_t *crypt, - bson_error_t *error, - bool error_expected) +_crypt_check_error (mongocrypt_t *crypt, bson_error_t *error, bool error_expected) { mongocrypt_status_t *status; @@ -284,12 +267,8 @@ static bool _bin_to_static_bson (mongocrypt_binary_t *bin, bson_t *out, bson_error_t *error) { /* Copy bin into bson_t result. */ - if (!bson_init_static ( - out, mongocrypt_binary_data (bin), mongocrypt_binary_len (bin))) { - bson_set_error (error, - MONGOC_ERROR_BSON, - MONGOC_ERROR_BSON_INVALID, - "invalid returned bson"); + if (!bson_init_static (out, mongocrypt_binary_data (bin), mongocrypt_binary_len (bin))) { + bson_set_error (error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "invalid returned bson"); return false; } return true; @@ -325,8 +304,7 @@ _state_machine_destroy (_state_machine_t *state_machine) /* State handler MONGOCRYPT_CTX_NEED_MONGO_COLLINFO */ static bool -_state_need_mongo_collinfo (_state_machine_t *state_machine, - bson_error_t *error) +_state_need_mongo_collinfo (_state_machine_t *state_machine, bson_error_t *error) { mongoc_database_t *db = NULL; mongoc_cursor_t *cursor = NULL; @@ -350,8 +328,7 @@ _state_need_mongo_collinfo (_state_machine_t *state_machine, } bson_append_document (&opts, "filter", -1, &filter_bson); - db = mongoc_client_get_database (state_machine->collinfo_client, - state_machine->db_name); + db = mongoc_client_get_database (state_machine->collinfo_client, state_machine->db_name); cursor = mongoc_database_find_collections_with_opts (db, &opts); if (mongoc_cursor_error (cursor, error)) { goto fail; @@ -360,8 +337,7 @@ _state_need_mongo_collinfo (_state_machine_t *state_machine, /* 2. Return the first result (if any) with mongocrypt_ctx_mongo_feed or * proceed to the next step if nothing was returned. */ if (mongoc_cursor_next (cursor, &collinfo_bson)) { - collinfo_bin = mongocrypt_binary_new_from_data ( - (uint8_t *) bson_get_data (collinfo_bson), collinfo_bson->len); + collinfo_bin = mongocrypt_binary_new_from_data ((uint8_t *) bson_get_data (collinfo_bson), collinfo_bson->len); if (!mongocrypt_ctx_mongo_feed (state_machine->ctx, collinfo_bin)) { _ctx_check_error (state_machine->ctx, error, true); goto fail; @@ -389,8 +365,7 @@ _state_need_mongo_collinfo (_state_machine_t *state_machine, } static bool -_state_need_mongo_markings (_state_machine_t *state_machine, - bson_error_t *error) +_state_need_mongo_markings (_state_machine_t *state_machine, bson_error_t *error) { bool ret = false; mongocrypt_binary_t *mongocryptd_cmd_bin = NULL; @@ -405,8 +380,7 @@ _state_need_mongo_markings (_state_machine_t *state_machine, goto fail; } - if (!_bin_to_static_bson ( - mongocryptd_cmd_bin, &mongocryptd_cmd_bson, error)) { + if (!_bin_to_static_bson (mongocryptd_cmd_bin, &mongocryptd_cmd_bson, error)) { goto fail; } @@ -424,8 +398,7 @@ _state_need_mongo_markings (_state_machine_t *state_machine, } /* 2. Feed the reply back with mongocrypt_ctx_mongo_feed. */ - mongocryptd_reply_bin = mongocrypt_binary_new_from_data ( - (uint8_t *) bson_get_data (&reply), reply.len); + mongocryptd_reply_bin = mongocrypt_binary_new_from_data ((uint8_t *) bson_get_data (&reply), reply.len); if (!mongocrypt_ctx_mongo_feed (state_machine->ctx, mongocryptd_reply_bin)) { _ctx_check_error (state_machine->ctx, error, true); goto fail; @@ -471,21 +444,17 @@ _state_need_mongo_keys (_state_machine_t *state_machine, bson_error_t *error) } { - const mongoc_read_concern_t *const rc = - mongoc_collection_get_read_concern (state_machine->keyvault_coll); + const mongoc_read_concern_t *const rc = mongoc_collection_get_read_concern (state_machine->keyvault_coll); const char *const level = rc ? mongoc_read_concern_get_level (rc) : NULL; - BSON_ASSERT (level && - strcmp (level, MONGOC_READ_CONCERN_LEVEL_MAJORITY) == 0); + BSON_ASSERT (level && strcmp (level, MONGOC_READ_CONCERN_LEVEL_MAJORITY) == 0); } - cursor = mongoc_collection_find_with_opts ( - state_machine->keyvault_coll, &filter_bson, &opts, NULL /* read prefs */); + cursor = mongoc_collection_find_with_opts (state_machine->keyvault_coll, &filter_bson, &opts, NULL /* read prefs */); /* 2. Feed all resulting documents back (if any) with repeated calls to * mongocrypt_ctx_mongo_feed. */ while (mongoc_cursor_next (cursor, &key_bson)) { mongocrypt_binary_destroy (key_bin); - key_bin = mongocrypt_binary_new_from_data ( - (uint8_t *) bson_get_data (key_bson), key_bson->len); + key_bin = mongocrypt_binary_new_from_data ((uint8_t *) bson_get_data (key_bson), key_bson->len); if (!mongocrypt_ctx_mongo_feed (state_machine->ctx, key_bin)) { _ctx_check_error (state_machine->ctx, error, true); goto fail; @@ -512,10 +481,7 @@ _state_need_mongo_keys (_state_machine_t *state_machine, bson_error_t *error) } static mongoc_stream_t * -_get_stream (const char *endpoint, - int32_t connecttimeoutms, - const mongoc_ssl_opt_t *ssl_opt, - bson_error_t *error) +_get_stream (const char *endpoint, int32_t connecttimeoutms, const mongoc_ssl_opt_t *ssl_opt, bson_error_t *error) { mongoc_stream_t *base_stream = NULL; mongoc_stream_t *tls_stream = NULL; @@ -534,20 +500,15 @@ _get_stream (const char *endpoint, /* Wrap in a tls_stream. */ _mongoc_ssl_opts_copy_to (ssl_opt, &ssl_opt_copy, true /* copy_internal */); - tls_stream = mongoc_stream_tls_new_with_hostname ( - base_stream, host.host, &ssl_opt_copy, 1 /* client */); + tls_stream = mongoc_stream_tls_new_with_hostname (base_stream, host.host, &ssl_opt_copy, 1 /* client */); if (!tls_stream) { - bson_set_error (error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_SOCKET, - "Failed to create TLS stream to: %s", - endpoint); + bson_set_error ( + error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "Failed to create TLS stream to: %s", endpoint); goto fail; } - if (!mongoc_stream_tls_handshake_block ( - tls_stream, host.host, connecttimeoutms, error)) { + if (!mongoc_stream_tls_handshake_block (tls_stream, host.host, connecttimeoutms, error)) { goto fail; } @@ -592,10 +553,8 @@ _state_need_kms (_state_machine_t *state_machine, bson_error_t *error) ssl_opt = &state_machine->crypt->azure_tls_opt; } else if (0 == strcmp ("gcp", provider)) { ssl_opt = &state_machine->crypt->gcp_tls_opt; - } else if (mcd_mapof_kmsid_to_tlsopts_has ( - state_machine->crypt->kmsid_to_tlsopts, provider)) { - ssl_opt = mcd_mapof_kmsid_to_tlsopts_get ( - state_machine->crypt->kmsid_to_tlsopts, provider); + } else if (mcd_mapof_kmsid_to_tlsopts_has (state_machine->crypt->kmsid_to_tlsopts, provider)) { + ssl_opt = mcd_mapof_kmsid_to_tlsopts_get (state_machine->crypt->kmsid_to_tlsopts, provider); } else { ssl_opt = mongoc_ssl_opt_get_default (); } @@ -627,8 +586,7 @@ _state_need_kms (_state_machine_t *state_machine, bson_error_t *error) iov.iov_base = (char *) mongocrypt_binary_data (http_req); iov.iov_len = mongocrypt_binary_len (http_req); - if (!_mongoc_stream_writev_full ( - tls_stream, &iov, 1, sockettimeout, error)) { + if (!_mongoc_stream_writev_full (tls_stream, &iov, 1, sockettimeout, error)) { goto fail; } @@ -644,30 +602,22 @@ _state_need_kms (_state_machine_t *state_machine, bson_error_t *error) bytes_needed = BUFFER_SIZE; } - read_ret = mongoc_stream_read ( - tls_stream, buf, bytes_needed, 1 /* min_bytes. */, sockettimeout); + read_ret = mongoc_stream_read (tls_stream, buf, bytes_needed, 1 /* min_bytes. */, sockettimeout); if (read_ret == -1) { - bson_set_error (error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_SOCKET, - "failed to read from KMS stream: %d", - errno); + bson_set_error ( + error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "failed to read from KMS stream: %d", errno); goto fail; } if (read_ret == 0) { - bson_set_error (error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_SOCKET, - "unexpected EOF from KMS stream"); + bson_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "unexpected EOF from KMS stream"); goto fail; } mongocrypt_binary_destroy (http_reply); BSON_ASSERT (bson_in_range_signed (uint32_t, read_ret)); - http_reply = - mongocrypt_binary_new_from_data (buf, (uint32_t) read_ret); + http_reply = mongocrypt_binary_new_from_data (buf, (uint32_t) read_ret); if (!mongocrypt_kms_ctx_feed (kms_ctx, http_reply)) { _kms_ctx_check_error (kms_ctx, error, true); goto fail; @@ -790,16 +740,14 @@ _try_add_aws_from_env (bson_t *out, bson_error_t *error) // Build the new "aws" subdoc bson_t aws; - bool okay = - BSON_APPEND_DOCUMENT_BEGIN (out, "aws", &aws) - // Add the accessKeyId and the secretAccessKey - && BSON_APPEND_UTF8 (&aws, "accessKeyId", creds.access_key_id) // - && BSON_APPEND_UTF8 (&aws, "secretAccessKey", creds.secret_access_key) // - // Add the sessionToken, if we got one: - && (!creds.session_token || - BSON_APPEND_UTF8 (&aws, "sessionToken", creds.session_token)) // - // Finish the document - && bson_append_document_end (out, &aws); + bool okay = BSON_APPEND_DOCUMENT_BEGIN (out, "aws", &aws) + // Add the accessKeyId and the secretAccessKey + && BSON_APPEND_UTF8 (&aws, "accessKeyId", creds.access_key_id) // + && BSON_APPEND_UTF8 (&aws, "secretAccessKey", creds.secret_access_key) // + // Add the sessionToken, if we got one: + && (!creds.session_token || BSON_APPEND_UTF8 (&aws, "sessionToken", creds.session_token)) // + // Finish the document + && bson_append_document_end (out, &aws); BSON_ASSERT (okay && "Failed to build aws credentials document"); // Good! _mongoc_aws_credentials_cleanup (&creds); @@ -834,15 +782,12 @@ _request_new_azure_token (mcd_azure_access_token *out, bson_error_t *error) * @retval false If there was an error obtaining or appending credentials */ static bool -_try_add_azure_from_env (_mongoc_crypt_t *crypt, - bson_t *out, - bson_error_t *error) +_try_add_azure_from_env (_mongoc_crypt_t *crypt, bson_t *out, bson_error_t *error) { if (crypt->azure_token.access_token) { // The access-token is non-null, so we may have one cached. mcd_time_point one_min_from_now = mcd_later (mcd_now (), mcd_minutes (1)); - mcd_time_point expires_at = mcd_later (crypt->azure_token_issued_at, - crypt->azure_token.expires_in); + mcd_time_point expires_at = mcd_later (crypt->azure_token_issued_at, crypt->azure_token.expires_in); if (mcd_time_compare (expires_at, one_min_from_now) >= 0) { // The token is still valid for at least another minute } else { @@ -869,9 +814,7 @@ _try_add_azure_from_env (_mongoc_crypt_t *crypt, // Build the new KMS credentials bson_t new_azure_creds = BSON_INITIALIZER; - const bool okay = BSON_APPEND_UTF8 (&new_azure_creds, - "accessToken", - crypt->azure_token.access_token) && + const bool okay = BSON_APPEND_UTF8 (&new_azure_creds, "accessToken", crypt->azure_token.access_token) && BSON_APPEND_DOCUMENT (out, "azure", &new_azure_creds); bson_destroy (&new_azure_creds); if (!okay) { @@ -948,9 +891,7 @@ _try_add_gcp_from_env (bson_t *out, bson_error_t *error) // Build the new KMS credentials bson_t new_gcp_creds = BSON_INITIALIZER; - const bool okay = BSON_APPEND_UTF8 (&new_gcp_creds, - "accessToken", - gcp_token.access_token) && + const bool okay = BSON_APPEND_UTF8 (&new_gcp_creds, "accessToken", gcp_token.access_token) && BSON_APPEND_DOCUMENT (out, "gcp", &new_gcp_creds); bson_destroy (&new_gcp_creds); gcp_access_token_destroy (&gcp_token); @@ -973,8 +914,7 @@ _state_need_kms_credentials (_state_machine_t *sm, bson_error_t *error) if (sm->crypt->creds_cb.fn) { // We have a user-provided credentials callback. Try it. - if (!sm->crypt->creds_cb.fn ( - sm->crypt->creds_cb.userdata, &empty, &creds, error)) { + if (!sm->crypt->creds_cb.fn (sm->crypt->creds_cb.userdata, &empty, &creds, error)) { // User-provided callback indicated failure if (!error->code) { // The callback did not set an error, so we'll provide a default @@ -991,11 +931,9 @@ _state_need_kms_credentials (_state_machine_t *sm, bson_error_t *error) } bson_iter_t iter; - const bool callback_provided_aws = - bson_iter_init_find (&iter, &creds, "aws"); + const bool callback_provided_aws = bson_iter_init_find (&iter, &creds, "aws"); - if (!callback_provided_aws && - _needs_on_demand_aws_kms (&sm->crypt->kms_providers)) { + if (!callback_provided_aws && _needs_on_demand_aws_kms (&sm->crypt->kms_providers)) { // The original kmsProviders had an empty "aws" property, and the // user-provided callback did not fill in a new "aws" property for us. // Attempt instead to load the AWS credentials from the environment: @@ -1008,8 +946,7 @@ _state_need_kms_credentials (_state_machine_t *sm, bson_error_t *error) // Whether the callback provided Azure credentials const bool cb_provided_azure = bson_iter_init_find (&iter, &creds, "azure"); // Whether the original kmsProviders requested auto-Azure credentials: - const bool orig_wants_auto_azure = - _check_azure_kms_auto (&sm->crypt->kms_providers, error); + const bool orig_wants_auto_azure = _check_azure_kms_auto (&sm->crypt->kms_providers, error); if (error->code) { // _check_azure_kms_auto failed goto fail; @@ -1024,8 +961,7 @@ _state_need_kms_credentials (_state_machine_t *sm, bson_error_t *error) // Whether the callback provided GCP credentials const bool cb_provided_gcp = bson_iter_init_find (&iter, &creds, "gcp"); // Whether the original kmsProviders requested auto-GCP credentials: - const bool orig_wants_auto_gcp = - _check_gcp_kms_auto (&sm->crypt->kms_providers, error); + const bool orig_wants_auto_gcp = _check_gcp_kms_auto (&sm->crypt->kms_providers, error); if (error->code) { // _check_gcp_kms_auto failed goto fail; @@ -1038,8 +974,7 @@ _state_need_kms_credentials (_state_machine_t *sm, bson_error_t *error) } // Now actually send that data to libmongocrypt - mongocrypt_binary_t *const def = mongocrypt_binary_new_from_data ( - (uint8_t *) bson_get_data (&creds), creds.len); + mongocrypt_binary_t *const def = mongocrypt_binary_new_from_data ((uint8_t *) bson_get_data (&creds), creds.len); okay = mongocrypt_ctx_provide_kms_providers (sm->ctx, def); if (!okay) { _ctx_check_error (sm->ctx, error, true); @@ -1054,9 +989,7 @@ _state_need_kms_credentials (_state_machine_t *sm, bson_error_t *error) static bool -_state_ready (_state_machine_t *state_machine, - bson_t *result, - bson_error_t *error) +_state_ready (_state_machine_t *state_machine, bson_t *result, bson_error_t *error) { mongocrypt_binary_t *result_bin = NULL; bson_t tmp; @@ -1095,9 +1028,7 @@ _state_ready (_state_machine_t *state_machine, * -------------------------------------------------------------------------- */ bool -_state_machine_run (_state_machine_t *state_machine, - bson_t *result, - bson_error_t *error) +_state_machine_run (_state_machine_t *state_machine, bson_t *result, bson_error_t *error) { bool ret = false; mongocrypt_binary_t *bin = NULL; @@ -1160,9 +1091,7 @@ _state_machine_run (_state_machine_t *state_machine, * - @out_opt is always initialized. * Returns false and sets @error on error. */ static bool -_parse_one_tls_opts (bson_iter_t *iter, - mongoc_ssl_opt_t *out_opt, - bson_error_t *error) +_parse_one_tls_opts (bson_iter_t *iter, mongoc_ssl_opt_t *out_opt, bson_error_t *error) { bool ok = false; const char *kms_provider; @@ -1187,8 +1116,7 @@ _parse_one_tls_opts (bson_iter_t *iter, } bson_iter_document (iter, &len, &data); - if (!bson_init_static (&tls_opts_doc, data, len) || - !bson_iter_init (&permitted_iter, &tls_opts_doc)) { + if (!bson_init_static (&tls_opts_doc, data, len) || !bson_iter_init (&permitted_iter, &tls_opts_doc)) { bson_set_error (error, MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION, MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG, @@ -1200,8 +1128,7 @@ _parse_one_tls_opts (bson_iter_t *iter, while (bson_iter_next (&permitted_iter)) { const char *key = bson_iter_key (&permitted_iter); - if (0 == - bson_strcasecmp (key, MONGOC_URI_TLSCERTIFICATEKEYFILEPASSWORD)) { + if (0 == bson_strcasecmp (key, MONGOC_URI_TLSCERTIFICATEKEYFILEPASSWORD)) { continue; } @@ -1217,13 +1144,12 @@ _parse_one_tls_opts (bson_iter_t *iter, continue; } - bson_set_error ( - error, - MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION, - MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG, - "Error setting TLS option %s for %s. Insecure TLS options prohibited.", - key, - kms_provider); + bson_set_error (error, + MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION, + MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG, + "Error setting TLS option %s for %s. Insecure TLS options prohibited.", + key, + kms_provider); goto fail; } @@ -1250,9 +1176,7 @@ _parse_one_tls_opts (bson_iter_t *iter, * Defaults to using mongoc_ssl_opt_get_default() if options are not passed for * a provider. Returns false and sets @error on error. */ static bool -_parse_all_tls_opts (_mongoc_crypt_t *crypt, - const bson_t *tls_opts, - bson_error_t *error) +_parse_all_tls_opts (_mongoc_crypt_t *crypt, const bson_t *tls_opts, bson_error_t *error) { bson_iter_t iter; bool ok = false; @@ -1362,8 +1286,7 @@ _parse_all_tls_opts (_mongoc_crypt_t *crypt, _mongoc_ssl_opts_cleanup (&tlsopts, true /* free_internal */); goto fail; } - mcd_mapof_kmsid_to_tlsopts_insert ( - crypt->kmsid_to_tlsopts, key, &tlsopts); + mcd_mapof_kmsid_to_tlsopts_insert (crypt->kmsid_to_tlsopts, key, &tlsopts); _mongoc_ssl_opts_cleanup (&tlsopts, true /* free_internal */); continue; } @@ -1381,27 +1304,19 @@ _parse_all_tls_opts (_mongoc_crypt_t *crypt, * MONGOC_SSL_DEFAULT_TRUST_FILE or MONGOC_SSL_DEFAULT_TRUST_DIR are defined. */ if (!has_aws) { - _mongoc_ssl_opts_copy_to (mongoc_ssl_opt_get_default (), - &crypt->aws_tls_opt, - false /* copy internal */); + _mongoc_ssl_opts_copy_to (mongoc_ssl_opt_get_default (), &crypt->aws_tls_opt, false /* copy internal */); } if (!has_azure) { - _mongoc_ssl_opts_copy_to (mongoc_ssl_opt_get_default (), - &crypt->azure_tls_opt, - false /* copy internal */); + _mongoc_ssl_opts_copy_to (mongoc_ssl_opt_get_default (), &crypt->azure_tls_opt, false /* copy internal */); } if (!has_gcp) { - _mongoc_ssl_opts_copy_to (mongoc_ssl_opt_get_default (), - &crypt->gcp_tls_opt, - false /* copy internal */); + _mongoc_ssl_opts_copy_to (mongoc_ssl_opt_get_default (), &crypt->gcp_tls_opt, false /* copy internal */); } if (!has_kmip) { - _mongoc_ssl_opts_copy_to (mongoc_ssl_opt_get_default (), - &crypt->kmip_tls_opt, - false /* copy internal */); + _mongoc_ssl_opts_copy_to (mongoc_ssl_opt_get_default (), &crypt->kmip_tls_opt, false /* copy internal */); } ok = true; fail: @@ -1446,19 +1361,16 @@ _mongoc_crypt_new (const bson_t *kms_providers, goto fail; } - mongocrypt_setopt_log_handler ( - crypt->handle, _log_callback, NULL /* context */); + mongocrypt_setopt_log_handler (crypt->handle, _log_callback, NULL /* context */); - kms_providers_bin = mongocrypt_binary_new_from_data ( - (uint8_t *) bson_get_data (kms_providers), kms_providers->len); + kms_providers_bin = mongocrypt_binary_new_from_data ((uint8_t *) bson_get_data (kms_providers), kms_providers->len); if (!mongocrypt_setopt_kms_providers (crypt->handle, kms_providers_bin)) { _crypt_check_error (crypt->handle, error, true); goto fail; } if (schema_map) { - schema_map_bin = mongocrypt_binary_new_from_data ( - (uint8_t *) bson_get_data (schema_map), schema_map->len); + schema_map_bin = mongocrypt_binary_new_from_data ((uint8_t *) bson_get_data (schema_map), schema_map->len); if (!mongocrypt_setopt_schema_map (crypt->handle, schema_map_bin)) { _crypt_check_error (crypt->handle, error, true); goto fail; @@ -1466,26 +1378,22 @@ _mongoc_crypt_new (const bson_t *kms_providers, } if (encrypted_fields_map) { - encrypted_fields_map_bin = mongocrypt_binary_new_from_data ( - (uint8_t *) bson_get_data (encrypted_fields_map), - encrypted_fields_map->len); - if (!mongocrypt_setopt_encrypted_field_config_map ( - crypt->handle, encrypted_fields_map_bin)) { + encrypted_fields_map_bin = + mongocrypt_binary_new_from_data ((uint8_t *) bson_get_data (encrypted_fields_map), encrypted_fields_map->len); + if (!mongocrypt_setopt_encrypted_field_config_map (crypt->handle, encrypted_fields_map_bin)) { _crypt_check_error (crypt->handle, error, true); goto fail; } } if (!bypass_auto_encryption) { - mongocrypt_setopt_append_crypt_shared_lib_search_path (crypt->handle, - "$SYSTEM"); + mongocrypt_setopt_append_crypt_shared_lib_search_path (crypt->handle, "$SYSTEM"); if (!_crypt_check_error (crypt->handle, error, false)) { goto fail; } if (crypt_shared_lib_path != NULL) { - mongocrypt_setopt_set_crypt_shared_lib_path_override ( - crypt->handle, crypt_shared_lib_path); + mongocrypt_setopt_set_crypt_shared_lib_path_override (crypt->handle, crypt_shared_lib_path); if (!_crypt_check_error (crypt->handle, error, false)) { goto fail; } @@ -1509,23 +1417,19 @@ _mongoc_crypt_new (const bson_t *kms_providers, if (crypt_shared_lib_required) { uint32_t len = 0; - const char *s = - mongocrypt_crypt_shared_lib_version_string (crypt->handle, &len); + const char *s = mongocrypt_crypt_shared_lib_version_string (crypt->handle, &len); if (!s || len == 0) { // empty/null version string indicates that crypt_shared was not loaded // by libmongocrypt - bson_set_error ( - error, - MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION, - MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE, - "Option 'cryptSharedLibRequired' is 'true', but failed to " - "load the crypt_shared runtime library"); + bson_set_error (error, + MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION, + MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE, + "Option 'cryptSharedLibRequired' is 'true', but failed to " + "load the crypt_shared runtime library"); goto fail; } - mongoc_log (MONGOC_LOG_LEVEL_DEBUG, - MONGOC_LOG_DOMAIN, - "crypt_shared library version '%s' was found and loaded", - s); + mongoc_log ( + MONGOC_LOG_LEVEL_DEBUG, MONGOC_LOG_DOMAIN, "crypt_shared library version '%s' was found and loaded", s); } crypt->creds_cb = creds_cb; @@ -1590,10 +1494,8 @@ _mongoc_crypt_auto_encrypt (_mongoc_crypt_t *crypt, goto fail; } - cmd_bin = mongocrypt_binary_new_from_data ( - (uint8_t *) bson_get_data (cmd_in), cmd_in->len); - if (!mongocrypt_ctx_encrypt_init ( - state_machine->ctx, db_name, -1, cmd_bin)) { + cmd_bin = mongocrypt_binary_new_from_data ((uint8_t *) bson_get_data (cmd_in), cmd_in->len); + if (!mongocrypt_ctx_encrypt_init (state_machine->ctx, db_name, -1, cmd_bin)) { _ctx_check_error (state_machine->ctx, error, true); goto fail; } @@ -1631,8 +1533,7 @@ _mongoc_crypt_auto_decrypt (_mongoc_crypt_t *crypt, goto fail; } - doc_bin = mongocrypt_binary_new_from_data ( - (uint8_t *) bson_get_data (doc_in), doc_in->len); + doc_bin = mongocrypt_binary_new_from_data ((uint8_t *) bson_get_data (doc_in), doc_in->len); if (!mongocrypt_ctx_decrypt_init (state_machine->ctx, doc_bin)) { _ctx_check_error (state_machine->ctx, error, true); goto fail; @@ -1692,10 +1593,9 @@ _create_explicit_state_machine (_mongoc_crypt_t *crypt, if (range_opts != NULL) { /* mongocrypt error checks and parses range options */ - mongocrypt_binary_t *binary_range_opts = mongocrypt_binary_new_from_data ( - (uint8_t *) bson_get_data (range_opts), range_opts->len); - if (!mongocrypt_ctx_setopt_algorithm_range (state_machine->ctx, - binary_range_opts)) { + mongocrypt_binary_t *binary_range_opts = + mongocrypt_binary_new_from_data ((uint8_t *) bson_get_data (range_opts), range_opts->len); + if (!mongocrypt_ctx_setopt_algorithm_range (state_machine->ctx, binary_range_opts)) { mongocrypt_binary_destroy (binary_range_opts); _ctx_check_error (state_machine->ctx, error, true); goto fail; @@ -1704,15 +1604,13 @@ _create_explicit_state_machine (_mongoc_crypt_t *crypt, } if (query_type != NULL) { - if (!mongocrypt_ctx_setopt_query_type ( - state_machine->ctx, query_type, -1)) { + if (!mongocrypt_ctx_setopt_query_type (state_machine->ctx, query_type, -1)) { goto fail; } } if (contention_factor != NULL) { - if (!mongocrypt_ctx_setopt_contention_factor (state_machine->ctx, - *contention_factor)) { + if (!mongocrypt_ctx_setopt_contention_factor (state_machine->ctx, *contention_factor)) { _ctx_check_error (state_machine->ctx, error, true); goto fail; } @@ -1724,10 +1622,9 @@ _create_explicit_state_machine (_mongoc_crypt_t *crypt, bson_t *keyaltname_doc; keyaltname_doc = BCON_NEW ("keyAltName", keyaltname); - keyaltname_bin = mongocrypt_binary_new_from_data ( - (uint8_t *) bson_get_data (keyaltname_doc), keyaltname_doc->len); - keyaltname_ret = mongocrypt_ctx_setopt_key_alt_name (state_machine->ctx, - keyaltname_bin); + keyaltname_bin = + mongocrypt_binary_new_from_data ((uint8_t *) bson_get_data (keyaltname_doc), keyaltname_doc->len); + keyaltname_ret = mongocrypt_ctx_setopt_key_alt_name (state_machine->ctx, keyaltname_bin); mongocrypt_binary_destroy (keyaltname_bin); bson_destroy (keyaltname_doc); if (!keyaltname_ret) { @@ -1741,15 +1638,12 @@ _create_explicit_state_machine (_mongoc_crypt_t *crypt, bool keyid_ret; if (keyid->value.v_binary.subtype != BSON_SUBTYPE_UUID) { - bson_set_error (error, - MONGOC_ERROR_CLIENT, - MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG, - "keyid must be a UUID"); + bson_set_error ( + error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG, "keyid must be a UUID"); goto fail; } - keyid_bin = mongocrypt_binary_new_from_data ( - keyid->value.v_binary.data, keyid->value.v_binary.data_len); + keyid_bin = mongocrypt_binary_new_from_data (keyid->value.v_binary.data, keyid->value.v_binary.data_len); keyid_ret = mongocrypt_ctx_setopt_key_id (state_machine->ctx, keyid_bin); mongocrypt_binary_destroy (keyid_bin); if (!keyid_ret) { @@ -1800,25 +1694,16 @@ _mongoc_crypt_explicit_encrypt (_mongoc_crypt_t *crypt, value_out->value_type = BSON_TYPE_EOD; - state_machine = _create_explicit_state_machine (crypt, - keyvault_coll, - algorithm, - keyid, - keyaltname, - query_type, - contention_factor, - range_opts, - error); + state_machine = _create_explicit_state_machine ( + crypt, keyvault_coll, algorithm, keyid, keyaltname, query_type, contention_factor, range_opts, error); if (!state_machine) { goto fail; } to_encrypt_doc = bson_new (); BSON_APPEND_VALUE (to_encrypt_doc, "v", value_in); - to_encrypt_bin = mongocrypt_binary_new_from_data ( - (uint8_t *) bson_get_data (to_encrypt_doc), to_encrypt_doc->len); - if (!mongocrypt_ctx_explicit_encrypt_init (state_machine->ctx, - to_encrypt_bin)) { + to_encrypt_bin = mongocrypt_binary_new_from_data ((uint8_t *) bson_get_data (to_encrypt_doc), to_encrypt_doc->len); + if (!mongocrypt_ctx_explicit_encrypt_init (state_machine->ctx, to_encrypt_bin)) { _ctx_check_error (state_machine->ctx, error, true); goto fail; } @@ -1884,25 +1769,16 @@ _mongoc_crypt_explicit_encrypt_expression (_mongoc_crypt_t *crypt, bson_init (expr_out); - state_machine = _create_explicit_state_machine (crypt, - keyvault_coll, - algorithm, - keyid, - keyaltname, - query_type, - contention_factor, - range_opts, - error); + state_machine = _create_explicit_state_machine ( + crypt, keyvault_coll, algorithm, keyid, keyaltname, query_type, contention_factor, range_opts, error); if (!state_machine) { goto fail; } to_encrypt_doc = bson_new (); BSON_APPEND_DOCUMENT (to_encrypt_doc, "v", expr_in); - to_encrypt_bin = mongocrypt_binary_new_from_data ( - (uint8_t *) bson_get_data (to_encrypt_doc), to_encrypt_doc->len); - if (!mongocrypt_ctx_explicit_encrypt_expression_init (state_machine->ctx, - to_encrypt_bin)) { + to_encrypt_bin = mongocrypt_binary_new_from_data ((uint8_t *) bson_get_data (to_encrypt_doc), to_encrypt_doc->len); + if (!mongocrypt_ctx_explicit_encrypt_expression_init (state_machine->ctx, to_encrypt_bin)) { _ctx_check_error (state_machine->ctx, error, true); goto fail; } @@ -1923,12 +1799,11 @@ _mongoc_crypt_explicit_encrypt_expression (_mongoc_crypt_t *crypt, bson_t tmp; if (!BSON_ITER_HOLDS_DOCUMENT (&iter)) { - bson_set_error ( - error, - MONGOC_ERROR_CLIENT, - MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE, - "encrypted result unexpected: 'v' is not a document, got: %s", - _mongoc_bson_type_to_str (bson_iter_type (&iter))); + bson_set_error (error, + MONGOC_ERROR_CLIENT, + MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE, + "encrypted result unexpected: 'v' is not a document, got: %s", + _mongoc_bson_type_to_str (bson_iter_type (&iter))); goto fail; } @@ -1972,10 +1847,8 @@ _mongoc_crypt_explicit_decrypt (_mongoc_crypt_t *crypt, to_decrypt_doc = bson_new (); BSON_APPEND_VALUE (to_decrypt_doc, "v", value_in); - to_decrypt_bin = mongocrypt_binary_new_from_data ( - (uint8_t *) bson_get_data (to_decrypt_doc), to_decrypt_doc->len); - if (!mongocrypt_ctx_explicit_decrypt_init (state_machine->ctx, - to_decrypt_bin)) { + to_decrypt_bin = mongocrypt_binary_new_from_data ((uint8_t *) bson_get_data (to_decrypt_doc), to_decrypt_doc->len); + if (!mongocrypt_ctx_explicit_decrypt_init (state_machine->ctx, to_decrypt_bin)) { _ctx_check_error (state_machine->ctx, error, true); goto fail; } @@ -1987,10 +1860,8 @@ _mongoc_crypt_explicit_decrypt (_mongoc_crypt_t *crypt, /* extract value */ if (!bson_iter_init_find (&iter, &result, "v")) { - bson_set_error (error, - MONGOC_ERROR_CLIENT, - MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE, - "decrypted result unexpected"); + bson_set_error ( + error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE, "decrypted result unexpected"); goto fail; } else { const bson_value_t *tmp; @@ -2036,12 +1907,10 @@ _mongoc_crypt_create_datakey (_mongoc_crypt_t *crypt, if (masterkey) { bson_concat (&masterkey_w_provider, masterkey); } - masterkey_w_provider_bin = mongocrypt_binary_new_from_data ( - (uint8_t *) bson_get_data (&masterkey_w_provider), - masterkey_w_provider.len); + masterkey_w_provider_bin = + mongocrypt_binary_new_from_data ((uint8_t *) bson_get_data (&masterkey_w_provider), masterkey_w_provider.len); - if (!mongocrypt_ctx_setopt_key_encryption_key (state_machine->ctx, - masterkey_w_provider_bin)) { + if (!mongocrypt_ctx_setopt_key_encryption_key (state_machine->ctx, masterkey_w_provider_bin)) { _ctx_check_error (state_machine->ctx, error, true); goto fail; } @@ -2053,10 +1922,9 @@ _mongoc_crypt_create_datakey (_mongoc_crypt_t *crypt, bson_t *keyaltname_doc; keyaltname_doc = BCON_NEW ("keyAltName", keyaltnames[i]); - keyaltname_bin = mongocrypt_binary_new_from_data ( - (uint8_t *) bson_get_data (keyaltname_doc), keyaltname_doc->len); - keyaltname_ret = mongocrypt_ctx_setopt_key_alt_name ( - state_machine->ctx, keyaltname_bin); + keyaltname_bin = + mongocrypt_binary_new_from_data ((uint8_t *) bson_get_data (keyaltname_doc), keyaltname_doc->len); + keyaltname_ret = mongocrypt_ctx_setopt_key_alt_name (state_machine->ctx, keyaltname_bin); mongocrypt_binary_destroy (keyaltname_bin); bson_destroy (keyaltname_doc); if (!keyaltname_ret) { @@ -2067,11 +1935,8 @@ _mongoc_crypt_create_datakey (_mongoc_crypt_t *crypt, } if (keymaterial) { - bson_t *const bson = BCON_NEW ( - "keyMaterial", - BCON_BIN (BSON_SUBTYPE_BINARY, keymaterial, keymaterial_len)); - mongocrypt_binary_t *const bin = mongocrypt_binary_new_from_data ( - (uint8_t *) bson_get_data (bson), bson->len); + bson_t *const bson = BCON_NEW ("keyMaterial", BCON_BIN (BSON_SUBTYPE_BINARY, keymaterial, keymaterial_len)); + mongocrypt_binary_t *const bin = mongocrypt_binary_new_from_data ((uint8_t *) bson_get_data (bson), bson->len); mongocrypt_ctx_setopt_key_material (state_machine->ctx, bin); @@ -2136,11 +2001,10 @@ _mongoc_crypt_rewrap_many_datakey (_mongoc_crypt_t *crypt, bson_concat (&new_provider, master_key); } - new_provider_bin = mongocrypt_binary_new_from_data ( - (uint8_t *) bson_get_data (&new_provider), new_provider.len); + new_provider_bin = + mongocrypt_binary_new_from_data ((uint8_t *) bson_get_data (&new_provider), new_provider.len); - if (!mongocrypt_ctx_setopt_key_encryption_key (state_machine->ctx, - new_provider_bin)) { + if (!mongocrypt_ctx_setopt_key_encryption_key (state_machine->ctx, new_provider_bin)) { _ctx_check_error (state_machine->ctx, error, true); success = false; } @@ -2159,11 +2023,9 @@ _mongoc_crypt_rewrap_many_datakey (_mongoc_crypt_t *crypt, filter = &empty_bson; } - filter_bin = mongocrypt_binary_new_from_data ( - (uint8_t *) bson_get_data (filter), filter->len); + filter_bin = mongocrypt_binary_new_from_data ((uint8_t *) bson_get_data (filter), filter->len); - if (!mongocrypt_ctx_rewrap_many_datakey_init (state_machine->ctx, - filter_bin)) { + if (!mongocrypt_ctx_rewrap_many_datakey_init (state_machine->ctx, filter_bin)) { _ctx_check_error (state_machine->ctx, error, true); goto fail; } diff --git a/src/libmongoc/src/mongoc/mongoc-crypto-cng.c b/src/libmongoc/src/mongoc/mongoc-crypto-cng.c index 4cf82ca473..ee4198e54d 100644 --- a/src/libmongoc/src/mongoc/mongoc-crypto-cng.c +++ b/src/libmongoc/src/mongoc/mongoc-crypto-cng.c @@ -38,33 +38,26 @@ mongoc_crypto_cng_init (void) { NTSTATUS status = STATUS_UNSUCCESSFUL; _sha1_hash_algo = 0; - status = BCryptOpenAlgorithmProvider ( - &_sha1_hash_algo, BCRYPT_SHA1_ALGORITHM, NULL, 0); + status = BCryptOpenAlgorithmProvider (&_sha1_hash_algo, BCRYPT_SHA1_ALGORITHM, NULL, 0); if (!NT_SUCCESS (status)) { MONGOC_ERROR ("BCryptOpenAlgorithmProvider(SHA1): %ld", status); } _sha1_hmac_algo = 0; - status = BCryptOpenAlgorithmProvider (&_sha1_hmac_algo, - BCRYPT_SHA1_ALGORITHM, - NULL, - BCRYPT_ALG_HANDLE_HMAC_FLAG); + status = BCryptOpenAlgorithmProvider (&_sha1_hmac_algo, BCRYPT_SHA1_ALGORITHM, NULL, BCRYPT_ALG_HANDLE_HMAC_FLAG); if (!NT_SUCCESS (status)) { MONGOC_ERROR ("BCryptOpenAlgorithmProvider(SHA1 HMAC): %ld", status); } _sha256_hash_algo = 0; - status = BCryptOpenAlgorithmProvider ( - &_sha256_hash_algo, BCRYPT_SHA256_ALGORITHM, NULL, 0); + status = BCryptOpenAlgorithmProvider (&_sha256_hash_algo, BCRYPT_SHA256_ALGORITHM, NULL, 0); if (!NT_SUCCESS (status)) { MONGOC_ERROR ("BCryptOpenAlgorithmProvider(SHA256): %ld", status); } _sha256_hmac_algo = 0; - status = BCryptOpenAlgorithmProvider (&_sha256_hmac_algo, - BCRYPT_SHA256_ALGORITHM, - NULL, - BCRYPT_ALG_HANDLE_HMAC_FLAG); + status = + BCryptOpenAlgorithmProvider (&_sha256_hmac_algo, BCRYPT_SHA256_ALGORITHM, NULL, BCRYPT_ALG_HANDLE_HMAC_FLAG); if (!NT_SUCCESS (status)) { MONGOC_ERROR ("BCryptOpenAlgorithmProvider(SHA256 HMAC): %ld", status); } @@ -88,12 +81,8 @@ mongoc_crypto_cng_cleanup (void) } bool -_mongoc_crypto_cng_hmac_or_hash (BCRYPT_ALG_HANDLE algorithm, - const void *key, - size_t key_length, - void *data, - size_t data_length, - void *output) +_mongoc_crypto_cng_hmac_or_hash ( + BCRYPT_ALG_HANDLE algorithm, const void *key, size_t key_length, void *data, size_t data_length, void *output) { unsigned char *hash_object_buffer = 0; ULONG hash_object_length = 0; @@ -103,24 +92,16 @@ _mongoc_crypto_cng_hmac_or_hash (BCRYPT_ALG_HANDLE algorithm, bool retval = false; ULONG noop = 0; - status = BCryptGetProperty (algorithm, - BCRYPT_OBJECT_LENGTH, - (unsigned char *) &hash_object_length, - sizeof hash_object_length, - &noop, - 0); + status = BCryptGetProperty ( + algorithm, BCRYPT_OBJECT_LENGTH, (unsigned char *) &hash_object_length, sizeof hash_object_length, &noop, 0); if (!NT_SUCCESS (status)) { MONGOC_ERROR ("BCryptGetProperty(): OBJECT_LENGTH %ld", status); return false; } - status = BCryptGetProperty (algorithm, - BCRYPT_HASH_LENGTH, - (unsigned char *) &mac_length, - sizeof mac_length, - &noop, - 0); + status = + BCryptGetProperty (algorithm, BCRYPT_HASH_LENGTH, (unsigned char *) &mac_length, sizeof mac_length, &noop, 0); if (!NT_SUCCESS (status)) { MONGOC_ERROR ("BCryptGetProperty(): HASH_LENGTH %ld", status); @@ -129,13 +110,8 @@ _mongoc_crypto_cng_hmac_or_hash (BCRYPT_ALG_HANDLE algorithm, hash_object_buffer = bson_malloc (hash_object_length); - status = BCryptCreateHash (algorithm, - &hash, - hash_object_buffer, - hash_object_length, - (PUCHAR) key, - (ULONG) key_length, - 0); + status = + BCryptCreateHash (algorithm, &hash, hash_object_buffer, hash_object_length, (PUCHAR) key, (ULONG) key_length, 0); if (!NT_SUCCESS (status)) { MONGOC_ERROR ("BCryptCreateHash(): %ld", status); @@ -177,8 +153,7 @@ mongoc_crypto_cng_hmac_sha1 (mongoc_crypto_t *crypto, return; } - _mongoc_crypto_cng_hmac_or_hash ( - _sha1_hmac_algo, key, key_len, (void *) data, data_len, hmac_out); + _mongoc_crypto_cng_hmac_or_hash (_sha1_hmac_algo, key, key_len, (void *) data, data_len, hmac_out); } bool @@ -193,8 +168,7 @@ mongoc_crypto_cng_sha1 (mongoc_crypto_t *crypto, return false; } - res = _mongoc_crypto_cng_hmac_or_hash ( - _sha1_hash_algo, NULL, 0, (void *) input, input_len, hash_out); + res = _mongoc_crypto_cng_hmac_or_hash (_sha1_hash_algo, NULL, 0, (void *) input, input_len, hash_out); return res; } @@ -210,8 +184,7 @@ mongoc_crypto_cng_hmac_sha256 (mongoc_crypto_t *crypto, return; } - _mongoc_crypto_cng_hmac_or_hash ( - _sha256_hmac_algo, key, key_len, (void *) data, data_len, hmac_out); + _mongoc_crypto_cng_hmac_or_hash (_sha256_hmac_algo, key, key_len, (void *) data, data_len, hmac_out); } bool @@ -226,8 +199,7 @@ mongoc_crypto_cng_sha256 (mongoc_crypto_t *crypto, return false; } - res = _mongoc_crypto_cng_hmac_or_hash ( - _sha256_hash_algo, NULL, 0, (void *) input, input_len, hash_out); + res = _mongoc_crypto_cng_hmac_or_hash (_sha256_hash_algo, NULL, 0, (void *) input, input_len, hash_out); return res; } #endif diff --git a/src/libmongoc/src/mongoc/mongoc-crypto-common-crypto.c b/src/libmongoc/src/mongoc/mongoc-crypto-common-crypto.c index 141a7afa16..48d603477b 100644 --- a/src/libmongoc/src/mongoc/mongoc-crypto-common-crypto.c +++ b/src/libmongoc/src/mongoc/mongoc-crypto-common-crypto.c @@ -31,8 +31,7 @@ mongoc_crypto_common_crypto_hmac_sha1 (mongoc_crypto_t *crypto, unsigned char *hmac_out) { /* U1 = HMAC(input, salt + 0001) */ - CCHmac ( - kCCHmacAlgSHA1, key, (size_t) key_len, data, (size_t) data_len, hmac_out); + CCHmac (kCCHmacAlgSHA1, key, (size_t) key_len, data, (size_t) data_len, hmac_out); } bool @@ -55,12 +54,7 @@ mongoc_crypto_common_crypto_hmac_sha256 (mongoc_crypto_t *crypto, int data_len, unsigned char *hmac_out) { - CCHmac (kCCHmacAlgSHA256, - key, - (size_t) key_len, - data, - (size_t) data_len, - hmac_out); + CCHmac (kCCHmacAlgSHA256, key, (size_t) key_len, data, (size_t) data_len, hmac_out); } bool diff --git a/src/libmongoc/src/mongoc/mongoc-crypto-openssl.c b/src/libmongoc/src/mongoc/mongoc-crypto-openssl.c index 6cc7c91a6e..34b9ac088d 100644 --- a/src/libmongoc/src/mongoc/mongoc-crypto-openssl.c +++ b/src/libmongoc/src/mongoc/mongoc-crypto-openssl.c @@ -40,8 +40,7 @@ mongoc_crypto_openssl_hmac_sha1 (mongoc_crypto_t *crypto, HMAC (EVP_sha1 (), key, key_len, data, data_len, hmac_out, NULL); } -#if OPENSSL_VERSION_NUMBER < 0x10100000L || \ - (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x20700000L) +#if OPENSSL_VERSION_NUMBER < 0x10100000L || (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x20700000L) static EVP_MD_CTX * EVP_MD_CTX_new (void) { diff --git a/src/libmongoc/src/mongoc/mongoc-crypto-private.h b/src/libmongoc/src/mongoc/mongoc-crypto-private.h index 0a4136022f..e29ca08a27 100644 --- a/src/libmongoc/src/mongoc/mongoc-crypto-private.h +++ b/src/libmongoc/src/mongoc/mongoc-crypto-private.h @@ -28,10 +28,7 @@ BSON_BEGIN_DECLS typedef struct _mongoc_crypto_t mongoc_crypto_t; -typedef enum { - MONGOC_CRYPTO_ALGORITHM_SHA_1, - MONGOC_CRYPTO_ALGORITHM_SHA_256 -} mongoc_crypto_hash_algorithm_t; +typedef enum { MONGOC_CRYPTO_ALGORITHM_SHA_1, MONGOC_CRYPTO_ALGORITHM_SHA_256 } mongoc_crypto_hash_algorithm_t; struct _mongoc_crypto_t { void (*hmac) (mongoc_crypto_t *crypto, @@ -40,16 +37,12 @@ struct _mongoc_crypto_t { const unsigned char *data, int data_len, unsigned char *hmac_out); - bool (*hash) (mongoc_crypto_t *crypto, - const unsigned char *input, - const size_t input_len, - unsigned char *hash_out); + bool (*hash) (mongoc_crypto_t *crypto, const unsigned char *input, const size_t input_len, unsigned char *hash_out); mongoc_crypto_hash_algorithm_t algorithm; }; void -mongoc_crypto_init (mongoc_crypto_t *crypto, - mongoc_crypto_hash_algorithm_t algo); +mongoc_crypto_init (mongoc_crypto_t *crypto, mongoc_crypto_hash_algorithm_t algo); void mongoc_crypto_hmac (mongoc_crypto_t *crypto, diff --git a/src/libmongoc/src/mongoc/mongoc-crypto.c b/src/libmongoc/src/mongoc/mongoc-crypto.c index 79c693efbd..df20a36255 100644 --- a/src/libmongoc/src/mongoc/mongoc-crypto.c +++ b/src/libmongoc/src/mongoc/mongoc-crypto.c @@ -29,8 +29,7 @@ #endif void -mongoc_crypto_init (mongoc_crypto_t *crypto, - mongoc_crypto_hash_algorithm_t algo) +mongoc_crypto_init (mongoc_crypto_t *crypto, mongoc_crypto_hash_algorithm_t algo) { crypto->hmac = NULL; crypto->hash = NULL; @@ -74,10 +73,7 @@ mongoc_crypto_hmac (mongoc_crypto_t *crypto, } bool -mongoc_crypto_hash (mongoc_crypto_t *crypto, - const unsigned char *input, - const size_t input_len, - unsigned char *output) +mongoc_crypto_hash (mongoc_crypto_t *crypto, const unsigned char *input, const size_t input_len, unsigned char *output) { return crypto->hash (crypto, input, input_len, output); } diff --git a/src/libmongoc/src/mongoc/mongoc-cursor-array.c b/src/libmongoc/src/mongoc/mongoc-cursor-array.c index ee7b2b5cf2..79c4f3dcc2 100644 --- a/src/libmongoc/src/mongoc/mongoc-cursor-array.c +++ b/src/libmongoc/src/mongoc/mongoc-cursor-array.c @@ -35,10 +35,8 @@ _prime (mongoc_cursor_t *cursor) bson_destroy (&data->array); /* this cursor is only used with the listDatabases command. it iterates * over the array in the response's "databases" field. */ - if (_mongoc_cursor_run_command ( - cursor, &data->cmd, &cursor->opts, &data->array, false) && - bson_iter_init_find (&iter, &data->array, data->field_name) && - BSON_ITER_HOLDS_ARRAY (&iter) && + if (_mongoc_cursor_run_command (cursor, &data->cmd, &cursor->opts, &data->array, false) && + bson_iter_init_find (&iter, &data->array, data->field_name) && BSON_ITER_HOLDS_ARRAY (&iter) && bson_iter_recurse (&iter, &data->iter)) { return IN_BATCH; } @@ -86,16 +84,12 @@ _destroy (mongoc_cursor_impl_t *impl) mongoc_cursor_t * -_mongoc_cursor_array_new (mongoc_client_t *client, - const char *db_and_coll, - const bson_t *cmd, - const bson_t *opts, - const char *field_name) +_mongoc_cursor_array_new ( + mongoc_client_t *client, const char *db_and_coll, const bson_t *cmd, const bson_t *opts, const char *field_name) { BSON_ASSERT_PARAM (client); - mongoc_cursor_t *cursor = _mongoc_cursor_new_with_opts ( - client, db_and_coll, opts, NULL, NULL, NULL); + mongoc_cursor_t *cursor = _mongoc_cursor_new_with_opts (client, db_and_coll, opts, NULL, NULL, NULL); data_array_t *data = BSON_ALIGNED_ALLOC0 (data_array_t); bson_copy_to (cmd, &data->cmd); bson_init (&data->array); diff --git a/src/libmongoc/src/mongoc/mongoc-cursor-change-stream.c b/src/libmongoc/src/mongoc/mongoc-cursor-change-stream.c index 451b42baa2..e22c0243d4 100644 --- a/src/libmongoc/src/mongoc/mongoc-cursor-change-stream.c +++ b/src/libmongoc/src/mongoc/mongoc-cursor-change-stream.c @@ -34,9 +34,7 @@ _update_post_batch_resume_token (mongoc_cursor_t *cursor) } if (bson_iter_init (&iter, &data->response.reply) && - bson_iter_find_descendant ( - &iter, "cursor.postBatchResumeToken", &child) && - BSON_ITER_HOLDS_DOCUMENT (&child)) { + bson_iter_find_descendant (&iter, "cursor.postBatchResumeToken", &child) && BSON_ITER_HOLDS_DOCUMENT (&child)) { uint32_t len; const uint8_t *buf; bson_t post_batch_resume_token; @@ -81,8 +79,7 @@ _get_next_batch (mongoc_cursor_t *cursor) bson_t getmore_cmd; _mongoc_cursor_prepare_getmore_command (cursor, &getmore_cmd); - _mongoc_cursor_response_refresh ( - cursor, &getmore_cmd, NULL /* opts */, &data->response); + _mongoc_cursor_response_refresh (cursor, &getmore_cmd, NULL /* opts */, &data->response); bson_destroy (&getmore_cmd); _update_post_batch_resume_token (cursor); @@ -113,9 +110,7 @@ _clone (mongoc_cursor_impl_t *dst, const mongoc_cursor_impl_t *src) mongoc_cursor_t * -_mongoc_cursor_change_stream_new (mongoc_client_t *client, - bson_t *reply, - const bson_t *getmore_opts) +_mongoc_cursor_change_stream_new (mongoc_client_t *client, bson_t *reply, const bson_t *getmore_opts) { mongoc_cursor_t *cursor; _data_change_stream_t *data; @@ -129,8 +124,7 @@ _mongoc_cursor_change_stream_new (mongoc_client_t *client, BSON_ASSERT (bson_steal (&data->response.reply, reply)); bson_init (&data->post_batch_resume_token); - cursor = _mongoc_cursor_new_with_opts ( - client, NULL, getmore_opts, NULL, NULL, NULL); + cursor = _mongoc_cursor_new_with_opts (client, NULL, getmore_opts, NULL, NULL, NULL); cursor->impl.prime = _prime; cursor->impl.pop_from_batch = _pop_from_batch; cursor->impl.get_next_batch = _get_next_batch; @@ -140,10 +134,8 @@ _mongoc_cursor_change_stream_new (mongoc_client_t *client, cursor->state = IN_BATCH; if (!_mongoc_cursor_start_reading_response (cursor, &data->response)) { - bson_set_error (&cursor->error, - MONGOC_ERROR_CURSOR, - MONGOC_ERROR_CURSOR_INVALID_CURSOR, - "Couldn't parse cursor document"); + bson_set_error ( + &cursor->error, MONGOC_ERROR_CURSOR, MONGOC_ERROR_CURSOR_INVALID_CURSOR, "Couldn't parse cursor document"); } _update_post_batch_resume_token (cursor); @@ -173,8 +165,7 @@ _mongoc_cursor_change_stream_end_of_batch (mongoc_cursor_t *cursor) const bson_t * -_mongoc_cursor_change_stream_get_post_batch_resume_token ( - mongoc_cursor_t *cursor) +_mongoc_cursor_change_stream_get_post_batch_resume_token (mongoc_cursor_t *cursor) { _data_change_stream_t *data = (_data_change_stream_t *) cursor->impl.data; @@ -183,8 +174,7 @@ _mongoc_cursor_change_stream_get_post_batch_resume_token ( bool -_mongoc_cursor_change_stream_has_post_batch_resume_token ( - mongoc_cursor_t *cursor) +_mongoc_cursor_change_stream_has_post_batch_resume_token (mongoc_cursor_t *cursor) { _data_change_stream_t *data = (_data_change_stream_t *) cursor->impl.data; diff --git a/src/libmongoc/src/mongoc/mongoc-cursor-cmd-deprecated.c b/src/libmongoc/src/mongoc/mongoc-cursor-cmd-deprecated.c index 1edf52668e..fa2026a9f1 100644 --- a/src/libmongoc/src/mongoc/mongoc-cursor-cmd-deprecated.c +++ b/src/libmongoc/src/mongoc/mongoc-cursor-cmd-deprecated.c @@ -31,8 +31,7 @@ _prime (mongoc_cursor_t *cursor) { data_cmd_deprecated_t *data = (data_cmd_deprecated_t *) cursor->impl.data; bson_destroy (&data->reply); - if (_mongoc_cursor_run_command ( - cursor, &data->cmd, &cursor->opts, &data->reply, true)) { + if (_mongoc_cursor_run_command (cursor, &data->cmd, &cursor->opts, &data->reply, true)) { return IN_BATCH; } else { return DONE; @@ -63,8 +62,7 @@ static void _clone (mongoc_cursor_impl_t *dst, const mongoc_cursor_impl_t *src) { data_cmd_deprecated_t *data_src = (data_cmd_deprecated_t *) src->data; - data_cmd_deprecated_t *data_dst = - BSON_ALIGNED_ALLOC0 (data_cmd_deprecated_t); + data_cmd_deprecated_t *data_dst = BSON_ALIGNED_ALLOC0 (data_cmd_deprecated_t); bson_init (&data_dst->reply); bson_copy_to (&data_src->cmd, &data_dst->cmd); dst->data = data_dst; @@ -89,13 +87,8 @@ _mongoc_cursor_cmd_deprecated_new (mongoc_client_t *client, { BSON_ASSERT_PARAM (client); - mongoc_cursor_t *cursor = - _mongoc_cursor_new_with_opts (client, - db_and_coll, - NULL, - read_prefs /* user prefs */, - NULL /* default prefs */, - NULL); + mongoc_cursor_t *cursor = _mongoc_cursor_new_with_opts ( + client, db_and_coll, NULL, read_prefs /* user prefs */, NULL /* default prefs */, NULL); data_cmd_deprecated_t *data = BSON_ALIGNED_ALLOC0 (data_cmd_deprecated_t); _mongoc_cursor_check_and_copy_to (cursor, "command", cmd, &data->cmd); bson_init (&data->reply); diff --git a/src/libmongoc/src/mongoc/mongoc-cursor-cmd.c b/src/libmongoc/src/mongoc/mongoc-cursor-cmd.c index a333ed7f11..79c0157a76 100644 --- a/src/libmongoc/src/mongoc/mongoc-cursor-cmd.c +++ b/src/libmongoc/src/mongoc/mongoc-cursor-cmd.c @@ -70,13 +70,11 @@ _prime (mongoc_cursor_t *cursor) cursor->operation_id = ++cursor->client->cluster.operation_id; /* commands like agg have a cursor field, so copy opts without "batchSize" */ - bson_copy_to_excluding_noinit ( - &cursor->opts, &copied_opts, "batchSize", "tailable", NULL); + bson_copy_to_excluding_noinit (&cursor->opts, &copied_opts, "batchSize", "tailable", NULL); /* server replies to aggregate/listIndexes/listCollections with: * {cursor: {id: N, firstBatch: []}} */ - _mongoc_cursor_response_refresh ( - cursor, &data->cmd, &copied_opts, &data->response); + _mongoc_cursor_response_refresh (cursor, &data->cmd, &copied_opts, &data->response); data->reading_from = CMD_RESPONSE; bson_destroy (&copied_opts); return IN_BATCH; @@ -118,8 +116,7 @@ _get_next_batch (mongoc_cursor_t *cursor) switch (getmore_type) { case GETMORE_CMD: _mongoc_cursor_prepare_getmore_command (cursor, &getmore_cmd); - _mongoc_cursor_response_refresh ( - cursor, &getmore_cmd, NULL /* opts */, &data->response); + _mongoc_cursor_response_refresh (cursor, &getmore_cmd, NULL /* opts */, &data->response); bson_destroy (&getmore_cmd); data->reading_from = CMD_RESPONSE; return IN_BATCH; @@ -171,8 +168,7 @@ _mongoc_cursor_cmd_new (mongoc_client_t *client, mongoc_cursor_t *cursor; data_cmd_t *data = BSON_ALIGNED_ALLOC0 (data_cmd_t); - cursor = _mongoc_cursor_new_with_opts ( - client, db_and_coll, opts, user_prefs, default_prefs, read_concern); + cursor = _mongoc_cursor_new_with_opts (client, db_and_coll, opts, user_prefs, default_prefs, read_concern); _mongoc_cursor_response_legacy_init (&data->response_legacy); _mongoc_cursor_check_and_copy_to (cursor, "command", cmd, &data->cmd); bson_init (&data->response.reply); @@ -187,15 +183,11 @@ _mongoc_cursor_cmd_new (mongoc_client_t *client, mongoc_cursor_t * -_mongoc_cursor_cmd_new_from_reply (mongoc_client_t *client, - const bson_t *cmd, - const bson_t *opts, - bson_t *reply) +_mongoc_cursor_cmd_new_from_reply (mongoc_client_t *client, const bson_t *cmd, const bson_t *opts, bson_t *reply) { BSON_ASSERT_PARAM (client); - mongoc_cursor_t *cursor = - _mongoc_cursor_cmd_new (client, NULL, cmd, opts, NULL, NULL, NULL); + mongoc_cursor_t *cursor = _mongoc_cursor_cmd_new (client, NULL, cmd, opts, NULL, NULL, NULL); data_cmd_t *data = (data_cmd_t *) cursor->impl.data; data->reading_from = CMD_RESPONSE; @@ -208,10 +200,8 @@ _mongoc_cursor_cmd_new_from_reply (mongoc_client_t *client, } if (!_mongoc_cursor_start_reading_response (cursor, &data->response)) { - bson_set_error (&cursor->error, - MONGOC_ERROR_CURSOR, - MONGOC_ERROR_CURSOR_INVALID_CURSOR, - "Couldn't parse cursor document"); + bson_set_error ( + &cursor->error, MONGOC_ERROR_CURSOR, MONGOC_ERROR_CURSOR_INVALID_CURSOR, "Couldn't parse cursor document"); } if (0 != cursor->cursor_id && 0 == cursor->server_id) { @@ -220,15 +210,14 @@ _mongoc_cursor_cmd_new_from_reply (mongoc_client_t *client, // identifies the server with the cursor. // The server with the cursor is required to send a "getMore" or // "killCursors" command. - bson_set_error ( - &cursor->error, - MONGOC_ERROR_CURSOR, - MONGOC_ERROR_CURSOR_INVALID_CURSOR, - "Expected `serverId` option to identify server with open cursor " - "(cursor ID is %" PRId64 "). " - "Consider using `mongoc_client_select_server` and using the " - "resulting server ID to create the cursor.", - cursor->cursor_id); + bson_set_error (&cursor->error, + MONGOC_ERROR_CURSOR, + MONGOC_ERROR_CURSOR_INVALID_CURSOR, + "Expected `serverId` option to identify server with open cursor " + "(cursor ID is %" PRId64 "). " + "Consider using `mongoc_client_select_server` and using the " + "resulting server ID to create the cursor.", + cursor->cursor_id); // Reset cursor_id to 0 to avoid an assertion error in // `mongoc_cursor_destroy` when attempting to send "killCursors". cursor->cursor_id = 0; diff --git a/src/libmongoc/src/mongoc/mongoc-cursor-find-cmd.c b/src/libmongoc/src/mongoc/mongoc-cursor-find-cmd.c index 7a245e0e39..3f3a1d4bac 100644 --- a/src/libmongoc/src/mongoc/mongoc-cursor-find-cmd.c +++ b/src/libmongoc/src/mongoc/mongoc-cursor-find-cmd.c @@ -33,8 +33,7 @@ _prime (mongoc_cursor_t *cursor) cursor->operation_id = ++cursor->client->cluster.operation_id; /* construct { find: "", filter: {} } */ _mongoc_cursor_prepare_find_command (cursor, &data->filter, &find_cmd); - _mongoc_cursor_response_refresh ( - cursor, &find_cmd, &cursor->opts, &data->response); + _mongoc_cursor_response_refresh (cursor, &find_cmd, &cursor->opts, &data->response); bson_destroy (&find_cmd); return IN_BATCH; } @@ -63,8 +62,7 @@ _get_next_batch (mongoc_cursor_t *cursor) return DONE; } _mongoc_cursor_prepare_getmore_command (cursor, &getmore_cmd); - _mongoc_cursor_response_refresh ( - cursor, &getmore_cmd, NULL /* opts */, &data->response); + _mongoc_cursor_response_refresh (cursor, &getmore_cmd, NULL /* opts */, &data->response); bson_destroy (&getmore_cmd); return IN_BATCH; } diff --git a/src/libmongoc/src/mongoc/mongoc-cursor-find.c b/src/libmongoc/src/mongoc/mongoc-cursor-find.c index e77d74b955..2371c1bdd1 100644 --- a/src/libmongoc/src/mongoc/mongoc-cursor-find.c +++ b/src/libmongoc/src/mongoc/mongoc-cursor-find.c @@ -49,8 +49,7 @@ _prime (mongoc_cursor_t *cursor) if (_mongoc_cursor_use_op_msg (cursor, wire_version)) { _mongoc_cursor_impl_find_cmd_init (cursor, &data->filter /* stolen */); } else { - _mongoc_cursor_impl_find_opquery_init (cursor, - &data->filter /* stolen */); + _mongoc_cursor_impl_find_opquery_init (cursor, &data->filter /* stolen */); } /* destroy this impl data since impl functions have been replaced. */ bson_free (data); @@ -91,8 +90,7 @@ _mongoc_cursor_find_new (mongoc_client_t *client, mongoc_cursor_t *cursor; data_find_t *data = BSON_ALIGNED_ALLOC0 (data_find_t); - cursor = _mongoc_cursor_new_with_opts ( - client, db_and_coll, opts, user_prefs, default_prefs, read_concern); + cursor = _mongoc_cursor_new_with_opts (client, db_and_coll, opts, user_prefs, default_prefs, read_concern); _mongoc_cursor_check_and_copy_to (cursor, "filter", filter, &data->filter); cursor->impl.prime = _prime; cursor->impl.clone = _clone; diff --git a/src/libmongoc/src/mongoc/mongoc-cursor-legacy.c b/src/libmongoc/src/mongoc/mongoc-cursor-legacy.c index 90be02df96..f5e29f32e5 100644 --- a/src/libmongoc/src/mongoc/mongoc-cursor-legacy.c +++ b/src/libmongoc/src/mongoc/mongoc-cursor-legacy.c @@ -36,8 +36,7 @@ #include static bool -_mongoc_cursor_monitor_legacy_get_more (mongoc_cursor_t *cursor, - mongoc_server_stream_t *server_stream) +_mongoc_cursor_monitor_legacy_get_more (mongoc_cursor_t *cursor, mongoc_server_stream_t *server_stream) { bson_t doc; char *db; @@ -101,9 +100,7 @@ _mongoc_cursor_monitor_legacy_query (mongoc_cursor_t *cursor, /* simulate a MongoDB 3.2+ "find" command */ _mongoc_cursor_prepare_find_command (cursor, filter, &doc); - bsonBuildAppend ( - cursor->opts, - insert (doc, not(key ("serverId", "maxAwaitTimeMS", "sessionId")))); + bsonBuildAppend (cursor->opts, insert (doc, not(key ("serverId", "maxAwaitTimeMS", "sessionId")))); r = _mongoc_cursor_monitor_command (cursor, server_stream, &doc, "find"); @@ -125,9 +122,7 @@ _mongoc_cursor_op_getmore_send (mongoc_cursor_t *cursor, BSON_ASSERT_PARAM (server_stream); BSON_ASSERT_PARAM (rpc); - const int32_t n_return = (flags & MONGOC_OP_QUERY_FLAG_TAILABLE_CURSOR) != 0 - ? 0 - : _mongoc_n_return (cursor); + const int32_t n_return = (flags & MONGOC_OP_QUERY_FLAG_TAILABLE_CURSOR) != 0 ? 0 : _mongoc_n_return (cursor); { int32_t message_length = 0; @@ -135,16 +130,12 @@ _mongoc_cursor_op_getmore_send (mongoc_cursor_t *cursor, message_length += mcd_rpc_header_set_message_length (rpc, 0); message_length += mcd_rpc_header_set_request_id (rpc, request_id); message_length += mcd_rpc_header_set_response_to (rpc, 0); - message_length += - mcd_rpc_header_set_op_code (rpc, MONGOC_OP_CODE_GET_MORE); + message_length += mcd_rpc_header_set_op_code (rpc, MONGOC_OP_CODE_GET_MORE); message_length += sizeof (int32_t); // ZERO - message_length += - mcd_rpc_op_get_more_set_full_collection_name (rpc, cursor->ns); - message_length += - mcd_rpc_op_get_more_set_number_to_return (rpc, n_return); - message_length += - mcd_rpc_op_get_more_set_cursor_id (rpc, cursor->cursor_id); + message_length += mcd_rpc_op_get_more_set_full_collection_name (rpc, cursor->ns); + message_length += mcd_rpc_op_get_more_set_number_to_return (rpc, n_return); + message_length += mcd_rpc_op_get_more_set_cursor_id (rpc, cursor->cursor_id); mcd_rpc_message_set_length (rpc, message_length); } @@ -153,8 +144,7 @@ _mongoc_cursor_op_getmore_send (mongoc_cursor_t *cursor, return false; } - if (!mongoc_cluster_legacy_rpc_sendv_to_server ( - &cursor->client->cluster, rpc, server_stream, &cursor->error)) { + if (!mongoc_cluster_legacy_rpc_sendv_to_server (&cursor->client->cluster, rpc, server_stream, &cursor->error)) { return false; } @@ -162,8 +152,7 @@ _mongoc_cursor_op_getmore_send (mongoc_cursor_t *cursor, } void -_mongoc_cursor_op_getmore (mongoc_cursor_t *cursor, - mongoc_cursor_response_legacy_t *response) +_mongoc_cursor_op_getmore (mongoc_cursor_t *cursor, mongoc_cursor_response_legacy_t *response) { BSON_ASSERT_PARAM (cursor); BSON_ASSERT_PARAM (response); @@ -172,8 +161,7 @@ _mongoc_cursor_op_getmore (mongoc_cursor_t *cursor, const int64_t started = bson_get_monotonic_time (); - mongoc_server_stream_t *const server_stream = - _mongoc_cursor_fetch_stream (cursor); + mongoc_server_stream_t *const server_stream = _mongoc_cursor_fetch_stream (cursor); if (!server_stream) { GOTO (done); @@ -185,13 +173,11 @@ _mongoc_cursor_op_getmore (mongoc_cursor_t *cursor, } mongoc_cluster_t *const cluster = &cursor->client->cluster; - const int32_t request_id = cursor->in_exhaust - ? mcd_rpc_header_get_request_id (response->rpc) - : ++cluster->request_id; + const int32_t request_id = + cursor->in_exhaust ? mcd_rpc_header_get_request_id (response->rpc) : ++cluster->request_id; if (!cursor->in_exhaust && - !_mongoc_cursor_op_getmore_send ( - cursor, server_stream, request_id, flags, response->rpc)) { + !_mongoc_cursor_op_getmore_send (cursor, server_stream, request_id, flags, response->rpc)) { GOTO (fail); } @@ -199,11 +185,7 @@ _mongoc_cursor_op_getmore (mongoc_cursor_t *cursor, _mongoc_buffer_clear (&response->buffer, false); cursor->cursor_id = 0; - if (!_mongoc_client_recv (cursor->client, - response->rpc, - &response->buffer, - server_stream, - &cursor->error)) { + if (!_mongoc_client_recv (cursor->client, response->rpc, &response->buffer, server_stream, &cursor->error)) { GOTO (fail); } @@ -212,8 +194,7 @@ _mongoc_cursor_op_getmore (mongoc_cursor_t *cursor, bson_set_error (&cursor->error, MONGOC_ERROR_PROTOCOL, MONGOC_ERROR_PROTOCOL_INVALID_REPLY, - "invalid opcode for OP_GET_MORE: expected %" PRId32 - ", got %" PRId32, + "invalid opcode for OP_GET_MORE: expected %" PRId32 ", got %" PRId32, MONGOC_OP_CODE_REPLY, op_code); GOTO (fail); @@ -224,17 +205,14 @@ _mongoc_cursor_op_getmore (mongoc_cursor_t *cursor, bson_set_error (&cursor->error, MONGOC_ERROR_PROTOCOL, MONGOC_ERROR_PROTOCOL_INVALID_REPLY, - "invalid response_to for OP_GET_MORE: expected %" PRId32 - ", got %" PRId32, + "invalid response_to for OP_GET_MORE: expected %" PRId32 ", got %" PRId32, request_id, response_to); GOTO (fail); } - if (!mcd_rpc_message_check_ok (response->rpc, - cursor->client->error_api_version, - &cursor->error, - &cursor->error_doc)) { + if (!mcd_rpc_message_check_ok ( + response->rpc, cursor->client->error_api_version, &cursor->error, &cursor->error_doc)) { GOTO (fail); } @@ -244,9 +222,8 @@ _mongoc_cursor_op_getmore (mongoc_cursor_t *cursor, cursor->cursor_id = mcd_rpc_op_reply_get_cursor_id (response->rpc); - response->reader = bson_reader_new_from_data ( - mcd_rpc_op_reply_get_documents (response->rpc), - mcd_rpc_op_reply_get_documents_len (response->rpc)); + response->reader = bson_reader_new_from_data (mcd_rpc_op_reply_get_documents (response->rpc), + mcd_rpc_op_reply_get_documents_len (response->rpc)); _mongoc_cursor_monitor_succeeded (cursor, response, @@ -258,8 +235,7 @@ _mongoc_cursor_op_getmore (mongoc_cursor_t *cursor, GOTO (done); fail: - _mongoc_cursor_monitor_failed ( - cursor, bson_get_monotonic_time () - started, server_stream, "getMore"); + _mongoc_cursor_monitor_failed (cursor, bson_get_monotonic_time () - started, server_stream, "getMore"); done: mongoc_server_stream_cleanup (server_stream); @@ -293,21 +269,17 @@ _mongoc_cursor_op_getmore (mongoc_cursor_t *cursor, } while (false) -#define OPT_ERR(_msg) \ - do { \ - bson_set_error (&cursor->error, \ - MONGOC_ERROR_COMMAND, \ - MONGOC_ERROR_COMMAND_INVALID_ARG, \ - _msg); \ - return NULL; \ +#define OPT_ERR(_msg) \ + do { \ + bson_set_error (&cursor->error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, _msg); \ + return NULL; \ } while (false) -#define OPT_BSON_ERR(_msg) \ - do { \ - bson_set_error ( \ - &cursor->error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, _msg); \ - return NULL; \ +#define OPT_BSON_ERR(_msg) \ + do { \ + bson_set_error (&cursor->error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, _msg); \ + return NULL; \ } while (false) @@ -448,14 +420,10 @@ _mongoc_cursor_parse_opts_for_op_query (mongoc_cursor_t *cursor, * maxAwaitTimeMS is handled in _mongoc_cursor_prepare_getmore_command * sessionId is used to retrieve the mongoc_client_session_t */ - else if (strcmp (key, MONGOC_CURSOR_SINGLE_BATCH) && - strcmp (key, MONGOC_CURSOR_LIMIT) && - strcmp (key, MONGOC_CURSOR_BATCH_SIZE) && - strcmp (key, MONGOC_CURSOR_EXHAUST) && - strcmp (key, MONGOC_CURSOR_NO_CURSOR_TIMEOUT) && - strcmp (key, MONGOC_CURSOR_OPLOG_REPLAY) && - strcmp (key, MONGOC_CURSOR_TAILABLE) && - strcmp (key, MONGOC_CURSOR_MAX_AWAIT_TIME_MS)) { + else if (strcmp (key, MONGOC_CURSOR_SINGLE_BATCH) && strcmp (key, MONGOC_CURSOR_LIMIT) && + strcmp (key, MONGOC_CURSOR_BATCH_SIZE) && strcmp (key, MONGOC_CURSOR_EXHAUST) && + strcmp (key, MONGOC_CURSOR_NO_CURSOR_TIMEOUT) && strcmp (key, MONGOC_CURSOR_OPLOG_REPLAY) && + strcmp (key, MONGOC_CURSOR_TAILABLE) && strcmp (key, MONGOC_CURSOR_MAX_AWAIT_TIME_MS)) { /* pass unrecognized options to server, prefixed with $ */ PUSH_DOLLAR_QUERY (); dollar_modifier = bson_strdup_printf ("$%s", key); @@ -503,15 +471,14 @@ _mongoc_cursor_op_query_find_send (mongoc_cursor_t *cursor, bson_t fields = BSON_INITIALIZER; int32_t skip; int32_t flags; - const bson_t *const query_ptr = _mongoc_cursor_parse_opts_for_op_query ( - cursor, server_stream, filter, &query, &fields, &flags, &skip); + const bson_t *const query_ptr = + _mongoc_cursor_parse_opts_for_op_query (cursor, server_stream, filter, &query, &fields, &flags, &skip); if (!query_ptr) { GOTO (done); } - assemble_query ( - cursor->read_prefs, server_stream, query_ptr, flags, &result); + assemble_query (cursor->read_prefs, server_stream, query_ptr, flags, &result); { int32_t message_length = 0; @@ -522,17 +489,13 @@ _mongoc_cursor_op_query_find_send (mongoc_cursor_t *cursor, message_length += mcd_rpc_header_set_op_code (rpc, MONGOC_OP_CODE_QUERY); message_length += mcd_rpc_op_query_set_flags (rpc, result.flags); - message_length += - mcd_rpc_op_query_set_full_collection_name (rpc, cursor->ns); + message_length += mcd_rpc_op_query_set_full_collection_name (rpc, cursor->ns); message_length += mcd_rpc_op_query_set_number_to_skip (rpc, skip); - message_length += - mcd_rpc_op_query_set_number_to_return (rpc, _mongoc_n_return (cursor)); - message_length += mcd_rpc_op_query_set_query ( - rpc, bson_get_data (result.assembled_query)); + message_length += mcd_rpc_op_query_set_number_to_return (rpc, _mongoc_n_return (cursor)); + message_length += mcd_rpc_op_query_set_query (rpc, bson_get_data (result.assembled_query)); if (!bson_empty (&fields)) { - message_length += mcd_rpc_op_query_set_return_fields_selector ( - rpc, bson_get_data (&fields)); + message_length += mcd_rpc_op_query_set_return_fields_selector (rpc, bson_get_data (&fields)); } mcd_rpc_message_set_length (rpc, message_length); @@ -542,8 +505,7 @@ _mongoc_cursor_op_query_find_send (mongoc_cursor_t *cursor, GOTO (done); } - if (!mongoc_cluster_legacy_rpc_sendv_to_server ( - &cursor->client->cluster, rpc, server_stream, &cursor->error)) { + if (!mongoc_cluster_legacy_rpc_sendv_to_server (&cursor->client->cluster, rpc, server_stream, &cursor->error)) { GOTO (done); } @@ -558,9 +520,7 @@ _mongoc_cursor_op_query_find_send (mongoc_cursor_t *cursor, } bool -_mongoc_cursor_op_query_find (mongoc_cursor_t *cursor, - bson_t *filter, - mongoc_cursor_response_legacy_t *response) +_mongoc_cursor_op_query_find (mongoc_cursor_t *cursor, bson_t *filter, mongoc_cursor_response_legacy_t *response) { BSON_ASSERT_PARAM (cursor); BSON_ASSERT_PARAM (filter); @@ -570,8 +530,7 @@ _mongoc_cursor_op_query_find (mongoc_cursor_t *cursor, bool ret = false; - mongoc_server_stream_t *const server_stream = - _mongoc_cursor_fetch_stream (cursor); + mongoc_server_stream_t *const server_stream = _mongoc_cursor_fetch_stream (cursor); if (!server_stream) { RETURN (false); @@ -581,19 +540,14 @@ _mongoc_cursor_op_query_find (mongoc_cursor_t *cursor, const int32_t request_id = ++cursor->client->cluster.request_id; mcd_rpc_message *const rpc = mcd_rpc_message_new (); - if (!_mongoc_cursor_op_query_find_send ( - cursor, server_stream, request_id, filter, rpc)) { + if (!_mongoc_cursor_op_query_find_send (cursor, server_stream, request_id, filter, rpc)) { GOTO (done); } mcd_rpc_message_reset (rpc); _mongoc_buffer_clear (&response->buffer, false); - if (!_mongoc_client_recv (cursor->client, - response->rpc, - &response->buffer, - server_stream, - &cursor->error)) { + if (!_mongoc_client_recv (cursor->client, response->rpc, &response->buffer, server_stream, &cursor->error)) { GOTO (done); } @@ -602,8 +556,7 @@ _mongoc_cursor_op_query_find (mongoc_cursor_t *cursor, bson_set_error (&cursor->error, MONGOC_ERROR_PROTOCOL, MONGOC_ERROR_PROTOCOL_INVALID_REPLY, - "invalid opcode for OP_QUERY: expected %" PRId32 - ", got %" PRId32, + "invalid opcode for OP_QUERY: expected %" PRId32 ", got %" PRId32, MONGOC_OP_CODE_REPLY, op_code); GOTO (done); @@ -614,17 +567,14 @@ _mongoc_cursor_op_query_find (mongoc_cursor_t *cursor, bson_set_error (&cursor->error, MONGOC_ERROR_PROTOCOL, MONGOC_ERROR_PROTOCOL_INVALID_REPLY, - "invalid response_to for OP_QUERY: expected %" PRId32 - ", got %" PRId32, + "invalid response_to for OP_QUERY: expected %" PRId32 ", got %" PRId32, request_id, response_to); GOTO (done); } - if (!mcd_rpc_message_check_ok (response->rpc, - cursor->client->error_api_version, - &cursor->error, - &cursor->error_doc)) { + if (!mcd_rpc_message_check_ok ( + response->rpc, cursor->client->error_api_version, &cursor->error, &cursor->error_doc)) { GOTO (done); } @@ -634,9 +584,8 @@ _mongoc_cursor_op_query_find (mongoc_cursor_t *cursor, cursor->cursor_id = mcd_rpc_op_reply_get_cursor_id (response->rpc); - response->reader = bson_reader_new_from_data ( - mcd_rpc_op_reply_get_documents (response->rpc), - mcd_rpc_op_reply_get_documents_len (response->rpc)); + response->reader = bson_reader_new_from_data (mcd_rpc_op_reply_get_documents (response->rpc), + mcd_rpc_op_reply_get_documents_len (response->rpc)); if (_mongoc_cursor_get_opt_bool (cursor, MONGOC_CURSOR_EXHAUST)) { cursor->in_exhaust = true; @@ -654,8 +603,7 @@ _mongoc_cursor_op_query_find (mongoc_cursor_t *cursor, done: if (!ret) { - _mongoc_cursor_monitor_failed ( - cursor, bson_get_monotonic_time () - started, server_stream, "find"); + _mongoc_cursor_monitor_failed (cursor, bson_get_monotonic_time () - started, server_stream, "find"); } mcd_rpc_message_destroy (rpc); @@ -674,8 +622,7 @@ _mongoc_cursor_response_legacy_init (mongoc_cursor_response_legacy_t *response) void -_mongoc_cursor_response_legacy_destroy ( - mongoc_cursor_response_legacy_t *response) +_mongoc_cursor_response_legacy_destroy (mongoc_cursor_response_legacy_t *response) { if (response->reader) { bson_reader_destroy (response->reader); diff --git a/src/libmongoc/src/mongoc/mongoc-cursor-private.h b/src/libmongoc/src/mongoc/mongoc-cursor-private.h index 98cb8e4d39..b3a7335d2a 100644 --- a/src/libmongoc/src/mongoc/mongoc-cursor-private.h +++ b/src/libmongoc/src/mongoc/mongoc-cursor-private.h @@ -91,8 +91,7 @@ BSON_BEGIN_DECLS typedef struct _mongoc_cursor_impl_t mongoc_cursor_impl_t; typedef enum { UNPRIMED, IN_BATCH, END_OF_BATCH, DONE } mongoc_cursor_state_t; -typedef mongoc_cursor_state_t (*_mongoc_cursor_impl_transition_t) ( - mongoc_cursor_t *cursor); +typedef mongoc_cursor_state_t (*_mongoc_cursor_impl_transition_t) (mongoc_cursor_t *cursor); struct _mongoc_cursor_impl_t { void (*clone) (mongoc_cursor_impl_t *dst, const mongoc_cursor_impl_t *src); void (*destroy) (mongoc_cursor_impl_t *ctx); @@ -169,33 +168,21 @@ _mongoc_set_cursor_ns (mongoc_cursor_t *cursor, const char *ns, uint32_t nslen); bool _mongoc_cursor_get_opt_bool (const mongoc_cursor_t *cursor, const char *option); void -_mongoc_cursor_flags_to_opts (mongoc_query_flags_t qflags, - bson_t *opts, - bool *secondary_ok); +_mongoc_cursor_flags_to_opts (mongoc_query_flags_t qflags, bson_t *opts, bool *secondary_ok); bool -_mongoc_cursor_translate_dollar_query_opts (const bson_t *query, - bson_t *opts, - bson_t *unwrapped, - bson_error_t *error); +_mongoc_cursor_translate_dollar_query_opts (const bson_t *query, bson_t *opts, bson_t *unwrapped, bson_error_t *error); mongoc_server_stream_t * _mongoc_cursor_fetch_stream (mongoc_cursor_t *cursor); void -_mongoc_cursor_collection (const mongoc_cursor_t *cursor, - const char **collection, - int *collection_len); +_mongoc_cursor_collection (const mongoc_cursor_t *cursor, const char **collection, int *collection_len); bool -_mongoc_cursor_run_command (mongoc_cursor_t *cursor, - const bson_t *command, - const bson_t *opts, - bson_t *reply, - bool retry_prohibited); +_mongoc_cursor_run_command ( + mongoc_cursor_t *cursor, const bson_t *command, const bson_t *opts, bson_t *reply, bool retry_prohibited); bool _mongoc_cursor_more (mongoc_cursor_t *cursor); bool -_mongoc_cursor_set_opt_int64 (mongoc_cursor_t *cursor, - const char *option, - int64_t value); +_mongoc_cursor_set_opt_int64 (mongoc_cursor_t *cursor, const char *option, int64_t value); void _mongoc_cursor_monitor_failed (mongoc_cursor_t *cursor, int64_t duration, @@ -207,17 +194,13 @@ _mongoc_cursor_monitor_command (mongoc_cursor_t *cursor, const bson_t *cmd, const char *cmd_name); void -_mongoc_cursor_prepare_find_command (mongoc_cursor_t *cursor, - const bson_t *filter, - bson_t *command); +_mongoc_cursor_prepare_find_command (mongoc_cursor_t *cursor, const bson_t *filter, bson_t *command); const bson_t * _mongoc_cursor_initial_query (mongoc_cursor_t *cursor); const bson_t * _mongoc_cursor_get_more (mongoc_cursor_t *cursor); bool -_mongoc_cursor_opts_to_flags (mongoc_cursor_t *cursor, - mongoc_server_stream_t *stream, - int32_t *flags /* OUT */); +_mongoc_cursor_opts_to_flags (mongoc_cursor_t *cursor, mongoc_server_stream_t *stream, int32_t *flags /* OUT */); bool _mongoc_cursor_use_op_msg (const mongoc_cursor_t *cursor, int32_t wire_version); void @@ -236,34 +219,24 @@ _mongoc_cursor_response_refresh (mongoc_cursor_t *cursor, const bson_t *opts, mongoc_cursor_response_t *response); bool -_mongoc_cursor_start_reading_response (mongoc_cursor_t *cursor, - mongoc_cursor_response_t *response); +_mongoc_cursor_start_reading_response (mongoc_cursor_t *cursor, mongoc_cursor_response_t *response); void -_mongoc_cursor_response_read (mongoc_cursor_t *cursor, - mongoc_cursor_response_t *response, - const bson_t **bson); +_mongoc_cursor_response_read (mongoc_cursor_t *cursor, mongoc_cursor_response_t *response, const bson_t **bson); void -_mongoc_cursor_prepare_getmore_command (mongoc_cursor_t *cursor, - bson_t *command); +_mongoc_cursor_prepare_getmore_command (mongoc_cursor_t *cursor, bson_t *command); void _mongoc_cursor_set_empty (mongoc_cursor_t *cursor); bool -_mongoc_cursor_check_and_copy_to (mongoc_cursor_t *cursor, - const char *err_prefix, - const bson_t *src, - bson_t *dst); +_mongoc_cursor_check_and_copy_to (mongoc_cursor_t *cursor, const char *err_prefix, const bson_t *src, bson_t *dst); void _mongoc_cursor_prime (mongoc_cursor_t *cursor); /* legacy functions defined in mongoc-cursor-legacy.c */ bool _mongoc_cursor_next (mongoc_cursor_t *cursor, const bson_t **bson); bool -_mongoc_cursor_op_query_find (mongoc_cursor_t *cursor, - bson_t *filter, - mongoc_cursor_response_legacy_t *response); +_mongoc_cursor_op_query_find (mongoc_cursor_t *cursor, bson_t *filter, mongoc_cursor_response_legacy_t *response); void -_mongoc_cursor_op_getmore (mongoc_cursor_t *cursor, - mongoc_cursor_response_legacy_t *response); +_mongoc_cursor_op_getmore (mongoc_cursor_t *cursor, mongoc_cursor_response_legacy_t *response); mongoc_cursor_t * _mongoc_cursor_new_with_opts (mongoc_client_t *client, const char *db_and_collection, @@ -274,8 +247,7 @@ _mongoc_cursor_new_with_opts (mongoc_client_t *client, void _mongoc_cursor_response_legacy_init (mongoc_cursor_response_legacy_t *response); void -_mongoc_cursor_response_legacy_destroy ( - mongoc_cursor_response_legacy_t *response); +_mongoc_cursor_response_legacy_destroy (mongoc_cursor_response_legacy_t *response); /* cursor constructors. */ mongoc_cursor_t * _mongoc_cursor_find_new (mongoc_client_t *client, @@ -296,10 +268,7 @@ _mongoc_cursor_cmd_new (mongoc_client_t *client, const mongoc_read_concern_t *read_concern); mongoc_cursor_t * -_mongoc_cursor_cmd_new_from_reply (mongoc_client_t *client, - const bson_t *cmd, - const bson_t *opts, - bson_t *reply); +_mongoc_cursor_cmd_new_from_reply (mongoc_client_t *client, const bson_t *cmd, const bson_t *opts, bson_t *reply); mongoc_cursor_t * _mongoc_cursor_cmd_deprecated_new (mongoc_client_t *client, @@ -308,27 +277,20 @@ _mongoc_cursor_cmd_deprecated_new (mongoc_client_t *client, const mongoc_read_prefs_t *read_prefs); mongoc_cursor_t * -_mongoc_cursor_array_new (mongoc_client_t *client, - const char *db_and_coll, - const bson_t *cmd, - const bson_t *opts, - const char *field_name); +_mongoc_cursor_array_new ( + mongoc_client_t *client, const char *db_and_coll, const bson_t *cmd, const bson_t *opts, const char *field_name); mongoc_cursor_t * -_mongoc_cursor_change_stream_new (mongoc_client_t *client, - bson_t *reply, - const bson_t *opts); +_mongoc_cursor_change_stream_new (mongoc_client_t *client, bson_t *reply, const bson_t *opts); bool _mongoc_cursor_change_stream_end_of_batch (mongoc_cursor_t *cursor); const bson_t * -_mongoc_cursor_change_stream_get_post_batch_resume_token ( - mongoc_cursor_t *cursor); +_mongoc_cursor_change_stream_get_post_batch_resume_token (mongoc_cursor_t *cursor); bool -_mongoc_cursor_change_stream_has_post_batch_resume_token ( - mongoc_cursor_t *cursor); +_mongoc_cursor_change_stream_has_post_batch_resume_token (mongoc_cursor_t *cursor); const bson_t * _mongoc_cursor_change_stream_get_reply (mongoc_cursor_t *cursor); diff --git a/src/libmongoc/src/mongoc/mongoc-cursor.c b/src/libmongoc/src/mongoc/mongoc-cursor.c index 924f8c15cf..d24640c2b0 100644 --- a/src/libmongoc/src/mongoc/mongoc-cursor.c +++ b/src/libmongoc/src/mongoc/mongoc-cursor.c @@ -39,15 +39,11 @@ #define CURSOR_FAILED(cursor_) ((cursor_)->error.domain != 0) static bool -_translate_query_opt (const char *query_field, - const char **cmd_field, - int *len); +_translate_query_opt (const char *query_field, const char **cmd_field, int *len); bool -_mongoc_cursor_set_opt_int64 (mongoc_cursor_t *cursor, - const char *option, - int64_t value) +_mongoc_cursor_set_opt_int64 (mongoc_cursor_t *cursor, const char *option, int64_t value) { bson_iter_t iter; @@ -65,9 +61,7 @@ _mongoc_cursor_set_opt_int64 (mongoc_cursor_t *cursor, static int64_t -_mongoc_cursor_get_opt_int64 (const mongoc_cursor_t *cursor, - const char *option, - int64_t default_value) +_mongoc_cursor_get_opt_int64 (const mongoc_cursor_t *cursor, const char *option, int64_t default_value) { bson_iter_t iter; @@ -80,9 +74,7 @@ _mongoc_cursor_get_opt_int64 (const mongoc_cursor_t *cursor, static bool -_mongoc_cursor_set_opt_bool (mongoc_cursor_t *cursor, - const char *option, - bool value) +_mongoc_cursor_set_opt_bool (mongoc_cursor_t *cursor, const char *option, bool value) { bson_iter_t iter; @@ -203,16 +195,12 @@ _first_dollar_field (const bson_t *bson) /* if src is non-NULL, it is validated and copied to dst. returns false and * sets the cursor error if validation fails. */ bool -_mongoc_cursor_check_and_copy_to (mongoc_cursor_t *cursor, - const char *err_prefix, - const bson_t *src, - bson_t *dst) +_mongoc_cursor_check_and_copy_to (mongoc_cursor_t *cursor, const char *err_prefix, const bson_t *src, bson_t *dst) { bson_error_t validate_err; bson_init (dst); if (src) { - if (!bson_validate_with_error ( - src, BSON_VALIDATE_EMPTY_KEYS, &validate_err)) { + if (!bson_validate_with_error (src, BSON_VALIDATE_EMPTY_KEYS, &validate_err)) { bson_set_error (&cursor->error, MONGOC_ERROR_CURSOR, MONGOC_ERROR_CURSOR_INVALID_CURSOR, @@ -258,8 +246,7 @@ _mongoc_cursor_new_with_opts (mongoc_client_t *client, bson_init (&cursor->error_doc); if (opts) { - if (!bson_validate_with_error ( - opts, BSON_VALIDATE_EMPTY_KEYS, &validate_err)) { + if (!bson_validate_with_error (opts, BSON_VALIDATE_EMPTY_KEYS, &validate_err)) { bson_set_error (&cursor->error, MONGOC_ERROR_CURSOR, MONGOC_ERROR_CURSOR_INVALID_CURSOR, @@ -279,8 +266,7 @@ _mongoc_cursor_new_with_opts (mongoc_client_t *client, } if (bson_iter_init_find (&iter, opts, "sessionId")) { - if (!_mongoc_client_session_from_iter ( - client, &iter, &cursor->client_session, &cursor->error)) { + if (!_mongoc_client_session_from_iter (client, &iter, &cursor->client_session, &cursor->error)) { GOTO (finish); } @@ -288,8 +274,7 @@ _mongoc_cursor_new_with_opts (mongoc_client_t *client, } if (bson_iter_init_find (&iter, opts, "readConcern")) { - read_concern_local = - _mongoc_read_concern_new_from_iter (&iter, &cursor->error); + read_concern_local = _mongoc_read_concern_new_from_iter (&iter, &cursor->error); if (!read_concern_local) { /* invalid read concern */ @@ -300,11 +285,8 @@ _mongoc_cursor_new_with_opts (mongoc_client_t *client, } /* true if there's a valid serverId or no serverId, false on err */ - if (!_mongoc_get_server_id_from_opts (opts, - MONGOC_ERROR_CURSOR, - MONGOC_ERROR_CURSOR_INVALID_CURSOR, - &server_id, - &cursor->error)) { + if (!_mongoc_get_server_id_from_opts ( + opts, MONGOC_ERROR_CURSOR, MONGOC_ERROR_CURSOR_INVALID_CURSOR, &server_id, &cursor->error)) { GOTO (finish); } @@ -313,12 +295,11 @@ _mongoc_cursor_new_with_opts (mongoc_client_t *client, } // Selectively copy the options: - bsonBuildAppend ( - cursor->opts, - insert (*opts, - not(key ("serverId", "sessionId"), - // Drop bypassDocumentValidation if it isn't true: - allOf (key ("bypassDocumentValidation"), isFalse)))); + bsonBuildAppend (cursor->opts, + insert (*opts, + not(key ("serverId", "sessionId"), + // Drop bypassDocumentValidation if it isn't true: + allOf (key ("bypassDocumentValidation"), isFalse)))); } if (_mongoc_client_session_in_txn (cursor->client_session)) { @@ -330,8 +311,7 @@ _mongoc_cursor_new_with_opts (mongoc_client_t *client, GOTO (finish); } - cursor->read_prefs = - mongoc_read_prefs_copy (cursor->client_session->txn.opts.read_prefs); + cursor->read_prefs = mongoc_read_prefs_copy (cursor->client_session->txn.opts.read_prefs); if (bson_has_field (opts, "readConcern")) { bson_set_error (&cursor->error, @@ -348,12 +328,10 @@ _mongoc_cursor_new_with_opts (mongoc_client_t *client, cursor->read_prefs = mongoc_read_prefs_new (MONGOC_READ_PRIMARY); } - cursor->read_concern = read_concern ? mongoc_read_concern_copy (read_concern) - : mongoc_read_concern_new (); + cursor->read_concern = read_concern ? mongoc_read_concern_copy (read_concern) : mongoc_read_concern_new (); if (db_and_collection) { - _mongoc_set_cursor_ns ( - cursor, db_and_collection, (uint32_t) strlen (db_and_collection)); + _mongoc_set_cursor_ns (cursor, db_and_collection, (uint32_t) strlen (db_and_collection)); } if (_mongoc_cursor_get_opt_bool (cursor, MONGOC_CURSOR_EXHAUST)) { @@ -391,8 +369,7 @@ _translate_query_opt (const char *query_field, const char **cmd_field, int *len) if (!strcmp (MONGOC_CURSOR_ORDERBY, query_field)) { *cmd_field = MONGOC_CURSOR_SORT; *len = MONGOC_CURSOR_SORT_LEN; - } else if (!strcmp (MONGOC_CURSOR_SHOW_DISK_LOC, - query_field)) { /* <= MongoDb 3.0 */ + } else if (!strcmp (MONGOC_CURSOR_SHOW_DISK_LOC, query_field)) { /* <= MongoDb 3.0 */ *cmd_field = MONGOC_CURSOR_SHOW_RECORD_ID; *len = MONGOC_CURSOR_SHOW_RECORD_ID_LEN; } else if (!strcmp (MONGOC_CURSOR_HINT, query_field)) { @@ -445,39 +422,27 @@ _mongoc_cursor_flags_to_opts (mongoc_query_flags_t qflags, } if (qflags & MONGOC_QUERY_TAILABLE_CURSOR) { - bson_append_bool ( - opts, MONGOC_CURSOR_TAILABLE, MONGOC_CURSOR_TAILABLE_LEN, true); + bson_append_bool (opts, MONGOC_CURSOR_TAILABLE, MONGOC_CURSOR_TAILABLE_LEN, true); } if (qflags & MONGOC_QUERY_OPLOG_REPLAY) { - bson_append_bool (opts, - MONGOC_CURSOR_OPLOG_REPLAY, - MONGOC_CURSOR_OPLOG_REPLAY_LEN, - true); + bson_append_bool (opts, MONGOC_CURSOR_OPLOG_REPLAY, MONGOC_CURSOR_OPLOG_REPLAY_LEN, true); } if (qflags & MONGOC_QUERY_NO_CURSOR_TIMEOUT) { - bson_append_bool (opts, - MONGOC_CURSOR_NO_CURSOR_TIMEOUT, - MONGOC_CURSOR_NO_CURSOR_TIMEOUT_LEN, - true); + bson_append_bool (opts, MONGOC_CURSOR_NO_CURSOR_TIMEOUT, MONGOC_CURSOR_NO_CURSOR_TIMEOUT_LEN, true); } if (qflags & MONGOC_QUERY_AWAIT_DATA) { - bson_append_bool ( - opts, MONGOC_CURSOR_AWAIT_DATA, MONGOC_CURSOR_AWAIT_DATA_LEN, true); + bson_append_bool (opts, MONGOC_CURSOR_AWAIT_DATA, MONGOC_CURSOR_AWAIT_DATA_LEN, true); } if (qflags & MONGOC_QUERY_EXHAUST) { - bson_append_bool ( - opts, MONGOC_CURSOR_EXHAUST, MONGOC_CURSOR_EXHAUST_LEN, true); + bson_append_bool (opts, MONGOC_CURSOR_EXHAUST, MONGOC_CURSOR_EXHAUST_LEN, true); } if (qflags & MONGOC_QUERY_PARTIAL) { - bson_append_bool (opts, - MONGOC_CURSOR_ALLOW_PARTIAL_RESULTS, - MONGOC_CURSOR_ALLOW_PARTIAL_RESULTS_LEN, - true); + bson_append_bool (opts, MONGOC_CURSOR_ALLOW_PARTIAL_RESULTS, MONGOC_CURSOR_ALLOW_PARTIAL_RESULTS_LEN, true); } } @@ -490,10 +455,7 @@ _mongoc_cursor_flags_to_opts (mongoc_query_flags_t qflags, * unwrapped must be uninitialized, and will be initialized at return. * Returns true if query was unwrapped. */ bool -_mongoc_cursor_translate_dollar_query_opts (const bson_t *query, - bson_t *opts, - bson_t *unwrapped, - bson_error_t *error) +_mongoc_cursor_translate_dollar_query_opts (const bson_t *query, bson_t *opts, bson_t *unwrapped, bson_error_t *error) { bool has_filter = false; const char *key; @@ -512,10 +474,7 @@ _mongoc_cursor_translate_dollar_query_opts (const bson_t *query, if (bson_has_field (query, "$query")) { /* like "{$query: {a: 1}, $orderby: {b: 1}, $otherModifier: true}" */ if (!bson_iter_init (&iter, query)) { - bson_set_error (&error_local, - MONGOC_ERROR_BSON, - MONGOC_ERROR_BSON_INVALID, - "Invalid BSON in query document"); + bson_set_error (&error_local, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "Invalid BSON in query document"); GOTO (done); } while (bson_iter_next (&iter)) { @@ -532,30 +491,22 @@ _mongoc_cursor_translate_dollar_query_opts (const bson_t *query, /* set "filter" to the incoming document's "$query" */ bson_iter_document (&iter, &data_len, &data); if (!bson_init_static (unwrapped, data, (size_t) data_len)) { - bson_set_error (&error_local, - MONGOC_ERROR_BSON, - MONGOC_ERROR_BSON_INVALID, - "Invalid BSON in $query subdocument"); + bson_set_error ( + &error_local, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "Invalid BSON in $query subdocument"); GOTO (done); } has_filter = true; } else if (_translate_query_opt (key, &opt_key, &len)) { /* "$orderby" becomes "sort", etc., "$unknown" -> "unknown" */ if (!bson_append_iter (opts, opt_key, len, &iter)) { - bson_set_error (&error_local, - MONGOC_ERROR_BSON, - MONGOC_ERROR_BSON_INVALID, - "Error adding \"%s\" to query", - opt_key); + bson_set_error ( + &error_local, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "Error adding \"%s\" to query", opt_key); } } else { /* strip leading "$" */ if (!bson_append_iter (opts, key + 1, -1, &iter)) { - bson_set_error (&error_local, - MONGOC_ERROR_BSON, - MONGOC_ERROR_BSON_INVALID, - "Error adding \"%s\" to query", - key); + bson_set_error ( + &error_local, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "Error adding \"%s\" to query", key); } } } @@ -593,8 +544,7 @@ mongoc_cursor_destroy (mongoc_cursor_t *cursor) if (cursor->state != DONE) { /* The only way to stop an exhaust cursor is to kill the connection */ - mongoc_cluster_disconnect_node (&cursor->client->cluster, - cursor->server_id); + mongoc_cluster_disconnect_node (&cursor->client->cluster, cursor->server_id); } } else if (cursor->client_generation == cursor->client->generation) { if (cursor->cursor_id) { @@ -642,13 +592,12 @@ _mongoc_cursor_fetch_stream (mongoc_cursor_t *cursor) if (cursor->server_id) { /* We already did server selection once before. Reuse the prior * selection to create a new stream on the same server. */ - server_stream = - mongoc_cluster_stream_for_server (&cursor->client->cluster, - cursor->server_id, - true /* reconnect_ok */, - cursor->client_session, - &reply, - &cursor->error); + server_stream = mongoc_cluster_stream_for_server (&cursor->client->cluster, + cursor->server_id, + true /* reconnect_ok */, + cursor->client_session, + &reply, + &cursor->error); if (server_stream) { /* Also restore whether primary read preference was forced by server * selection */ @@ -658,17 +607,9 @@ _mongoc_cursor_fetch_stream (mongoc_cursor_t *cursor) server_stream = cursor->is_aggr_with_write_stage ? mongoc_cluster_stream_for_aggr_with_write ( - &cursor->client->cluster, - cursor->read_prefs, - cursor->client_session, - &reply, - &cursor->error) - : mongoc_cluster_stream_for_reads (&cursor->client->cluster, - cursor->read_prefs, - cursor->client_session, - NULL, - &reply, - &cursor->error); + &cursor->client->cluster, cursor->read_prefs, cursor->client_session, &reply, &cursor->error) + : mongoc_cluster_stream_for_reads ( + &cursor->client->cluster, cursor->read_prefs, cursor->client_session, NULL, &reply, &cursor->error); if (server_stream) { /* Remember the selected server_id and whether primary read mode was @@ -732,9 +673,7 @@ _mongoc_cursor_monitor_command (mongoc_cursor_t *cursor, /* append array of docs from current cursor batch */ static void -_mongoc_cursor_append_docs_array (mongoc_cursor_t *cursor, - bson_t *docs, - mongoc_cursor_response_legacy_t *response) +_mongoc_cursor_append_docs_array (mongoc_cursor_t *cursor, bson_t *docs, mongoc_cursor_response_legacy_t *response) { bool eof = false; char str[16]; @@ -785,8 +724,7 @@ _mongoc_cursor_monitor_succeeded (mongoc_cursor_t *cursor, kv ("cursor", doc (kv ("id", int64 (mongoc_cursor_get_id (cursor))), kv ("ns", utf8_w_len (cursor->ns, cursor->nslen)), - kv (first_batch ? "firstBatch" : "nextBatch", - bsonArray (docs_array))))); + kv (first_batch ? "firstBatch" : "nextBatch", bsonArray (docs_array))))); bson_destroy (&docs_array); @@ -873,9 +811,7 @@ _mongoc_cursor_monitor_failed (mongoc_cursor_t *cursor, } while (false) bool -_mongoc_cursor_opts_to_flags (mongoc_cursor_t *cursor, - mongoc_server_stream_t *stream, - int32_t *flags /* OUT */) +_mongoc_cursor_opts_to_flags (mongoc_cursor_t *cursor, mongoc_server_stream_t *stream, int32_t *flags /* OUT */) { /* CDRIVER-4722: these flags are only used in legacy OP_QUERY */ bson_iter_t iter; @@ -884,10 +820,7 @@ _mongoc_cursor_opts_to_flags (mongoc_cursor_t *cursor, *flags = MONGOC_OP_QUERY_FLAG_NONE; if (!bson_iter_init (&iter, &cursor->opts)) { - bson_set_error (&cursor->error, - MONGOC_ERROR_BSON, - MONGOC_ERROR_BSON_INVALID, - "Invalid 'opts' parameter."); + bson_set_error (&cursor->error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "Invalid 'opts' parameter."); return false; } @@ -926,16 +859,12 @@ _mongoc_cursor_use_op_msg (const mongoc_cursor_t *cursor, int32_t wire_version) { /* CDRIVER-4722: always true once 4.2 is the minimum supported No check needed for 3.6 as it's the current minimum */ - return !_mongoc_cursor_get_opt_bool (cursor, MONGOC_CURSOR_EXHAUST) || - wire_version >= WIRE_VERSION_4_2; + return !_mongoc_cursor_get_opt_bool (cursor, MONGOC_CURSOR_EXHAUST) || wire_version >= WIRE_VERSION_4_2; } bool -_mongoc_cursor_run_command (mongoc_cursor_t *cursor, - const bson_t *command, - const bson_t *opts, - bson_t *reply, - bool retry_prohibited) +_mongoc_cursor_run_command ( + mongoc_cursor_t *cursor, const bson_t *command, const bson_t *opts, bson_t *reply, bool retry_prohibited) { mongoc_server_stream_t *server_stream; bson_iter_t iter; @@ -950,8 +879,7 @@ _mongoc_cursor_run_command (mongoc_cursor_t *cursor, ENTRY; - mongoc_cmd_parts_init ( - &parts, cursor->client, db, MONGOC_QUERY_NONE, command); + mongoc_cmd_parts_init (&parts, cursor->client, db, MONGOC_QUERY_NONE, command); parts.is_read_command = true; parts.read_prefs = cursor->read_prefs; parts.assembled.operation_id = cursor->operation_id; @@ -965,10 +893,7 @@ _mongoc_cursor_run_command (mongoc_cursor_t *cursor, if (opts) { if (!bson_iter_init (&iter, opts)) { _mongoc_bson_init_if_set (reply); - bson_set_error (&cursor->error, - MONGOC_ERROR_BSON, - MONGOC_ERROR_BSON_INVALID, - "Invalid BSON in opts document"); + bson_set_error (&cursor->error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "Invalid BSON in opts document"); GOTO (done); } if (!mongoc_cmd_parts_append_opts (&parts, &iter, &cursor->error)) { @@ -994,14 +919,12 @@ _mongoc_cursor_run_command (mongoc_cursor_t *cursor, session_opts = mongoc_session_opts_new (); mongoc_session_opts_set_causal_consistency (session_opts, false); /* returns NULL if sessions aren't supported. ignore errors. */ - cursor->client_session = - mongoc_client_start_session (cursor->client, session_opts, NULL); + cursor->client_session = mongoc_client_start_session (cursor->client, session_opts, NULL); mongoc_cmd_parts_set_session (&parts, cursor->client_session); mongoc_session_opts_destroy (session_opts); } - if (!mongoc_cmd_parts_set_read_concern ( - &parts, cursor->read_concern, &cursor->error)) { + if (!mongoc_cmd_parts_set_read_concern (&parts, cursor->read_concern, &cursor->error)) { _mongoc_bson_init_if_set (reply); GOTO (done); } @@ -1019,9 +942,7 @@ _mongoc_cursor_run_command (mongoc_cursor_t *cursor, } if (_mongoc_cursor_get_opt_bool (cursor, MONGOC_CURSOR_EXHAUST)) { - const bool sharded = - _mongoc_topology_get_type (cursor->client->topology) == - MONGOC_TOPOLOGY_SHARDED; + const bool sharded = _mongoc_topology_get_type (cursor->client->topology) == MONGOC_TOPOLOGY_SHARDED; const int32_t wire_version = server_stream->sd->max_wire_version; if (sharded && wire_version < WIRE_VERSION_MONGOS_EXHAUST) { /* Return error since mongos < 7.2 doesn't support exhaust cursors */ @@ -1045,13 +966,10 @@ _mongoc_cursor_run_command (mongoc_cursor_t *cursor, * $readPreference. */ cmd_name = _mongoc_get_command_name (command); - is_primary = - !cursor->read_prefs || cursor->read_prefs->mode == MONGOC_READ_PRIMARY; + is_primary = !cursor->read_prefs || cursor->read_prefs->mode == MONGOC_READ_PRIMARY; - if (strcmp (cmd_name, "getMore") != 0 && is_primary && - parts.user_query_flags & MONGOC_QUERY_SECONDARY_OK) { - parts.read_prefs = prefs = - mongoc_read_prefs_new (MONGOC_READ_PRIMARY_PREFERRED); + if (strcmp (cmd_name, "getMore") != 0 && is_primary && parts.user_query_flags & MONGOC_QUERY_SECONDARY_OK) { + parts.read_prefs = prefs = mongoc_read_prefs_new (MONGOC_READ_PRIMARY_PREFERRED); } else { parts.read_prefs = cursor->read_prefs; } @@ -1062,8 +980,7 @@ _mongoc_cursor_run_command (mongoc_cursor_t *cursor, } if (!strcmp (cmd_name, "aggregate")) { bson_iter_t pipeline_iter; - if (bson_iter_init_find (&pipeline_iter, command, "pipeline") && - BSON_ITER_HOLDS_ARRAY (&pipeline_iter) && + if (bson_iter_init_find (&pipeline_iter, command, "pipeline") && BSON_ITER_HOLDS_ARRAY (&pipeline_iter) && bson_iter_recurse (&pipeline_iter, &pipeline_iter)) { if (_has_write_key (&pipeline_iter)) { is_retryable = false; @@ -1074,10 +991,8 @@ _mongoc_cursor_run_command (mongoc_cursor_t *cursor, is_retryable = false; } - if (cursor->write_concern && - !mongoc_write_concern_is_default (cursor->write_concern)) { - parts.assembled.is_acknowledged = - mongoc_write_concern_is_acknowledged (cursor->write_concern); + if (cursor->write_concern && !mongoc_write_concern_is_default (cursor->write_concern)) { + parts.assembled.is_acknowledged = mongoc_write_concern_is_acknowledged (cursor->write_concern); mongoc_write_concern_append (cursor->write_concern, &parts.extra); } @@ -1087,37 +1002,26 @@ _mongoc_cursor_run_command (mongoc_cursor_t *cursor, } retry: - ret = mongoc_cluster_run_command_monitored ( - &cursor->client->cluster, &parts.assembled, reply, &cursor->error); + ret = mongoc_cluster_run_command_monitored (&cursor->client->cluster, &parts.assembled, reply, &cursor->error); if (ret) { memset (&cursor->error, 0, sizeof (bson_error_t)); } - if (is_retryable && - _mongoc_read_error_get_type (ret, &cursor->error, reply) == - MONGOC_READ_ERR_RETRY) { + if (is_retryable && _mongoc_read_error_get_type (ret, &cursor->error, reply) == MONGOC_READ_ERR_RETRY) { is_retryable = false; { - mongoc_deprioritized_servers_t *const ds = - mongoc_deprioritized_servers_new (); + mongoc_deprioritized_servers_t *const ds = mongoc_deprioritized_servers_new (); - mongoc_deprioritized_servers_add_if_sharded ( - ds, server_stream->topology_type, server_stream->sd); + mongoc_deprioritized_servers_add_if_sharded (ds, server_stream->topology_type, server_stream->sd); mongoc_server_stream_cleanup (server_stream); - BSON_ASSERT (!cursor->is_aggr_with_write_stage && - "Cannot attempt a retry on an aggregate operation that " - "contains write stages"); - server_stream = - mongoc_cluster_stream_for_reads (&cursor->client->cluster, - cursor->read_prefs, - cursor->client_session, - ds, - reply, - &cursor->error); + BSON_ASSERT (!cursor->is_aggr_with_write_stage && "Cannot attempt a retry on an aggregate operation that " + "contains write stages"); + server_stream = mongoc_cluster_stream_for_reads ( + &cursor->client->cluster, cursor->read_prefs, cursor->client_session, ds, reply, &cursor->error); mongoc_deprioritized_servers_destroy (ds); } @@ -1158,9 +1062,7 @@ _mongoc_cursor_run_command (mongoc_cursor_t *cursor, void -_mongoc_cursor_collection (const mongoc_cursor_t *cursor, - const char **collection, - int *collection_len) +_mongoc_cursor_collection (const mongoc_cursor_t *cursor, const char **collection, int *collection_len) { /* ns is like "db.collection". Collection name is located past the ".". */ *collection = cursor->ns + (cursor->dblen + 1); @@ -1172,21 +1074,14 @@ _mongoc_cursor_collection (const mongoc_cursor_t *cursor, void -_mongoc_cursor_prepare_find_command (mongoc_cursor_t *cursor, - const bson_t *filter, - bson_t *command) +_mongoc_cursor_prepare_find_command (mongoc_cursor_t *cursor, const bson_t *filter, bson_t *command) { const char *collection; int collection_len; _mongoc_cursor_collection (cursor, &collection, &collection_len); - bson_append_utf8 (command, - MONGOC_CURSOR_FIND, - MONGOC_CURSOR_FIND_LEN, - collection, - collection_len); - bson_append_document ( - command, MONGOC_CURSOR_FILTER, MONGOC_CURSOR_FILTER_LEN, filter); + bson_append_utf8 (command, MONGOC_CURSOR_FIND, MONGOC_CURSOR_FIND_LEN, collection, collection_len); + bson_append_document (command, MONGOC_CURSOR_FILTER, MONGOC_CURSOR_FILTER_LEN, filter); } @@ -1200,20 +1095,14 @@ mongoc_cursor_error (mongoc_cursor_t *cursor, bson_error_t *error) bool -mongoc_cursor_error_document (mongoc_cursor_t *cursor, - bson_error_t *error, - const bson_t **doc) +mongoc_cursor_error_document (mongoc_cursor_t *cursor, bson_error_t *error, const bson_t **doc) { ENTRY; BSON_ASSERT (cursor); if (BSON_UNLIKELY (CURSOR_FAILED (cursor))) { - bson_set_error (error, - cursor->error.domain, - cursor->error.code, - "%s", - cursor->error.message); + bson_set_error (error, cursor->error.domain, cursor->error.code, "%s", cursor->error.message); if (doc) { *doc = &cursor->error_doc; @@ -1381,8 +1270,7 @@ mongoc_cursor_get_host (mongoc_cursor_t *cursor, mongoc_host_list_t *host) } td = mc_tpld_take_ref (cursor->client->topology); - description = mongoc_topology_description_server_by_id_const ( - td.ptr, cursor->server_id, &cursor->error); + description = mongoc_topology_description_server_by_id_const (td.ptr, cursor->server_id, &cursor->error); if (description) { *host = description->host; } @@ -1471,10 +1359,7 @@ mongoc_cursor_set_batch_size (mongoc_cursor_t *cursor, uint32_t batch_size) BSON_ASSERT (cursor); bson_iter_t iter; if (!bson_iter_init_find (&iter, &cursor->opts, MONGOC_CURSOR_BATCH_SIZE)) { - bson_append_int64 (&cursor->opts, - MONGOC_CURSOR_BATCH_SIZE, - MONGOC_CURSOR_BATCH_SIZE_LEN, - batch_size); + bson_append_int64 (&cursor->opts, MONGOC_CURSOR_BATCH_SIZE, MONGOC_CURSOR_BATCH_SIZE_LEN, batch_size); } else if (BSON_ITER_HOLDS_INT64 (&iter)) { bson_iter_overwrite_int64 (&iter, (int64_t) batch_size); } else if (BSON_ITER_HOLDS_INT32 (&iter)) { @@ -1503,8 +1388,7 @@ mongoc_cursor_get_batch_size (const mongoc_cursor_t *cursor) { BSON_ASSERT (cursor); - return (uint32_t) _mongoc_cursor_get_opt_int64 ( - cursor, MONGOC_CURSOR_BATCH_SIZE, 0); + return (uint32_t) _mongoc_cursor_get_opt_int64 (cursor, MONGOC_CURSOR_BATCH_SIZE, 0); } @@ -1515,13 +1399,10 @@ mongoc_cursor_set_limit (mongoc_cursor_t *cursor, int64_t limit) if (cursor->state == UNPRIMED) { if (limit < 0) { - return _mongoc_cursor_set_opt_int64 ( - cursor, MONGOC_CURSOR_LIMIT, -limit) && - _mongoc_cursor_set_opt_bool ( - cursor, MONGOC_CURSOR_SINGLE_BATCH, true); + return _mongoc_cursor_set_opt_int64 (cursor, MONGOC_CURSOR_LIMIT, -limit) && + _mongoc_cursor_set_opt_bool (cursor, MONGOC_CURSOR_SINGLE_BATCH, true); } else { - return _mongoc_cursor_set_opt_int64 ( - cursor, MONGOC_CURSOR_LIMIT, limit); + return _mongoc_cursor_set_opt_int64 (cursor, MONGOC_CURSOR_LIMIT, limit); } } else { return false; @@ -1538,8 +1419,7 @@ mongoc_cursor_get_limit (const mongoc_cursor_t *cursor) BSON_ASSERT (cursor); limit = _mongoc_cursor_get_opt_int64 (cursor, MONGOC_CURSOR_LIMIT, 0); - single_batch = - _mongoc_cursor_get_opt_bool (cursor, MONGOC_CURSOR_SINGLE_BATCH); + single_batch = _mongoc_cursor_get_opt_bool (cursor, MONGOC_CURSOR_SINGLE_BATCH); if (limit > 0 && single_batch) { limit = -limit; @@ -1589,14 +1469,12 @@ mongoc_cursor_get_id (const mongoc_cursor_t *cursor) void -mongoc_cursor_set_max_await_time_ms (mongoc_cursor_t *cursor, - uint32_t max_await_time_ms) +mongoc_cursor_set_max_await_time_ms (mongoc_cursor_t *cursor, uint32_t max_await_time_ms) { BSON_ASSERT (cursor); if (cursor->state == UNPRIMED) { - _mongoc_cursor_set_opt_int64 ( - cursor, MONGOC_CURSOR_MAX_AWAIT_TIME_MS, (int64_t) max_await_time_ms); + _mongoc_cursor_set_opt_int64 (cursor, MONGOC_CURSOR_MAX_AWAIT_TIME_MS, (int64_t) max_await_time_ms); } } @@ -1608,8 +1486,7 @@ mongoc_cursor_get_max_await_time_ms (const mongoc_cursor_t *cursor) BSON_ASSERT (cursor); - if (bson_iter_init_find ( - &iter, &cursor->opts, MONGOC_CURSOR_MAX_AWAIT_TIME_MS)) { + if (bson_iter_init_find (&iter, &cursor->opts, MONGOC_CURSOR_MAX_AWAIT_TIME_MS)) { return (uint32_t) bson_iter_as_int64 (&iter); } @@ -1619,9 +1496,7 @@ mongoc_cursor_get_max_await_time_ms (const mongoc_cursor_t *cursor) /* deprecated for mongoc_cursor_new_from_command_reply_with_opts */ mongoc_cursor_t * -mongoc_cursor_new_from_command_reply (mongoc_client_t *client, - bson_t *reply, - uint32_t server_id) +mongoc_cursor_new_from_command_reply (mongoc_client_t *client, bson_t *reply, uint32_t server_id) { mongoc_cursor_t *cursor; bson_t cmd = BSON_INITIALIZER; @@ -1630,12 +1505,7 @@ mongoc_cursor_new_from_command_reply (mongoc_client_t *client, BSON_ASSERT_PARAM (client); BSON_ASSERT (reply); /* options are passed through by adding them to reply. */ - bsonBuildAppend ( - *reply, - insert ( - opts, - not(key ( - "cursor", "ok", "operationTime", "$clusterTime", "$gleStats")))); + bsonBuildAppend (*reply, insert (opts, not(key ("cursor", "ok", "operationTime", "$clusterTime", "$gleStats")))); if (server_id) { bson_append_int64 (&opts, "serverId", 8, server_id); @@ -1650,9 +1520,7 @@ mongoc_cursor_new_from_command_reply (mongoc_client_t *client, mongoc_cursor_t * -mongoc_cursor_new_from_command_reply_with_opts (mongoc_client_t *client, - bson_t *reply, - const bson_t *opts) +mongoc_cursor_new_from_command_reply_with_opts (mongoc_client_t *client, bson_t *reply, const bson_t *opts) { mongoc_cursor_t *cursor; bson_t cmd = BSON_INITIALIZER; @@ -1668,8 +1536,7 @@ mongoc_cursor_new_from_command_reply_with_opts (mongoc_client_t *client, bool -_mongoc_cursor_start_reading_response (mongoc_cursor_t *cursor, - mongoc_cursor_response_t *response) +_mongoc_cursor_start_reading_response (mongoc_cursor_t *cursor, mongoc_cursor_response_t *response) { bson_iter_t iter; bson_iter_t child; @@ -1677,18 +1544,16 @@ _mongoc_cursor_start_reading_response (mongoc_cursor_t *cursor, uint32_t nslen; bool in_batch = false; - if (bson_iter_init_find (&iter, &response->reply, "cursor") && - BSON_ITER_HOLDS_DOCUMENT (&iter) && bson_iter_recurse (&iter, &child)) { + if (bson_iter_init_find (&iter, &response->reply, "cursor") && BSON_ITER_HOLDS_DOCUMENT (&iter) && + bson_iter_recurse (&iter, &child)) { while (bson_iter_next (&child)) { if (BSON_ITER_IS_KEY (&child, "id")) { cursor->cursor_id = bson_iter_as_int64 (&child); } else if (BSON_ITER_IS_KEY (&child, "ns")) { ns = bson_iter_utf8 (&child, &nslen); _mongoc_set_cursor_ns (cursor, ns, nslen); - } else if (BSON_ITER_IS_KEY (&child, "firstBatch") || - BSON_ITER_IS_KEY (&child, "nextBatch")) { - if (BSON_ITER_HOLDS_ARRAY (&child) && - bson_iter_recurse (&child, &response->batch_iter)) { + } else if (BSON_ITER_IS_KEY (&child, "firstBatch") || BSON_ITER_IS_KEY (&child, "nextBatch")) { + if (BSON_ITER_HOLDS_ARRAY (&child) && bson_iter_recurse (&child, &response->batch_iter)) { in_batch = true; } } @@ -1699,8 +1564,7 @@ _mongoc_cursor_start_reading_response (mongoc_cursor_t *cursor, * cursor for use with getMore operations, the session MUST be returned to * the pool immediately following a getMore operation that indicates that the * cursor has been exhausted." */ - if (cursor->cursor_id == 0 && cursor->client_session && - !cursor->explicit_session) { + if (cursor->cursor_id == 0 && cursor->client_session && !cursor->explicit_session) { mongoc_client_session_destroy (cursor->client_session); cursor->client_session = NULL; } @@ -1710,9 +1574,7 @@ _mongoc_cursor_start_reading_response (mongoc_cursor_t *cursor, void -_mongoc_cursor_response_read (mongoc_cursor_t *cursor, - mongoc_cursor_response_t *response, - const bson_t **bson) +_mongoc_cursor_response_read (mongoc_cursor_t *cursor, mongoc_cursor_response_t *response, const bson_t **bson) { const uint8_t *data = NULL; uint32_t data_len = 0; @@ -1721,8 +1583,7 @@ _mongoc_cursor_response_read (mongoc_cursor_t *cursor, BSON_UNUSED (cursor); - if (bson_iter_next (&response->batch_iter) && - BSON_ITER_HOLDS_DOCUMENT (&response->batch_iter)) { + if (bson_iter_next (&response->batch_iter) && BSON_ITER_HOLDS_DOCUMENT (&response->batch_iter)) { bson_iter_document (&response->batch_iter, &data_len, &data); /* bson_iter_next guarantees valid BSON, so this must succeed */ @@ -1744,8 +1605,7 @@ _mongoc_cursor_response_refresh (mongoc_cursor_t *cursor, /* server replies to find / aggregate with {cursor: {id: N, firstBatch: []}}, * to getMore command with {cursor: {id: N, nextBatch: []}}. */ - if (_mongoc_cursor_run_command ( - cursor, command, opts, &response->reply, false)) { + if (_mongoc_cursor_run_command (cursor, command, opts, &response->reply, false)) { if (_mongoc_cursor_start_reading_response (cursor, response)) { cursor->in_exhaust = cursor->client->in_exhaust; return; @@ -1761,8 +1621,7 @@ _mongoc_cursor_response_refresh (mongoc_cursor_t *cursor, } void -_mongoc_cursor_prepare_getmore_command (mongoc_cursor_t *cursor, - bson_t *command) +_mongoc_cursor_prepare_getmore_command (mongoc_cursor_t *cursor, bson_t *command) { const char *collection; int collection_len; @@ -1783,10 +1642,8 @@ _mongoc_cursor_prepare_getmore_command (mongoc_cursor_t *cursor, /* See find, getMore, and killCursors Spec for batchSize rules */ if (batch_size) { - bson_append_int64 (command, - MONGOC_CURSOR_BATCH_SIZE, - MONGOC_CURSOR_BATCH_SIZE_LEN, - abs (_mongoc_n_return (cursor))); + bson_append_int64 ( + command, MONGOC_CURSOR_BATCH_SIZE, MONGOC_CURSOR_BATCH_SIZE_LEN, abs (_mongoc_n_return (cursor))); } if (bson_iter_init_find (&iter, &cursor->opts, MONGOC_CURSOR_COMMENT) && @@ -1803,10 +1660,8 @@ _mongoc_cursor_prepare_getmore_command (mongoc_cursor_t *cursor, * fetch a stream. */ server_stream = _mongoc_cursor_fetch_stream (cursor); - if (server_stream != NULL && - server_stream->sd->max_wire_version >= WIRE_VERSION_4_4) { - bson_append_value ( - command, MONGOC_CURSOR_COMMENT, MONGOC_CURSOR_COMMENT_LEN, comment); + if (server_stream != NULL && server_stream->sd->max_wire_version >= WIRE_VERSION_4_4) { + bson_append_value (command, MONGOC_CURSOR_COMMENT, MONGOC_CURSOR_COMMENT_LEN, comment); } mongoc_server_stream_cleanup (server_stream); @@ -1823,13 +1678,9 @@ _mongoc_cursor_prepare_getmore_command (mongoc_cursor_t *cursor, _mongoc_cursor_get_opt_bool (cursor, MONGOC_CURSOR_AWAIT_DATA); if (await_data) { - max_await_time_ms = _mongoc_cursor_get_opt_int64 ( - cursor, MONGOC_CURSOR_MAX_AWAIT_TIME_MS, 0); + max_await_time_ms = _mongoc_cursor_get_opt_int64 (cursor, MONGOC_CURSOR_MAX_AWAIT_TIME_MS, 0); if (max_await_time_ms) { - bson_append_int64 (command, - MONGOC_CURSOR_MAX_TIME_MS, - MONGOC_CURSOR_MAX_TIME_MS_LEN, - max_await_time_ms); + bson_append_int64 (command, MONGOC_CURSOR_MAX_TIME_MS, MONGOC_CURSOR_MAX_TIME_MS_LEN, max_await_time_ms); } } } diff --git a/src/libmongoc/src/mongoc/mongoc-cursor.h b/src/libmongoc/src/mongoc/mongoc-cursor.h index b844c4761b..c745ad326f 100644 --- a/src/libmongoc/src/mongoc/mongoc-cursor.h +++ b/src/libmongoc/src/mongoc/mongoc-cursor.h @@ -34,8 +34,7 @@ typedef struct _mongoc_cursor_t mongoc_cursor_t; struct _mongoc_client_t; MONGOC_EXPORT (mongoc_cursor_t *) -mongoc_cursor_clone (const mongoc_cursor_t *cursor) - BSON_GNUC_WARN_UNUSED_RESULT; +mongoc_cursor_clone (const mongoc_cursor_t *cursor) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (void) mongoc_cursor_destroy (mongoc_cursor_t *cursor); MONGOC_EXPORT (bool) @@ -45,14 +44,11 @@ mongoc_cursor_next (mongoc_cursor_t *cursor, const bson_t **bson); MONGOC_EXPORT (bool) mongoc_cursor_error (mongoc_cursor_t *cursor, bson_error_t *error); MONGOC_EXPORT (bool) -mongoc_cursor_error_document (mongoc_cursor_t *cursor, - bson_error_t *error, - const bson_t **doc); +mongoc_cursor_error_document (mongoc_cursor_t *cursor, bson_error_t *error, const bson_t **doc); MONGOC_EXPORT (void) mongoc_cursor_get_host (mongoc_cursor_t *cursor, mongoc_host_list_t *host); MONGOC_EXPORT (bool) -mongoc_cursor_is_alive (const mongoc_cursor_t *cursor) - BSON_GNUC_DEPRECATED_FOR (mongoc_cursor_more); +mongoc_cursor_is_alive (const mongoc_cursor_t *cursor) BSON_GNUC_DEPRECATED_FOR (mongoc_cursor_more); MONGOC_EXPORT (const bson_t *) mongoc_cursor_current (const mongoc_cursor_t *cursor); MONGOC_EXPORT (void) @@ -72,21 +68,18 @@ mongoc_cursor_get_hint (const mongoc_cursor_t *cursor); MONGOC_EXPORT (int64_t) mongoc_cursor_get_id (const mongoc_cursor_t *cursor); MONGOC_EXPORT (void) -mongoc_cursor_set_max_await_time_ms (mongoc_cursor_t *cursor, - uint32_t max_await_time_ms); +mongoc_cursor_set_max_await_time_ms (mongoc_cursor_t *cursor, uint32_t max_await_time_ms); MONGOC_EXPORT (uint32_t) mongoc_cursor_get_max_await_time_ms (const mongoc_cursor_t *cursor); MONGOC_EXPORT (mongoc_cursor_t *) mongoc_cursor_new_from_command_reply (struct _mongoc_client_t *client, bson_t *reply, - uint32_t server_id) - BSON_GNUC_WARN_UNUSED_RESULT + uint32_t server_id) BSON_GNUC_WARN_UNUSED_RESULT BSON_GNUC_DEPRECATED_FOR (mongoc_cursor_new_from_command_reply_with_opts); MONGOC_EXPORT (mongoc_cursor_t *) mongoc_cursor_new_from_command_reply_with_opts (struct _mongoc_client_t *client, bson_t *reply, - const bson_t *opts) - BSON_GNUC_WARN_UNUSED_RESULT; + const bson_t *opts) BSON_GNUC_WARN_UNUSED_RESULT; BSON_END_DECLS diff --git a/src/libmongoc/src/mongoc/mongoc-cyrus-private.h b/src/libmongoc/src/mongoc/mongoc-cyrus-private.h index 993ea10c70..4813c66857 100644 --- a/src/libmongoc/src/mongoc/mongoc-cyrus-private.h +++ b/src/libmongoc/src/mongoc/mongoc-cyrus-private.h @@ -49,11 +49,8 @@ struct _mongoc_cyrus_t { void _mongoc_cyrus_init (mongoc_cyrus_t *sasl); bool -_mongoc_cyrus_new_from_cluster (mongoc_cyrus_t *sasl, - mongoc_cluster_t *cluster, - mongoc_stream_t *stream, - const char *hostname, - bson_error_t *error); +_mongoc_cyrus_new_from_cluster ( + mongoc_cyrus_t *sasl, mongoc_cluster_t *cluster, mongoc_stream_t *stream, const char *hostname, bson_error_t *error); int _mongoc_cyrus_log (mongoc_cyrus_t *sasl, int level, const char *message); void diff --git a/src/libmongoc/src/mongoc/mongoc-cyrus.c b/src/libmongoc/src/mongoc/mongoc-cyrus.c index 9111c76887..f0e34fcde1 100644 --- a/src/libmongoc/src/mongoc/mongoc-cyrus.c +++ b/src/libmongoc/src/mongoc/mongoc-cyrus.c @@ -30,9 +30,7 @@ #define MONGOC_LOG_DOMAIN "CYRUS-SASL" bool -_mongoc_cyrus_set_mechanism (mongoc_cyrus_t *sasl, - const char *mechanism, - bson_error_t *error) +_mongoc_cyrus_set_mechanism (mongoc_cyrus_t *sasl, const char *mechanism, bson_error_t *error) { bson_string_t *str = bson_string_new (""); const char **mechs = sasl_global_listmech (); @@ -71,10 +69,7 @@ _mongoc_cyrus_set_mechanism (mongoc_cyrus_t *sasl, static int -_mongoc_cyrus_get_pass (mongoc_cyrus_t *sasl, - int param_id, - const char **result, - unsigned *result_len) +_mongoc_cyrus_get_pass (mongoc_cyrus_t *sasl, int param_id, const char **result, unsigned *result_len) { BSON_ASSERT (sasl); BSON_ASSERT (param_id == SASL_CB_PASS); @@ -84,9 +79,7 @@ _mongoc_cyrus_get_pass (mongoc_cyrus_t *sasl, } if (result_len) { - *result_len = sasl->credentials.pass - ? (unsigned) strlen (sasl->credentials.pass) - : 0; + *result_len = sasl->credentials.pass ? (unsigned) strlen (sasl->credentials.pass) : 0; } return (sasl->credentials.pass != NULL) ? SASL_OK : SASL_FAIL; @@ -117,10 +110,7 @@ _mongoc_cyrus_canon_user (sasl_conn_t *conn, } static int -_mongoc_cyrus_get_user (mongoc_cyrus_t *sasl, - int param_id, - const char **result, - unsigned *result_len) +_mongoc_cyrus_get_user (mongoc_cyrus_t *sasl, int param_id, const char **result, unsigned *result_len) { BSON_ASSERT (sasl); BSON_ASSERT ((param_id == SASL_CB_USER) || (param_id == SASL_CB_AUTHNAME)); @@ -130,9 +120,7 @@ _mongoc_cyrus_get_user (mongoc_cyrus_t *sasl, } if (result_len) { - *result_len = sasl->credentials.user - ? (unsigned) strlen (sasl->credentials.user) - : 0; + *result_len = sasl->credentials.user ? (unsigned) strlen (sasl->credentials.user) : 0; } return (sasl->credentials.user != NULL) ? SASL_OK : SASL_FAIL; @@ -142,12 +130,11 @@ _mongoc_cyrus_get_user (mongoc_cyrus_t *sasl, void _mongoc_cyrus_init (mongoc_cyrus_t *sasl) { - sasl_callback_t callbacks[] = { - {SASL_CB_AUTHNAME, SASL_CALLBACK_FN (_mongoc_cyrus_get_user), sasl}, - {SASL_CB_USER, SASL_CALLBACK_FN (_mongoc_cyrus_get_user), sasl}, - {SASL_CB_PASS, SASL_CALLBACK_FN (_mongoc_cyrus_get_pass), sasl}, - {SASL_CB_CANON_USER, SASL_CALLBACK_FN (_mongoc_cyrus_canon_user), sasl}, - {SASL_CB_LIST_END}}; + sasl_callback_t callbacks[] = {{SASL_CB_AUTHNAME, SASL_CALLBACK_FN (_mongoc_cyrus_get_user), sasl}, + {SASL_CB_USER, SASL_CALLBACK_FN (_mongoc_cyrus_get_user), sasl}, + {SASL_CB_PASS, SASL_CALLBACK_FN (_mongoc_cyrus_get_pass), sasl}, + {SASL_CB_CANON_USER, SASL_CALLBACK_FN (_mongoc_cyrus_canon_user), sasl}, + {SASL_CB_LIST_END}}; BSON_ASSERT (sasl); @@ -167,11 +154,8 @@ _mongoc_cyrus_init (mongoc_cyrus_t *sasl) } bool -_mongoc_cyrus_new_from_cluster (mongoc_cyrus_t *sasl, - mongoc_cluster_t *cluster, - mongoc_stream_t *stream, - const char *hostname, - bson_error_t *error) +_mongoc_cyrus_new_from_cluster ( + mongoc_cyrus_t *sasl, mongoc_cluster_t *cluster, mongoc_stream_t *stream, const char *hostname, bson_error_t *error) { const char *mechanism; char real_name[BSON_HOST_NAME_MAX + 1]; @@ -188,10 +172,8 @@ _mongoc_cyrus_new_from_cluster (mongoc_cyrus_t *sasl, return false; } - _mongoc_sasl_set_pass ((mongoc_sasl_t *) sasl, - mongoc_uri_get_password (cluster->uri)); - _mongoc_sasl_set_user ((mongoc_sasl_t *) sasl, - mongoc_uri_get_username (cluster->uri)); + _mongoc_sasl_set_pass ((mongoc_sasl_t *) sasl, mongoc_uri_get_password (cluster->uri)); + _mongoc_sasl_set_user ((mongoc_sasl_t *) sasl, mongoc_uri_get_username (cluster->uri)); _mongoc_sasl_set_properties ((mongoc_sasl_t *) sasl, cluster->uri); /* @@ -206,8 +188,7 @@ _mongoc_cyrus_new_from_cluster (mongoc_cyrus_t *sasl, * See CDRIVER-323 for more information. */ if (sasl->credentials.canonicalize_host_name && - _mongoc_sasl_get_canonicalized_name ( - stream, real_name, sizeof real_name)) { + _mongoc_sasl_get_canonicalized_name (stream, real_name, sizeof real_name)) { _mongoc_sasl_set_service_host ((mongoc_sasl_t *) sasl, real_name); } else { _mongoc_sasl_set_service_host ((mongoc_sasl_t *) sasl, hostname); @@ -238,18 +219,11 @@ _mongoc_cyrus_is_failure (int status, bson_error_t *error) { bool ret = (status < 0); - TRACE ("Got status: %d ok is %d, continue=%d interact=%d\n", - status, - SASL_OK, - SASL_CONTINUE, - SASL_INTERACT); + TRACE ("Got status: %d ok is %d, continue=%d interact=%d\n", status, SASL_OK, SASL_CONTINUE, SASL_INTERACT); if (ret) { switch (status) { case SASL_NOMEM: - bson_set_error (error, - MONGOC_ERROR_SASL, - status, - "SASL Failure: insufficient memory."); + bson_set_error (error, MONGOC_ERROR_SASL, status, "SASL Failure: insufficient memory."); break; case SASL_NOMECH: { bson_string_t *str = bson_string_new ("available mechanisms: "); @@ -262,11 +236,8 @@ _mongoc_cyrus_is_failure (int status, bson_error_t *error) bson_string_append (str, ","); } } - bson_set_error (error, - MONGOC_ERROR_SASL, - status, - "SASL Failure: failure to negotiate mechanism (%s)", - str->str); + bson_set_error ( + error, MONGOC_ERROR_SASL, status, "SASL Failure: failure to negotiate mechanism (%s)", str->str); bson_string_free (str, 0); } break; case SASL_BADPARAM: @@ -277,12 +248,8 @@ _mongoc_cyrus_is_failure (int status, bson_error_t *error) "with mongo-c-driver."); break; default: - bson_set_error (error, - MONGOC_ERROR_SASL, - status, - "SASL Failure: (%d): %s", - status, - sasl_errstring (status, NULL, NULL)); + bson_set_error ( + error, MONGOC_ERROR_SASL, status, "SASL Failure: (%d): %s", status, sasl_errstring (status, NULL, NULL)); break; } } @@ -292,10 +259,7 @@ _mongoc_cyrus_is_failure (int status, bson_error_t *error) static bool -_mongoc_cyrus_start (mongoc_cyrus_t *sasl, - uint8_t **outbuf, - uint32_t *outbuflen, - bson_error_t *error) +_mongoc_cyrus_start (mongoc_cyrus_t *sasl, uint8_t **outbuf, uint32_t *outbuflen, bson_error_t *error) { const char *service_name = "mongodb"; const char *service_host = ""; @@ -316,48 +280,31 @@ _mongoc_cyrus_start (mongoc_cyrus_t *sasl, service_host = sasl->credentials.service_host; } - status = sasl_client_new ( - service_name, service_host, NULL, NULL, sasl->callbacks, 0, &sasl->conn); - TRACE ("Created new sasl client %s", - status == SASL_OK ? "successfully" : "UNSUCCESSFULLY"); + status = sasl_client_new (service_name, service_host, NULL, NULL, sasl->callbacks, 0, &sasl->conn); + TRACE ("Created new sasl client %s", status == SASL_OK ? "successfully" : "UNSUCCESSFULLY"); if (_mongoc_cyrus_is_failure (status, error)) { return false; } - status = sasl_client_start (sasl->conn, - sasl->credentials.mechanism, - &sasl->interact, - &raw, - &raw_len, - &mechanism); - TRACE ("Started the sasl client %s", - status == SASL_CONTINUE ? "successfully" : "UNSUCCESSFULLY"); + status = sasl_client_start (sasl->conn, sasl->credentials.mechanism, &sasl->interact, &raw, &raw_len, &mechanism); + TRACE ("Started the sasl client %s", status == SASL_CONTINUE ? "successfully" : "UNSUCCESSFULLY"); if (_mongoc_cyrus_is_failure (status, error)) { return false; } - if ((0 != strcasecmp (mechanism, "GSSAPI")) && - (0 != strcasecmp (mechanism, "PLAIN"))) { - bson_set_error (error, - MONGOC_ERROR_SASL, - SASL_NOMECH, - "SASL Failure: invalid mechanism \"%s\"", - mechanism); + if ((0 != strcasecmp (mechanism, "GSSAPI")) && (0 != strcasecmp (mechanism, "PLAIN"))) { + bson_set_error (error, MONGOC_ERROR_SASL, SASL_NOMECH, "SASL Failure: invalid mechanism \"%s\"", mechanism); return false; } *outbuflen = 0; - const size_t outbuf_capacity = - mcommon_b64_ntop_calculate_target_size (raw_len); + const size_t outbuf_capacity = mcommon_b64_ntop_calculate_target_size (raw_len); *outbuf = bson_malloc (outbuf_capacity); - const int b64_ret = mcommon_b64_ntop ( - (uint8_t *) raw, raw_len, (char *) *outbuf, outbuf_capacity); + const int b64_ret = mcommon_b64_ntop ((uint8_t *) raw, raw_len, (char *) *outbuf, outbuf_capacity); if (b64_ret < 0) { - bson_set_error (error, - MONGOC_ERROR_SASL, - MONGOC_ERROR_CLIENT_AUTHENTICATE, - "Unable to base64 encode client SASL message"); + bson_set_error ( + error, MONGOC_ERROR_SASL, MONGOC_ERROR_CLIENT_AUTHENTICATE, "Unable to base64 encode client SASL message"); return false; } else { BSON_ASSERT (bson_in_range_signed (uint32_t, b64_ret)); @@ -393,10 +340,7 @@ _mongoc_cyrus_step (mongoc_cyrus_t *sasl, if (sasl->step == 1) { return _mongoc_cyrus_start (sasl, outbuf, outbuflen, error); } else if (sasl->step >= 10) { - bson_set_error (error, - MONGOC_ERROR_SASL, - SASL_NOTDONE, - "SASL Failure: maximum steps detected"); + bson_set_error (error, MONGOC_ERROR_SASL, SASL_NOTDONE, "SASL Failure: maximum steps detected"); return false; } @@ -411,18 +355,14 @@ _mongoc_cyrus_step (mongoc_cyrus_t *sasl, } unsigned int decoded_len = 0; - const size_t decoded_capacity = - mcommon_b64_pton_calculate_target_size (inbuflen); + const size_t decoded_capacity = mcommon_b64_pton_calculate_target_size (inbuflen); char *const decoded = bson_malloc (decoded_capacity); { - const int b64_ret = mcommon_b64_pton ( - (char *) inbuf, (uint8_t *) decoded, decoded_capacity); + const int b64_ret = mcommon_b64_pton ((char *) inbuf, (uint8_t *) decoded, decoded_capacity); if (b64_ret < 0) { - bson_set_error (error, - MONGOC_ERROR_SASL, - MONGOC_ERROR_CLIENT_AUTHENTICATE, - "Unable to base64 decode client SASL message"); + bson_set_error ( + error, MONGOC_ERROR_SASL, MONGOC_ERROR_CLIENT_AUTHENTICATE, "Unable to base64 decode client SASL message"); bson_free (decoded); bson_free (*outbuf); *outbuf = NULL; @@ -435,27 +375,21 @@ _mongoc_cyrus_step (mongoc_cyrus_t *sasl, } TRACE ("%s", "Running client_step"); - status = sasl_client_step ( - sasl->conn, decoded, decoded_len, &sasl->interact, &raw, &rawlen); - TRACE ("%s sent a client step", - status == SASL_OK ? "Successfully" : "UNSUCCESSFULLY"); + status = sasl_client_step (sasl->conn, decoded, decoded_len, &sasl->interact, &raw, &rawlen); + TRACE ("%s sent a client step", status == SASL_OK ? "Successfully" : "UNSUCCESSFULLY"); if (_mongoc_cyrus_is_failure (status, error)) { bson_free (decoded); return false; } *outbuflen = 0; - const size_t outbuf_capacity = - mcommon_b64_ntop_calculate_target_size (rawlen); + const size_t outbuf_capacity = mcommon_b64_ntop_calculate_target_size (rawlen); *outbuf = bson_malloc0 (outbuf_capacity); { - const int b64_ret = mcommon_b64_ntop ( - (const uint8_t *) raw, rawlen, (char *) *outbuf, outbuf_capacity); + const int b64_ret = mcommon_b64_ntop ((const uint8_t *) raw, rawlen, (char *) *outbuf, outbuf_capacity); if (b64_ret < 0) { - bson_set_error (error, - MONGOC_ERROR_SASL, - MONGOC_ERROR_CLIENT_AUTHENTICATE, - "Unable to base64 encode client SASL message"); + bson_set_error ( + error, MONGOC_ERROR_SASL, MONGOC_ERROR_CLIENT_AUTHENTICATE, "Unable to base64 encode client SASL message"); bson_free (decoded); bson_free (*outbuf); *outbuf = NULL; diff --git a/src/libmongoc/src/mongoc/mongoc-database-private.h b/src/libmongoc/src/mongoc/mongoc-database-private.h index 640264303f..1934bca2aa 100644 --- a/src/libmongoc/src/mongoc/mongoc-database-private.h +++ b/src/libmongoc/src/mongoc/mongoc-database-private.h @@ -50,22 +50,16 @@ _mongoc_database_new (mongoc_client_t *client, * encryptedFields is always initialized on return. */ bool -_mongoc_get_encryptedFields_from_map (mongoc_client_t *client, - const char *dbName, - const char *collName, - bson_t *encryptedFields, - bson_error_t *error); +_mongoc_get_encryptedFields_from_map ( + mongoc_client_t *client, const char *dbName, const char *collName, bson_t *encryptedFields, bson_error_t *error); /* _mongoc_get_encryptedFields_from_map checks the collection has an * encryptedFields by running listCollections. * encryptedFields is always initialized on return. */ bool -_mongoc_get_encryptedFields_from_server (mongoc_client_t *client, - const char *dbName, - const char *collName, - bson_t *encryptedFields, - bson_error_t *error); +_mongoc_get_encryptedFields_from_server ( + mongoc_client_t *client, const char *dbName, const char *collName, bson_t *encryptedFields, bson_error_t *error); /** * @brief Look up the encryptedFields to use for the given collection. @@ -103,11 +97,10 @@ _mongoc_get_collection_encryptedFields (mongoc_client_t *client, /* _mongoc_get_encryptedField_state_collection returns the state collection * name. Returns NULL on error. */ char * -_mongoc_get_encryptedField_state_collection ( - const bson_t *encryptedFields, - const char *data_collection, - const char *state_collection_suffix, - bson_error_t *error); +_mongoc_get_encryptedField_state_collection (const bson_t *encryptedFields, + const char *data_collection, + const char *state_collection_suffix, + bson_error_t *error); BSON_END_DECLS diff --git a/src/libmongoc/src/mongoc/mongoc-database.c b/src/libmongoc/src/mongoc/mongoc-database.c index 46fc2d6204..4e4e28f98b 100644 --- a/src/libmongoc/src/mongoc/mongoc-database.c +++ b/src/libmongoc/src/mongoc/mongoc-database.c @@ -72,12 +72,9 @@ _mongoc_database_new (mongoc_client_t *client, db = (mongoc_database_t *) bson_malloc0 (sizeof *db); db->client = client; - db->write_concern = write_concern ? mongoc_write_concern_copy (write_concern) - : mongoc_write_concern_new (); - db->read_concern = read_concern ? mongoc_read_concern_copy (read_concern) - : mongoc_read_concern_new (); - db->read_prefs = read_prefs ? mongoc_read_prefs_copy (read_prefs) - : mongoc_read_prefs_new (MONGOC_READ_PRIMARY); + db->write_concern = write_concern ? mongoc_write_concern_copy (write_concern) : mongoc_write_concern_new (); + db->read_concern = read_concern ? mongoc_read_concern_copy (read_concern) : mongoc_read_concern_new (); + db->read_prefs = read_prefs ? mongoc_read_prefs_copy (read_prefs) : mongoc_read_prefs_new (MONGOC_READ_PRIMARY); db->name = bson_strdup (name); @@ -174,11 +171,8 @@ mongoc_database_copy (mongoc_database_t *database) BSON_ASSERT_PARAM (database); - RETURN (_mongoc_database_new (database->client, - database->name, - database->read_prefs, - database->read_concern, - database->write_concern)); + RETURN (_mongoc_database_new ( + database->client, database->name, database->read_prefs, database->read_concern, database->write_concern)); } mongoc_cursor_t * @@ -213,8 +207,7 @@ mongoc_database_command (mongoc_database_t *database, */ /* flags, skip, limit, batch_size, fields are unused */ - cursor = _mongoc_cursor_cmd_deprecated_new ( - database->client, ns, command, read_prefs); + cursor = _mongoc_cursor_cmd_deprecated_new (database->client, ns, command, read_prefs); bson_free (ns); return cursor; } @@ -276,11 +269,8 @@ mongoc_database_read_command_with_opts (mongoc_database_t *database, bool -mongoc_database_write_command_with_opts (mongoc_database_t *database, - const bson_t *command, - const bson_t *opts, - bson_t *reply, - bson_error_t *error) +mongoc_database_write_command_with_opts ( + mongoc_database_t *database, const bson_t *command, const bson_t *opts, bson_t *reply, bson_error_t *error) { return _mongoc_client_command_with_opts (database->client, database->name, @@ -298,13 +288,12 @@ mongoc_database_write_command_with_opts (mongoc_database_t *database, bool -mongoc_database_read_write_command_with_opts ( - mongoc_database_t *database, - const bson_t *command, - const mongoc_read_prefs_t *read_prefs /* IGNORED */, - const bson_t *opts, - bson_t *reply, - bson_error_t *error) +mongoc_database_read_write_command_with_opts (mongoc_database_t *database, + const bson_t *command, + const mongoc_read_prefs_t *read_prefs /* IGNORED */, + const bson_t *opts, + bson_t *reply, + bson_error_t *error) { return _mongoc_client_command_with_opts (database->client, database->name, @@ -371,9 +360,7 @@ mongoc_database_drop (mongoc_database_t *database, bson_error_t *error) bool -mongoc_database_drop_with_opts (mongoc_database_t *database, - const bson_t *opts, - bson_error_t *error) +mongoc_database_drop_with_opts (mongoc_database_t *database, const bson_t *opts, bson_error_t *error) { bool ret; bson_t cmd; @@ -402,9 +389,7 @@ mongoc_database_drop_with_opts (mongoc_database_t *database, bool -mongoc_database_remove_user (mongoc_database_t *database, - const char *username, - bson_error_t *error) +mongoc_database_remove_user (mongoc_database_t *database, const char *username, bson_error_t *error) { bson_t cmd; bool ret; @@ -424,8 +409,7 @@ mongoc_database_remove_user (mongoc_database_t *database, bool -mongoc_database_remove_all_users (mongoc_database_t *database, - bson_error_t *error) +mongoc_database_remove_all_users (mongoc_database_t *database, bson_error_t *error) { bson_t cmd; bool ret; @@ -537,8 +521,7 @@ mongoc_database_get_read_prefs (const mongoc_database_t *database) /* IN */ */ void -mongoc_database_set_read_prefs (mongoc_database_t *database, - const mongoc_read_prefs_t *read_prefs) +mongoc_database_set_read_prefs (mongoc_database_t *database, const mongoc_read_prefs_t *read_prefs) { BSON_ASSERT_PARAM (database); @@ -595,8 +578,7 @@ mongoc_database_get_read_concern (const mongoc_database_t *database) */ void -mongoc_database_set_read_concern (mongoc_database_t *database, - const mongoc_read_concern_t *read_concern) +mongoc_database_set_read_concern (mongoc_database_t *database, const mongoc_read_concern_t *read_concern) { BSON_ASSERT_PARAM (database); @@ -653,8 +635,7 @@ mongoc_database_get_write_concern (const mongoc_database_t *database) */ void -mongoc_database_set_write_concern (mongoc_database_t *database, - const mongoc_write_concern_t *write_concern) +mongoc_database_set_write_concern (mongoc_database_t *database, const mongoc_write_concern_t *write_concern) { BSON_ASSERT_PARAM (database); @@ -687,9 +668,7 @@ mongoc_database_set_write_concern (mongoc_database_t *database, * Returns: %true if @name exists, otherwise %false. @error may be set. */ bool -mongoc_database_has_collection (mongoc_database_t *database, - const char *name, - bson_error_t *error) +mongoc_database_has_collection (mongoc_database_t *database, const char *name, bson_error_t *error) { bson_iter_t col_iter; bool ret = false; @@ -714,9 +693,7 @@ mongoc_database_has_collection (mongoc_database_t *database, cursor = mongoc_database_find_collections_with_opts (database, &opts); while (mongoc_cursor_next (cursor, &doc)) { - if (bson_iter_init (&col_iter, doc) && - bson_iter_find (&col_iter, "name") && - BSON_ITER_HOLDS_UTF8 (&col_iter) && + if (bson_iter_init (&col_iter, doc) && bson_iter_find (&col_iter, "name") && BSON_ITER_HOLDS_UTF8 (&col_iter) && (cur_name = bson_iter_utf8 (&col_iter, NULL))) { if (!strcmp (cur_name, name)) { ret = true; @@ -736,9 +713,7 @@ mongoc_database_has_collection (mongoc_database_t *database, mongoc_cursor_t * -mongoc_database_find_collections (mongoc_database_t *database, - const bson_t *filter, - bson_error_t *error) +mongoc_database_find_collections (mongoc_database_t *database, const bson_t *filter, bson_error_t *error) { bson_t opts = BSON_INITIALIZER; mongoc_cursor_t *cursor; @@ -747,10 +722,7 @@ mongoc_database_find_collections (mongoc_database_t *database, if (filter) { if (!BSON_APPEND_DOCUMENT (&opts, "filter", filter)) { - bson_set_error (error, - MONGOC_ERROR_BSON, - MONGOC_ERROR_BSON_INVALID, - "Invalid 'filter' parameter."); + bson_set_error (error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "Invalid 'filter' parameter."); bson_destroy (&opts); return NULL; } @@ -771,8 +743,7 @@ mongoc_database_find_collections (mongoc_database_t *database, mongoc_cursor_t * -mongoc_database_find_collections_with_opts (mongoc_database_t *database, - const bson_t *opts) +mongoc_database_find_collections_with_opts (mongoc_database_t *database, const bson_t *opts) { mongoc_cursor_t *cursor; bson_t cmd = BSON_INITIALIZER; @@ -783,8 +754,7 @@ mongoc_database_find_collections_with_opts (mongoc_database_t *database, /* Enumerate Collections Spec: "run listCollections on the primary node in * replicaset mode" */ - cursor = _mongoc_cursor_cmd_new ( - database->client, database->name, &cmd, opts, NULL, NULL, NULL); + cursor = _mongoc_cursor_cmd_new (database->client, database->name, &cmd, opts, NULL, NULL, NULL); if (cursor->error.domain == 0) { _mongoc_cursor_prime (cursor); } @@ -795,18 +765,14 @@ mongoc_database_find_collections_with_opts (mongoc_database_t *database, char ** -mongoc_database_get_collection_names (mongoc_database_t *database, - bson_error_t *error) +mongoc_database_get_collection_names (mongoc_database_t *database, bson_error_t *error) { - return mongoc_database_get_collection_names_with_opts ( - database, NULL, error); + return mongoc_database_get_collection_names_with_opts (database, NULL, error); } char ** -mongoc_database_get_collection_names_with_opts (mongoc_database_t *database, - const bson_t *opts, - bson_error_t *error) +mongoc_database_get_collection_names_with_opts (mongoc_database_t *database, const bson_t *opts, bson_error_t *error) { bson_t opts_copy; bson_iter_t col; @@ -836,8 +802,8 @@ mongoc_database_get_collection_names_with_opts (mongoc_database_t *database, _mongoc_array_init (&strv_buf, sizeof (char *)); while (mongoc_cursor_next (cursor, &doc)) { - if (bson_iter_init (&col, doc) && bson_iter_find (&col, "name") && - BSON_ITER_HOLDS_UTF8 (&col) && (name = bson_iter_utf8 (&col, NULL))) { + if (bson_iter_init (&col, doc) && bson_iter_find (&col, "name") && BSON_ITER_HOLDS_UTF8 (&col) && + (name = bson_iter_utf8 (&col, NULL))) { namecopy = bson_strdup (name); _mongoc_array_append_val (&strv_buf, namecopy); } @@ -862,10 +828,7 @@ mongoc_database_get_collection_names_with_opts (mongoc_database_t *database, } static mongoc_collection_t * -create_collection (mongoc_database_t *database, - const char *name, - const bson_t *opts, - bson_error_t *error) +create_collection (mongoc_database_t *database, const char *name, const bson_t *opts, bson_error_t *error) { mongoc_collection_t *collection = NULL; bson_iter_t iter; @@ -876,11 +839,8 @@ create_collection (mongoc_database_t *database, BSON_ASSERT_PARAM (name); if (strchr (name, '$')) { - bson_set_error (error, - MONGOC_ERROR_NAMESPACE, - MONGOC_ERROR_NAMESPACE_INVALID, - "The namespace \"%s\" is invalid.", - name); + bson_set_error ( + error, MONGOC_ERROR_NAMESPACE, MONGOC_ERROR_NAMESPACE_INVALID, "The namespace \"%s\" is invalid.", name); return NULL; } @@ -905,11 +865,10 @@ create_collection (mongoc_database_t *database, return NULL; } if (!capped) { - bson_set_error ( - error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "The \"size\" parameter requires {\"capped\": true}"); + bson_set_error (error, + MONGOC_ERROR_COMMAND, + MONGOC_ERROR_COMMAND_INVALID_ARG, + "The \"size\" parameter requires {\"capped\": true}"); return NULL; } } @@ -923,22 +882,20 @@ create_collection (mongoc_database_t *database, return NULL; } if (!capped) { - bson_set_error ( - error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "The \"max\" parameter requires {\"capped\": true}"); + bson_set_error (error, + MONGOC_ERROR_COMMAND, + MONGOC_ERROR_COMMAND_INVALID_ARG, + "The \"max\" parameter requires {\"capped\": true}"); return NULL; } } if (bson_iter_init_find (&iter, opts, "storageEngine")) { if (!BSON_ITER_HOLDS_DOCUMENT (&iter)) { - bson_set_error ( - error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "The \"storageEngine\" parameter must be a document"); + bson_set_error (error, + MONGOC_ERROR_COMMAND, + MONGOC_ERROR_COMMAND_INVALID_ARG, + "The \"storageEngine\" parameter must be a document"); return NULL; } @@ -955,11 +912,10 @@ create_collection (mongoc_database_t *database, if (bson_iter_find (&iter, "configString")) { if (!BSON_ITER_HOLDS_UTF8 (&iter)) { - bson_set_error ( - error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "The \"configString\" parameter must be a string"); + bson_set_error (error, + MONGOC_ERROR_COMMAND, + MONGOC_ERROR_COMMAND_INVALID_ARG, + "The \"configString\" parameter must be a string"); return NULL; } } else { @@ -990,12 +946,8 @@ create_collection (mongoc_database_t *database, database->write_concern, NULL, /* reply */ error)) { - collection = _mongoc_collection_new (database->client, - database->name, - name, - database->read_prefs, - database->read_concern, - database->write_concern); + collection = _mongoc_collection_new ( + database->client, database->name, name, database->read_prefs, database->read_concern, database->write_concern); } bson_destroy (&cmd); @@ -1004,11 +956,10 @@ create_collection (mongoc_database_t *database, } char * -_mongoc_get_encryptedField_state_collection ( - const bson_t *encryptedFields, - const char *data_collection, - const char *state_collection_suffix, - bson_error_t *error) +_mongoc_get_encryptedField_state_collection (const bson_t *encryptedFields, + const char *data_collection, + const char *state_collection_suffix, + bson_error_t *error) { bson_iter_t iter; const char *fieldName = NULL; @@ -1038,8 +989,7 @@ _mongoc_get_encryptedField_state_collection ( } return bson_strdup (bson_iter_utf8 (&iter, NULL)); } - return bson_strdup_printf ( - "enxcol_.%s.%s", data_collection, state_collection_suffix); + return bson_strdup_printf ("enxcol_.%s.%s", data_collection, state_collection_suffix); } static bool @@ -1054,23 +1004,13 @@ create_encField_state_collection (mongoc_database_t *database, bool ok = false; bson_t opts = BSON_INITIALIZER; - state_collection = _mongoc_get_encryptedField_state_collection ( - encryptedFields, data_collection, state_collection_suffix, error); + state_collection = + _mongoc_get_encryptedField_state_collection (encryptedFields, data_collection, state_collection_suffix, error); if (!state_collection) { goto fail; } - BCON_APPEND (&opts, - "clusteredIndex", - "{", - "key", - "{", - "_id", - BCON_INT32 (1), - "}", - "unique", - BCON_BOOL (true), - "}"); + BCON_APPEND (&opts, "clusteredIndex", "{", "key", "{", "_id", BCON_INT32 (1), "}", "unique", BCON_BOOL (true), "}"); collection = create_collection (database, state_collection, &opts, error); if (collection == NULL) { @@ -1098,36 +1038,31 @@ create_collection_with_encryptedFields (mongoc_database_t *database, // Check the wire version to ensure server is 7.0.0 or newer. { - mongoc_server_stream_t *stream = - mongoc_cluster_stream_for_writes (&database->client->cluster, - NULL /* client session */, - NULL /* deprioritized servers */, - NULL /* reply */, - error); + mongoc_server_stream_t *stream = mongoc_cluster_stream_for_writes (&database->client->cluster, + NULL /* client session */, + NULL /* deprioritized servers */, + NULL /* reply */, + error); if (!stream) { goto fail; } if (stream->sd->max_wire_version < WIRE_VERSION_7_0) { - bson_set_error ( - error, - MONGOC_ERROR_PROTOCOL, - MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION, - "Driver support of Queryable Encryption is incompatible " - "with server. Upgrade server to use Queryable Encryption. " - "Got maxWireVersion %" PRId32 " but need maxWireVersion >= %d", - stream->sd->max_wire_version, - WIRE_VERSION_7_0); + bson_set_error (error, + MONGOC_ERROR_PROTOCOL, + MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION, + "Driver support of Queryable Encryption is incompatible " + "with server. Upgrade server to use Queryable Encryption. " + "Got maxWireVersion %" PRId32 " but need maxWireVersion >= %d", + stream->sd->max_wire_version, + WIRE_VERSION_7_0); mongoc_server_stream_cleanup (stream); goto fail; } mongoc_server_stream_cleanup (stream); } - bool state_collections_ok = - create_encField_state_collection ( - database, encryptedFields, name, "esc", error) && - create_encField_state_collection ( - database, encryptedFields, name, "ecoc", error); + bool state_collections_ok = create_encField_state_collection (database, encryptedFields, name, "esc", error) && + create_encField_state_collection (database, encryptedFields, name, "ecoc", error); if (!state_collections_ok) { // Failed to create one or more state collections goto fail; @@ -1136,10 +1071,8 @@ create_collection_with_encryptedFields (mongoc_database_t *database, /* Create data collection. */ cc_opts = bson_copy (opts); if (!BSON_APPEND_DOCUMENT (cc_opts, "encryptedFields", encryptedFields)) { - bson_set_error (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "unable to append encryptedFields"); + bson_set_error ( + error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "unable to append encryptedFields"); goto fail; } dataCollection = create_collection (database, name, cc_opts, error); @@ -1151,8 +1084,8 @@ create_collection_with_encryptedFields (mongoc_database_t *database, { bson_t *keys = BCON_NEW ("__safeContent__", BCON_INT32 (1)); mongoc_index_model_t *im = mongoc_index_model_new (keys, NULL /* opts */); - ok = mongoc_collection_create_indexes_with_opts ( - dataCollection, &im, 1, NULL /* opts */, NULL /* reply */, error); + ok = + mongoc_collection_create_indexes_with_opts (dataCollection, &im, 1, NULL /* opts */, NULL /* reply */, error); mongoc_index_model_destroy (im); bson_destroy (keys); if (!ok) { @@ -1172,11 +1105,8 @@ create_collection_with_encryptedFields (mongoc_database_t *database, } bool -_mongoc_get_encryptedFields_from_map (mongoc_client_t *client, - const char *dbName, - const char *collName, - bson_t *encryptedFields, - bson_error_t *error) +_mongoc_get_encryptedFields_from_map ( + mongoc_client_t *client, const char *dbName, const char *collName, bson_t *encryptedFields, bson_error_t *error) { BSON_ASSERT_PARAM (client); @@ -1207,11 +1137,8 @@ _mongoc_get_encryptedFields_from_map (mongoc_client_t *client, } bool -_mongoc_get_encryptedFields_from_server (mongoc_client_t *client, - const char *dbName, - const char *collName, - bson_t *encryptedFields, - bson_error_t *error) +_mongoc_get_encryptedFields_from_server ( + mongoc_client_t *client, const char *dbName, const char *collName, bson_t *encryptedFields, bson_error_t *error) { BSON_ASSERT_PARAM (client); @@ -1232,10 +1159,8 @@ _mongoc_get_encryptedFields_from_server (mongoc_client_t *client, /* Check if the collInfo has options.encryptedFields. */ bson_iter_t iter; if (!bson_iter_init (&iter, collInfo)) { - bson_set_error (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "unable to iterate listCollections result"); + bson_set_error ( + error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "unable to iterate listCollections result"); goto fail; } @@ -1281,14 +1206,12 @@ _mongoc_get_collection_encryptedFields (mongoc_client_t *client, if (opts) { // We have collection options, which may have encryptedFields in it bool found = false; - bsonParse ( - *opts, - find (key ("encryptedFields"), - if (not(type (doc)), - then (error ("'encryptedFields' should be a document"))), - // Update encryptedFields to be a reference to the subdocument: - storeDocRef (*encryptedFields), - do (found = true))); + bsonParse (*opts, + find (key ("encryptedFields"), + if (not(type (doc)), then (error ("'encryptedFields' should be a document"))), + // Update encryptedFields to be a reference to the subdocument: + storeDocRef (*encryptedFields), + do (found = true))); if (bsonParseError) { // Error while parsing bson_set_error (error, @@ -1307,8 +1230,7 @@ _mongoc_get_collection_encryptedFields (mongoc_client_t *client, // Look in the encryptedFieldsMap based on this collection name if (checkEncryptedFieldsMap && - !_mongoc_get_encryptedFields_from_map ( - client, dbName, collName, encryptedFields, error)) { + !_mongoc_get_encryptedFields_from_map (client, dbName, collName, encryptedFields, error)) { // Error during lookup. return false; } @@ -1330,14 +1252,13 @@ mongoc_database_create_collection (mongoc_database_t *database, BSON_ASSERT (error || true); bson_t encryptedFields = BSON_INITIALIZER; - if (!_mongoc_get_collection_encryptedFields ( - database->client, - mongoc_database_get_name (database), - name, - opts, - true /* checkEncryptedFieldsMap */, - &encryptedFields, - error)) { + if (!_mongoc_get_collection_encryptedFields (database->client, + mongoc_database_get_name (database), + name, + opts, + true /* checkEncryptedFieldsMap */, + &encryptedFields, + error)) { // Error during fields lookup bson_destroy (&encryptedFields); return false; @@ -1345,16 +1266,10 @@ mongoc_database_create_collection (mongoc_database_t *database, if (!bson_empty (&encryptedFields)) { // Clone 'opts' without the encryptedFields element - bsonBuildDecl ( - opts_without_encryptedFields, - if (opts, then (insert (*opts, not(key ("encryptedFields")))))); + bsonBuildDecl (opts_without_encryptedFields, if (opts, then (insert (*opts, not(key ("encryptedFields")))))); - mongoc_collection_t *ret = - create_collection_with_encryptedFields (database, - name, - &opts_without_encryptedFields, - &encryptedFields, - error); + mongoc_collection_t *ret = create_collection_with_encryptedFields ( + database, name, &opts_without_encryptedFields, &encryptedFields, error); bson_destroy (&encryptedFields); bson_destroy (&opts_without_encryptedFields); @@ -1367,8 +1282,7 @@ mongoc_database_create_collection (mongoc_database_t *database, mongoc_collection_t * -mongoc_database_get_collection (mongoc_database_t *database, - const char *collection) +mongoc_database_get_collection (mongoc_database_t *database, const char *collection) { BSON_ASSERT_PARAM (database); BSON_ASSERT_PARAM (collection); @@ -1392,9 +1306,7 @@ mongoc_database_get_name (mongoc_database_t *database) mongoc_change_stream_t * -mongoc_database_watch (const mongoc_database_t *db, - const bson_t *pipeline, - const bson_t *opts) +mongoc_database_watch (const mongoc_database_t *db, const bson_t *pipeline, const bson_t *opts) { return _mongoc_change_stream_new_from_database (db, pipeline, opts); } diff --git a/src/libmongoc/src/mongoc/mongoc-database.h b/src/libmongoc/src/mongoc/mongoc-database.h index e958cd3968..763eaef3cd 100644 --- a/src/libmongoc/src/mongoc/mongoc-database.h +++ b/src/libmongoc/src/mongoc/mongoc-database.h @@ -37,12 +37,9 @@ typedef struct _mongoc_database_t mongoc_database_t; MONGOC_EXPORT (const char *) mongoc_database_get_name (mongoc_database_t *database); MONGOC_EXPORT (bool) -mongoc_database_remove_user (mongoc_database_t *database, - const char *username, - bson_error_t *error); +mongoc_database_remove_user (mongoc_database_t *database, const char *username, bson_error_t *error); MONGOC_EXPORT (bool) -mongoc_database_remove_all_users (mongoc_database_t *database, - bson_error_t *error); +mongoc_database_remove_all_users (mongoc_database_t *database, bson_error_t *error); MONGOC_EXPORT (bool) mongoc_database_add_user (mongoc_database_t *database, const char *username, @@ -56,8 +53,7 @@ MONGOC_EXPORT (mongoc_cursor_t *) mongoc_database_aggregate (mongoc_database_t *db, const bson_t *pipeline, const bson_t *opts, - const mongoc_read_prefs_t *read_prefs) - BSON_GNUC_WARN_UNUSED_RESULT; + const mongoc_read_prefs_t *read_prefs) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (mongoc_database_t *) mongoc_database_copy (mongoc_database_t *database) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (mongoc_cursor_t *) @@ -68,8 +64,7 @@ mongoc_database_command (mongoc_database_t *database, uint32_t batch_size, const bson_t *command, const bson_t *fields, - const mongoc_read_prefs_t *read_prefs) - BSON_GNUC_WARN_UNUSED_RESULT; + const mongoc_read_prefs_t *read_prefs) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (bool) mongoc_database_read_command_with_opts (mongoc_database_t *database, const bson_t *command, @@ -78,19 +73,15 @@ mongoc_database_read_command_with_opts (mongoc_database_t *database, bson_t *reply, bson_error_t *error); MONGOC_EXPORT (bool) -mongoc_database_write_command_with_opts (mongoc_database_t *database, - const bson_t *command, - const bson_t *opts, - bson_t *reply, - bson_error_t *error); +mongoc_database_write_command_with_opts ( + mongoc_database_t *database, const bson_t *command, const bson_t *opts, bson_t *reply, bson_error_t *error); MONGOC_EXPORT (bool) -mongoc_database_read_write_command_with_opts ( - mongoc_database_t *database, - const bson_t *command, - const mongoc_read_prefs_t *read_prefs /* IGNORED */, - const bson_t *opts, - bson_t *reply, - bson_error_t *error); +mongoc_database_read_write_command_with_opts (mongoc_database_t *database, + const bson_t *command, + const mongoc_read_prefs_t *read_prefs /* IGNORED */, + const bson_t *opts, + bson_t *reply, + bson_error_t *error); MONGOC_EXPORT (bool) mongoc_database_command_with_opts (mongoc_database_t *database, const bson_t *command, @@ -107,57 +98,43 @@ mongoc_database_command_simple (mongoc_database_t *database, MONGOC_EXPORT (bool) mongoc_database_drop (mongoc_database_t *database, bson_error_t *error); MONGOC_EXPORT (bool) -mongoc_database_drop_with_opts (mongoc_database_t *database, - const bson_t *opts, - bson_error_t *error); +mongoc_database_drop_with_opts (mongoc_database_t *database, const bson_t *opts, bson_error_t *error); MONGOC_EXPORT (bool) -mongoc_database_has_collection (mongoc_database_t *database, - const char *name, - bson_error_t *error); +mongoc_database_has_collection (mongoc_database_t *database, const char *name, bson_error_t *error); MONGOC_EXPORT (mongoc_collection_t *) mongoc_database_create_collection (mongoc_database_t *database, const char *name, const bson_t *options, - bson_error_t *error) - BSON_GNUC_WARN_UNUSED_RESULT; + bson_error_t *error) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (const mongoc_read_prefs_t *) mongoc_database_get_read_prefs (const mongoc_database_t *database); MONGOC_EXPORT (void) -mongoc_database_set_read_prefs (mongoc_database_t *database, - const mongoc_read_prefs_t *read_prefs); +mongoc_database_set_read_prefs (mongoc_database_t *database, const mongoc_read_prefs_t *read_prefs); MONGOC_EXPORT (const mongoc_write_concern_t *) mongoc_database_get_write_concern (const mongoc_database_t *database); MONGOC_EXPORT (void) -mongoc_database_set_write_concern (mongoc_database_t *database, - const mongoc_write_concern_t *write_concern); +mongoc_database_set_write_concern (mongoc_database_t *database, const mongoc_write_concern_t *write_concern); MONGOC_EXPORT (const mongoc_read_concern_t *) mongoc_database_get_read_concern (const mongoc_database_t *database); MONGOC_EXPORT (void) -mongoc_database_set_read_concern (mongoc_database_t *database, - const mongoc_read_concern_t *read_concern); +mongoc_database_set_read_concern (mongoc_database_t *database, const mongoc_read_concern_t *read_concern); MONGOC_EXPORT (mongoc_cursor_t *) mongoc_database_find_collections (mongoc_database_t *database, const bson_t *filter, - bson_error_t *error) - BSON_GNUC_WARN_UNUSED_RESULT + bson_error_t *error) BSON_GNUC_WARN_UNUSED_RESULT BSON_GNUC_DEPRECATED_FOR (mongoc_database_find_collections_with_opts); MONGOC_EXPORT (mongoc_cursor_t *) mongoc_database_find_collections_with_opts (mongoc_database_t *database, - const bson_t *opts) - BSON_GNUC_WARN_UNUSED_RESULT; + const bson_t *opts) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (char **) -mongoc_database_get_collection_names (mongoc_database_t *database, - bson_error_t *error) - BSON_GNUC_WARN_UNUSED_RESULT +mongoc_database_get_collection_names (mongoc_database_t *database, bson_error_t *error) BSON_GNUC_WARN_UNUSED_RESULT BSON_GNUC_DEPRECATED_FOR (mongoc_database_get_collection_names_with_opts); MONGOC_EXPORT (char **) mongoc_database_get_collection_names_with_opts (mongoc_database_t *database, const bson_t *opts, - bson_error_t *error) - BSON_GNUC_WARN_UNUSED_RESULT; + bson_error_t *error) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (mongoc_collection_t *) -mongoc_database_get_collection (mongoc_database_t *database, - const char *name) BSON_GNUC_WARN_UNUSED_RESULT; +mongoc_database_get_collection (mongoc_database_t *database, const char *name) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (mongoc_change_stream_t *) mongoc_database_watch (const mongoc_database_t *db, const bson_t *pipeline, diff --git a/src/libmongoc/src/mongoc/mongoc-deprioritized-servers-private.h b/src/libmongoc/src/mongoc/mongoc-deprioritized-servers-private.h index 0e8122e8d9..d3b98c5337 100644 --- a/src/libmongoc/src/mongoc/mongoc-deprioritized-servers-private.h +++ b/src/libmongoc/src/mongoc/mongoc-deprioritized-servers-private.h @@ -36,12 +36,10 @@ void mongoc_deprioritized_servers_destroy (mongoc_deprioritized_servers_t *ds); void -mongoc_deprioritized_servers_add (mongoc_deprioritized_servers_t *ds, - const mongoc_server_description_t *sd); +mongoc_deprioritized_servers_add (mongoc_deprioritized_servers_t *ds, const mongoc_server_description_t *sd); bool -mongoc_deprioritized_servers_contains (const mongoc_deprioritized_servers_t *ds, - const mongoc_server_description_t *sd); +mongoc_deprioritized_servers_contains (const mongoc_deprioritized_servers_t *ds, const mongoc_server_description_t *sd); BSON_END_DECLS diff --git a/src/libmongoc/src/mongoc/mongoc-deprioritized-servers.c b/src/libmongoc/src/mongoc/mongoc-deprioritized-servers.c index 71369f595a..5f0007739f 100644 --- a/src/libmongoc/src/mongoc/mongoc-deprioritized-servers.c +++ b/src/libmongoc/src/mongoc/mongoc-deprioritized-servers.c @@ -35,24 +35,19 @@ mongoc_deprioritized_servers_destroy (mongoc_deprioritized_servers_t *ds) } void -mongoc_deprioritized_servers_add (mongoc_deprioritized_servers_t *ds, - const mongoc_server_description_t *sd) +mongoc_deprioritized_servers_add (mongoc_deprioritized_servers_t *ds, const mongoc_server_description_t *sd) { BSON_ASSERT_PARAM (ds); BSON_ASSERT_PARAM (sd); - mongoc_set_add (ds->ids, - mongoc_server_description_id (sd), - MONGOC_DEPRIORITIZED_SERVERS_ITEM_VALUE); + mongoc_set_add (ds->ids, mongoc_server_description_id (sd), MONGOC_DEPRIORITIZED_SERVERS_ITEM_VALUE); } bool -mongoc_deprioritized_servers_contains (const mongoc_deprioritized_servers_t *ds, - const mongoc_server_description_t *sd) +mongoc_deprioritized_servers_contains (const mongoc_deprioritized_servers_t *ds, const mongoc_server_description_t *sd) { BSON_ASSERT_PARAM (ds); BSON_ASSERT_PARAM (sd); - return mongoc_set_get_const (ds->ids, mongoc_server_description_id (sd)) == - MONGOC_DEPRIORITIZED_SERVERS_ITEM_VALUE; + return mongoc_set_get_const (ds->ids, mongoc_server_description_id (sd)) == MONGOC_DEPRIORITIZED_SERVERS_ITEM_VALUE; } diff --git a/src/libmongoc/src/mongoc/mongoc-errno-private.h b/src/libmongoc/src/mongoc/mongoc-errno-private.h index 3a8125d8c2..514f03b93c 100644 --- a/src/libmongoc/src/mongoc/mongoc-errno-private.h +++ b/src/libmongoc/src/mongoc/mongoc-errno-private.h @@ -31,19 +31,16 @@ BSON_BEGIN_DECLS #if defined(_WIN32) -#define MONGOC_ERRNO_IS_AGAIN(errno) \ - ((errno == EAGAIN) || (errno == WSAEWOULDBLOCK) || (errno == WSAEINPROGRESS)) +#define MONGOC_ERRNO_IS_AGAIN(errno) ((errno == EAGAIN) || (errno == WSAEWOULDBLOCK) || (errno == WSAEINPROGRESS)) #define MONGOC_ERRNO_IS_TIMEDOUT(errno) (errno == WSAETIMEDOUT) #elif defined(__sun) /* for some reason, accept() returns -1 and errno of 0 */ -#define MONGOC_ERRNO_IS_AGAIN(errno) \ - ((errno == EINTR) || (errno == EAGAIN) || (errno == EWOULDBLOCK) || \ - (errno == EINPROGRESS) || (errno == 0)) +#define MONGOC_ERRNO_IS_AGAIN(errno) \ + ((errno == EINTR) || (errno == EAGAIN) || (errno == EWOULDBLOCK) || (errno == EINPROGRESS) || (errno == 0)) #define MONGOC_ERRNO_IS_TIMEDOUT(errno) (errno == ETIMEDOUT) #else -#define MONGOC_ERRNO_IS_AGAIN(errno) \ - ((errno == EINTR) || (errno == EAGAIN) || (errno == EWOULDBLOCK) || \ - (errno == EINPROGRESS)) +#define MONGOC_ERRNO_IS_AGAIN(errno) \ + ((errno == EINTR) || (errno == EAGAIN) || (errno == EWOULDBLOCK) || (errno == EINPROGRESS)) #define MONGOC_ERRNO_IS_TIMEDOUT(errno) (errno == ETIMEDOUT) #endif diff --git a/src/libmongoc/src/mongoc/mongoc-error-private.h b/src/libmongoc/src/mongoc/mongoc-error-private.h index 073c76d84c..fd0f2b10b6 100644 --- a/src/libmongoc/src/mongoc/mongoc-error-private.h +++ b/src/libmongoc/src/mongoc/mongoc-error-private.h @@ -23,11 +23,7 @@ BSON_BEGIN_DECLS -typedef enum { - MONGOC_READ_ERR_NONE, - MONGOC_READ_ERR_OTHER, - MONGOC_READ_ERR_RETRY -} mongoc_read_err_type_t; +typedef enum { MONGOC_READ_ERR_NONE, MONGOC_READ_ERR_OTHER, MONGOC_READ_ERR_RETRY } mongoc_read_err_type_t; /* Server error codes libmongoc cares about. Compare with: * https://github.com/mongodb/mongo/blob/master/src/mongo/base/error_codes.yml @@ -58,14 +54,10 @@ typedef enum { } mongoc_server_err_t; mongoc_read_err_type_t -_mongoc_read_error_get_type (bool cmd_ret, - const bson_error_t *cmd_err, - const bson_t *reply); +_mongoc_read_error_get_type (bool cmd_ret, const bson_error_t *cmd_err, const bson_t *reply); void -_mongoc_error_copy_labels_and_upsert (const bson_t *src, - bson_t *dst, - char *label); +_mongoc_error_copy_labels_and_upsert (const bson_t *src, bson_t *dst, char *label); void _mongoc_write_error_append_retryable_label (bson_t *reply); diff --git a/src/libmongoc/src/mongoc/mongoc-error.c b/src/libmongoc/src/mongoc/mongoc-error.c index b25d910ac3..a9b9501eaf 100644 --- a/src/libmongoc/src/mongoc/mongoc-error.c +++ b/src/libmongoc/src/mongoc/mongoc-error.c @@ -31,11 +31,9 @@ mongoc_error_has_label (const bson_t *reply, const char *label) BSON_ASSERT (reply); BSON_ASSERT (label); - if (bson_iter_init_find (&iter, reply, "errorLabels") && - bson_iter_recurse (&iter, &error_labels)) { + if (bson_iter_init_find (&iter, reply, "errorLabels") && bson_iter_recurse (&iter, &error_labels)) { while (bson_iter_next (&error_labels)) { - if (BSON_ITER_HOLDS_UTF8 (&error_labels) && - !strcmp (bson_iter_utf8 (&error_labels, NULL), label)) { + if (BSON_ITER_HOLDS_UTF8 (&error_labels) && !strcmp (bson_iter_utf8 (&error_labels, NULL), label)) { return true; } } @@ -51,8 +49,7 @@ _mongoc_error_is_server (const bson_error_t *error) return false; } - return error->domain == MONGOC_ERROR_SERVER || - error->domain == MONGOC_ERROR_WRITE_CONCERN; + return error->domain == MONGOC_ERROR_SERVER || error->domain == MONGOC_ERROR_WRITE_CONCERN; } static bool @@ -92,8 +89,7 @@ _mongoc_write_error_append_retryable_label (bson_t *reply) } bson_copy_to_excluding_noinit (reply, &reply_local, "errorLabels", NULL); - _mongoc_error_copy_labels_and_upsert ( - reply, &reply_local, RETRYABLE_WRITE_ERROR); + _mongoc_error_copy_labels_and_upsert (reply, &reply_local, RETRYABLE_WRITE_ERROR); bson_destroy (reply); bson_steal (reply, &reply_local); @@ -127,8 +123,7 @@ _mongoc_write_error_handle_labels (bool cmd_ret, return; } } else { - if (_mongoc_cmd_check_ok_no_wce ( - reply, MONGOC_ERROR_API_VERSION_2, &error)) { + if (_mongoc_cmd_check_ok_no_wce (reply, MONGOC_ERROR_API_VERSION_2, &error)) { return; } } @@ -156,9 +151,7 @@ _mongoc_write_error_handle_labels (bool cmd_ret, *-------------------------------------------------------------------------- */ mongoc_read_err_type_t -_mongoc_read_error_get_type (bool cmd_ret, - const bson_error_t *cmd_err, - const bson_t *reply) +_mongoc_read_error_get_type (bool cmd_ret, const bson_error_t *cmd_err, const bson_t *reply) { bson_error_t error; @@ -170,8 +163,7 @@ _mongoc_read_error_get_type (bool cmd_ret, } /* check for a server error. */ - if (_mongoc_cmd_check_ok_no_wce ( - reply, MONGOC_ERROR_API_VERSION_2, &error)) { + if (_mongoc_cmd_check_ok_no_wce (reply, MONGOC_ERROR_API_VERSION_2, &error)) { return MONGOC_READ_ERR_NONE; } @@ -191,8 +183,7 @@ _mongoc_read_error_get_type (bool cmd_ret, case MONGOC_SERVER_ERR_SOCKETEXCEPTION: return MONGOC_READ_ERR_RETRY; default: - if (strstr (error.message, "not master") || - strstr (error.message, "node is recovering")) { + if (strstr (error.message, "not master") || strstr (error.message, "node is recovering")) { return MONGOC_READ_ERR_RETRY; } return MONGOC_READ_ERR_OTHER; @@ -200,9 +191,7 @@ _mongoc_read_error_get_type (bool cmd_ret, } void -_mongoc_error_copy_labels_and_upsert (const bson_t *src, - bson_t *dst, - char *label) +_mongoc_error_copy_labels_and_upsert (const bson_t *src, bson_t *dst, char *label) { bson_iter_t iter; bson_iter_t src_label; @@ -212,12 +201,10 @@ _mongoc_error_copy_labels_and_upsert (const bson_t *src, bson_array_builder_append_utf8 (dst_labels, label, -1); /* append any other errorLabels already in "src" */ - if (bson_iter_init_find (&iter, src, "errorLabels") && - bson_iter_recurse (&iter, &src_label)) { + if (bson_iter_init_find (&iter, src, "errorLabels") && bson_iter_recurse (&iter, &src_label)) { while (bson_iter_next (&src_label) && BSON_ITER_HOLDS_UTF8 (&src_label)) { if (strcmp (bson_iter_utf8 (&src_label, NULL), label) != 0) { - bson_array_builder_append_utf8 ( - dst_labels, bson_iter_utf8 (&src_label, NULL), -1); + bson_array_builder_append_utf8 (dst_labels, bson_iter_utf8 (&src_label, NULL), -1); } } } @@ -295,8 +282,7 @@ _mongoc_error_is_recovering (bson_error_t *error) bool _mongoc_error_is_state_change (bson_error_t *error) { - return _mongoc_error_is_recovering (error) || - _mongoc_error_is_not_primary (error); + return _mongoc_error_is_recovering (error) || _mongoc_error_is_not_primary (error); } bool @@ -309,8 +295,7 @@ _mongoc_error_is_network (const bson_error_t *error) return true; } - if (error->domain == MONGOC_ERROR_PROTOCOL && - error->code == MONGOC_ERROR_PROTOCOL_INVALID_REPLY) { + if (error->domain == MONGOC_ERROR_PROTOCOL && error->code == MONGOC_ERROR_PROTOCOL_INVALID_REPLY) { return true; } @@ -324,6 +309,5 @@ _mongoc_error_is_auth (const bson_error_t *error) return false; } - return error->domain == MONGOC_ERROR_CLIENT && - error->code == MONGOC_ERROR_CLIENT_AUTHENTICATE; + return error->domain == MONGOC_ERROR_CLIENT && error->code == MONGOC_ERROR_CLIENT_AUTHENTICATE; } diff --git a/src/libmongoc/src/mongoc/mongoc-find-and-modify.c b/src/libmongoc/src/mongoc/mongoc-find-and-modify.c index ba6bbcdfc1..eec7b1e919 100644 --- a/src/libmongoc/src/mongoc/mongoc-find-and-modify.c +++ b/src/libmongoc/src/mongoc/mongoc-find-and-modify.c @@ -43,8 +43,7 @@ mongoc_find_and_modify_opts_new (void) } bool -mongoc_find_and_modify_opts_set_sort (mongoc_find_and_modify_opts_t *opts, - const bson_t *sort) +mongoc_find_and_modify_opts_set_sort (mongoc_find_and_modify_opts_t *opts, const bson_t *sort) { BSON_ASSERT (opts); @@ -58,8 +57,7 @@ mongoc_find_and_modify_opts_set_sort (mongoc_find_and_modify_opts_t *opts, } void -mongoc_find_and_modify_opts_get_sort (const mongoc_find_and_modify_opts_t *opts, - bson_t *sort) +mongoc_find_and_modify_opts_get_sort (const mongoc_find_and_modify_opts_t *opts, bson_t *sort) { BSON_ASSERT (opts); BSON_ASSERT (sort); @@ -72,8 +70,7 @@ mongoc_find_and_modify_opts_get_sort (const mongoc_find_and_modify_opts_t *opts, } bool -mongoc_find_and_modify_opts_set_update (mongoc_find_and_modify_opts_t *opts, - const bson_t *update) +mongoc_find_and_modify_opts_set_update (mongoc_find_and_modify_opts_t *opts, const bson_t *update) { BSON_ASSERT (opts); @@ -87,8 +84,7 @@ mongoc_find_and_modify_opts_set_update (mongoc_find_and_modify_opts_t *opts, } void -mongoc_find_and_modify_opts_get_update ( - const mongoc_find_and_modify_opts_t *opts, bson_t *update) +mongoc_find_and_modify_opts_get_update (const mongoc_find_and_modify_opts_t *opts, bson_t *update) { BSON_ASSERT (opts); BSON_ASSERT (update); @@ -101,8 +97,7 @@ mongoc_find_and_modify_opts_get_update ( } bool -mongoc_find_and_modify_opts_set_fields (mongoc_find_and_modify_opts_t *opts, - const bson_t *fields) +mongoc_find_and_modify_opts_set_fields (mongoc_find_and_modify_opts_t *opts, const bson_t *fields) { BSON_ASSERT (opts); @@ -116,8 +111,7 @@ mongoc_find_and_modify_opts_set_fields (mongoc_find_and_modify_opts_t *opts, } void -mongoc_find_and_modify_opts_get_fields ( - const mongoc_find_and_modify_opts_t *opts, bson_t *fields) +mongoc_find_and_modify_opts_get_fields (const mongoc_find_and_modify_opts_t *opts, bson_t *fields) { BSON_ASSERT (opts); BSON_ASSERT (fields); @@ -130,9 +124,7 @@ mongoc_find_and_modify_opts_get_fields ( } bool -mongoc_find_and_modify_opts_set_flags ( - mongoc_find_and_modify_opts_t *opts, - const mongoc_find_and_modify_flags_t flags) +mongoc_find_and_modify_opts_set_flags (mongoc_find_and_modify_opts_t *opts, const mongoc_find_and_modify_flags_t flags) { BSON_ASSERT (opts); @@ -141,8 +133,7 @@ mongoc_find_and_modify_opts_set_flags ( } mongoc_find_and_modify_flags_t -mongoc_find_and_modify_opts_get_flags ( - const mongoc_find_and_modify_opts_t *opts) +mongoc_find_and_modify_opts_get_flags (const mongoc_find_and_modify_opts_t *opts) { BSON_ASSERT (opts); @@ -150,8 +141,7 @@ mongoc_find_and_modify_opts_get_flags ( } bool -mongoc_find_and_modify_opts_set_bypass_document_validation ( - mongoc_find_and_modify_opts_t *opts, bool bypass) +mongoc_find_and_modify_opts_set_bypass_document_validation (mongoc_find_and_modify_opts_t *opts, bool bypass) { BSON_ASSERT (opts); @@ -160,8 +150,7 @@ mongoc_find_and_modify_opts_set_bypass_document_validation ( } bool -mongoc_find_and_modify_opts_get_bypass_document_validation ( - const mongoc_find_and_modify_opts_t *opts) +mongoc_find_and_modify_opts_get_bypass_document_validation (const mongoc_find_and_modify_opts_t *opts) { BSON_ASSERT (opts); @@ -169,8 +158,7 @@ mongoc_find_and_modify_opts_get_bypass_document_validation ( } bool -mongoc_find_and_modify_opts_set_max_time_ms ( - mongoc_find_and_modify_opts_t *opts, uint32_t max_time_ms) +mongoc_find_and_modify_opts_set_max_time_ms (mongoc_find_and_modify_opts_t *opts, uint32_t max_time_ms) { BSON_ASSERT (opts); @@ -179,8 +167,7 @@ mongoc_find_and_modify_opts_set_max_time_ms ( } uint32_t -mongoc_find_and_modify_opts_get_max_time_ms ( - const mongoc_find_and_modify_opts_t *opts) +mongoc_find_and_modify_opts_get_max_time_ms (const mongoc_find_and_modify_opts_t *opts) { BSON_ASSERT (opts); @@ -188,8 +175,7 @@ mongoc_find_and_modify_opts_get_max_time_ms ( } bool -mongoc_find_and_modify_opts_append (mongoc_find_and_modify_opts_t *opts, - const bson_t *extra) +mongoc_find_and_modify_opts_append (mongoc_find_and_modify_opts_t *opts, const bson_t *extra) { BSON_ASSERT (opts); @@ -201,8 +187,7 @@ mongoc_find_and_modify_opts_append (mongoc_find_and_modify_opts_t *opts, } void -mongoc_find_and_modify_opts_get_extra ( - const mongoc_find_and_modify_opts_t *opts, bson_t *extra) +mongoc_find_and_modify_opts_get_extra (const mongoc_find_and_modify_opts_t *opts, bson_t *extra) { BSON_ASSERT (opts); BSON_ASSERT (extra); diff --git a/src/libmongoc/src/mongoc/mongoc-find-and-modify.h b/src/libmongoc/src/mongoc/mongoc-find-and-modify.h index 7dfedcc58a..8ad61c8827 100644 --- a/src/libmongoc/src/mongoc/mongoc-find-and-modify.h +++ b/src/libmongoc/src/mongoc/mongoc-find-and-modify.h @@ -38,61 +38,46 @@ MONGOC_EXPORT (mongoc_find_and_modify_opts_t *) mongoc_find_and_modify_opts_new (void) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (bool) -mongoc_find_and_modify_opts_set_sort (mongoc_find_and_modify_opts_t *opts, - const bson_t *sort); +mongoc_find_and_modify_opts_set_sort (mongoc_find_and_modify_opts_t *opts, const bson_t *sort); MONGOC_EXPORT (void) -mongoc_find_and_modify_opts_get_sort (const mongoc_find_and_modify_opts_t *opts, - bson_t *sort); +mongoc_find_and_modify_opts_get_sort (const mongoc_find_and_modify_opts_t *opts, bson_t *sort); MONGOC_EXPORT (bool) -mongoc_find_and_modify_opts_set_update (mongoc_find_and_modify_opts_t *opts, - const bson_t *update); +mongoc_find_and_modify_opts_set_update (mongoc_find_and_modify_opts_t *opts, const bson_t *update); MONGOC_EXPORT (void) -mongoc_find_and_modify_opts_get_update ( - const mongoc_find_and_modify_opts_t *opts, bson_t *update); +mongoc_find_and_modify_opts_get_update (const mongoc_find_and_modify_opts_t *opts, bson_t *update); MONGOC_EXPORT (bool) -mongoc_find_and_modify_opts_set_fields (mongoc_find_and_modify_opts_t *opts, - const bson_t *fields); +mongoc_find_and_modify_opts_set_fields (mongoc_find_and_modify_opts_t *opts, const bson_t *fields); MONGOC_EXPORT (void) -mongoc_find_and_modify_opts_get_fields ( - const mongoc_find_and_modify_opts_t *opts, bson_t *fields); +mongoc_find_and_modify_opts_get_fields (const mongoc_find_and_modify_opts_t *opts, bson_t *fields); MONGOC_EXPORT (bool) -mongoc_find_and_modify_opts_set_flags ( - mongoc_find_and_modify_opts_t *opts, - const mongoc_find_and_modify_flags_t flags); +mongoc_find_and_modify_opts_set_flags (mongoc_find_and_modify_opts_t *opts, const mongoc_find_and_modify_flags_t flags); MONGOC_EXPORT (mongoc_find_and_modify_flags_t) -mongoc_find_and_modify_opts_get_flags ( - const mongoc_find_and_modify_opts_t *opts); +mongoc_find_and_modify_opts_get_flags (const mongoc_find_and_modify_opts_t *opts); MONGOC_EXPORT (bool) -mongoc_find_and_modify_opts_set_bypass_document_validation ( - mongoc_find_and_modify_opts_t *opts, bool bypass); +mongoc_find_and_modify_opts_set_bypass_document_validation (mongoc_find_and_modify_opts_t *opts, bool bypass); MONGOC_EXPORT (bool) -mongoc_find_and_modify_opts_get_bypass_document_validation ( - const mongoc_find_and_modify_opts_t *opts); +mongoc_find_and_modify_opts_get_bypass_document_validation (const mongoc_find_and_modify_opts_t *opts); MONGOC_EXPORT (bool) -mongoc_find_and_modify_opts_set_max_time_ms ( - mongoc_find_and_modify_opts_t *opts, uint32_t max_time_ms); +mongoc_find_and_modify_opts_set_max_time_ms (mongoc_find_and_modify_opts_t *opts, uint32_t max_time_ms); MONGOC_EXPORT (uint32_t) -mongoc_find_and_modify_opts_get_max_time_ms ( - const mongoc_find_and_modify_opts_t *opts); +mongoc_find_and_modify_opts_get_max_time_ms (const mongoc_find_and_modify_opts_t *opts); MONGOC_EXPORT (bool) -mongoc_find_and_modify_opts_append (mongoc_find_and_modify_opts_t *opts, - const bson_t *extra); +mongoc_find_and_modify_opts_append (mongoc_find_and_modify_opts_t *opts, const bson_t *extra); MONGOC_EXPORT (void) -mongoc_find_and_modify_opts_get_extra ( - const mongoc_find_and_modify_opts_t *opts, bson_t *extra); +mongoc_find_and_modify_opts_get_extra (const mongoc_find_and_modify_opts_t *opts, bson_t *extra); MONGOC_EXPORT (void) mongoc_find_and_modify_opts_destroy (mongoc_find_and_modify_opts_t *opts); diff --git a/src/libmongoc/src/mongoc/mongoc-flags.c b/src/libmongoc/src/mongoc/mongoc-flags.c index 1393e49999..2613646733 100644 --- a/src/libmongoc/src/mongoc/mongoc-flags.c +++ b/src/libmongoc/src/mongoc/mongoc-flags.c @@ -26,54 +26,37 @@ // Document and ensure consistency between equivalent macros in mcd-rpc and // libmongoc. -BSON_STATIC_ASSERT (MONGOC_OP_COMPRESSED_COMPRESSOR_ID_NOOP == - MONGOC_COMPRESSOR_NOOP_ID); -BSON_STATIC_ASSERT (MONGOC_OP_COMPRESSED_COMPRESSOR_ID_SNAPPY == - MONGOC_COMPRESSOR_SNAPPY_ID); -BSON_STATIC_ASSERT (MONGOC_OP_COMPRESSED_COMPRESSOR_ID_ZLIB == - MONGOC_COMPRESSOR_ZLIB_ID); -BSON_STATIC_ASSERT (MONGOC_OP_COMPRESSED_COMPRESSOR_ID_ZSTD == - MONGOC_COMPRESSOR_ZSTD_ID); +BSON_STATIC_ASSERT (MONGOC_OP_COMPRESSED_COMPRESSOR_ID_NOOP == MONGOC_COMPRESSOR_NOOP_ID); +BSON_STATIC_ASSERT (MONGOC_OP_COMPRESSED_COMPRESSOR_ID_SNAPPY == MONGOC_COMPRESSOR_SNAPPY_ID); +BSON_STATIC_ASSERT (MONGOC_OP_COMPRESSED_COMPRESSOR_ID_ZLIB == MONGOC_COMPRESSOR_ZLIB_ID); +BSON_STATIC_ASSERT (MONGOC_OP_COMPRESSED_COMPRESSOR_ID_ZSTD == MONGOC_COMPRESSOR_ZSTD_ID); BSON_STATIC_ASSERT (MONGOC_OP_MSG_FLAG_NONE == MONGOC_MSG_NONE); -BSON_STATIC_ASSERT (MONGOC_OP_MSG_FLAG_CHECKSUM_PRESENT == - MONGOC_MSG_CHECKSUM_PRESENT); +BSON_STATIC_ASSERT (MONGOC_OP_MSG_FLAG_CHECKSUM_PRESENT == MONGOC_MSG_CHECKSUM_PRESENT); BSON_STATIC_ASSERT (MONGOC_OP_MSG_FLAG_MORE_TO_COME == MONGOC_MSG_MORE_TO_COME); -BSON_STATIC_ASSERT (MONGOC_OP_MSG_FLAG_EXHAUST_ALLOWED == - MONGOC_MSG_EXHAUST_ALLOWED); +BSON_STATIC_ASSERT (MONGOC_OP_MSG_FLAG_EXHAUST_ALLOWED == MONGOC_MSG_EXHAUST_ALLOWED); BSON_STATIC_ASSERT (MONGOC_OP_REPLY_RESPONSE_FLAG_NONE == MONGOC_REPLY_NONE); -BSON_STATIC_ASSERT (MONGOC_OP_REPLY_RESPONSE_FLAG_CURSOR_NOT_FOUND == - MONGOC_REPLY_CURSOR_NOT_FOUND); -BSON_STATIC_ASSERT (MONGOC_OP_REPLY_RESPONSE_FLAG_QUERY_FAILURE == - MONGOC_REPLY_QUERY_FAILURE); -BSON_STATIC_ASSERT (MONGOC_OP_REPLY_RESPONSE_FLAG_SHARD_CONFIG_STALE == - MONGOC_REPLY_SHARD_CONFIG_STALE); -BSON_STATIC_ASSERT (MONGOC_OP_REPLY_RESPONSE_FLAG_AWAIT_CAPABLE == - MONGOC_REPLY_AWAIT_CAPABLE); +BSON_STATIC_ASSERT (MONGOC_OP_REPLY_RESPONSE_FLAG_CURSOR_NOT_FOUND == MONGOC_REPLY_CURSOR_NOT_FOUND); +BSON_STATIC_ASSERT (MONGOC_OP_REPLY_RESPONSE_FLAG_QUERY_FAILURE == MONGOC_REPLY_QUERY_FAILURE); +BSON_STATIC_ASSERT (MONGOC_OP_REPLY_RESPONSE_FLAG_SHARD_CONFIG_STALE == MONGOC_REPLY_SHARD_CONFIG_STALE); +BSON_STATIC_ASSERT (MONGOC_OP_REPLY_RESPONSE_FLAG_AWAIT_CAPABLE == MONGOC_REPLY_AWAIT_CAPABLE); BSON_STATIC_ASSERT (MONGOC_OP_UPDATE_FLAG_NONE == MONGOC_UPDATE_NONE); BSON_STATIC_ASSERT (MONGOC_OP_UPDATE_FLAG_UPSERT == MONGOC_UPDATE_UPSERT); -BSON_STATIC_ASSERT (MONGOC_OP_UPDATE_FLAG_MULTI_UPDATE == - MONGOC_UPDATE_MULTI_UPDATE); +BSON_STATIC_ASSERT (MONGOC_OP_UPDATE_FLAG_MULTI_UPDATE == MONGOC_UPDATE_MULTI_UPDATE); BSON_STATIC_ASSERT (MONGOC_OP_INSERT_FLAG_NONE == MONGOC_INSERT_NONE); -BSON_STATIC_ASSERT (MONGOC_OP_INSERT_FLAG_CONTINUE_ON_ERROR == - MONGOC_INSERT_CONTINUE_ON_ERROR); +BSON_STATIC_ASSERT (MONGOC_OP_INSERT_FLAG_CONTINUE_ON_ERROR == MONGOC_INSERT_CONTINUE_ON_ERROR); BSON_STATIC_ASSERT (MONGOC_OP_QUERY_FLAG_NONE == MONGOC_QUERY_NONE); -BSON_STATIC_ASSERT (MONGOC_OP_QUERY_FLAG_TAILABLE_CURSOR == - MONGOC_QUERY_TAILABLE_CURSOR); -BSON_STATIC_ASSERT (MONGOC_OP_QUERY_FLAG_SECONDARY_OK == - MONGOC_QUERY_SECONDARY_OK); -BSON_STATIC_ASSERT (MONGOC_OP_QUERY_FLAG_OPLOG_REPLAY == - MONGOC_QUERY_OPLOG_REPLAY); -BSON_STATIC_ASSERT (MONGOC_OP_QUERY_FLAG_NO_CURSOR_TIMEOUT == - MONGOC_QUERY_NO_CURSOR_TIMEOUT); +BSON_STATIC_ASSERT (MONGOC_OP_QUERY_FLAG_TAILABLE_CURSOR == MONGOC_QUERY_TAILABLE_CURSOR); +BSON_STATIC_ASSERT (MONGOC_OP_QUERY_FLAG_SECONDARY_OK == MONGOC_QUERY_SECONDARY_OK); +BSON_STATIC_ASSERT (MONGOC_OP_QUERY_FLAG_OPLOG_REPLAY == MONGOC_QUERY_OPLOG_REPLAY); +BSON_STATIC_ASSERT (MONGOC_OP_QUERY_FLAG_NO_CURSOR_TIMEOUT == MONGOC_QUERY_NO_CURSOR_TIMEOUT); BSON_STATIC_ASSERT (MONGOC_OP_QUERY_FLAG_AWAIT_DATA == MONGOC_QUERY_AWAIT_DATA); BSON_STATIC_ASSERT (MONGOC_OP_QUERY_FLAG_EXHAUST == MONGOC_QUERY_EXHAUST); BSON_STATIC_ASSERT (MONGOC_OP_QUERY_FLAG_PARTIAL == MONGOC_QUERY_PARTIAL); BSON_STATIC_ASSERT (MONGOC_OP_DELETE_FLAG_NONE == MONGOC_DELETE_NONE); -BSON_STATIC_ASSERT (MONGOC_OP_DELETE_FLAG_SINGLE_REMOVE == - MONGOC_DELETE_SINGLE_REMOVE); +BSON_STATIC_ASSERT (MONGOC_OP_DELETE_FLAG_SINGLE_REMOVE == MONGOC_DELETE_SINGLE_REMOVE); diff --git a/src/libmongoc/src/mongoc/mongoc-generation-map-private.h b/src/libmongoc/src/mongoc/mongoc-generation-map-private.h index 8d700b48a1..282d38c4f8 100644 --- a/src/libmongoc/src/mongoc/mongoc-generation-map-private.h +++ b/src/libmongoc/src/mongoc/mongoc-generation-map-private.h @@ -32,12 +32,10 @@ mongoc_generation_map_t * mongoc_generation_map_copy (const mongoc_generation_map_t *gm); uint32_t -mongoc_generation_map_get (const mongoc_generation_map_t *gm, - const bson_oid_t *key); +mongoc_generation_map_get (const mongoc_generation_map_t *gm, const bson_oid_t *key); void -mongoc_generation_map_increment (mongoc_generation_map_t *gm, - const bson_oid_t *key); +mongoc_generation_map_increment (mongoc_generation_map_t *gm, const bson_oid_t *key); void mongoc_generation_map_destroy (mongoc_generation_map_t *gm); diff --git a/src/libmongoc/src/mongoc/mongoc-generation-map.c b/src/libmongoc/src/mongoc/mongoc-generation-map.c index a19caabc35..cfd28628bc 100644 --- a/src/libmongoc/src/mongoc/mongoc-generation-map.c +++ b/src/libmongoc/src/mongoc/mongoc-generation-map.c @@ -84,8 +84,7 @@ mongoc_generation_map_copy (const mongoc_generation_map_t *gm) } uint32_t -mongoc_generation_map_get (const mongoc_generation_map_t *gm, - const bson_oid_t *key) +mongoc_generation_map_get (const mongoc_generation_map_t *gm, const bson_oid_t *key) { gm_node_t *iter = NULL; @@ -107,8 +106,7 @@ mongoc_generation_map_get (const mongoc_generation_map_t *gm, } void -mongoc_generation_map_increment (mongoc_generation_map_t *gm, - const bson_oid_t *key) +mongoc_generation_map_increment (mongoc_generation_map_t *gm, const bson_oid_t *key) { gm_node_t *match; gm_node_t *iter = NULL; diff --git a/src/libmongoc/src/mongoc/mongoc-gridfs-bucket-file-private.h b/src/libmongoc/src/mongoc/mongoc-gridfs-bucket-file-private.h index e4d599cfc4..6766bdd28c 100644 --- a/src/libmongoc/src/mongoc/mongoc-gridfs-bucket-file-private.h +++ b/src/libmongoc/src/mongoc/mongoc-gridfs-bucket-file-private.h @@ -54,14 +54,10 @@ typedef struct { } mongoc_gridfs_bucket_file_t; ssize_t -_mongoc_gridfs_bucket_file_writev (mongoc_gridfs_bucket_file_t *file, - const mongoc_iovec_t *iov, - size_t iovcnt); +_mongoc_gridfs_bucket_file_writev (mongoc_gridfs_bucket_file_t *file, const mongoc_iovec_t *iov, size_t iovcnt); ssize_t -_mongoc_gridfs_bucket_file_readv (mongoc_gridfs_bucket_file_t *file, - mongoc_iovec_t *iov, - size_t iovcnt); +_mongoc_gridfs_bucket_file_readv (mongoc_gridfs_bucket_file_t *file, mongoc_iovec_t *iov, size_t iovcnt); bool _mongoc_gridfs_bucket_file_save (mongoc_gridfs_bucket_file_t *file); diff --git a/src/libmongoc/src/mongoc/mongoc-gridfs-bucket-file.c b/src/libmongoc/src/mongoc/mongoc-gridfs-bucket-file.c index 425b8c80cd..d251a5db70 100644 --- a/src/libmongoc/src/mongoc/mongoc-gridfs-bucket-file.c +++ b/src/libmongoc/src/mongoc/mongoc-gridfs-bucket-file.c @@ -44,8 +44,7 @@ _mongoc_min (const size_t a, const size_t b) *-------------------------------------------------------------------------- */ static bool -_mongoc_gridfs_bucket_create_indexes (mongoc_gridfs_bucket_t *bucket, - bson_error_t *error) +_mongoc_gridfs_bucket_create_indexes (mongoc_gridfs_bucket_t *bucket, bson_error_t *error) { mongoc_read_prefs_t *prefs; bson_t filter; @@ -63,8 +62,7 @@ _mongoc_gridfs_bucket_create_indexes (mongoc_gridfs_bucket_t *bucket, bson_append_bool (&opts, "singleBatch", 11, true); bson_append_int32 (&opts, "limit", 5, 1); prefs = mongoc_read_prefs_new (MONGOC_READ_PRIMARY); - cursor = - mongoc_collection_find_with_opts (bucket->files, &filter, &opts, prefs); + cursor = mongoc_collection_find_with_opts (bucket->files, &filter, &opts, prefs); bson_destroy (&filter); bson_destroy (&opts); @@ -86,8 +84,7 @@ _mongoc_gridfs_bucket_create_indexes (mongoc_gridfs_bucket_t *bucket, BSON_APPEND_INT32 (&files_index, "filename", 1); BSON_APPEND_INT32 (&files_index, "uploadDate", 1); - r = _mongoc_collection_create_index_if_not_exists ( - bucket->files, &files_index, NULL, error); + r = _mongoc_collection_create_index_if_not_exists (bucket->files, &files_index, NULL, error); bson_destroy (&files_index); if (!r) { return false; @@ -102,8 +99,7 @@ _mongoc_gridfs_bucket_create_indexes (mongoc_gridfs_bucket_t *bucket, BSON_APPEND_INT32 (&chunks_index, "files_id", 1); BSON_APPEND_INT32 (&chunks_index, "n", 1); - r = _mongoc_collection_create_index_if_not_exists ( - bucket->chunks, &chunks_index, &opts, error); + r = _mongoc_collection_create_index_if_not_exists (bucket->chunks, &chunks_index, &opts, error); bson_destroy (&opts); bson_destroy (&chunks_index); @@ -138,18 +134,10 @@ _mongoc_gridfs_bucket_write_chunk (mongoc_gridfs_bucket_file_t *file) BSON_APPEND_INT32 (&chunk, "n", file->curr_chunk); BSON_APPEND_VALUE (&chunk, "files_id", file->file_id); - BSON_APPEND_BINARY (&chunk, - "data", - BSON_SUBTYPE_BINARY, - file->buffer, - (uint32_t) file->in_buffer); - - - r = mongoc_collection_insert_one (file->bucket->chunks, - &chunk, - NULL /* opts */, - NULL /* reply */, - &file->err); + BSON_APPEND_BINARY (&chunk, "data", BSON_SUBTYPE_BINARY, file->buffer, (uint32_t) file->in_buffer); + + + r = mongoc_collection_insert_one (file->bucket->chunks, &chunk, NULL /* opts */, NULL /* reply */, &file->err); bson_destroy (&chunk); if (!r) { return false; @@ -185,8 +173,7 @@ _mongoc_gridfs_bucket_init_cursor (mongoc_gridfs_bucket_file_t *file) BSON_APPEND_INT32 (&sort, "n", 1); BSON_APPEND_DOCUMENT (&opts, "sort", &sort); - file->cursor = mongoc_collection_find_with_opts ( - file->bucket->chunks, &filter, &opts, NULL); + file->cursor = mongoc_collection_find_with_opts (file->bucket->chunks, &filter, &opts, NULL); bson_destroy (&filter); bson_destroy (&opts); @@ -250,11 +237,8 @@ _mongoc_gridfs_bucket_read_chunk (mongoc_gridfs_bucket_file_t *file) } if (!r) { - bson_set_error (&file->err, - MONGOC_ERROR_GRIDFS, - MONGOC_ERROR_GRIDFS_CHUNK_MISSING, - "Missing chunk %d.", - file->curr_chunk); + bson_set_error ( + &file->err, MONGOC_ERROR_GRIDFS, MONGOC_ERROR_GRIDFS_CHUNK_MISSING, "Missing chunk %d.", file->curr_chunk); return false; } @@ -271,11 +255,8 @@ _mongoc_gridfs_bucket_read_chunk (mongoc_gridfs_bucket_file_t *file) n = bson_iter_int32 (&iter); if (n != file->curr_chunk) { - bson_set_error (&file->err, - MONGOC_ERROR_GRIDFS, - MONGOC_ERROR_GRIDFS_CHUNK_MISSING, - "Missing chunk %d.", - file->curr_chunk); + bson_set_error ( + &file->err, MONGOC_ERROR_GRIDFS, MONGOC_ERROR_GRIDFS_CHUNK_MISSING, "Missing chunk %d.", file->curr_chunk); return false; } @@ -302,8 +283,7 @@ _mongoc_gridfs_bucket_read_chunk (mongoc_gridfs_bucket_file_t *file) bson_set_error (&file->err, MONGOC_ERROR_GRIDFS, MONGOC_ERROR_GRIDFS_CORRUPT, - "Chunk %d expected to have size %" PRId64 - " but is size %d.", + "Chunk %d expected to have size %" PRId64 " but is size %d.", file->curr_chunk, expected_size, data_len); @@ -319,9 +299,7 @@ _mongoc_gridfs_bucket_read_chunk (mongoc_gridfs_bucket_file_t *file) } ssize_t -_mongoc_gridfs_bucket_file_writev (mongoc_gridfs_bucket_file_t *file, - const mongoc_iovec_t *iov, - size_t iovcnt) +_mongoc_gridfs_bucket_file_writev (mongoc_gridfs_bucket_file_t *file, const mongoc_iovec_t *iov, size_t iovcnt) { BSON_ASSERT (file); BSON_ASSERT (iov); @@ -361,9 +339,7 @@ _mongoc_gridfs_bucket_file_writev (mongoc_gridfs_bucket_file_t *file, const size_t space_available = chunk_size - file->in_buffer; const size_t to_write = _mongoc_min (bytes_available, space_available); - memcpy (file->buffer + file->in_buffer, - ((char *) iov[i].iov_base) + written_this_iov, - to_write); + memcpy (file->buffer + file->in_buffer, ((char *) iov[i].iov_base) + written_this_iov, to_write); file->in_buffer += to_write; written_this_iov += to_write; @@ -381,9 +357,7 @@ _mongoc_gridfs_bucket_file_writev (mongoc_gridfs_bucket_file_t *file, } ssize_t -_mongoc_gridfs_bucket_file_readv (mongoc_gridfs_bucket_file_t *file, - mongoc_iovec_t *iov, - size_t iovcnt) +_mongoc_gridfs_bucket_file_readv (mongoc_gridfs_bucket_file_t *file, mongoc_iovec_t *iov, size_t iovcnt) { BSON_ASSERT (file); BSON_ASSERT (iov); @@ -407,9 +381,7 @@ _mongoc_gridfs_bucket_file_readv (mongoc_gridfs_bucket_file_t *file, const size_t space_available = iov[i].iov_len - read_this_iov; const size_t to_read = _mongoc_min (bytes_available, space_available); - memcpy (((char *) iov[i].iov_base) + read_this_iov, - file->buffer + file->bytes_read, - to_read); + memcpy (((char *) iov[i].iov_base) + read_this_iov, file->buffer + file->bytes_read, to_read); file->bytes_read += to_read; read_this_iov += to_read; @@ -485,8 +457,7 @@ _mongoc_gridfs_bucket_file_save (mongoc_gridfs_bucket_file_t *file) BSON_APPEND_DOCUMENT (&new_doc, "metadata", file->metadata); } - r = mongoc_collection_insert_one ( - file->bucket->files, &new_doc, NULL, NULL, &file->err); + r = mongoc_collection_insert_one (file->bucket->files, &new_doc, NULL, NULL, &file->err); bson_destroy (&new_doc); file->saved = r; return (file->err.code) ? false : true; diff --git a/src/libmongoc/src/mongoc/mongoc-gridfs-bucket.c b/src/libmongoc/src/mongoc/mongoc-gridfs-bucket.c index 6ccacab9d1..7edce80369 100644 --- a/src/libmongoc/src/mongoc/mongoc-gridfs-bucket.c +++ b/src/libmongoc/src/mongoc/mongoc-gridfs-bucket.c @@ -58,17 +58,14 @@ _mongoc_gridfs_find_file_with_id (mongoc_gridfs_bucket_t *bucket, BSON_APPEND_VALUE (&filter, "_id", file_id); - cursor = - mongoc_collection_find_with_opts (bucket->files, &filter, NULL, NULL); + cursor = mongoc_collection_find_with_opts (bucket->files, &filter, NULL, NULL); bson_destroy (&filter); r = mongoc_cursor_next (cursor, &doc); if (!r) { if (!mongoc_cursor_error (cursor, error)) { - bson_set_error (error, - MONGOC_ERROR_GRIDFS, - MONGOC_ERROR_GRIDFS_BUCKET_FILE_NOT_FOUND, - "No file with given id exists"); + bson_set_error ( + error, MONGOC_ERROR_GRIDFS, MONGOC_ERROR_GRIDFS_BUCKET_FILE_NOT_FOUND, "No file with given id exists"); } } else { if (file) { @@ -92,15 +89,13 @@ mongoc_gridfs_bucket_new (mongoc_database_t *db, BSON_ASSERT (db); - if (!_mongoc_gridfs_bucket_opts_parse ( - db->client, opts, &gridfs_opts, error)) { + if (!_mongoc_gridfs_bucket_opts_parse (db->client, opts, &gridfs_opts, error)) { _mongoc_gridfs_bucket_opts_cleanup (&gridfs_opts); return NULL; } /* Initialize the bucket fields */ - if (strlen (gridfs_opts.bucketName) + strlen (".chunks") + 1 > - sizeof (buf)) { + if (strlen (gridfs_opts.bucketName) + strlen (".chunks") + 1 > sizeof (buf)) { bson_set_error (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, @@ -118,17 +113,13 @@ mongoc_gridfs_bucket_new (mongoc_database_t *db, bucket->files = mongoc_database_get_collection (db, buf); if (gridfs_opts.writeConcern) { - mongoc_collection_set_write_concern (bucket->chunks, - gridfs_opts.writeConcern); - mongoc_collection_set_write_concern (bucket->files, - gridfs_opts.writeConcern); + mongoc_collection_set_write_concern (bucket->chunks, gridfs_opts.writeConcern); + mongoc_collection_set_write_concern (bucket->files, gridfs_opts.writeConcern); } if (gridfs_opts.readConcern) { - mongoc_collection_set_read_concern (bucket->chunks, - gridfs_opts.readConcern); - mongoc_collection_set_read_concern (bucket->files, - gridfs_opts.readConcern); + mongoc_collection_set_read_concern (bucket->chunks, gridfs_opts.readConcern); + mongoc_collection_set_read_concern (bucket->files, gridfs_opts.readConcern); } if (read_prefs) { @@ -160,8 +151,7 @@ mongoc_gridfs_bucket_open_upload_stream_with_id (mongoc_gridfs_bucket_t *bucket, BSON_ASSERT (file_id); BSON_ASSERT (filename); - if (!_mongoc_gridfs_bucket_upload_opts_parse ( - bucket->files->client, opts, &gridfs_opts, error)) { + if (!_mongoc_gridfs_bucket_upload_opts_parse (bucket->files->client, opts, &gridfs_opts, error)) { _mongoc_gridfs_bucket_upload_opts_cleanup (&gridfs_opts); return NULL; } @@ -211,8 +201,7 @@ mongoc_gridfs_bucket_open_upload_stream (mongoc_gridfs_bucket_t *bucket, val.value_type = BSON_TYPE_OID; val.value.v_oid = object_id; - stream = mongoc_gridfs_bucket_open_upload_stream_with_id ( - bucket, &val, filename, opts, error); + stream = mongoc_gridfs_bucket_open_upload_stream_with_id (bucket, &val, filename, opts, error); if (!stream) { return NULL; @@ -243,8 +232,7 @@ mongoc_gridfs_bucket_upload_from_stream_with_id (mongoc_gridfs_bucket_t *bucket, BSON_ASSERT (filename); BSON_ASSERT (source); - upload_stream = mongoc_gridfs_bucket_open_upload_stream_with_id ( - bucket, file_id, filename, opts, error); + upload_stream = mongoc_gridfs_bucket_open_upload_stream_with_id (bucket, file_id, filename, opts, error); if (!upload_stream) { return false; @@ -262,10 +250,8 @@ mongoc_gridfs_bucket_upload_from_stream_with_id (mongoc_gridfs_bucket_t *bucket, if (bytes_read < 0) { mongoc_gridfs_bucket_abort_upload (upload_stream); - bson_set_error (error, - MONGOC_ERROR_GRIDFS, - MONGOC_ERROR_GRIDFS_BUCKET_STREAM, - "Error occurred on the provided stream."); + bson_set_error ( + error, MONGOC_ERROR_GRIDFS, MONGOC_ERROR_GRIDFS_BUCKET_STREAM, "Error occurred on the provided stream."); mongoc_stream_destroy (upload_stream); return false; } else { @@ -295,8 +281,7 @@ mongoc_gridfs_bucket_upload_from_stream (mongoc_gridfs_bucket_t *bucket, val.value_type = BSON_TYPE_OID; val.value.v_oid = object_id; - r = mongoc_gridfs_bucket_upload_from_stream_with_id ( - bucket, &val, filename, source, opts, error); + r = mongoc_gridfs_bucket_upload_from_stream_with_id (bucket, &val, filename, source, opts, error); if (!r) { return false; @@ -333,10 +318,7 @@ mongoc_gridfs_bucket_open_download_stream (mongoc_gridfs_bucket_t *bucket, } if (!bson_iter_init (&iter, &file_doc)) { - bson_set_error (error, - MONGOC_ERROR_BSON, - MONGOC_ERROR_BSON_INVALID, - "File document malformed"); + bson_set_error (error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "File document malformed"); return NULL; } @@ -384,17 +366,13 @@ mongoc_gridfs_bucket_download_to_stream (mongoc_gridfs_bucket_t *bucket, BSON_ASSERT (destination); /* Make the download stream */ - download_stream = - mongoc_gridfs_bucket_open_download_stream (bucket, file_id, error); + download_stream = mongoc_gridfs_bucket_open_download_stream (bucket, file_id, error); - while ((bytes_read = mongoc_stream_read (download_stream, buf, 256, 1, 0)) > - 0) { + while ((bytes_read = mongoc_stream_read (download_stream, buf, 256, 1, 0)) > 0) { bytes_written = mongoc_stream_write (destination, buf, bytes_read, 0); if (bytes_written < 0) { - bson_set_error (error, - MONGOC_ERROR_GRIDFS, - MONGOC_ERROR_GRIDFS_BUCKET_STREAM, - "Error occurred on the provided stream."); + bson_set_error ( + error, MONGOC_ERROR_GRIDFS, MONGOC_ERROR_GRIDFS_BUCKET_STREAM, "Error occurred on the provided stream."); mongoc_stream_destroy (download_stream); return false; } @@ -405,9 +383,7 @@ mongoc_gridfs_bucket_download_to_stream (mongoc_gridfs_bucket_t *bucket, } bool -mongoc_gridfs_bucket_delete_by_id (mongoc_gridfs_bucket_t *bucket, - const bson_value_t *file_id, - bson_error_t *error) +mongoc_gridfs_bucket_delete_by_id (mongoc_gridfs_bucket_t *bucket, const bson_value_t *file_id, bson_error_t *error) { bson_t files_selector; bson_t chunks_selector; @@ -422,8 +398,7 @@ mongoc_gridfs_bucket_delete_by_id (mongoc_gridfs_bucket_t *bucket, BSON_APPEND_VALUE (&files_selector, "_id", file_id); - r = mongoc_collection_delete_one ( - bucket->files, &files_selector, NULL, &reply, error); + r = mongoc_collection_delete_one (bucket->files, &files_selector, NULL, &reply, error); bson_destroy (&files_selector); if (!r) { bson_destroy (&reply); @@ -433,10 +408,7 @@ mongoc_gridfs_bucket_delete_by_id (mongoc_gridfs_bucket_t *bucket, BSON_ASSERT (bson_iter_init_find (&iter, &reply, "deletedCount")); if (bson_iter_as_int64 (&iter) != 1) { - bson_set_error (error, - MONGOC_ERROR_GRIDFS, - MONGOC_ERROR_GRIDFS_BUCKET_FILE_NOT_FOUND, - "File not found"); + bson_set_error (error, MONGOC_ERROR_GRIDFS, MONGOC_ERROR_GRIDFS_BUCKET_FILE_NOT_FOUND, "File not found"); bson_destroy (&reply); return false; } @@ -447,8 +419,7 @@ mongoc_gridfs_bucket_delete_by_id (mongoc_gridfs_bucket_t *bucket, BSON_APPEND_VALUE (&chunks_selector, "files_id", file_id); - r = mongoc_collection_delete_many ( - bucket->chunks, &chunks_selector, NULL, NULL, error); + r = mongoc_collection_delete_many (bucket->chunks, &chunks_selector, NULL, NULL, error); bson_destroy (&chunks_selector); if (!r) { return false; @@ -458,21 +429,16 @@ mongoc_gridfs_bucket_delete_by_id (mongoc_gridfs_bucket_t *bucket, } mongoc_cursor_t * -mongoc_gridfs_bucket_find (mongoc_gridfs_bucket_t *bucket, - const bson_t *filter, - const bson_t *opts) +mongoc_gridfs_bucket_find (mongoc_gridfs_bucket_t *bucket, const bson_t *filter, const bson_t *opts) { mongoc_cursor_t *cursor; BSON_ASSERT (bucket); BSON_ASSERT (filter); - cursor = - mongoc_collection_find_with_opts (bucket->files, filter, opts, NULL); + cursor = mongoc_collection_find_with_opts (bucket->files, filter, opts, NULL); if (!cursor->error.code && opts && bson_has_field (opts, "sessionId")) { - bson_set_error (&cursor->error, - MONGOC_ERROR_CURSOR, - MONGOC_ERROR_CURSOR_INVALID_CURSOR, - "Cannot pass sessionId as an option"); + bson_set_error ( + &cursor->error, MONGOC_ERROR_CURSOR, MONGOC_ERROR_CURSOR_INVALID_CURSOR, "Cannot pass sessionId as an option"); } return cursor; } @@ -531,8 +497,7 @@ mongoc_gridfs_bucket_abort_upload (mongoc_stream_t *stream) bson_init (&chunks_selector); BSON_APPEND_VALUE (&chunks_selector, "files_id", file->file_id); - r = mongoc_collection_delete_many ( - file->bucket->chunks, &chunks_selector, NULL, NULL, &file->err); + r = mongoc_collection_delete_many (file->bucket->chunks, &chunks_selector, NULL, NULL, &file->err); bson_destroy (&chunks_selector); return r; } diff --git a/src/libmongoc/src/mongoc/mongoc-gridfs-bucket.h b/src/libmongoc/src/mongoc/mongoc-gridfs-bucket.h index 9bde457e2e..934df233e1 100644 --- a/src/libmongoc/src/mongoc/mongoc-gridfs-bucket.h +++ b/src/libmongoc/src/mongoc/mongoc-gridfs-bucket.h @@ -39,16 +39,14 @@ mongoc_gridfs_bucket_open_upload_stream (mongoc_gridfs_bucket_t *bucket, const char *filename, const bson_t *opts, bson_value_t *file_id, - bson_error_t *error) - BSON_GNUC_WARN_UNUSED_RESULT; + bson_error_t *error) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (mongoc_stream_t *) mongoc_gridfs_bucket_open_upload_stream_with_id (mongoc_gridfs_bucket_t *bucket, const bson_value_t *file_id, const char *filename, const bson_t *opts, - bson_error_t *error) - BSON_GNUC_WARN_UNUSED_RESULT; + bson_error_t *error) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (bool) mongoc_gridfs_bucket_upload_from_stream (mongoc_gridfs_bucket_t *bucket, @@ -69,8 +67,7 @@ mongoc_gridfs_bucket_upload_from_stream_with_id (mongoc_gridfs_bucket_t *bucket, MONGOC_EXPORT (mongoc_stream_t *) mongoc_gridfs_bucket_open_download_stream (mongoc_gridfs_bucket_t *bucket, const bson_value_t *file_id, - bson_error_t *error) - BSON_GNUC_WARN_UNUSED_RESULT; + bson_error_t *error) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (bool) mongoc_gridfs_bucket_download_to_stream (mongoc_gridfs_bucket_t *bucket, @@ -79,9 +76,7 @@ mongoc_gridfs_bucket_download_to_stream (mongoc_gridfs_bucket_t *bucket, bson_error_t *error); MONGOC_EXPORT (bool) -mongoc_gridfs_bucket_delete_by_id (mongoc_gridfs_bucket_t *bucket, - const bson_value_t *file_id, - bson_error_t *error); +mongoc_gridfs_bucket_delete_by_id (mongoc_gridfs_bucket_t *bucket, const bson_value_t *file_id, bson_error_t *error); MONGOC_EXPORT (mongoc_cursor_t *) mongoc_gridfs_bucket_find (mongoc_gridfs_bucket_t *bucket, @@ -89,8 +84,7 @@ mongoc_gridfs_bucket_find (mongoc_gridfs_bucket_t *bucket, const bson_t *opts) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (bool) -mongoc_gridfs_bucket_stream_error (mongoc_stream_t *stream, - bson_error_t *error); +mongoc_gridfs_bucket_stream_error (mongoc_stream_t *stream, bson_error_t *error); MONGOC_EXPORT (void) mongoc_gridfs_bucket_destroy (mongoc_gridfs_bucket_t *bucket); diff --git a/src/libmongoc/src/mongoc/mongoc-gridfs-file-list-private.h b/src/libmongoc/src/mongoc/mongoc-gridfs-file-list-private.h index d7179ca15d..2d081fc91f 100644 --- a/src/libmongoc/src/mongoc/mongoc-gridfs-file-list-private.h +++ b/src/libmongoc/src/mongoc/mongoc-gridfs-file-list-private.h @@ -37,13 +37,9 @@ struct _mongoc_gridfs_file_list_t { mongoc_gridfs_file_list_t * -_mongoc_gridfs_file_list_new (mongoc_gridfs_t *gridfs, - const bson_t *query, - uint32_t limit); +_mongoc_gridfs_file_list_new (mongoc_gridfs_t *gridfs, const bson_t *query, uint32_t limit); mongoc_gridfs_file_list_t * -_mongoc_gridfs_file_list_new_with_opts (mongoc_gridfs_t *gridfs, - const bson_t *filter, - const bson_t *opts); +_mongoc_gridfs_file_list_new_with_opts (mongoc_gridfs_t *gridfs, const bson_t *filter, const bson_t *opts); BSON_END_DECLS diff --git a/src/libmongoc/src/mongoc/mongoc-gridfs-file-list.c b/src/libmongoc/src/mongoc/mongoc-gridfs-file-list.c index eef37dfc52..d3f32923db 100644 --- a/src/libmongoc/src/mongoc/mongoc-gridfs-file-list.c +++ b/src/libmongoc/src/mongoc/mongoc-gridfs-file-list.c @@ -34,9 +34,7 @@ mongoc_gridfs_file_list_t * -_mongoc_gridfs_file_list_new (mongoc_gridfs_t *gridfs, - const bson_t *query, - uint32_t limit) +_mongoc_gridfs_file_list_new (mongoc_gridfs_t *gridfs, const bson_t *query, uint32_t limit) { mongoc_gridfs_file_list_t *list; mongoc_cursor_t *cursor; @@ -45,8 +43,7 @@ _mongoc_gridfs_file_list_new (mongoc_gridfs_t *gridfs, bson_t unwrapped; bson_error_t error; bson_init (&opts); - use_unwrapped = _mongoc_cursor_translate_dollar_query_opts ( - query, &opts, &unwrapped, &error); + use_unwrapped = _mongoc_cursor_translate_dollar_query_opts (query, &opts, &unwrapped, &error); cursor = _mongoc_cursor_find_new (gridfs->client, @@ -76,15 +73,12 @@ _mongoc_gridfs_file_list_new (mongoc_gridfs_t *gridfs, mongoc_gridfs_file_list_t * -_mongoc_gridfs_file_list_new_with_opts (mongoc_gridfs_t *gridfs, - const bson_t *filter, - const bson_t *opts) +_mongoc_gridfs_file_list_new_with_opts (mongoc_gridfs_t *gridfs, const bson_t *filter, const bson_t *opts) { mongoc_gridfs_file_list_t *list; mongoc_cursor_t *cursor; - cursor = mongoc_collection_find_with_opts ( - gridfs->files, filter, opts, NULL /* read prefs */); + cursor = mongoc_collection_find_with_opts (gridfs->files, filter, opts, NULL /* read prefs */); BSON_ASSERT (cursor); @@ -113,8 +107,7 @@ mongoc_gridfs_file_list_next (mongoc_gridfs_file_list_t *list) bool -mongoc_gridfs_file_list_error (mongoc_gridfs_file_list_t *list, - bson_error_t *error) +mongoc_gridfs_file_list_error (mongoc_gridfs_file_list_t *list, bson_error_t *error) { return mongoc_cursor_error (list->cursor, error); } diff --git a/src/libmongoc/src/mongoc/mongoc-gridfs-file-list.h b/src/libmongoc/src/mongoc/mongoc-gridfs-file-list.h index 284204ae48..627b97b6fe 100644 --- a/src/libmongoc/src/mongoc/mongoc-gridfs-file-list.h +++ b/src/libmongoc/src/mongoc/mongoc-gridfs-file-list.h @@ -32,13 +32,11 @@ typedef struct _mongoc_gridfs_file_list_t mongoc_gridfs_file_list_t; MONGOC_EXPORT (mongoc_gridfs_file_t *) -mongoc_gridfs_file_list_next (mongoc_gridfs_file_list_t *list) - BSON_GNUC_WARN_UNUSED_RESULT; +mongoc_gridfs_file_list_next (mongoc_gridfs_file_list_t *list) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (void) mongoc_gridfs_file_list_destroy (mongoc_gridfs_file_list_t *list); MONGOC_EXPORT (bool) -mongoc_gridfs_file_list_error (mongoc_gridfs_file_list_t *list, - bson_error_t *error); +mongoc_gridfs_file_list_error (mongoc_gridfs_file_list_t *list, bson_error_t *error); BSON_END_DECLS diff --git a/src/libmongoc/src/mongoc/mongoc-gridfs-file-page-private.h b/src/libmongoc/src/mongoc/mongoc-gridfs-file-page-private.h index c57943123c..0401c90fb4 100644 --- a/src/libmongoc/src/mongoc/mongoc-gridfs-file-page-private.h +++ b/src/libmongoc/src/mongoc/mongoc-gridfs-file-page-private.h @@ -37,25 +37,17 @@ struct _mongoc_gridfs_file_page_t { mongoc_gridfs_file_page_t * -_mongoc_gridfs_file_page_new (const uint8_t *data, - uint32_t len, - uint32_t chunk_size); +_mongoc_gridfs_file_page_new (const uint8_t *data, uint32_t len, uint32_t chunk_size); void _mongoc_gridfs_file_page_destroy (mongoc_gridfs_file_page_t *page); bool -_mongoc_gridfs_file_page_seek (mongoc_gridfs_file_page_t *page, - uint32_t offset); +_mongoc_gridfs_file_page_seek (mongoc_gridfs_file_page_t *page, uint32_t offset); int32_t -_mongoc_gridfs_file_page_read (mongoc_gridfs_file_page_t *page, - void *dst, - uint32_t len); +_mongoc_gridfs_file_page_read (mongoc_gridfs_file_page_t *page, void *dst, uint32_t len); int32_t -_mongoc_gridfs_file_page_write (mongoc_gridfs_file_page_t *page, - const void *src, - uint32_t len); +_mongoc_gridfs_file_page_write (mongoc_gridfs_file_page_t *page, const void *src, uint32_t len); uint32_t -_mongoc_gridfs_file_page_memset0 (mongoc_gridfs_file_page_t *page, - uint32_t len); +_mongoc_gridfs_file_page_memset0 (mongoc_gridfs_file_page_t *page, uint32_t len); uint32_t _mongoc_gridfs_file_page_tell (mongoc_gridfs_file_page_t *page); const uint8_t * diff --git a/src/libmongoc/src/mongoc/mongoc-gridfs-file-page.c b/src/libmongoc/src/mongoc/mongoc-gridfs-file-page.c index e161ef950c..2fa38bb826 100644 --- a/src/libmongoc/src/mongoc/mongoc-gridfs-file-page.c +++ b/src/libmongoc/src/mongoc/mongoc-gridfs-file-page.c @@ -29,9 +29,7 @@ * The buffer should stick around for the life of the page */ mongoc_gridfs_file_page_t * -_mongoc_gridfs_file_page_new (const uint8_t *data, - uint32_t len, - uint32_t chunk_size) +_mongoc_gridfs_file_page_new (const uint8_t *data, uint32_t len, uint32_t chunk_size) { mongoc_gridfs_file_page_t *page; @@ -64,9 +62,7 @@ _mongoc_gridfs_file_page_seek (mongoc_gridfs_file_page_t *page, uint32_t offset) int32_t -_mongoc_gridfs_file_page_read (mongoc_gridfs_file_page_t *page, - void *dst, - uint32_t len) +_mongoc_gridfs_file_page_read (mongoc_gridfs_file_page_t *page, void *dst, uint32_t len) { int bytes_read; const uint8_t *src; @@ -101,9 +97,7 @@ _mongoc_gridfs_file_page_read (mongoc_gridfs_file_page_t *page, * A write of zero bytes will trigger the copy-on-write mechanism. */ int32_t -_mongoc_gridfs_file_page_write (mongoc_gridfs_file_page_t *page, - const void *src, - uint32_t len) +_mongoc_gridfs_file_page_write (mongoc_gridfs_file_page_t *page, const void *src, uint32_t len) { int bytes_written; @@ -116,8 +110,7 @@ _mongoc_gridfs_file_page_write (mongoc_gridfs_file_page_t *page, if (!page->buf) { page->buf = (uint8_t *) bson_malloc (page->chunk_size); - memcpy ( - page->buf, page->read_buf, BSON_MIN (page->chunk_size, page->len)); + memcpy (page->buf, page->read_buf, BSON_MIN (page->chunk_size, page->len)); } /* Copy bytes and adjust the page position */ @@ -158,8 +151,7 @@ _mongoc_gridfs_file_page_memset0 (mongoc_gridfs_file_page_t *page, uint32_t len) if (!page->buf) { page->buf = (uint8_t *) bson_malloc0 (page->chunk_size); - memcpy ( - page->buf, page->read_buf, BSON_MIN (page->chunk_size, page->len)); + memcpy (page->buf, page->read_buf, BSON_MIN (page->chunk_size, page->len)); } /* Set bytes and adjust the page position */ diff --git a/src/libmongoc/src/mongoc/mongoc-gridfs-file-private.h b/src/libmongoc/src/mongoc/mongoc-gridfs-file-private.h index 571afa51f1..1b5ba886c2 100644 --- a/src/libmongoc/src/mongoc/mongoc-gridfs-file-private.h +++ b/src/libmongoc/src/mongoc/mongoc-gridfs-file-private.h @@ -62,8 +62,7 @@ struct _mongoc_gridfs_file_t { mongoc_gridfs_file_t * _mongoc_gridfs_file_new_from_bson (mongoc_gridfs_t *gridfs, const bson_t *data); mongoc_gridfs_file_t * -_mongoc_gridfs_file_new (mongoc_gridfs_t *gridfs, - mongoc_gridfs_file_opt_t *opt); +_mongoc_gridfs_file_new (mongoc_gridfs_t *gridfs, mongoc_gridfs_file_opt_t *opt); BSON_END_DECLS diff --git a/src/libmongoc/src/mongoc/mongoc-gridfs-file.c b/src/libmongoc/src/mongoc/mongoc-gridfs-file.c index 7245eebb49..c5190326a4 100644 --- a/src/libmongoc/src/mongoc/mongoc-gridfs-file.c +++ b/src/libmongoc/src/mongoc/mongoc-gridfs-file.c @@ -54,40 +54,38 @@ _mongoc_gridfs_file_extend (mongoc_gridfs_file_t *file); * setters we need *****************************************************************/ -#define MONGOC_GRIDFS_FILE_STR_ACCESSOR(name) \ - const char *mongoc_gridfs_file_get_##name (mongoc_gridfs_file_t *file) \ - { \ - return file->name ? file->name : file->bson_##name; \ - } \ - void mongoc_gridfs_file_set_##name (mongoc_gridfs_file_t *file, \ - const char *str) \ - { \ - if (file->name) { \ - bson_free (file->name); \ - } \ - file->name = bson_strdup (str); \ - file->is_dirty = 1; \ +#define MONGOC_GRIDFS_FILE_STR_ACCESSOR(name) \ + const char *mongoc_gridfs_file_get_##name (mongoc_gridfs_file_t *file) \ + { \ + return file->name ? file->name : file->bson_##name; \ + } \ + void mongoc_gridfs_file_set_##name (mongoc_gridfs_file_t *file, const char *str) \ + { \ + if (file->name) { \ + bson_free (file->name); \ + } \ + file->name = bson_strdup (str); \ + file->is_dirty = 1; \ } -#define MONGOC_GRIDFS_FILE_BSON_ACCESSOR(name) \ - const bson_t *mongoc_gridfs_file_get_##name (mongoc_gridfs_file_t *file) \ - { \ - if (file->name.len) { \ - return &file->name; \ - } else if (file->bson_##name.len) { \ - return &file->bson_##name; \ - } else { \ - return NULL; \ - } \ - } \ - void mongoc_gridfs_file_set_##name (mongoc_gridfs_file_t *file, \ - const bson_t *bson) \ - { \ - if (file->name.len) { \ - bson_destroy (&file->name); \ - } \ - bson_copy_to (bson, &(file->name)); \ - file->is_dirty = 1; \ +#define MONGOC_GRIDFS_FILE_BSON_ACCESSOR(name) \ + const bson_t *mongoc_gridfs_file_get_##name (mongoc_gridfs_file_t *file) \ + { \ + if (file->name.len) { \ + return &file->name; \ + } else if (file->bson_##name.len) { \ + return &file->bson_##name; \ + } else { \ + return NULL; \ + } \ + } \ + void mongoc_gridfs_file_set_##name (mongoc_gridfs_file_t *file, const bson_t *bson) \ + { \ + if (file->name.len) { \ + bson_destroy (&file->name); \ + } \ + bson_copy_to (bson, &(file->name)); \ + file->is_dirty = 1; \ } MONGOC_GRIDFS_FILE_STR_ACCESSOR (md5) @@ -105,15 +103,11 @@ MONGOC_GRIDFS_FILE_BSON_ACCESSOR (metadata) */ bool -mongoc_gridfs_file_set_id (mongoc_gridfs_file_t *file, - const bson_value_t *id, - bson_error_t *error) +mongoc_gridfs_file_set_id (mongoc_gridfs_file_t *file, const bson_value_t *id, bson_error_t *error) { if (!file->is_dirty) { - bson_set_error (error, - MONGOC_ERROR_GRIDFS, - MONGOC_ERROR_GRIDFS_PROTOCOL_ERROR, - "Cannot set file id after saving file."); + bson_set_error ( + error, MONGOC_ERROR_GRIDFS, MONGOC_ERROR_GRIDFS_PROTOCOL_ERROR, "Cannot set file id after saving file."); return false; } bson_value_copy (id, &file->files_id); @@ -181,12 +175,7 @@ mongoc_gridfs_file_save (mongoc_gridfs_file_t *file) bson_append_document_end (update, &child); - r = mongoc_collection_update (file->gridfs->files, - MONGOC_UPDATE_UPSERT, - selector, - update, - NULL, - &file->error); + r = mongoc_collection_update (file->gridfs->files, MONGOC_UPDATE_UPSERT, selector, update, NULL, &file->error); bson_destroy (selector); bson_destroy (update); @@ -428,11 +417,8 @@ mongoc_gridfs_file_destroy (mongoc_gridfs_file_t *file) /** readv against a gridfs file * timeout_msec is unused */ ssize_t -mongoc_gridfs_file_readv (mongoc_gridfs_file_t *file, - mongoc_iovec_t *iov, - size_t iovcnt, - size_t min_bytes, - uint32_t timeout_msec) +mongoc_gridfs_file_readv ( + mongoc_gridfs_file_t *file, mongoc_iovec_t *iov, size_t iovcnt, size_t min_bytes, uint32_t timeout_msec) { uint32_t bytes_read = 0; int32_t r; @@ -462,9 +448,7 @@ mongoc_gridfs_file_readv (mongoc_gridfs_file_t *file, for (;;) { r = _mongoc_gridfs_file_page_read ( - file->page, - (uint8_t *) iov[i].iov_base + iov_pos, - (uint32_t) (iov[i].iov_len - iov_pos)); + file->page, (uint8_t *) iov[i].iov_base + iov_pos, (uint32_t) (iov[i].iov_len - iov_pos)); BSON_ASSERT (r >= 0); iov_pos += r; @@ -493,10 +477,7 @@ mongoc_gridfs_file_readv (mongoc_gridfs_file_t *file, /** writev against a gridfs file * timeout_msec is unused */ ssize_t -mongoc_gridfs_file_writev (mongoc_gridfs_file_t *file, - const mongoc_iovec_t *iov, - size_t iovcnt, - uint32_t timeout_msec) +mongoc_gridfs_file_writev (mongoc_gridfs_file_t *file, const mongoc_iovec_t *iov, size_t iovcnt, uint32_t timeout_msec) { uint32_t bytes_written = 0; int32_t r; @@ -517,8 +498,7 @@ mongoc_gridfs_file_writev (mongoc_gridfs_file_t *file, } /* When writing past the end-of-file, fill the gap with zeros */ - if (bson_cmp_greater_us (file->pos, file->length) && - !_mongoc_gridfs_file_extend (file)) { + if (bson_cmp_greater_us (file->pos, file->length) && !_mongoc_gridfs_file_extend (file)) { return -1; } @@ -532,9 +512,7 @@ mongoc_gridfs_file_writev (mongoc_gridfs_file_t *file, /* write bytes until an iov is exhausted or the page is full */ r = _mongoc_gridfs_file_page_write ( - file->page, - (uint8_t *) iov[i].iov_base + iov_pos, - (uint32_t) (iov[i].iov_len - iov_pos)); + file->page, (uint8_t *) iov[i].iov_base + iov_pos, (uint32_t) (iov[i].iov_len - iov_pos)); BSON_ASSERT (r >= 0); iov_pos += r; @@ -607,8 +585,7 @@ _mongoc_gridfs_file_extend (mongoc_gridfs_file_t *file) { const uint64_t len = target_length - file->pos; BSON_ASSERT (bson_in_range_unsigned (uint32_t, len)); - file->pos += - _mongoc_gridfs_file_page_memset0 (file->page, (uint32_t) len); + file->pos += _mongoc_gridfs_file_page_memset0 (file->page, (uint32_t) len); } if (file->pos == target_length) { @@ -669,12 +646,7 @@ _mongoc_gridfs_file_flush_page (mongoc_gridfs_file_t *file) bson_append_int32 (update, "n", -1, file->n); bson_append_binary (update, "data", -1, BSON_SUBTYPE_BINARY, buf, len); - r = mongoc_collection_update (file->gridfs->chunks, - MONGOC_UPDATE_UPSERT, - selector, - update, - NULL, - &file->error); + r = mongoc_collection_update (file->gridfs->chunks, MONGOC_UPDATE_UPSERT, selector, update, NULL, &file->error); bson_destroy (selector); bson_destroy (update); @@ -737,11 +709,8 @@ divide_round_up (int64_t num, int64_t denom) static void missing_chunk (mongoc_gridfs_file_t *file) { - bson_set_error (&file->error, - MONGOC_ERROR_GRIDFS, - MONGOC_ERROR_GRIDFS_CHUNK_MISSING, - "missing chunk number %" PRId32, - file->n); + bson_set_error ( + &file->error, MONGOC_ERROR_GRIDFS, MONGOC_ERROR_GRIDFS_CHUNK_MISSING, "missing chunk number %" PRId32, file->n); if (file->cursor) { mongoc_cursor_destroy (file->cursor); @@ -790,10 +759,8 @@ _mongoc_gridfs_file_refresh_page (mongoc_gridfs_file_t *file) /* if the file pointer is past the end of the current file (i.e. pointing to * a new chunk), we'll pass the page constructor a new empty page. */ - const int64_t existing_chunks = - divide_round_up (file->length, file->chunk_size); - const int64_t required_chunks = - divide_round_up (file->pos + 1, file->chunk_size); + const int64_t existing_chunks = divide_round_up (file->length, file->chunk_size); + const int64_t required_chunks = divide_round_up (file->pos + 1, file->chunk_size); if (required_chunks > existing_chunks) { data = (uint8_t *) ""; @@ -829,8 +796,7 @@ _mongoc_gridfs_file_refresh_page (mongoc_gridfs_file_t *file) bson_append_document_end (&opts, &child); /* find all chunks greater than or equal to our current file pos */ - file->cursor = mongoc_collection_find_with_opts ( - file->gridfs->chunks, &query, &opts, NULL); + file->cursor = mongoc_collection_find_with_opts (file->gridfs->chunks, &query, &opts, NULL); file->cursor_range[0] = file->n; file->cursor_range[1] = (uint32_t) (file->length / file->chunk_size); @@ -904,8 +870,7 @@ _mongoc_gridfs_file_refresh_page (mongoc_gridfs_file_t *file) file->page = _mongoc_gridfs_file_page_new (data, len, file->chunk_size); /* seek in the page towards wherever we're supposed to be */ - RETURN ( - _mongoc_gridfs_file_page_seek (file->page, file->pos % file->chunk_size)); + RETURN (_mongoc_gridfs_file_page_seek (file->page, file->pos % file->chunk_size)); } @@ -1015,11 +980,7 @@ mongoc_gridfs_file_error (mongoc_gridfs_file_t *file, bson_error_t *error) BSON_ASSERT (error); if (BSON_UNLIKELY (file->error.domain)) { - bson_set_error (error, - file->error.domain, - file->error.code, - "%s", - file->error.message); + bson_set_error (error, file->error.domain, file->error.code, "%s", file->error.message); RETURN (true); } @@ -1068,16 +1029,14 @@ mongoc_gridfs_file_remove (mongoc_gridfs_file_t *file, bson_error_t *error) BSON_APPEND_VALUE (&sel, "_id", &file->files_id); - if (!mongoc_collection_delete_one ( - file->gridfs->files, &sel, NULL, NULL, error)) { + if (!mongoc_collection_delete_one (file->gridfs->files, &sel, NULL, NULL, error)) { goto cleanup; } bson_reinit (&sel); BSON_APPEND_VALUE (&sel, "files_id", &file->files_id); - if (!mongoc_collection_delete_many ( - file->gridfs->chunks, &sel, NULL, NULL, error)) { + if (!mongoc_collection_delete_many (file->gridfs->chunks, &sel, NULL, NULL, error)) { goto cleanup; } diff --git a/src/libmongoc/src/mongoc/mongoc-gridfs-file.h b/src/libmongoc/src/mongoc/mongoc-gridfs-file.h index 2af8f793f2..1792c4c002 100644 --- a/src/libmongoc/src/mongoc/mongoc-gridfs-file.h +++ b/src/libmongoc/src/mongoc/mongoc-gridfs-file.h @@ -38,8 +38,7 @@ BSON_BEGIN_DECLS MONGOC_EXPORT (const bson_t *) \ mongoc_gridfs_file_get_##name (mongoc_gridfs_file_t *file); \ MONGOC_EXPORT (void) \ - mongoc_gridfs_file_set_##name (mongoc_gridfs_file_t *file, \ - const bson_t *bson); + mongoc_gridfs_file_set_##name (mongoc_gridfs_file_t *file, const bson_t *bson); typedef struct _mongoc_gridfs_file_t mongoc_gridfs_file_t; @@ -76,16 +75,10 @@ MONGOC_EXPORT (int64_t) mongoc_gridfs_file_get_upload_date (mongoc_gridfs_file_t *file); MONGOC_EXPORT (ssize_t) -mongoc_gridfs_file_writev (mongoc_gridfs_file_t *file, - const mongoc_iovec_t *iov, - size_t iovcnt, - uint32_t timeout_msec); +mongoc_gridfs_file_writev (mongoc_gridfs_file_t *file, const mongoc_iovec_t *iov, size_t iovcnt, uint32_t timeout_msec); MONGOC_EXPORT (ssize_t) -mongoc_gridfs_file_readv (mongoc_gridfs_file_t *file, - mongoc_iovec_t *iov, - size_t iovcnt, - size_t min_bytes, - uint32_t timeout_msec); +mongoc_gridfs_file_readv ( + mongoc_gridfs_file_t *file, mongoc_iovec_t *iov, size_t iovcnt, size_t min_bytes, uint32_t timeout_msec); MONGOC_EXPORT (int) mongoc_gridfs_file_seek (mongoc_gridfs_file_t *file, int64_t delta, int whence); @@ -93,9 +86,7 @@ MONGOC_EXPORT (uint64_t) mongoc_gridfs_file_tell (mongoc_gridfs_file_t *file); MONGOC_EXPORT (bool) -mongoc_gridfs_file_set_id (mongoc_gridfs_file_t *file, - const bson_value_t *id, - bson_error_t *error); +mongoc_gridfs_file_set_id (mongoc_gridfs_file_t *file, const bson_value_t *id, bson_error_t *error); MONGOC_EXPORT (bool) mongoc_gridfs_file_save (mongoc_gridfs_file_t *file); diff --git a/src/libmongoc/src/mongoc/mongoc-gridfs-private.h b/src/libmongoc/src/mongoc/mongoc-gridfs-private.h index 1138d331df..b1a0661eba 100644 --- a/src/libmongoc/src/mongoc/mongoc-gridfs-private.h +++ b/src/libmongoc/src/mongoc/mongoc-gridfs-private.h @@ -37,10 +37,7 @@ struct _mongoc_gridfs_t { mongoc_gridfs_t * -_mongoc_gridfs_new (mongoc_client_t *client, - const char *db, - const char *prefix, - bson_error_t *error); +_mongoc_gridfs_new (mongoc_client_t *client, const char *db, const char *prefix, bson_error_t *error); BSON_END_DECLS diff --git a/src/libmongoc/src/mongoc/mongoc-gridfs.c b/src/libmongoc/src/mongoc/mongoc-gridfs.c index 39f8bef80b..6889e9669a 100644 --- a/src/libmongoc/src/mongoc/mongoc-gridfs.c +++ b/src/libmongoc/src/mongoc/mongoc-gridfs.c @@ -63,8 +63,7 @@ _mongoc_gridfs_ensure_index (mongoc_gridfs_t *gridfs, bson_error_t *error) BSON_APPEND_INT32 (&keys, "files_id", 1); BSON_APPEND_INT32 (&keys, "n", 1); - r = _mongoc_collection_create_index_if_not_exists ( - gridfs->chunks, &keys, &opts, error); + r = _mongoc_collection_create_index_if_not_exists (gridfs->chunks, &keys, &opts, error); bson_destroy (&opts); bson_destroy (&keys); @@ -78,8 +77,7 @@ _mongoc_gridfs_ensure_index (mongoc_gridfs_t *gridfs, bson_error_t *error) BSON_APPEND_INT32 (&keys, "filename", 1); BSON_APPEND_INT32 (&keys, "uploadDate", 1); - r = _mongoc_collection_create_index_if_not_exists ( - gridfs->files, &keys, NULL, error); + r = _mongoc_collection_create_index_if_not_exists (gridfs->files, &keys, NULL, error); bson_destroy (&keys); @@ -92,10 +90,7 @@ _mongoc_gridfs_ensure_index (mongoc_gridfs_t *gridfs, bson_error_t *error) mongoc_gridfs_t * -_mongoc_gridfs_new (mongoc_client_t *client, - const char *db, - const char *prefix, - bson_error_t *error) +_mongoc_gridfs_new (mongoc_client_t *client, const char *db, const char *prefix, bson_error_t *error) { mongoc_gridfs_t *gridfs; char buf[128]; @@ -187,9 +182,7 @@ mongoc_gridfs_find (mongoc_gridfs_t *gridfs, const bson_t *query) /** find a single gridfs file */ mongoc_gridfs_file_t * -mongoc_gridfs_find_one (mongoc_gridfs_t *gridfs, - const bson_t *query, - bson_error_t *error) +mongoc_gridfs_find_one (mongoc_gridfs_t *gridfs, const bson_t *query, bson_error_t *error) { mongoc_gridfs_file_list_t *list; mongoc_gridfs_file_t *file; @@ -212,9 +205,7 @@ mongoc_gridfs_find_one (mongoc_gridfs_t *gridfs, /** find all matching gridfs files */ mongoc_gridfs_file_list_t * -mongoc_gridfs_find_with_opts (mongoc_gridfs_t *gridfs, - const bson_t *filter, - const bson_t *opts) +mongoc_gridfs_find_with_opts (mongoc_gridfs_t *gridfs, const bson_t *filter, const bson_t *opts) { return _mongoc_gridfs_file_list_new_with_opts (gridfs, filter, opts); } @@ -258,9 +249,7 @@ mongoc_gridfs_find_one_with_opts (mongoc_gridfs_t *gridfs, /** find a single gridfs file by filename */ mongoc_gridfs_file_t * -mongoc_gridfs_find_one_by_filename (mongoc_gridfs_t *gridfs, - const char *filename, - bson_error_t *error) +mongoc_gridfs_find_one_by_filename (mongoc_gridfs_t *gridfs, const char *filename, bson_error_t *error) { mongoc_gridfs_file_t *file; @@ -283,9 +272,7 @@ mongoc_gridfs_find_one_by_filename (mongoc_gridfs_t *gridfs, * The stream is fully consumed in creating the file */ mongoc_gridfs_file_t * -mongoc_gridfs_create_file_from_stream (mongoc_gridfs_t *gridfs, - mongoc_stream_t *stream, - mongoc_gridfs_file_opt_t *opt) +mongoc_gridfs_create_file_from_stream (mongoc_gridfs_t *gridfs, mongoc_stream_t *stream, mongoc_gridfs_file_opt_t *opt) { mongoc_gridfs_file_t *file; ssize_t r; @@ -305,8 +292,7 @@ mongoc_gridfs_create_file_from_stream (mongoc_gridfs_t *gridfs, timeout = gridfs->client->cluster.sockettimeoutms; for (;;) { - r = mongoc_stream_read ( - stream, iov.iov_base, MONGOC_GRIDFS_STREAM_CHUNK, 0, timeout); + r = mongoc_stream_read (stream, iov.iov_base, MONGOC_GRIDFS_STREAM_CHUNK, 0, timeout); if (r > 0) { iov.iov_len = r; @@ -338,8 +324,7 @@ mongoc_gridfs_create_file_from_stream (mongoc_gridfs_t *gridfs, /** create an empty gridfs file */ mongoc_gridfs_file_t * -mongoc_gridfs_create_file (mongoc_gridfs_t *gridfs, - mongoc_gridfs_file_opt_t *opt) +mongoc_gridfs_create_file (mongoc_gridfs_t *gridfs, mongoc_gridfs_file_opt_t *opt) { mongoc_gridfs_file_t *file; @@ -371,9 +356,7 @@ mongoc_gridfs_get_chunks (mongoc_gridfs_t *gridfs) bool -mongoc_gridfs_remove_by_filename (mongoc_gridfs_t *gridfs, - const char *filename, - bson_error_t *error) +mongoc_gridfs_remove_by_filename (mongoc_gridfs_t *gridfs, const char *filename, bson_error_t *error) { mongoc_bulk_operation_t *bulk_files = NULL; mongoc_bulk_operation_t *bulk_chunks = NULL; @@ -399,10 +382,8 @@ mongoc_gridfs_remove_by_filename (mongoc_gridfs_t *gridfs, BSON_ASSERT (gridfs); if (!filename) { - bson_set_error (error, - MONGOC_ERROR_GRIDFS, - MONGOC_ERROR_GRIDFS_INVALID_FILENAME, - "A non-NULL filename must be specified."); + bson_set_error ( + error, MONGOC_ERROR_GRIDFS, MONGOC_ERROR_GRIDFS_INVALID_FILENAME, "A non-NULL filename must be specified."); return false; } @@ -440,10 +421,8 @@ mongoc_gridfs_remove_by_filename (mongoc_gridfs_t *gridfs, } bson_append_bool (&opts, "ordered", 7, false); - bulk_files = - mongoc_collection_create_bulk_operation_with_opts (gridfs->files, &opts); - bulk_chunks = - mongoc_collection_create_bulk_operation_with_opts (gridfs->chunks, &opts); + bulk_files = mongoc_collection_create_bulk_operation_with_opts (gridfs->files, &opts); + bulk_chunks = mongoc_collection_create_bulk_operation_with_opts (gridfs->chunks, &opts); bson_destroy (&opts); @@ -454,8 +433,7 @@ mongoc_gridfs_remove_by_filename (mongoc_gridfs_t *gridfs, mongoc_bulk_operation_remove (bulk_chunks, chunks_q); files_ret = mongoc_bulk_operation_execute (bulk_files, NULL, &files_error); - chunks_ret = - mongoc_bulk_operation_execute (bulk_chunks, NULL, &chunks_error); + chunks_ret = mongoc_bulk_operation_execute (bulk_chunks, NULL, &chunks_error); if (error) { if (!files_ret) { diff --git a/src/libmongoc/src/mongoc/mongoc-gridfs.h b/src/libmongoc/src/mongoc/mongoc-gridfs.h index e75ba39729..d907b4705c 100644 --- a/src/libmongoc/src/mongoc/mongoc-gridfs.h +++ b/src/libmongoc/src/mongoc/mongoc-gridfs.h @@ -37,20 +37,14 @@ typedef struct _mongoc_gridfs_t mongoc_gridfs_t; MONGOC_EXPORT (mongoc_gridfs_file_t *) mongoc_gridfs_create_file_from_stream (mongoc_gridfs_t *gridfs, mongoc_stream_t *stream, - mongoc_gridfs_file_opt_t *opt) - BSON_GNUC_WARN_UNUSED_RESULT; + mongoc_gridfs_file_opt_t *opt) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (mongoc_gridfs_file_t *) -mongoc_gridfs_create_file (mongoc_gridfs_t *gridfs, - mongoc_gridfs_file_opt_t *opt) - BSON_GNUC_WARN_UNUSED_RESULT; +mongoc_gridfs_create_file (mongoc_gridfs_t *gridfs, mongoc_gridfs_file_opt_t *opt) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (mongoc_gridfs_file_list_t *) -mongoc_gridfs_find (mongoc_gridfs_t *gridfs, - const bson_t *query) BSON_GNUC_WARN_UNUSED_RESULT +mongoc_gridfs_find (mongoc_gridfs_t *gridfs, const bson_t *query) BSON_GNUC_WARN_UNUSED_RESULT BSON_GNUC_DEPRECATED_FOR (mongoc_gridfs_find_with_opts); MONGOC_EXPORT (mongoc_gridfs_file_t *) -mongoc_gridfs_find_one (mongoc_gridfs_t *gridfs, - const bson_t *query, - bson_error_t *error) BSON_GNUC_WARN_UNUSED_RESULT +mongoc_gridfs_find_one (mongoc_gridfs_t *gridfs, const bson_t *query, bson_error_t *error) BSON_GNUC_WARN_UNUSED_RESULT BSON_GNUC_DEPRECATED_FOR (mongoc_gridfs_find_one_with_opts); MONGOC_EXPORT (mongoc_gridfs_file_list_t *) mongoc_gridfs_find_with_opts (mongoc_gridfs_t *gridfs, @@ -60,13 +54,11 @@ MONGOC_EXPORT (mongoc_gridfs_file_t *) mongoc_gridfs_find_one_with_opts (mongoc_gridfs_t *gridfs, const bson_t *filter, const bson_t *opts, - bson_error_t *error) - BSON_GNUC_WARN_UNUSED_RESULT; + bson_error_t *error) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (mongoc_gridfs_file_t *) mongoc_gridfs_find_one_by_filename (mongoc_gridfs_t *gridfs, const char *filename, - bson_error_t *error) - BSON_GNUC_WARN_UNUSED_RESULT; + bson_error_t *error) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (bool) mongoc_gridfs_drop (mongoc_gridfs_t *gridfs, bson_error_t *error); MONGOC_EXPORT (void) @@ -76,9 +68,7 @@ mongoc_gridfs_get_files (mongoc_gridfs_t *gridfs); MONGOC_EXPORT (mongoc_collection_t *) mongoc_gridfs_get_chunks (mongoc_gridfs_t *gridfs); MONGOC_EXPORT (bool) -mongoc_gridfs_remove_by_filename (mongoc_gridfs_t *gridfs, - const char *filename, - bson_error_t *error); +mongoc_gridfs_remove_by_filename (mongoc_gridfs_t *gridfs, const char *filename, bson_error_t *error); BSON_END_DECLS diff --git a/src/libmongoc/src/mongoc/mongoc-handshake-compiler-private.h b/src/libmongoc/src/mongoc/mongoc-handshake-compiler-private.h index 66e7cc5b0e..f37b3a237c 100644 --- a/src/libmongoc/src/mongoc/mongoc-handshake-compiler-private.h +++ b/src/libmongoc/src/mongoc/mongoc-handshake-compiler-private.h @@ -46,10 +46,9 @@ #define MONGOC_COMPILER_VERSION MONGOC_EVALUATE_STR (_MSC_VER) #elif defined(__PGI) #define MONGOC_COMPILER "Portland PGCC" -#define MONGOC_COMPILER_VERSION \ - MONGOC_EVALUATE_STR (__PGIC__) \ - "." MONGOC_EVALUATE_STR (__PGIC_MINOR) "." MONGOC_EVALUATE_STR ( \ - __PGIC_PATCHLEVEL__) +#define MONGOC_COMPILER_VERSION \ + MONGOC_EVALUATE_STR (__PGIC__) \ + "." MONGOC_EVALUATE_STR (__PGIC_MINOR) "." MONGOC_EVALUATE_STR (__PGIC_PATCHLEVEL__) #elif defined(__SUNPRO_C) || defined(__SUNPRO_CC) #define MONGOC_COMPILER "Solaris Studio" #define MONGOC_COMPILER_VERSION MONGOC_EVALUATE_STR (__SUNPRO_C) diff --git a/src/libmongoc/src/mongoc/mongoc-handshake-private.h b/src/libmongoc/src/mongoc/mongoc-handshake-private.h index d138c91ffe..41efa2ad91 100644 --- a/src/libmongoc/src/mongoc/mongoc-handshake-private.h +++ b/src/libmongoc/src/mongoc/mongoc-handshake-private.h @@ -69,8 +69,7 @@ typedef enum { MONGOC_MD_FLAG_ENABLE_COMPRESSION = 18, MONGOC_MD_FLAG_ENABLE_COMPRESSION_SNAPPY = 19, MONGOC_MD_FLAG_ENABLE_COMPRESSION_ZLIB = 20, - MONGOC_MD_FLAG_ENABLE_SASL_GSSAPI_UNUSED = - 21, /* CDRIVER-2654 removed this . */ + MONGOC_MD_FLAG_ENABLE_SASL_GSSAPI_UNUSED = 21, /* CDRIVER-2654 removed this . */ MONGOC_MD_FLAG_ENABLE_RES_NSEARCH = 22, MONGOC_MD_FLAG_ENABLE_RES_NDESTROY = 23, MONGOC_MD_FLAG_ENABLE_RES_NCLOSE = 24, @@ -145,13 +144,11 @@ typedef struct { } mongoc_handshake_sasl_supported_mechs_t; void -_mongoc_handshake_append_sasl_supported_mechs (const mongoc_uri_t *uri, - bson_t *hello); +_mongoc_handshake_append_sasl_supported_mechs (const mongoc_uri_t *uri, bson_t *hello); void -_mongoc_handshake_parse_sasl_supported_mechs ( - const bson_t *hello, - mongoc_handshake_sasl_supported_mechs_t *sasl_supported_mechs); +_mongoc_handshake_parse_sasl_supported_mechs (const bson_t *hello, + mongoc_handshake_sasl_supported_mechs_t *sasl_supported_mechs); BSON_END_DECLS diff --git a/src/libmongoc/src/mongoc/mongoc-handshake.c b/src/libmongoc/src/mongoc/mongoc-handshake.c index 6b3fc28eee..22de7f36e6 100644 --- a/src/libmongoc/src/mongoc/mongoc-handshake.c +++ b/src/libmongoc/src/mongoc/mongoc-handshake.c @@ -63,8 +63,7 @@ _set_bit (uint8_t *bf, uint32_t byte_count, uint32_t bit) char * _mongoc_handshake_get_config_hex_string (void) { - const uint32_t byte_count = - (LAST_MONGOC_MD_FLAG + 7) / 8; /* ceil (num_bits / 8) */ + const uint32_t byte_count = (LAST_MONGOC_MD_FLAG + 7) / 8; /* ceil (num_bits / 8) */ /* allocate enough bytes to fit all config bits. */ uint8_t *const bf = (uint8_t *) bson_malloc0 (byte_count); @@ -302,12 +301,8 @@ _get_os_version (void) #endif if (res) { - bson_snprintf (ret, - HANDSHAKE_OS_VERSION_MAX, - "%lu.%lu (%lu)", - osvi.dwMajorVersion, - osvi.dwMinorVersion, - osvi.dwBuildNumber); + bson_snprintf ( + ret, HANDSHAKE_OS_VERSION_MAX, "%lu.%lu (%lu)", osvi.dwMajorVersion, osvi.dwMinorVersion, osvi.dwBuildNumber); found = true; } else { MONGOC_WARNING ("Error with GetVersionEx(): %lu", GetLastError ()); @@ -340,8 +335,7 @@ _get_system_info (mongoc_handshake_t *handshake) handshake->os_type = _get_os_type (); #ifdef MONGOC_OS_IS_LINUX - _mongoc_linux_distro_scanner_get_distro (&handshake->os_name, - &handshake->os_version); + _mongoc_linux_distro_scanner_get_distro (&handshake->os_name, &handshake->os_version); #else handshake->os_name = _get_os_name (); handshake->os_version = _get_os_version (); @@ -363,8 +357,7 @@ static void _get_driver_info (mongoc_handshake_t *handshake) { handshake->driver_name = bson_strndup ("mongoc", HANDSHAKE_DRIVER_NAME_MAX); - handshake->driver_version = - bson_strndup (MONGOC_VERSION_S, HANDSHAKE_DRIVER_VERSION_MAX); + handshake->driver_version = bson_strndup (MONGOC_VERSION_S, HANDSHAKE_DRIVER_VERSION_MAX); } static void @@ -402,8 +395,7 @@ _get_env_info (mongoc_handshake_t *handshake) char *timeout_str = NULL; char *region_str = NULL; - bool is_aws = (aws_env && strlen (aws_env) && - (aws_env == strstr (aws_env, "AWS_Lambda_"))) || + bool is_aws = (aws_env && strlen (aws_env) && (aws_env == strstr (aws_env, "AWS_Lambda_"))) || (aws_lambda && strlen (aws_lambda)); bool is_vercel = vercel_env && strlen (vercel_env); bool is_azure = azure_env && strlen (azure_env); @@ -507,13 +499,11 @@ _set_flags (mongoc_handshake_t *handshake) str = bson_string_new (""); if (strlen (MONGOC_EVALUATE_STR (MONGOC_USER_SET_CFLAGS)) > 0) { - bson_string_append_printf ( - str, " CFLAGS=%s", MONGOC_EVALUATE_STR (MONGOC_USER_SET_CFLAGS)); + bson_string_append_printf (str, " CFLAGS=%s", MONGOC_EVALUATE_STR (MONGOC_USER_SET_CFLAGS)); } if (strlen (MONGOC_EVALUATE_STR (MONGOC_USER_SET_LDFLAGS)) > 0) { - bson_string_append_printf ( - str, " LDFLAGS=%s", MONGOC_EVALUATE_STR (MONGOC_USER_SET_LDFLAGS)); + bson_string_append_printf (str, " LDFLAGS=%s", MONGOC_EVALUATE_STR (MONGOC_USER_SET_LDFLAGS)); } handshake->flags = bson_string_free (str, false); @@ -562,16 +552,15 @@ _append_platform_field (bson_t *doc, const char *platform, bool truncate) bson_string_t *combined_platform = bson_string_new (platform); /* Compute space left for platform field */ - const int max_platform_str_size = - HANDSHAKE_MAX_SIZE - ((int) doc->len + - /* 1 byte for utf8 tag */ - 1 + + const int max_platform_str_size = HANDSHAKE_MAX_SIZE - ((int) doc->len + + /* 1 byte for utf8 tag */ + 1 + - /* key size */ - (int) strlen (HANDSHAKE_PLATFORM_FIELD) + 1 + + /* key size */ + (int) strlen (HANDSHAKE_PLATFORM_FIELD) + 1 + - /* 4 bytes for length of string */ - 4); + /* 4 bytes for length of string */ + 4); if (truncate && max_platform_str_size <= 0) { bson_string_free (combined_platform, true); @@ -582,25 +571,19 @@ _append_platform_field (bson_t *doc, const char *platform, bool truncate) * platform information is truncated * Try to drop flags first, and if there is still not enough space also * drop compiler info */ - if (!truncate || bson_cmp_greater_equal_su ( - max_platform_str_size, - combined_platform->len + strlen (compiler_info) + 1u)) { + if (!truncate || + bson_cmp_greater_equal_su (max_platform_str_size, combined_platform->len + strlen (compiler_info) + 1u)) { bson_string_append (combined_platform, compiler_info); } - if (!truncate || bson_cmp_greater_equal_su (max_platform_str_size, - combined_platform->len + - strlen (flags) + 1u)) { + if (!truncate || bson_cmp_greater_equal_su (max_platform_str_size, combined_platform->len + strlen (flags) + 1u)) { bson_string_append (combined_platform, flags); } /* We use the flags_index field to check if the CLAGS/LDFLAGS need to be * truncated, and if so we drop them altogether */ BSON_ASSERT (bson_in_range_unsigned (int, combined_platform->len)); - int length = truncate ? BSON_MIN (max_platform_str_size - 1, - (int) combined_platform->len) - : -1; - bson_append_utf8 ( - doc, HANDSHAKE_PLATFORM_FIELD, -1, combined_platform->str, length); + int length = truncate ? BSON_MIN (max_platform_str_size - 1, (int) combined_platform->len) : -1; + bson_append_utf8 (doc, HANDSHAKE_PLATFORM_FIELD, -1, combined_platform->str, length); bson_string_free (combined_platform, true); } @@ -609,8 +592,7 @@ static bool _get_subdoc_static (bson_t *doc, char *subdoc_name, bson_t *out) { bson_iter_t iter; - if (bson_iter_init_find (&iter, doc, subdoc_name) && - BSON_ITER_HOLDS_DOCUMENT (&iter)) { + if (bson_iter_init_find (&iter, doc, subdoc_name) && BSON_ITER_HOLDS_DOCUMENT (&iter)) { uint32_t len; const uint8_t *data; bson_iter_document (&iter, &len, &data); @@ -709,29 +691,19 @@ _mongoc_handshake_build_doc_with_application (const char *appname) // Optimistically include all handshake data bsonBuildAppend ( *doc, - if (appname, - then (kv ("application", doc (kv ("name", cstr (appname)))))), - kv ("driver", - doc (kv ("name", cstr (md->driver_name)), - kv ("version", cstr (md->driver_version)))), - kv ( - "os", - doc (kv ("type", cstr (md->os_type)), - if (md->os_name, then (kv ("name", cstr (md->os_name)))), - if (md->os_version, then (kv ("version", cstr (md->os_version)))), - if (md->os_architecture, - then (kv ("architecture", cstr (md->os_architecture)))))), + if (appname, then (kv ("application", doc (kv ("name", cstr (appname)))))), + kv ("driver", doc (kv ("name", cstr (md->driver_name)), kv ("version", cstr (md->driver_version)))), + kv ("os", + doc (kv ("type", cstr (md->os_type)), + if (md->os_name, then (kv ("name", cstr (md->os_name)))), + if (md->os_version, then (kv ("version", cstr (md->os_version)))), + if (md->os_architecture, then (kv ("architecture", cstr (md->os_architecture)))))), if (env_name, - then (kv ( - "env", - doc (kv ("name", cstr (env_name)), - if (md->env_timeout_sec.set, - then (kv ("timeout_sec", - int32 (md->env_timeout_sec.value)))), - if (md->env_memory_mb.set, - then (kv ("memory_mb", int32 (md->env_memory_mb.value)))), - if (md->env_region, - then (kv ("region", cstr (md->env_region))))))))); + then (kv ("env", + doc (kv ("name", cstr (env_name)), + if (md->env_timeout_sec.set, then (kv ("timeout_sec", int32 (md->env_timeout_sec.value)))), + if (md->env_memory_mb.set, then (kv ("memory_mb", int32 (md->env_memory_mb.value)))), + if (md->env_region, then (kv ("region", cstr (md->env_region))))))))); if (md->platform) { _append_platform_field (doc, md->platform, false); @@ -776,8 +748,7 @@ _append_and_truncate (char **s, const char *suffix, size_t max_len) const size_t space_for_suffix = max_len - required_space; BSON_ASSERT (bson_in_range_unsigned (int, space_for_suffix)); - *s = - bson_strdup_printf ("%s / %.*s", prefix, (int) space_for_suffix, suffix); + *s = bson_strdup_printf ("%s / %.*s", prefix, (int) space_for_suffix, suffix); BSON_ASSERT (strlen (*s) <= max_len); bson_free (old_str); @@ -794,9 +765,7 @@ _append_and_truncate (char **s, const char *suffix, size_t max_len) * All arguments are optional. */ bool -mongoc_handshake_data_append (const char *driver_name, - const char *driver_version, - const char *platform) +mongoc_handshake_data_append (const char *driver_name, const char *driver_version, const char *platform) { int platform_space; @@ -811,8 +780,7 @@ mongoc_handshake_data_append (const char *driver_name, /* allow practically any size for "platform", we'll trim it down in * _mongoc_handshake_build_doc_with_application */ - platform_space = - HANDSHAKE_MAX_SIZE - (int) strlen (_mongoc_handshake_get ()->platform); + platform_space = HANDSHAKE_MAX_SIZE - (int) strlen (_mongoc_handshake_get ()->platform); if (platform) { /* we check for an empty string as a special case to avoid an @@ -820,24 +788,18 @@ mongoc_handshake_data_append (const char *driver_name, * _append_and_truncate */ if (_mongoc_handshake_get ()->platform[0] == '\0') { bson_free (_mongoc_handshake_get ()->platform); - _mongoc_handshake_get ()->platform = - bson_strdup_printf ("%.*s", platform_space, platform); + _mongoc_handshake_get ()->platform = bson_strdup_printf ("%.*s", platform_space, platform); } else { - _append_and_truncate ( - &_mongoc_handshake_get ()->platform, platform, HANDSHAKE_MAX_SIZE); + _append_and_truncate (&_mongoc_handshake_get ()->platform, platform, HANDSHAKE_MAX_SIZE); } } if (driver_name) { - _append_and_truncate (&_mongoc_handshake_get ()->driver_name, - driver_name, - HANDSHAKE_DRIVER_NAME_MAX); + _append_and_truncate (&_mongoc_handshake_get ()->driver_name, driver_name, HANDSHAKE_DRIVER_NAME_MAX); } if (driver_version) { - _append_and_truncate (&_mongoc_handshake_get ()->driver_version, - driver_version, - HANDSHAKE_DRIVER_VERSION_MAX); + _append_and_truncate (&_mongoc_handshake_get ()->driver_version, driver_version, HANDSHAKE_DRIVER_VERSION_MAX); } _mongoc_handshake_freeze (); @@ -859,29 +821,23 @@ _mongoc_handshake_appname_is_valid (const char *appname) } void -_mongoc_handshake_append_sasl_supported_mechs (const mongoc_uri_t *uri, - bson_t *cmd) +_mongoc_handshake_append_sasl_supported_mechs (const mongoc_uri_t *uri, bson_t *cmd) { const char *username; char *db_user; username = mongoc_uri_get_username (uri); - db_user = - bson_strdup_printf ("%s.%s", mongoc_uri_get_auth_source (uri), username); + db_user = bson_strdup_printf ("%s.%s", mongoc_uri_get_auth_source (uri), username); bson_append_utf8 (cmd, "saslSupportedMechs", 18, db_user, -1); bson_free (db_user); } void -_mongoc_handshake_parse_sasl_supported_mechs ( - const bson_t *hello, - mongoc_handshake_sasl_supported_mechs_t *sasl_supported_mechs) +_mongoc_handshake_parse_sasl_supported_mechs (const bson_t *hello, + mongoc_handshake_sasl_supported_mechs_t *sasl_supported_mechs) { memset (sasl_supported_mechs, 0, sizeof (*sasl_supported_mechs)); bsonParse (*hello, find (keyWithType ("saslSupportedMechs", array), - visitEach (case ( - when (strEqual ("SCRAM-SHA-256"), - do (sasl_supported_mechs->scram_sha_256 = true)), - when (strEqual ("SCRAM-SHA-1"), - do (sasl_supported_mechs->scram_sha_1 = true)))))); + visitEach (case (when (strEqual ("SCRAM-SHA-256"), do (sasl_supported_mechs->scram_sha_256 = true)), + when (strEqual ("SCRAM-SHA-1"), do (sasl_supported_mechs->scram_sha_1 = true)))))); } diff --git a/src/libmongoc/src/mongoc/mongoc-handshake.h b/src/libmongoc/src/mongoc/mongoc-handshake.h index fccefe5232..e1590360c7 100644 --- a/src/libmongoc/src/mongoc/mongoc-handshake.h +++ b/src/libmongoc/src/mongoc/mongoc-handshake.h @@ -29,9 +29,7 @@ BSON_BEGIN_DECLS #define MONGOC_HANDSHAKE_APPNAME_MAX 128 MONGOC_EXPORT (bool) -mongoc_handshake_data_append (const char *driver_name, - const char *driver_version, - const char *platform); +mongoc_handshake_data_append (const char *driver_name, const char *driver_version, const char *platform); BSON_END_DECLS diff --git a/src/libmongoc/src/mongoc/mongoc-host-list-private.h b/src/libmongoc/src/mongoc/mongoc-host-list-private.h index 14d47c8abd..d8bca0448e 100644 --- a/src/libmongoc/src/mongoc/mongoc-host-list-private.h +++ b/src/libmongoc/src/mongoc/mongoc-host-list-private.h @@ -25,26 +25,19 @@ BSON_BEGIN_DECLS mongoc_host_list_t * -_mongoc_host_list_push (const char *host, - uint16_t port, - int family, - mongoc_host_list_t *next); +_mongoc_host_list_push (const char *host, uint16_t port, int family, mongoc_host_list_t *next); void -_mongoc_host_list_upsert (mongoc_host_list_t **list, - const mongoc_host_list_t *new_host); +_mongoc_host_list_upsert (mongoc_host_list_t **list, const mongoc_host_list_t *new_host); mongoc_host_list_t * _mongoc_host_list_copy_all (const mongoc_host_list_t *src); bool -_mongoc_host_list_from_string (mongoc_host_list_t *host_list, - const char *host_and_port); +_mongoc_host_list_from_string (mongoc_host_list_t *host_list, const char *host_and_port); bool -_mongoc_host_list_from_string_with_err (mongoc_host_list_t *host_list, - const char *host_and_port, - bson_error_t *error); +_mongoc_host_list_from_string_with_err (mongoc_host_list_t *host_list, const char *host_and_port, bson_error_t *error); bool _mongoc_host_list_from_hostport_with_err (mongoc_host_list_t *host_list, @@ -56,20 +49,16 @@ size_t _mongoc_host_list_length (const mongoc_host_list_t *list); bool -_mongoc_host_list_compare_one (const mongoc_host_list_t *host_a, - const mongoc_host_list_t *host_b); +_mongoc_host_list_compare_one (const mongoc_host_list_t *host_a, const mongoc_host_list_t *host_b); void -_mongoc_host_list_remove_host (mongoc_host_list_t **phosts, - const char *host, - uint16_t port); +_mongoc_host_list_remove_host (mongoc_host_list_t **phosts, const char *host, uint16_t port); void _mongoc_host_list_destroy_all (mongoc_host_list_t *host); bool -_mongoc_host_list_contains_one (mongoc_host_list_t *host_list, - mongoc_host_list_t *host); +_mongoc_host_list_contains_one (mongoc_host_list_t *host_list, mongoc_host_list_t *host); BSON_END_DECLS diff --git a/src/libmongoc/src/mongoc/mongoc-host-list.c b/src/libmongoc/src/mongoc/mongoc-host-list.c index 3adbb952ad..46741cedd8 100644 --- a/src/libmongoc/src/mongoc/mongoc-host-list.c +++ b/src/libmongoc/src/mongoc/mongoc-host-list.c @@ -34,10 +34,7 @@ *-------------------------------------------------------------------------- */ mongoc_host_list_t * -_mongoc_host_list_push (const char *host, - uint16_t port, - int family, - mongoc_host_list_t *next) +_mongoc_host_list_push (const char *host, uint16_t port, int family, mongoc_host_list_t *next) { mongoc_host_list_t *h; @@ -46,8 +43,7 @@ _mongoc_host_list_push (const char *host, h = bson_malloc0 (sizeof (mongoc_host_list_t)); bson_strncpy (h->host, host, sizeof h->host); h->port = port; - bson_snprintf ( - h->host_and_port, sizeof h->host_and_port, "%s:%hu", host, port); + bson_snprintf (h->host_and_port, sizeof h->host_and_port, "%s:%hu", host, port); h->family = family; h->next = next; @@ -56,8 +52,7 @@ _mongoc_host_list_push (const char *host, } static mongoc_host_list_t * -_mongoc_host_list_find_host_and_port (mongoc_host_list_t *hosts, - const char *host_and_port) +_mongoc_host_list_find_host_and_port (mongoc_host_list_t *hosts, const char *host_and_port) { mongoc_host_list_t *iter; LL_FOREACH (hosts, iter) @@ -86,8 +81,7 @@ _mongoc_host_list_find_host_and_port (mongoc_host_list_t *hosts, *-------------------------------------------------------------------------- */ void -_mongoc_host_list_upsert (mongoc_host_list_t **list, - const mongoc_host_list_t *new_host) +_mongoc_host_list_upsert (mongoc_host_list_t **list, const mongoc_host_list_t *new_host) { mongoc_host_list_t *link = NULL; mongoc_host_list_t *next_link = NULL; @@ -161,19 +155,15 @@ _mongoc_host_list_length (const mongoc_host_list_t *list) *-------------------------------------------------------------------------- */ bool -_mongoc_host_list_compare_one (const mongoc_host_list_t *host_a, - const mongoc_host_list_t *host_b) +_mongoc_host_list_compare_one (const mongoc_host_list_t *host_a, const mongoc_host_list_t *host_b) { - return (0 == strcasecmp (host_a->host_and_port, host_b->host_and_port) && - host_a->family == host_b->family); + return (0 == strcasecmp (host_a->host_and_port, host_b->host_and_port) && host_a->family == host_b->family); } bool -_mongoc_host_list_contains_one (mongoc_host_list_t *host_list, - mongoc_host_list_t *host) +_mongoc_host_list_contains_one (mongoc_host_list_t *host_list, mongoc_host_list_t *host) { - return NULL != - _mongoc_host_list_find_host_and_port (host_list, host->host_and_port); + return NULL != _mongoc_host_list_find_host_and_port (host_list, host->host_and_port); } @@ -220,9 +210,7 @@ _mongoc_host_list_from_string (mongoc_host_list_t *link_, const char *address) } bool -_mongoc_host_list_from_string_with_err (mongoc_host_list_t *link_, - const char *address, - bson_error_t *error) +_mongoc_host_list_from_string_with_err (mongoc_host_list_t *link_, const char *address, bson_error_t *error) { char *close_bracket; char *sport; @@ -257,10 +245,8 @@ _mongoc_host_list_from_string_with_err (mongoc_host_list_t *link_, } if (*address != '[') { - bson_set_error (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Missing matching bracket \"[\""); + bson_set_error ( + error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Missing matching bracket \"[\""); return false; } @@ -283,10 +269,7 @@ _mongoc_host_list_from_string_with_err (mongoc_host_list_t *link_, } if (!mongoc_parse_port (&port, sport + 1)) { - bson_set_error (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Port could not be parsed"); + bson_set_error (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Port could not be parsed"); return false; } @@ -323,10 +306,7 @@ _mongoc_host_list_from_hostport_with_err (mongoc_host_list_t *link_, link_->port = port; if (host_len == 0) { - bson_set_error (error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_NAME_RESOLUTION, - "Empty hostname in URI"); + bson_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_NAME_RESOLUTION, "Empty hostname in URI"); return false; } @@ -348,21 +328,17 @@ _mongoc_host_list_from_hostport_with_err (mongoc_host_list_t *link_, // Check that IPv6 literal is two less than the max to account for `[` and // `]` added below. if (host_len > BSON_HOST_NAME_MAX - 2) { - bson_set_error ( - error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_NAME_RESOLUTION, - "IPv6 literal provided in URI is too long, max is %d chars", - BSON_HOST_NAME_MAX - 2); + bson_set_error (error, + MONGOC_ERROR_STREAM, + MONGOC_ERROR_STREAM_NAME_RESOLUTION, + "IPv6 literal provided in URI is too long, max is %d chars", + BSON_HOST_NAME_MAX - 2); return false; } mongoc_lowercase (link_->host, link_->host); - int req = bson_snprintf (link_->host_and_port, - sizeof link_->host_and_port, - "[%s]:%" PRIu16, - link_->host, - link_->port); + int req = + bson_snprintf (link_->host_and_port, sizeof link_->host_and_port, "[%s]:%" PRIu16, link_->host, link_->port); BSON_ASSERT (bson_in_range_size_t_signed (req)); // Use `<`, not `<=` to account for NULL byte. BSON_ASSERT ((size_t) req < sizeof link_->host_and_port); @@ -374,11 +350,8 @@ _mongoc_host_list_from_hostport_with_err (mongoc_host_list_t *link_, link_->family = AF_UNSPEC; mongoc_lowercase (link_->host, link_->host); - int req = bson_snprintf (link_->host_and_port, - sizeof link_->host_and_port, - "%s:%" PRIu16, - link_->host, - link_->port); + int req = + bson_snprintf (link_->host_and_port, sizeof link_->host_and_port, "%s:%" PRIu16, link_->host, link_->port); BSON_ASSERT (bson_in_range_size_t_signed (req)); // Use `<`, not `<=` to account for NULL byte. BSON_ASSERT ((size_t) req < sizeof link_->host_and_port); @@ -389,9 +362,7 @@ _mongoc_host_list_from_hostport_with_err (mongoc_host_list_t *link_, } void -_mongoc_host_list_remove_host (mongoc_host_list_t **hosts, - const char *host, - uint16_t port) +_mongoc_host_list_remove_host (mongoc_host_list_t **hosts, const char *host, uint16_t port) { mongoc_host_list_t *current; mongoc_host_list_t *prev = NULL; diff --git a/src/libmongoc/src/mongoc/mongoc-http.c b/src/libmongoc/src/mongoc/mongoc-http.c index eba1754c2a..363dbfdc5a 100644 --- a/src/libmongoc/src/mongoc/mongoc-http.c +++ b/src/libmongoc/src/mongoc/mongoc-http.c @@ -75,8 +75,7 @@ _mongoc_http_render_request_head (const mongoc_http_request_t *req) bson_string_append_printf (string, "Connection: close\r\n"); /* Add Content-Length if body is included. */ if (req->body_len) { - bson_string_append_printf ( - string, "Content-Length: %d\r\n", req->body_len); + bson_string_append_printf (string, "Content-Length: %d\r\n", req->body_len); } // Add any extra headers if (req->extra_headers) { @@ -115,14 +114,12 @@ _mongoc_http_send (const mongoc_http_request_t *req, char *ptr; const char *header_delimiter = "\r\n\r\n"; - const mcd_timer timer = - mcd_timer_expire_after (mcd_milliseconds (timeout_ms)); + const mcd_timer timer = mcd_timer_expire_after (mcd_milliseconds (timeout_ms)); memset (res, 0, sizeof (*res)); _mongoc_buffer_init (&http_response_buf, NULL, 0, NULL, NULL); - if (!_mongoc_host_list_from_hostport_with_err ( - &host_list, req->host, (uint16_t) req->port, error)) { + if (!_mongoc_host_list_from_hostport_with_err (&host_list, req->host, (uint16_t) req->port, error)) { goto fail; } @@ -132,22 +129,17 @@ _mongoc_http_send (const mongoc_http_request_t *req, &host_list, error); if (!stream) { - bson_set_error (error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_SOCKET, - "Failed to connect to: %s", - req->host); + bson_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "Failed to connect to: %s", req->host); goto fail; } #ifndef MONGOC_ENABLE_SSL if (use_tls) { - bson_set_error ( - error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_SOCKET, - "Failed to connect to %s: libmongoc not built with TLS support", - req->host); + bson_set_error (error, + MONGOC_ERROR_STREAM, + MONGOC_ERROR_STREAM_SOCKET, + "Failed to connect to %s: libmongoc not built with TLS support", + req->host); goto fail; } #else @@ -155,20 +147,15 @@ _mongoc_http_send (const mongoc_http_request_t *req, mongoc_stream_t *tls_stream; BSON_ASSERT (ssl_opts); - tls_stream = mongoc_stream_tls_new_with_hostname ( - stream, req->host, ssl_opts, true); + tls_stream = mongoc_stream_tls_new_with_hostname (stream, req->host, ssl_opts, true); if (!tls_stream) { - bson_set_error (error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_SOCKET, - "Failed create TLS stream to: %s", - req->host); + bson_set_error ( + error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "Failed create TLS stream to: %s", req->host); goto fail; } stream = tls_stream; - if (!mongoc_stream_tls_handshake_block ( - stream, req->host, _mongoc_http_msec_remaining (timer), error)) { + if (!mongoc_stream_tls_handshake_block (stream, req->host, _mongoc_http_msec_remaining (timer), error)) { goto fail; } } @@ -186,16 +173,14 @@ _mongoc_http_send (const mongoc_http_request_t *req, iovec.iov_base = http_request->str; iovec.iov_len = http_request->len; - if (!_mongoc_stream_writev_full ( - stream, &iovec, 1, _mongoc_http_msec_remaining (timer), error)) { + if (!_mongoc_stream_writev_full (stream, &iovec, 1, _mongoc_http_msec_remaining (timer), error)) { goto fail; } if (req->body && req->body_len) { iovec.iov_base = (void *) req->body; iovec.iov_len = req->body_len; - if (!_mongoc_stream_writev_full ( - stream, &iovec, 1, _mongoc_http_msec_remaining (timer), error)) { + if (!_mongoc_stream_writev_full (stream, &iovec, 1, _mongoc_http_msec_remaining (timer), error)) { goto fail; } } @@ -203,10 +188,7 @@ _mongoc_http_send (const mongoc_http_request_t *req, /* Read until connection close. */ while (1) { const ssize_t bytes_read = _mongoc_buffer_try_append_from_stream ( - &http_response_buf, - stream, - 1024 * 32, - _mongoc_http_msec_remaining (timer)); + &http_response_buf, stream, 1024 * 32, _mongoc_http_msec_remaining (timer)); if (mongoc_stream_should_retry (stream)) { continue; } @@ -214,27 +196,18 @@ _mongoc_http_send (const mongoc_http_request_t *req, break; } if (http_response_buf.len > 1024 * 1024 * 8) { - bson_set_error (error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_SOCKET, - "HTTP response message is too large"); + bson_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "HTTP response message is too large"); goto fail; } } if (mongoc_stream_timed_out (stream)) { - bson_set_error (error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_SOCKET, - "Timeout reading from stream"); + bson_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "Timeout reading from stream"); goto fail; } if (http_response_buf.len == 0) { - bson_set_error (error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_SOCKET, - "No response received"); + bson_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "No response received"); goto fail; } @@ -250,13 +223,12 @@ _mongoc_http_send (const mongoc_http_request_t *req, } if (!ptr) { - bson_set_error ( - error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_SOCKET, - "No HTTP version leader in HTTP response. Expected '%s' or '%s'", - proto_leader_10, - proto_leader_11); + bson_set_error (error, + MONGOC_ERROR_STREAM, + MONGOC_ERROR_STREAM_SOCKET, + "No HTTP version leader in HTTP response. Expected '%s' or '%s'", + proto_leader_10, + proto_leader_11); goto fail; } @@ -264,10 +236,7 @@ _mongoc_http_send (const mongoc_http_request_t *req, ptr += strlen (proto_leader_10); ssize_t remain = resp_end_ptr - ptr; if (remain < 4) { - bson_set_error (error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_SOCKET, - "Short read in HTTP response"); + bson_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "Short read in HTTP response"); goto fail; } @@ -288,19 +257,17 @@ _mongoc_http_send (const mongoc_http_request_t *req, /* Find the end of the headers. */ ptr = strstr (http_response_str, header_delimiter); if (NULL == ptr) { - bson_set_error ( - error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_SOCKET, - "Error occurred reading response: end of headers not found"); + bson_set_error (error, + MONGOC_ERROR_STREAM, + MONGOC_ERROR_STREAM_SOCKET, + "Error occurred reading response: end of headers not found"); goto fail; } const size_t headers_len = (size_t) (ptr - http_response_str); BSON_ASSERT (bson_in_range_unsigned (int, headers_len)); - const size_t body_len = - http_response_buf.len - headers_len - strlen (header_delimiter); + const size_t body_len = http_response_buf.len - headers_len - strlen (header_delimiter); BSON_ASSERT (bson_in_range_unsigned (int, body_len)); res->headers_len = (int) headers_len; diff --git a/src/libmongoc/src/mongoc/mongoc-init.c b/src/libmongoc/src/mongoc/mongoc-init.c index b45dcdc337..360a0af29c 100644 --- a/src/libmongoc/src/mongoc/mongoc-init.c +++ b/src/libmongoc/src/mongoc/mongoc-init.c @@ -46,8 +46,7 @@ #endif #ifndef MONGOC_NO_AUTOMATIC_GLOBALS -#pragma message( \ - "Configure the driver with ENABLE_AUTOMATIC_INIT_AND_CLEANUP=OFF.\ +#pragma message("Configure the driver with ENABLE_AUTOMATIC_INIT_AND_CLEANUP=OFF.\ Automatic cleanup is deprecated and will be removed in version 2.0.") #endif @@ -108,10 +107,8 @@ static BSON_ONCE_FUN (_mongoc_do_init) #ifdef MONGOC_ENABLE_SASL_CYRUS /* The following functions should not use tracing, as they may be invoked * before mongoc_log_set_handler() can complete. */ - sasl_set_mutex (mongoc_cyrus_mutex_alloc, - mongoc_cyrus_mutex_lock, - mongoc_cyrus_mutex_unlock, - mongoc_cyrus_mutex_free); + sasl_set_mutex ( + mongoc_cyrus_mutex_alloc, mongoc_cyrus_mutex_lock, mongoc_cyrus_mutex_unlock, mongoc_cyrus_mutex_free); status = sasl_client_init (NULL); BSON_ASSERT (status == SASL_OK); diff --git a/src/libmongoc/src/mongoc/mongoc-interrupt.c b/src/libmongoc/src/mongoc/mongoc-interrupt.c index b22767c33c..6779b55d30 100644 --- a/src/libmongoc/src/mongoc/mongoc-interrupt.c +++ b/src/libmongoc/src/mongoc/mongoc-interrupt.c @@ -88,9 +88,7 @@ _mongoc_interrupt_new (uint32_t timeout_ms) memset (&server_addr_in, 0, sizeof (server_addr_in)); server_addr_in.sin_family = AF_INET; server_addr_in.sin_addr.s_addr = htonl (INADDR_LOOPBACK); - ret = mongoc_socket_bind (listen_socket, - (struct sockaddr *) &server_addr_in, - sizeof (server_addr_in)); + ret = mongoc_socket_bind (listen_socket, (struct sockaddr *) &server_addr_in, sizeof (server_addr_in)); if (ret == -1) { _log_errno ("bind failed", mongoc_socket_errno (listen_socket)); GOTO (fail); @@ -103,34 +101,27 @@ _mongoc_interrupt_new (uint32_t timeout_ms) } sock_len = sizeof (server_addr); - ret = mongoc_socket_getsockname ( - listen_socket, (struct sockaddr *) &server_addr, &sock_len); + ret = mongoc_socket_getsockname (listen_socket, (struct sockaddr *) &server_addr, &sock_len); if (-1 == ret) { _log_errno ("getsockname failed", mongoc_socket_errno (listen_socket)); GOTO (fail); } - interrupt->impl.socket_pair.read = - mongoc_socket_new (server_addr.ss_family, SOCK_STREAM, 0); + interrupt->impl.socket_pair.read = mongoc_socket_new (server_addr.ss_family, SOCK_STREAM, 0); if (!interrupt->impl.socket_pair.read) { MONGOC_ERROR ("socket creation failed"); GOTO (fail); } /* Begin non-blocking connect. */ - ret = mongoc_socket_connect (interrupt->impl.socket_pair.read, - (struct sockaddr *) &server_addr, - sock_len, - 0); - if (ret == -1 && !MONGOC_ERRNO_IS_AGAIN (mongoc_socket_errno ( - interrupt->impl.socket_pair.read))) { - _log_errno ("connect failed", - mongoc_socket_errno (interrupt->impl.socket_pair.read)); + ret = mongoc_socket_connect (interrupt->impl.socket_pair.read, (struct sockaddr *) &server_addr, sock_len, 0); + if (ret == -1 && !MONGOC_ERRNO_IS_AGAIN (mongoc_socket_errno (interrupt->impl.socket_pair.read))) { + _log_errno ("connect failed", mongoc_socket_errno (interrupt->impl.socket_pair.read)); GOTO (fail); } - interrupt->impl.socket_pair.write = mongoc_socket_accept ( - listen_socket, bson_get_monotonic_time () + timeout_ms * 1000); + interrupt->impl.socket_pair.write = + mongoc_socket_accept (listen_socket, bson_get_monotonic_time () + timeout_ms * 1000); if (!interrupt->impl.socket_pair.write) { _log_errno ("accept failed", mongoc_socket_errno (listen_socket)); GOTO (fail); @@ -171,15 +162,13 @@ _mongoc_interrupt_flush (mongoc_interrupt_t *interrupt) { uint8_t buf[1]; while (true) { - if (-1 == mongoc_socket_recv ( - interrupt->impl.socket_pair.read, buf, sizeof (buf), 0, 0)) { + if (-1 == mongoc_socket_recv (interrupt->impl.socket_pair.read, buf, sizeof (buf), 0, 0)) { if (MONGOC_ERRNO_IS_AGAIN (errno)) { /* Nothing left to read. */ return true; } else { /* Unexpected error. */ - _log_errno ("interrupt recv failed", - mongoc_socket_errno (interrupt->impl.socket_pair.read)); + _log_errno ("interrupt recv failed", mongoc_socket_errno (interrupt->impl.socket_pair.read)); return false; } } @@ -192,11 +181,8 @@ bool _mongoc_interrupt_interrupt (mongoc_interrupt_t *interrupt) { bson_mutex_lock (&interrupt->mutex); - if (mongoc_socket_send (interrupt->impl.socket_pair.write, "!", 1, 0) == - -1 && - !MONGOC_ERRNO_IS_AGAIN (errno)) { - _log_errno ("interrupt send failed", - mongoc_socket_errno (interrupt->impl.socket_pair.write)); + if (mongoc_socket_send (interrupt->impl.socket_pair.write, "!", 1, 0) == -1 && !MONGOC_ERRNO_IS_AGAIN (errno)) { + _log_errno ("interrupt send failed", mongoc_socket_errno (interrupt->impl.socket_pair.write)); bson_mutex_unlock (&interrupt->mutex); return false; } @@ -248,8 +234,7 @@ _mongoc_interrupt_new (uint32_t timeout_ms) } /* Make the pipe non-blocking and close-on-exec. */ - if (!_set_pipe_flags (interrupt->impl.pipe_fds[0]) || - !_set_pipe_flags (interrupt->impl.pipe_fds[1])) { + if (!_set_pipe_flags (interrupt->impl.pipe_fds[0]) || !_set_pipe_flags (interrupt->impl.pipe_fds[1])) { _log_errno ("unable to configure pipes", errno); } @@ -293,8 +278,7 @@ bool _mongoc_interrupt_interrupt (mongoc_interrupt_t *interrupt) { bson_mutex_lock (&interrupt->mutex); - if (write (interrupt->impl.pipe_fds[1], "!", 1) == -1 && - !MONGOC_ERRNO_IS_AGAIN (errno)) { + if (write (interrupt->impl.pipe_fds[1], "!", 1) == -1 && !MONGOC_ERRNO_IS_AGAIN (errno)) { MONGOC_ERROR ("failed to write to pipe: %d", errno); bson_mutex_unlock (&interrupt->mutex); return false; diff --git a/src/libmongoc/src/mongoc/mongoc-iovec.h b/src/libmongoc/src/mongoc/mongoc-iovec.h index f18f41126f..a05a853670 100644 --- a/src/libmongoc/src/mongoc/mongoc-iovec.h +++ b/src/libmongoc/src/mongoc/mongoc-iovec.h @@ -38,14 +38,9 @@ typedef struct { char *iov_base; } mongoc_iovec_t; -BSON_STATIC_ASSERT2 (sizeof_iovect_t, - sizeof (mongoc_iovec_t) == sizeof (WSABUF)); -BSON_STATIC_ASSERT2 (offsetof_iovec_base, - offsetof (mongoc_iovec_t, iov_base) == - offsetof (WSABUF, buf)); -BSON_STATIC_ASSERT2 (offsetof_iovec_len, - offsetof (mongoc_iovec_t, iov_len) == - offsetof (WSABUF, len)); +BSON_STATIC_ASSERT2 (sizeof_iovect_t, sizeof (mongoc_iovec_t) == sizeof (WSABUF)); +BSON_STATIC_ASSERT2 (offsetof_iovec_base, offsetof (mongoc_iovec_t, iov_base) == offsetof (WSABUF, buf)); +BSON_STATIC_ASSERT2 (offsetof_iovec_len, offsetof (mongoc_iovec_t, iov_len) == offsetof (WSABUF, len)); #else typedef struct iovec mongoc_iovec_t; diff --git a/src/libmongoc/src/mongoc/mongoc-libressl-private.h b/src/libmongoc/src/mongoc/mongoc-libressl-private.h index b40d550ea5..670ef5f079 100644 --- a/src/libmongoc/src/mongoc/mongoc-libressl-private.h +++ b/src/libmongoc/src/mongoc/mongoc-libressl-private.h @@ -30,11 +30,9 @@ BSON_BEGIN_DECLS bool -mongoc_libressl_setup_ca (mongoc_stream_tls_libressl_t *libressl, - mongoc_ssl_opt_t *opt); +mongoc_libressl_setup_ca (mongoc_stream_tls_libressl_t *libressl, mongoc_ssl_opt_t *opt); bool -mongoc_libressl_setup_certificate (mongoc_stream_tls_libressl_t *libressl, - mongoc_ssl_opt_t *opt); +mongoc_libressl_setup_certificate (mongoc_stream_tls_libressl_t *libressl, mongoc_ssl_opt_t *opt); BSON_END_DECLS diff --git a/src/libmongoc/src/mongoc/mongoc-libressl.c b/src/libmongoc/src/mongoc/mongoc-libressl.c index 9c92337dc3..fe7cc65fd8 100644 --- a/src/libmongoc/src/mongoc/mongoc-libressl.c +++ b/src/libmongoc/src/mongoc/mongoc-libressl.c @@ -35,8 +35,7 @@ bool -mongoc_libressl_setup_certificate (mongoc_stream_tls_libressl_t *libressl, - mongoc_ssl_opt_t *opt) +mongoc_libressl_setup_certificate (mongoc_stream_tls_libressl_t *libressl, mongoc_ssl_opt_t *opt) { uint8_t *file; size_t file_len; @@ -51,8 +50,7 @@ mongoc_libressl_setup_certificate (mongoc_stream_tls_libressl_t *libressl, return false; } - if (tls_config_set_keypair_mem ( - libressl->config, file, file_len, file, file_len) == -1) { + if (tls_config_set_keypair_mem (libressl->config, file, file_len, file, file_len) == -1) { MONGOC_ERROR ("%s", tls_config_error (libressl->config)); return false; } @@ -61,8 +59,7 @@ mongoc_libressl_setup_certificate (mongoc_stream_tls_libressl_t *libressl, } bool -mongoc_libressl_setup_ca (mongoc_stream_tls_libressl_t *libressl, - mongoc_ssl_opt_t *opt) +mongoc_libressl_setup_ca (mongoc_stream_tls_libressl_t *libressl, mongoc_ssl_opt_t *opt) { if (opt->ca_file) { tls_config_set_ca_file (libressl->config, opt->ca_file); diff --git a/src/libmongoc/src/mongoc/mongoc-linux-distro-scanner-private.h b/src/libmongoc/src/mongoc/mongoc-linux-distro-scanner-private.h index fb6a40a161..8ad29c07cc 100644 --- a/src/libmongoc/src/mongoc/mongoc-linux-distro-scanner-private.h +++ b/src/libmongoc/src/mongoc/mongoc-linux-distro-scanner-private.h @@ -39,14 +39,9 @@ _mongoc_linux_distro_scanner_read_key_value_file (const char *path, ssize_t version_key_len, char **version); void -_mongoc_linux_distro_scanner_read_generic_release_file (const char **paths, - char **name, - char **version); +_mongoc_linux_distro_scanner_read_generic_release_file (const char **paths, char **name, char **version); void -_mongoc_linux_distro_scanner_split_line_by_release (const char *line, - ssize_t line_len, - char **name, - char **version); +_mongoc_linux_distro_scanner_split_line_by_release (const char *line, ssize_t line_len, char **name, char **version); BSON_END_DECLS #endif diff --git a/src/libmongoc/src/mongoc/mongoc-linux-distro-scanner.c b/src/libmongoc/src/mongoc/mongoc-linux-distro-scanner.c index 79246532fa..e1fd41ba83 100644 --- a/src/libmongoc/src/mongoc/mongoc-linux-distro-scanner.c +++ b/src/libmongoc/src/mongoc/mongoc-linux-distro-scanner.c @@ -115,12 +115,10 @@ _process_line (const char *name_key, /* If we find two copies of either key, the *name == NULL check will fail * so we will just keep the first value encountered. */ - if (name_key_len == key_len && strncmp (line, name_key, key_len) == 0 && - !(*name)) { + if (name_key_len == key_len && strncmp (line, name_key, key_len) == 0 && !(*name)) { *name = bson_strndup (value, value_len); TRACE ("Found name: %s", *name); - } else if (version_key_len == key_len && - strncmp (line, version_key, key_len) == 0 && !(*version)) { + } else if (version_key_len == key_len && strncmp (line, version_key, key_len) == 0 && !(*version)) { *version = bson_strndup (value, value_len); TRACE ("Found version: %s", *version); } @@ -184,14 +182,7 @@ _mongoc_linux_distro_scanner_read_key_value_file (const char *path, break; } - _process_line (name_key, - name_key_len, - name, - version_key, - version_key_len, - version, - buffer, - buflen); + _process_line (name_key, name_key_len, name, version_key, version_key_len, version, buffer, buflen); if (*version && *name) { /* No point in reading any more */ @@ -243,10 +234,7 @@ _get_first_existing (const char **paths) * (even if the string is empty). */ void -_mongoc_linux_distro_scanner_split_line_by_release (const char *line, - ssize_t line_len, - char **name, - char **version) +_mongoc_linux_distro_scanner_split_line_by_release (const char *line, ssize_t line_len, char **name, char **version) { const char *needle_loc; const char *const needle = " release "; @@ -286,9 +274,7 @@ _mongoc_linux_distro_scanner_split_line_by_release (const char *line, * Search for a *-release file, and read its contents. */ void -_mongoc_linux_distro_scanner_read_generic_release_file (const char **paths, - char **name, - char **version) +_mongoc_linux_distro_scanner_read_generic_release_file (const char **paths, char **name, char **version) { const char *path; size_t buflen; @@ -320,8 +306,7 @@ _mongoc_linux_distro_scanner_read_generic_release_file (const char **paths, TRACE ("Trying to split buffer with contents %s", buffer); /* Try splitting the string. If we can't it'll store everything in * *name. */ - _mongoc_linux_distro_scanner_split_line_by_release ( - buffer, buflen, name, version); + _mongoc_linux_distro_scanner_split_line_by_release (buffer, buflen, name, version); } fclose (f); @@ -347,10 +332,7 @@ _get_kernel_version_from_uname (char **version) * should not be used after this call. */ static bool -_set_name_and_version_if_needed (char **name, - char **version, - char *new_name, - char *new_version) +_set_name_and_version_if_needed (char **name, char **version, char *new_name, char *new_version) { if (new_name && !(*name)) { *name = new_name; @@ -391,28 +373,21 @@ _mongoc_linux_distro_scanner_get_distro (char **name, char **version) *name = NULL; *version = NULL; - _mongoc_linux_distro_scanner_read_key_value_file ( - "/etc/os-release", "NAME", -1, name, "VERSION_ID", -1, version); + _mongoc_linux_distro_scanner_read_key_value_file ("/etc/os-release", "NAME", -1, name, "VERSION_ID", -1, version); if (*name && *version) { RETURN (true); } - _mongoc_linux_distro_scanner_read_key_value_file ("/etc/lsb-release", - "DISTRIB_ID", - -1, - &new_name, - "DISTRIB_RELEASE", - -1, - &new_version); + _mongoc_linux_distro_scanner_read_key_value_file ( + "/etc/lsb-release", "DISTRIB_ID", -1, &new_name, "DISTRIB_RELEASE", -1, &new_version); if (_set_name_and_version_if_needed (name, version, new_name, new_version)) { RETURN (true); } /* Try to read from a generic release file */ - _mongoc_linux_distro_scanner_read_generic_release_file ( - generic_release_paths, &new_name, &new_version); + _mongoc_linux_distro_scanner_read_generic_release_file (generic_release_paths, &new_name, &new_version); if (_set_name_and_version_if_needed (name, version, new_name, new_version)) { RETURN (true); diff --git a/src/libmongoc/src/mongoc/mongoc-list-private.h b/src/libmongoc/src/mongoc/mongoc-list-private.h index 8171e78038..3b6c1f4bd5 100644 --- a/src/libmongoc/src/mongoc/mongoc-list-private.h +++ b/src/libmongoc/src/mongoc/mongoc-list-private.h @@ -41,9 +41,7 @@ _mongoc_list_prepend (mongoc_list_t *list, void *data); mongoc_list_t * _mongoc_list_remove (mongoc_list_t *list, void *data); void -_mongoc_list_foreach (mongoc_list_t *list, - void (*func) (void *data, void *user_data), - void *user_data); +_mongoc_list_foreach (mongoc_list_t *list, void (*func) (void *data, void *user_data), void *user_data); void _mongoc_list_destroy (mongoc_list_t *list); diff --git a/src/libmongoc/src/mongoc/mongoc-list.c b/src/libmongoc/src/mongoc/mongoc-list.c index 4d36523cef..628debe591 100644 --- a/src/libmongoc/src/mongoc/mongoc-list.c +++ b/src/libmongoc/src/mongoc/mongoc-list.c @@ -113,9 +113,7 @@ _mongoc_list_remove (mongoc_list_t *list, void *data) * Calls @func for each item in @list. */ void -_mongoc_list_foreach (mongoc_list_t *list, - void (*func) (void *data, void *user_data), - void *user_data) +_mongoc_list_foreach (mongoc_list_t *list, void (*func) (void *data, void *user_data), void *user_data) { mongoc_list_t *iter; diff --git a/src/libmongoc/src/mongoc/mongoc-log-private.h b/src/libmongoc/src/mongoc/mongoc-log-private.h index 150844820e..b9bddb0e3c 100644 --- a/src/libmongoc/src/mongoc/mongoc-log-private.h +++ b/src/libmongoc/src/mongoc/mongoc-log-private.h @@ -32,8 +32,6 @@ void mongoc_log_trace_bytes (const char *domain, const uint8_t *_b, size_t _l); void -mongoc_log_trace_iovec (const char *domain, - const mongoc_iovec_t *_iov, - size_t _iovcnt); +mongoc_log_trace_iovec (const char *domain, const mongoc_iovec_t *_iov, size_t _iovcnt); #endif /* MONGOC_LOG_PRIVATE_H */ diff --git a/src/libmongoc/src/mongoc/mongoc-log.c b/src/libmongoc/src/mongoc/mongoc-log.c index fc0dba695e..ce66392031 100644 --- a/src/libmongoc/src/mongoc/mongoc-log.c +++ b/src/libmongoc/src/mongoc/mongoc-log.c @@ -91,10 +91,7 @@ _mongoc_log_get_handler (mongoc_log_func_t *log_func, void **user_data) void -mongoc_log (mongoc_log_level_t log_level, - const char *log_domain, - const char *format, - ...) +mongoc_log (mongoc_log_level_t log_level, const char *log_domain, const char *format, ...) { va_list args; char *message; @@ -103,8 +100,7 @@ mongoc_log (mongoc_log_level_t log_level, bson_once (&once, &_mongoc_ensure_mutex_once); stop_logging = !gLogFunc; - stop_logging = stop_logging || (log_level == MONGOC_LOG_LEVEL_TRACE && - !_mongoc_log_trace_is_enabled ()); + stop_logging = stop_logging || (log_level == MONGOC_LOG_LEVEL_TRACE && !_mongoc_log_trace_is_enabled ()); if (stop_logging) { return; } @@ -148,10 +144,7 @@ mongoc_log_level_str (mongoc_log_level_t log_level) void -mongoc_log_default_handler (mongoc_log_level_t log_level, - const char *log_domain, - const char *message, - void *user_data) +mongoc_log_default_handler (mongoc_log_level_t log_level, const char *log_domain, const char *message, void *user_data) { struct timeval tv; struct tm tt; @@ -248,8 +241,7 @@ mongoc_log_trace_bytes (const char *domain, const uint8_t *_b, size_t _l) } if (rem == 15u) { - mongoc_log ( - MONGOC_LOG_LEVEL_TRACE, domain, "%s %s", str->str, astr->str); + mongoc_log (MONGOC_LOG_LEVEL_TRACE, domain, "%s %s", str->str, astr->str); bson_string_truncate (str, 0); bson_string_truncate (astr, 0); } else if (rem == 7u) { @@ -259,8 +251,7 @@ mongoc_log_trace_bytes (const char *domain, const uint8_t *_b, size_t _l) } if (_i != 16u) { - mongoc_log ( - MONGOC_LOG_LEVEL_TRACE, domain, "%-56s %s", str->str, astr->str); + mongoc_log (MONGOC_LOG_LEVEL_TRACE, domain, "%-56s %s", str->str, astr->str); } bson_string_free (str, true); @@ -268,9 +259,7 @@ mongoc_log_trace_bytes (const char *domain, const uint8_t *_b, size_t _l) } void -mongoc_log_trace_iovec (const char *domain, - const mongoc_iovec_t *_iov, - size_t _iovcnt) +mongoc_log_trace_iovec (const char *domain, const mongoc_iovec_t *_iov, size_t _iovcnt) { bson_string_t *str, *astr; const char *_b; @@ -310,8 +299,7 @@ mongoc_log_trace_iovec (const char *domain, } if ((_i % 16) == 15) { - mongoc_log ( - MONGOC_LOG_LEVEL_TRACE, domain, "%s %s", str->str, astr->str); + mongoc_log (MONGOC_LOG_LEVEL_TRACE, domain, "%s %s", str->str, astr->str); bson_string_truncate (str, 0); bson_string_truncate (astr, 0); } else if ((_i % 16) == 7) { @@ -322,8 +310,7 @@ mongoc_log_trace_iovec (const char *domain, } if (_i != 16) { - mongoc_log ( - MONGOC_LOG_LEVEL_TRACE, domain, "%-56s %s", str->str, astr->str); + mongoc_log (MONGOC_LOG_LEVEL_TRACE, domain, "%-56s %s", str->str, astr->str); } bson_string_free (str, true); diff --git a/src/libmongoc/src/mongoc/mongoc-log.h b/src/libmongoc/src/mongoc/mongoc-log.h index 8f5236479d..b43be57c76 100644 --- a/src/libmongoc/src/mongoc/mongoc-log.h +++ b/src/libmongoc/src/mongoc/mongoc-log.h @@ -31,18 +31,12 @@ BSON_BEGIN_DECLS #endif -#define MONGOC_ERROR(...) \ - mongoc_log (MONGOC_LOG_LEVEL_ERROR, MONGOC_LOG_DOMAIN, __VA_ARGS__) -#define MONGOC_CRITICAL(...) \ - mongoc_log (MONGOC_LOG_LEVEL_CRITICAL, MONGOC_LOG_DOMAIN, __VA_ARGS__) -#define MONGOC_WARNING(...) \ - mongoc_log (MONGOC_LOG_LEVEL_WARNING, MONGOC_LOG_DOMAIN, __VA_ARGS__) -#define MONGOC_MESSAGE(...) \ - mongoc_log (MONGOC_LOG_LEVEL_MESSAGE, MONGOC_LOG_DOMAIN, __VA_ARGS__) -#define MONGOC_INFO(...) \ - mongoc_log (MONGOC_LOG_LEVEL_INFO, MONGOC_LOG_DOMAIN, __VA_ARGS__) -#define MONGOC_DEBUG(...) \ - mongoc_log (MONGOC_LOG_LEVEL_DEBUG, MONGOC_LOG_DOMAIN, __VA_ARGS__) +#define MONGOC_ERROR(...) mongoc_log (MONGOC_LOG_LEVEL_ERROR, MONGOC_LOG_DOMAIN, __VA_ARGS__) +#define MONGOC_CRITICAL(...) mongoc_log (MONGOC_LOG_LEVEL_CRITICAL, MONGOC_LOG_DOMAIN, __VA_ARGS__) +#define MONGOC_WARNING(...) mongoc_log (MONGOC_LOG_LEVEL_WARNING, MONGOC_LOG_DOMAIN, __VA_ARGS__) +#define MONGOC_MESSAGE(...) mongoc_log (MONGOC_LOG_LEVEL_MESSAGE, MONGOC_LOG_DOMAIN, __VA_ARGS__) +#define MONGOC_INFO(...) mongoc_log (MONGOC_LOG_LEVEL_INFO, MONGOC_LOG_DOMAIN, __VA_ARGS__) +#define MONGOC_DEBUG(...) mongoc_log (MONGOC_LOG_LEVEL_DEBUG, MONGOC_LOG_DOMAIN, __VA_ARGS__) typedef enum { @@ -98,17 +92,11 @@ mongoc_log_set_handler (mongoc_log_func_t log_func, void *user_data); * */ MONGOC_EXPORT (void) -mongoc_log (mongoc_log_level_t log_level, - const char *log_domain, - const char *format, - ...) BSON_GNUC_PRINTF (3, 4); +mongoc_log (mongoc_log_level_t log_level, const char *log_domain, const char *format, ...) BSON_GNUC_PRINTF (3, 4); MONGOC_EXPORT (void) -mongoc_log_default_handler (mongoc_log_level_t log_level, - const char *log_domain, - const char *message, - void *user_data); +mongoc_log_default_handler (mongoc_log_level_t log_level, const char *log_domain, const char *message, void *user_data); /** diff --git a/src/libmongoc/src/mongoc/mongoc-matcher-op-private.h b/src/libmongoc/src/mongoc/mongoc-matcher-op-private.h index 5b944790f5..0c8cc08d76 100644 --- a/src/libmongoc/src/mongoc/mongoc-matcher-op-private.h +++ b/src/libmongoc/src/mongoc/mongoc-matcher-op-private.h @@ -103,13 +103,9 @@ union _mongoc_matcher_op_t { mongoc_matcher_op_t * -_mongoc_matcher_op_logical_new (mongoc_matcher_opcode_t opcode, - mongoc_matcher_op_t *left, - mongoc_matcher_op_t *right); +_mongoc_matcher_op_logical_new (mongoc_matcher_opcode_t opcode, mongoc_matcher_op_t *left, mongoc_matcher_op_t *right); mongoc_matcher_op_t * -_mongoc_matcher_op_compare_new (mongoc_matcher_opcode_t opcode, - const char *path, - const bson_iter_t *iter); +_mongoc_matcher_op_compare_new (mongoc_matcher_opcode_t opcode, const char *path, const bson_iter_t *iter); mongoc_matcher_op_t * _mongoc_matcher_op_exists_new (const char *path, bool exists); mongoc_matcher_op_t * diff --git a/src/libmongoc/src/mongoc/mongoc-matcher-op.c b/src/libmongoc/src/mongoc/mongoc-matcher-op.c index a4f63e0393..6c8f66d4e1 100644 --- a/src/libmongoc/src/mongoc/mongoc-matcher-op.c +++ b/src/libmongoc/src/mongoc/mongoc-matcher-op.c @@ -117,8 +117,7 @@ _mongoc_matcher_op_logical_new (mongoc_matcher_opcode_t opcode, /* IN */ mongoc_matcher_op_t *op; BSON_ASSERT (left); - BSON_ASSERT ((opcode >= MONGOC_MATCHER_OPCODE_OR) && - (opcode <= MONGOC_MATCHER_OPCODE_NOR)); + BSON_ASSERT ((opcode >= MONGOC_MATCHER_OPCODE_OR) && (opcode <= MONGOC_MATCHER_OPCODE_NOR)); op = BSON_ALIGNED_ALLOC0 (mongoc_matcher_op_t); op->logical.base.opcode = opcode; @@ -298,8 +297,7 @@ _mongoc_matcher_op_exists_match (mongoc_matcher_op_exists_t *exists, /* IN */ BSON_ASSERT (exists); BSON_ASSERT (bson); - found = (bson_iter_init (&iter, bson) && - bson_iter_find_descendant (&iter, exists->path, &desc)); + found = (bson_iter_init (&iter, bson) && bson_iter_find_descendant (&iter, exists->path, &desc)); return (found == exists->exists); } @@ -332,8 +330,7 @@ _mongoc_matcher_op_type_match (mongoc_matcher_op_type_t *type, /* IN */ BSON_ASSERT (type); BSON_ASSERT (bson); - if (bson_iter_init (&iter, bson) && - bson_iter_find_descendant (&iter, type->path, &desc)) { + if (bson_iter_init (&iter, bson) && bson_iter_find_descendant (&iter, type->path, &desc)) { return (bson_iter_type (&iter) == type->type); } @@ -371,8 +368,7 @@ _mongoc_matcher_op_not_match (mongoc_matcher_op_not_t *not_, /* IN */ #define _TYPE_CODE(l, r) ((((int) (l)) << 8) | ((int) (r))) -#define _NATIVE_COMPARE(op, t1, t2) \ - (bson_iter##t2 (iter) op bson_iter##t1 (compare_iter)) +#define _NATIVE_COMPARE(op, t1, t2) (bson_iter##t2 (iter) op bson_iter##t1 (compare_iter)) #define _EQ_COMPARE(t1, t2) _NATIVE_COMPARE (==, t1, t2) #define _NE_COMPARE(t1, t2) _NATIVE_COMPARE (!=, t1, t2) #define _GT_COMPARE(t1, t2) _NATIVE_COMPARE (>, t1, t2) @@ -604,9 +600,7 @@ _mongoc_matcher_op_gt_match (mongoc_matcher_op_compare_t *compare, /* IN */ return _GT_COMPARE (_int64, _int64); default: - MONGOC_WARNING ("Implement for (Type(%d) > Type(%d))", - bson_iter_type (compare_iter), - bson_iter_type (iter)); + MONGOC_WARNING ("Implement for (Type(%d) > Type(%d))", bson_iter_type (compare_iter), bson_iter_type (iter)); break; } @@ -675,9 +669,7 @@ _mongoc_matcher_op_gte_match (mongoc_matcher_op_compare_t *compare, /* IN */ return _GTE_COMPARE (_int64, _int64); default: - MONGOC_WARNING ("Implement for (Type(%d) >= Type(%d))", - bson_iter_type (compare_iter), - bson_iter_type (iter)); + MONGOC_WARNING ("Implement for (Type(%d) >= Type(%d))", bson_iter_type (compare_iter), bson_iter_type (iter)); break; } @@ -710,8 +702,7 @@ _mongoc_matcher_op_in_match (mongoc_matcher_op_compare_t *compare, /* IN */ op.base.opcode = MONGOC_MATCHER_OPCODE_EQ; op.path = compare->path; - if (!BSON_ITER_HOLDS_ARRAY (&compare->iter) || - !bson_iter_recurse (&compare->iter, &op.iter)) { + if (!BSON_ITER_HOLDS_ARRAY (&compare->iter) || !bson_iter_recurse (&compare->iter, &op.iter)) { return false; } @@ -786,9 +777,7 @@ _mongoc_matcher_op_lt_match (mongoc_matcher_op_compare_t *compare, /* IN */ return _LT_COMPARE (_int64, _int64); default: - MONGOC_WARNING ("Implement for (Type(%d) < Type(%d))", - bson_iter_type (compare_iter), - bson_iter_type (iter)); + MONGOC_WARNING ("Implement for (Type(%d) < Type(%d))", bson_iter_type (compare_iter), bson_iter_type (iter)); break; } @@ -857,9 +846,7 @@ _mongoc_matcher_op_lte_match (mongoc_matcher_op_compare_t *compare, /* IN */ return _LTE_COMPARE (_int64, _int64); default: - MONGOC_WARNING ("Implement for (Type(%d) <= Type(%d))", - bson_iter_type (compare_iter), - bson_iter_type (iter)); + MONGOC_WARNING ("Implement for (Type(%d) <= Type(%d))", bson_iter_type (compare_iter), bson_iter_type (iter)); break; } @@ -944,8 +931,7 @@ _mongoc_matcher_op_compare_match (mongoc_matcher_op_compare_t *compare, /* IN */ BSON_ASSERT (bson); if (strchr (compare->path, '.')) { - if (!bson_iter_init (&tmp, bson) || - !bson_iter_find_descendant (&tmp, compare->path, &iter)) { + if (!bson_iter_init (&tmp, bson) || !bson_iter_find_descendant (&tmp, compare->path, &iter)) { return false; } } else if (!bson_iter_init_find (&iter, bson, compare->path)) { @@ -1004,14 +990,11 @@ _mongoc_matcher_op_logical_match (mongoc_matcher_op_logical_t *logical, /* IN */ switch ((int) logical->base.opcode) { case MONGOC_MATCHER_OPCODE_OR: - return (_mongoc_matcher_op_match (logical->left, bson) || - _mongoc_matcher_op_match (logical->right, bson)); + return (_mongoc_matcher_op_match (logical->left, bson) || _mongoc_matcher_op_match (logical->right, bson)); case MONGOC_MATCHER_OPCODE_AND: - return (_mongoc_matcher_op_match (logical->left, bson) && - _mongoc_matcher_op_match (logical->right, bson)); + return (_mongoc_matcher_op_match (logical->left, bson) && _mongoc_matcher_op_match (logical->right, bson)); case MONGOC_MATCHER_OPCODE_NOR: - return !(_mongoc_matcher_op_match (logical->left, bson) || - _mongoc_matcher_op_match (logical->right, bson)); + return !(_mongoc_matcher_op_match (logical->left, bson) || _mongoc_matcher_op_match (logical->right, bson)); default: BSON_ASSERT (false); break; diff --git a/src/libmongoc/src/mongoc/mongoc-matcher.c b/src/libmongoc/src/mongoc/mongoc-matcher.c index fff40144c2..ab9de3318e 100644 --- a/src/libmongoc/src/mongoc/mongoc-matcher.c +++ b/src/libmongoc/src/mongoc/mongoc-matcher.c @@ -24,10 +24,7 @@ static mongoc_matcher_op_t * -_mongoc_matcher_parse_logical (mongoc_matcher_opcode_t opcode, - bson_iter_t *iter, - bool is_root, - bson_error_t *error); +_mongoc_matcher_parse_logical (mongoc_matcher_opcode_t opcode, bson_iter_t *iter, bool is_root, bson_error_t *error); /* @@ -65,60 +62,43 @@ _mongoc_matcher_parse_compare (bson_iter_t *iter, /* IN */ if (bson_iter_type (iter) == BSON_TYPE_DOCUMENT) { if (!bson_iter_recurse (iter, &child) || !bson_iter_next (&child)) { - bson_set_error (error, - MONGOC_ERROR_MATCHER, - MONGOC_ERROR_MATCHER_INVALID, - "Document contains no operations."); + bson_set_error (error, MONGOC_ERROR_MATCHER, MONGOC_ERROR_MATCHER_INVALID, "Document contains no operations."); return NULL; } key = bson_iter_key (&child); if (key[0] != '$') { - op = _mongoc_matcher_op_compare_new ( - MONGOC_MATCHER_OPCODE_EQ, path, iter); + op = _mongoc_matcher_op_compare_new (MONGOC_MATCHER_OPCODE_EQ, path, iter); } else if (strcmp (key, "$not") == 0) { - if (!(op_child = - _mongoc_matcher_parse_compare (&child, path, error))) { + if (!(op_child = _mongoc_matcher_parse_compare (&child, path, error))) { return NULL; } op = _mongoc_matcher_op_not_new (path, op_child); } else if (strcmp (key, "$gt") == 0) { - op = _mongoc_matcher_op_compare_new ( - MONGOC_MATCHER_OPCODE_GT, path, &child); + op = _mongoc_matcher_op_compare_new (MONGOC_MATCHER_OPCODE_GT, path, &child); } else if (strcmp (key, "$gte") == 0) { - op = _mongoc_matcher_op_compare_new ( - MONGOC_MATCHER_OPCODE_GTE, path, &child); + op = _mongoc_matcher_op_compare_new (MONGOC_MATCHER_OPCODE_GTE, path, &child); } else if (strcmp (key, "$in") == 0) { - op = _mongoc_matcher_op_compare_new ( - MONGOC_MATCHER_OPCODE_IN, path, &child); + op = _mongoc_matcher_op_compare_new (MONGOC_MATCHER_OPCODE_IN, path, &child); } else if (strcmp (key, "$lt") == 0) { - op = _mongoc_matcher_op_compare_new ( - MONGOC_MATCHER_OPCODE_LT, path, &child); + op = _mongoc_matcher_op_compare_new (MONGOC_MATCHER_OPCODE_LT, path, &child); } else if (strcmp (key, "$lte") == 0) { - op = _mongoc_matcher_op_compare_new ( - MONGOC_MATCHER_OPCODE_LTE, path, &child); + op = _mongoc_matcher_op_compare_new (MONGOC_MATCHER_OPCODE_LTE, path, &child); } else if (strcmp (key, "$ne") == 0) { - op = _mongoc_matcher_op_compare_new ( - MONGOC_MATCHER_OPCODE_NE, path, &child); + op = _mongoc_matcher_op_compare_new (MONGOC_MATCHER_OPCODE_NE, path, &child); } else if (strcmp (key, "$nin") == 0) { - op = _mongoc_matcher_op_compare_new ( - MONGOC_MATCHER_OPCODE_NIN, path, &child); + op = _mongoc_matcher_op_compare_new (MONGOC_MATCHER_OPCODE_NIN, path, &child); } else if (strcmp (key, "$exists") == 0) { op = _mongoc_matcher_op_exists_new (path, bson_iter_bool (&child)); } else if (strcmp (key, "$type") == 0) { op = _mongoc_matcher_op_type_new (path, bson_iter_type (&child)); } else { - bson_set_error (error, - MONGOC_ERROR_MATCHER, - MONGOC_ERROR_MATCHER_INVALID, - "Invalid operator \"%s\"", - key); + bson_set_error (error, MONGOC_ERROR_MATCHER, MONGOC_ERROR_MATCHER_INVALID, "Invalid operator \"%s\"", key); return NULL; } } else { - op = - _mongoc_matcher_op_compare_new (MONGOC_MATCHER_OPCODE_EQ, path, iter); + op = _mongoc_matcher_op_compare_new (MONGOC_MATCHER_OPCODE_EQ, path, iter); } BSON_ASSERT (op); @@ -161,31 +141,21 @@ _mongoc_matcher_parse (bson_iter_t *iter, /* IN */ BSON_ASSERT (bson_iter_type (iter) == BSON_TYPE_ARRAY); if (!bson_iter_recurse (iter, &child)) { - bson_set_error (error, - MONGOC_ERROR_MATCHER, - MONGOC_ERROR_MATCHER_INVALID, - "Invalid value for operator \"%s\"", - key); + bson_set_error ( + error, MONGOC_ERROR_MATCHER, MONGOC_ERROR_MATCHER_INVALID, "Invalid value for operator \"%s\"", key); return NULL; } if (strcmp (key, "$or") == 0) { - return _mongoc_matcher_parse_logical ( - MONGOC_MATCHER_OPCODE_OR, &child, false, error); + return _mongoc_matcher_parse_logical (MONGOC_MATCHER_OPCODE_OR, &child, false, error); } else if (strcmp (key, "$and") == 0) { - return _mongoc_matcher_parse_logical ( - MONGOC_MATCHER_OPCODE_AND, &child, false, error); + return _mongoc_matcher_parse_logical (MONGOC_MATCHER_OPCODE_AND, &child, false, error); } else if (strcmp (key, "$nor") == 0) { - return _mongoc_matcher_parse_logical ( - MONGOC_MATCHER_OPCODE_NOR, &child, false, error); + return _mongoc_matcher_parse_logical (MONGOC_MATCHER_OPCODE_NOR, &child, false, error); } } - bson_set_error (error, - MONGOC_ERROR_MATCHER, - MONGOC_ERROR_MATCHER_INVALID, - "Invalid operator \"%s\"", - key); + bson_set_error (error, MONGOC_ERROR_MATCHER, MONGOC_ERROR_MATCHER_INVALID, "Invalid operator \"%s\"", key); return NULL; } @@ -230,10 +200,7 @@ _mongoc_matcher_parse_logical (mongoc_matcher_opcode_t opcode, /* IN */ BSON_ASSERT (iter); if (!bson_iter_next (iter)) { - bson_set_error (error, - MONGOC_ERROR_MATCHER, - MONGOC_ERROR_MATCHER_INVALID, - "Invalid logical operator."); + bson_set_error (error, MONGOC_ERROR_MATCHER, MONGOC_ERROR_MATCHER_INVALID, "Invalid logical operator."); return NULL; } @@ -243,26 +210,17 @@ _mongoc_matcher_parse_logical (mongoc_matcher_opcode_t opcode, /* IN */ } } else { if (!BSON_ITER_HOLDS_DOCUMENT (iter)) { - bson_set_error (error, - MONGOC_ERROR_MATCHER, - MONGOC_ERROR_MATCHER_INVALID, - "Expected document in value."); + bson_set_error (error, MONGOC_ERROR_MATCHER, MONGOC_ERROR_MATCHER_INVALID, "Expected document in value."); return NULL; } if (!bson_iter_recurse (iter, &child)) { - bson_set_error (error, - MONGOC_ERROR_BSON, - MONGOC_ERROR_BSON_INVALID, - "corrupt BSON"); + bson_set_error (error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "corrupt BSON"); return NULL; } if (!bson_iter_next (&child)) { - bson_set_error (error, - MONGOC_ERROR_BSON, - MONGOC_ERROR_BSON_INVALID, - "corrupt BSON"); + bson_set_error (error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "corrupt BSON"); return NULL; } @@ -281,26 +239,17 @@ _mongoc_matcher_parse_logical (mongoc_matcher_opcode_t opcode, /* IN */ } } else { if (!BSON_ITER_HOLDS_DOCUMENT (iter)) { - bson_set_error (error, - MONGOC_ERROR_MATCHER, - MONGOC_ERROR_MATCHER_INVALID, - "Expected document in value."); + bson_set_error (error, MONGOC_ERROR_MATCHER, MONGOC_ERROR_MATCHER_INVALID, "Expected document in value."); return NULL; } if (!bson_iter_recurse (iter, &child)) { - bson_set_error (error, - MONGOC_ERROR_BSON, - MONGOC_ERROR_BSON_INVALID, - "bson_iter_recurse failed."); + bson_set_error (error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "bson_iter_recurse failed."); return NULL; } if (!bson_iter_next (&child)) { - bson_set_error (error, - MONGOC_ERROR_BSON, - MONGOC_ERROR_BSON_INVALID, - "corrupt BSON"); + bson_set_error (error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "corrupt BSON"); return NULL; } @@ -361,8 +310,7 @@ mongoc_matcher_new (const bson_t *query, /* IN */ goto failure; } - if (!(op = _mongoc_matcher_parse_logical ( - MONGOC_MATCHER_OPCODE_AND, &iter, true, error))) { + if (!(op = _mongoc_matcher_parse_logical (MONGOC_MATCHER_OPCODE_AND, &iter, true, error))) { goto failure; } diff --git a/src/libmongoc/src/mongoc/mongoc-matcher.h b/src/libmongoc/src/mongoc/mongoc-matcher.h index 2534290fe6..135de85058 100644 --- a/src/libmongoc/src/mongoc/mongoc-matcher.h +++ b/src/libmongoc/src/mongoc/mongoc-matcher.h @@ -30,11 +30,9 @@ typedef struct _mongoc_matcher_t mongoc_matcher_t; MONGOC_EXPORT (mongoc_matcher_t *) -mongoc_matcher_new (const bson_t *query, bson_error_t *error) - BSON_GNUC_WARN_UNUSED_RESULT BSON_GNUC_DEPRECATED; +mongoc_matcher_new (const bson_t *query, bson_error_t *error) BSON_GNUC_WARN_UNUSED_RESULT BSON_GNUC_DEPRECATED; MONGOC_EXPORT (bool) -mongoc_matcher_match (const mongoc_matcher_t *matcher, - const bson_t *document) BSON_GNUC_DEPRECATED; +mongoc_matcher_match (const mongoc_matcher_t *matcher, const bson_t *document) BSON_GNUC_DEPRECATED; MONGOC_EXPORT (void) mongoc_matcher_destroy (mongoc_matcher_t *matcher) BSON_GNUC_DEPRECATED; diff --git a/src/libmongoc/src/mongoc/mongoc-ocsp-cache-private.h b/src/libmongoc/src/mongoc/mongoc-ocsp-cache-private.h index 7b93de114a..abd185cba1 100644 --- a/src/libmongoc/src/mongoc/mongoc-ocsp-cache-private.h +++ b/src/libmongoc/src/mongoc/mongoc-ocsp-cache-private.h @@ -30,11 +30,8 @@ void _mongoc_ocsp_cache_init (void); void -_mongoc_ocsp_cache_set_resp (OCSP_CERTID *id, - int cert_status, - int reason, - ASN1_GENERALIZEDTIME *this_update, - ASN1_GENERALIZEDTIME *next_update); +_mongoc_ocsp_cache_set_resp ( + OCSP_CERTID *id, int cert_status, int reason, ASN1_GENERALIZEDTIME *this_update, ASN1_GENERALIZEDTIME *next_update); int _mongoc_ocsp_cache_length (void); diff --git a/src/libmongoc/src/mongoc/mongoc-ocsp-cache.c b/src/libmongoc/src/mongoc/mongoc-ocsp-cache.c index d43e74fe69..14c27ecd9b 100644 --- a/src/libmongoc/src/mongoc/mongoc-ocsp-cache.c +++ b/src/libmongoc/src/mongoc/mongoc-ocsp-cache.c @@ -101,11 +101,8 @@ _cmp_time (ASN1_TIME *a, ASN1_TIME *b) #endif void -_mongoc_ocsp_cache_set_resp (OCSP_CERTID *id, - int cert_status, - int reason, - ASN1_GENERALIZEDTIME *this_update, - ASN1_GENERALIZEDTIME *next_update) +_mongoc_ocsp_cache_set_resp ( + OCSP_CERTID *id, int cert_status, int reason, ASN1_GENERALIZEDTIME *this_update, ASN1_GENERALIZEDTIME *next_update) { cache_entry_list_t *entry = NULL; ENTRY; diff --git a/src/libmongoc/src/mongoc/mongoc-openssl-private.h b/src/libmongoc/src/mongoc/mongoc-openssl-private.h index b276622fb8..22ca6dc0b2 100644 --- a/src/libmongoc/src/mongoc/mongoc-openssl-private.h +++ b/src/libmongoc/src/mongoc/mongoc-openssl-private.h @@ -27,8 +27,7 @@ #include "mongoc-ssl.h" #include "mongoc-stream-tls-openssl-private.h" -#if (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_OCSP) && \ - !defined(LIBRESSL_VERSION_NUMBER) +#if (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_OCSP) && !defined(LIBRESSL_VERSION_NUMBER) #define MONGOC_ENABLE_OCSP_OPENSSL #endif @@ -36,9 +35,7 @@ BSON_BEGIN_DECLS bool -_mongoc_openssl_check_peer_hostname (SSL *ssl, - const char *host, - bool allow_invalid_hostname); +_mongoc_openssl_check_peer_hostname (SSL *ssl, const char *host, bool allow_invalid_hostname); SSL_CTX * _mongoc_openssl_ctx_new (mongoc_ssl_opt_t *opt); char * diff --git a/src/libmongoc/src/mongoc/mongoc-openssl.c b/src/libmongoc/src/mongoc/mongoc-openssl.c index 8d7d73ba13..26d2549cba 100644 --- a/src/libmongoc/src/mongoc/mongoc-openssl.c +++ b/src/libmongoc/src/mongoc/mongoc-openssl.c @@ -95,8 +95,7 @@ _mongoc_openssl_init (void) tlsfeature_nid = NID_tlsfeature; #else /* TLS versions before 1.1.0 did not define the TLS Feature extension. */ - tlsfeature_nid = - OBJ_create ("1.3.6.1.5.5.7.1.24", "tlsfeature", "TLS Feature"); + tlsfeature_nid = OBJ_create ("1.3.6.1.5.5.7.1.24", "tlsfeature", "TLS Feature"); #endif SSL_CTX_free (ctx); @@ -128,25 +127,20 @@ _mongoc_openssl_password_cb (char *buf, int num, int rwflag, void *user_data) #ifdef _WIN32 bool -_mongoc_openssl_import_cert_store (LPWSTR store_name, - DWORD dwFlags, - X509_STORE *openssl_store) +_mongoc_openssl_import_cert_store (LPWSTR store_name, DWORD dwFlags, X509_STORE *openssl_store) { PCCERT_CONTEXT cert = NULL; HCERTSTORE cert_store; - cert_store = CertOpenStore ( - CERT_STORE_PROV_SYSTEM, /* provider */ - X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, /* certificate encoding */ - 0, /* unused */ - dwFlags, /* dwFlags */ - store_name); /* system store name. "My" or "Root" */ + cert_store = CertOpenStore (CERT_STORE_PROV_SYSTEM, /* provider */ + X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, /* certificate encoding */ + 0, /* unused */ + dwFlags, /* dwFlags */ + store_name); /* system store name. "My" or "Root" */ if (cert_store == NULL) { LPTSTR msg = NULL; - FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_ARGUMENT_ARRAY, + FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY, NULL, GetLastError (), LANG_NEUTRAL, @@ -159,13 +153,10 @@ _mongoc_openssl_import_cert_store (LPWSTR store_name, } while ((cert = CertEnumCertificatesInStore (cert_store, cert)) != NULL) { - X509 *x509Obj = d2i_X509 (NULL, - (const unsigned char **) &cert->pbCertEncoded, - cert->cbCertEncoded); + X509 *x509Obj = d2i_X509 (NULL, (const unsigned char **) &cert->pbCertEncoded, cert->cbCertEncoded); if (x509Obj == NULL) { - MONGOC_WARNING ( - "Error parsing X509 object from Windows certificate store"); + MONGOC_WARNING ("Error parsing X509 object from Windows certificate store"); continue; } @@ -189,12 +180,10 @@ _mongoc_openssl_import_cert_stores (SSL_CTX *context) return false; } - retval = _mongoc_openssl_import_cert_store (L"root", - CERT_SYSTEM_STORE_CURRENT_USER | - CERT_STORE_READONLY_FLAG, - store); - retval &= _mongoc_openssl_import_cert_store ( - L"CA", CERT_SYSTEM_STORE_CURRENT_USER | CERT_STORE_READONLY_FLAG, store); + retval = + _mongoc_openssl_import_cert_store (L"root", CERT_SYSTEM_STORE_CURRENT_USER | CERT_STORE_READONLY_FLAG, store); + retval &= + _mongoc_openssl_import_cert_store (L"CA", CERT_SYSTEM_STORE_CURRENT_USER | CERT_STORE_READONLY_FLAG, store); return retval; } @@ -202,9 +191,7 @@ _mongoc_openssl_import_cert_stores (SSL_CTX *context) #if OPENSSL_VERSION_NUMBER > 0x10002000L bool -_mongoc_openssl_check_peer_hostname (SSL *ssl, - const char *host, - bool allow_invalid_hostname) +_mongoc_openssl_check_peer_hostname (SSL *ssl, const char *host, bool allow_invalid_hostname) { X509 *peer = NULL; @@ -213,8 +200,7 @@ _mongoc_openssl_check_peer_hostname (SSL *ssl, } peer = SSL_get_peer_certificate (ssl); - if (peer && (X509_check_host (peer, host, 0, 0, NULL) == 1 || - X509_check_ip_asc (peer, host, 0) == 1)) { + if (peer && (X509_check_host (peer, host, 0, 0, NULL) == 1 || X509_check_ip_asc (peer, host, 0) == 1)) { X509_free (peer); return true; } @@ -257,18 +243,15 @@ _mongoc_openssl_hostcheck (const char *pattern, const char *hostname) * o the wildcard isn't in the left most group (separated by dots) * o the pattern is embedded in an A-label or U-label */ - if (pattern_label_end == NULL || - strchr (pattern_label_end + 1, '.') == NULL || - pattern_wildcard > pattern_label_end || - strncasecmp (pattern, "xn--", 4) == 0) { + if (pattern_label_end == NULL || strchr (pattern_label_end + 1, '.') == NULL || + pattern_wildcard > pattern_label_end || strncasecmp (pattern, "xn--", 4) == 0) { return strcasecmp (pattern, hostname) == 0; } hostname_label_end = strchr (hostname, '.'); /* we know we have a dot in the pattern, we need one in the hostname */ - if (hostname_label_end == NULL || - strcasecmp (pattern_label_end, hostname_label_end)) { + if (hostname_label_end == NULL || strcasecmp (pattern_label_end, hostname_label_end)) { return 0; } @@ -283,18 +266,14 @@ _mongoc_openssl_hostcheck (const char *pattern, const char *hostname) prefixlen = pattern_wildcard - pattern; suffixlen = pattern_label_end - (pattern_wildcard + 1); return strncasecmp (pattern, hostname, prefixlen) == 0 && - strncasecmp (pattern_wildcard + 1, - hostname_label_end - suffixlen, - suffixlen) == 0; + strncasecmp (pattern_wildcard + 1, hostname_label_end - suffixlen, suffixlen) == 0; } /** check if a provided cert matches a passed hostname */ bool -_mongoc_openssl_check_peer_hostname (SSL *ssl, - const char *host, - bool allow_invalid_hostname) +_mongoc_openssl_check_peer_hostname (SSL *ssl, const char *host, bool allow_invalid_hostname) { X509 *peer; X509_NAME *subject_name; @@ -335,8 +314,7 @@ _mongoc_openssl_check_peer_hostname (SSL *ssl, peer = SSL_get_peer_certificate (ssl); if (!peer) { - MONGOC_WARNING ("SSL Certification verification failed: %s", - ERR_error_string (ERR_get_error (), NULL)); + MONGOC_WARNING ("SSL Certification verification failed: %s", ERR_error_string (ERR_get_error (), NULL)); RETURN (false); } @@ -344,8 +322,7 @@ _mongoc_openssl_check_peer_hostname (SSL *ssl, if (verify_status == X509_V_OK) { /* gets a stack of alt names that we can iterate through */ - sans = (STACK_OF (GENERAL_NAME) *) X509_get_ext_d2i ( - (X509 *) peer, NID_subject_alt_name, NULL, NULL); + sans = (STACK_OF (GENERAL_NAME) *) X509_get_ext_d2i ((X509 *) peer, NID_subject_alt_name, NULL, NULL); if (sans) { n_sans = sk_GENERAL_NAME_num (sans); @@ -366,19 +343,16 @@ _mongoc_openssl_check_peer_hostname (SSL *ssl, case GEN_DNS: /* check that we don't have an embedded null byte */ - if ((length == bson_strnlen (check, length)) && - _mongoc_openssl_hostcheck (check, host)) { + if ((length == bson_strnlen (check, length)) && _mongoc_openssl_hostcheck (check, host)) { r = 1; } break; case GEN_IPADD: if (length == addrlen) { - if (length == sizeof addr6 && - !memcmp (check, &addr6, length)) { + if (length == sizeof addr6 && !memcmp (check, &addr6, length)) { r = 1; - } else if (length == sizeof addr4 && - !memcmp (check, &addr4, length)) { + } else if (length == sizeof addr4 && !memcmp (check, &addr4, length)) { r = 1; } } @@ -398,8 +372,7 @@ _mongoc_openssl_check_peer_hostname (SSL *ssl, i = -1; /* skip to the last common name */ - while ((idx = X509_NAME_get_index_by_NID ( - subject_name, NID_commonName, i)) >= 0) { + while ((idx = X509_NAME_get_index_by_NID (subject_name, NID_commonName, i)) >= 0) { i = idx; } @@ -413,13 +386,11 @@ _mongoc_openssl_check_peer_hostname (SSL *ssl, /* TODO: I've heard tell that old versions of SSL crap out * when calling ASN1_STRING_to_UTF8 on already utf8 data. * Check up on that */ - length = ASN1_STRING_to_UTF8 ((unsigned char **) &check, - entry_data); + length = ASN1_STRING_to_UTF8 ((unsigned char **) &check, entry_data); if (length >= 0) { /* check for embedded nulls */ - if ((length == bson_strnlen (check, length)) && - _mongoc_openssl_hostcheck (check, host)) { + if ((length == bson_strnlen (check, length)) && _mongoc_openssl_hostcheck (check, host)) { r = 1; } @@ -444,9 +415,7 @@ _mongoc_openssl_setup_ca (SSL_CTX *ctx, const char *cert, const char *cert_dir) BSON_ASSERT (cert || cert_dir); if (!SSL_CTX_load_verify_locations (ctx, cert, cert_dir)) { - MONGOC_ERROR ("Cannot load Certificate Authorities from '%s' and '%s'", - cert, - cert_dir); + MONGOC_ERROR ("Cannot load Certificate Authorities from '%s' and '%s'", cert, cert_dir); return 0; } @@ -473,9 +442,7 @@ _mongoc_openssl_setup_crl (SSL_CTX *ctx, const char *crlfile) static bool -_mongoc_openssl_setup_pem_file (SSL_CTX *ctx, - const char *pem_file, - const char *password) +_mongoc_openssl_setup_pem_file (SSL_CTX *ctx, const char *pem_file, const char *password) { if (!SSL_CTX_use_certificate_chain_file (ctx, pem_file)) { MONGOC_ERROR ("Cannot find certificate in '%s'", pem_file); @@ -657,18 +624,14 @@ _get_must_staple (X509 *cert) ext_data = X509_EXTENSION_get_data (ext); /* Data is a DER encoded sequence of integers. */ - return _mongoc_tlsfeature_has_status_request ( - ASN1_STRING_get0_data (ext_data), ASN1_STRING_length (ext_data)); + return _mongoc_tlsfeature_has_status_request (ASN1_STRING_get0_data (ext_data), ASN1_STRING_length (ext_data)); } #define ERR_STR (ERR_error_string (ERR_get_error (), NULL)) #define MONGOC_OCSP_REQUEST_TIMEOUT_MS 5000 static OCSP_RESPONSE * -_contact_ocsp_responder (OCSP_CERTID *id, - X509 *peer, - mongoc_ssl_opt_t *ssl_opts, - int *ocsp_uri_count) +_contact_ocsp_responder (OCSP_CERTID *id, X509 *peer, mongoc_ssl_opt_t *ssl_opts, int *ocsp_uri_count) { STACK_OF (OPENSSL_STRING) *url_stack = NULL; OPENSSL_STRING url = NULL, host = NULL, path = NULL, port = NULL; @@ -727,20 +690,14 @@ _contact_ocsp_responder (OCSP_CERTID *id, http_req.port = (int) bson_ascii_strtoll (port, NULL, 10); http_req.body = (const char *) request_der; http_req.body_len = request_der_len; - if (!_mongoc_http_send (&http_req, - MONGOC_OCSP_REQUEST_TIMEOUT_MS, - ssl != 0, - ssl_opts, - &http_res, - &error)) { + if (!_mongoc_http_send (&http_req, MONGOC_OCSP_REQUEST_TIMEOUT_MS, ssl != 0, ssl_opts, &http_res, &error)) { MONGOC_DEBUG ("Could not send HTTP request: %s", error.message); GOTO (retry); } resp_data = (const unsigned char *) http_res.body; - if (http_res.body_len == 0 || - !d2i_OCSP_RESPONSE (&resp, &resp_data, http_res.body_len)) { + if (http_res.body_len == 0 || !d2i_OCSP_RESPONSE (&resp, &resp_data, http_res.body_len)) { MONGOC_DEBUG ("Could not parse OCSP response from HTTP response"); MONGOC_DEBUG ("Response headers: %s", http_res.headers); GOTO (retry); @@ -765,9 +722,7 @@ _contact_ocsp_responder (OCSP_CERTID *id, RETURN (resp); } -#define SOFT_FAIL(...) \ - ((stapled_response) ? MONGOC_ERROR (__VA_ARGS__) \ - : MONGOC_DEBUG (__VA_ARGS__)) +#define SOFT_FAIL(...) ((stapled_response) ? MONGOC_ERROR (__VA_ARGS__) : MONGOC_DEBUG (__VA_ARGS__)) #define X509_CHECK_SUCCESS 1 #define OCSP_VERIFY_SUCCESS 1 @@ -787,8 +742,7 @@ _mongoc_ocsp_tlsext_status (SSL *ssl, mongoc_openssl_ocsp_opt_t *opts) unsigned char *mutable_resp_data = NULL; int cert_status, reason, len, status; OCSP_CERTID *id = NULL; - ASN1_GENERALIZEDTIME *produced_at = NULL, *this_update = NULL, - *next_update = NULL; + ASN1_GENERALIZEDTIME *produced_at = NULL, *this_update = NULL, *next_update = NULL; int ocsp_uri_count = 0; if (opts->weak_cert_validation) { @@ -821,8 +775,7 @@ _mongoc_ocsp_tlsext_status (SSL *ssl, mongoc_openssl_ocsp_opt_t *opts) GOTO (done); } - if (_mongoc_ocsp_cache_get_status ( - id, &cert_status, &reason, &this_update, &next_update)) { + if (_mongoc_ocsp_cache_get_status (id, &cert_status, &reason, &this_update, &next_update)) { GOTO (validate); } @@ -847,8 +800,7 @@ _mongoc_ocsp_tlsext_status (SSL *ssl, mongoc_openssl_ocsp_opt_t *opts) } if (opts->disable_endpoint_check || - !(resp = _contact_ocsp_responder ( - id, peer, &opts->ssl_opts, &ocsp_uri_count))) { + !(resp = _contact_ocsp_responder (id, peer, &opts->ssl_opts, &ocsp_uri_count))) { if (ocsp_uri_count > 0) { /* Only log a soft failure if there were OCSP responders listed in * the certificate. */ @@ -863,9 +815,7 @@ _mongoc_ocsp_tlsext_status (SSL *ssl, mongoc_openssl_ocsp_opt_t *opts) /* Validate the OCSP response status of the OCSP_RESPONSE object */ status = OCSP_response_status (resp); if (status != OCSP_RESPONSE_STATUS_SUCCESSFUL) { - SOFT_FAIL ("OCSP response error %d %s", - status, - OCSP_response_status_str (status)); + SOFT_FAIL ("OCSP response error %d %s", status, OCSP_response_status_str (status)); ret = OCSP_CB_ERROR; GOTO (done); } @@ -895,21 +845,14 @@ _mongoc_ocsp_tlsext_status (SSL *ssl, mongoc_openssl_ocsp_opt_t *opts) * cert_chain has already been verified. Use OCSP_TRUSTOTHER so the signer * certificate can be considered verified if it is in cert_chain. */ - if (OCSP_basic_verify (basic, cert_chain, store, OCSP_TRUSTOTHER) != - OCSP_VERIFY_SUCCESS) { + if (OCSP_basic_verify (basic, cert_chain, store, OCSP_TRUSTOTHER) != OCSP_VERIFY_SUCCESS) { SOFT_FAIL ("OCSP response failed verification: %s", ERR_STR); ret = OCSP_CB_ERROR; GOTO (done); } /* searches the basic response for an OCSP response for the given cert ID */ - if (!OCSP_resp_find_status (basic, - id, - &cert_status, - &reason, - &produced_at, - &this_update, - &next_update)) { + if (!OCSP_resp_find_status (basic, id, &cert_status, &reason, &produced_at, &this_update, &next_update)) { SOFT_FAIL ("No OCSP response found for the peer certificate"); ret = OCSP_CB_ERROR; GOTO (done); @@ -926,16 +869,13 @@ _mongoc_ocsp_tlsext_status (SSL *ssl, mongoc_openssl_ocsp_opt_t *opts) switch (cert_status) { case V_OCSP_CERTSTATUS_GOOD: TRACE ("%s", "OCSP Certificate Status: Good"); - _mongoc_ocsp_cache_set_resp ( - id, cert_status, reason, this_update, next_update); + _mongoc_ocsp_cache_set_resp (id, cert_status, reason, this_update, next_update); break; case V_OCSP_CERTSTATUS_REVOKED: - MONGOC_ERROR ("OCSP Certificate Status: Revoked. Reason: %s", - OCSP_crl_reason_str (reason)); + MONGOC_ERROR ("OCSP Certificate Status: Revoked. Reason: %s", OCSP_crl_reason_str (reason)); ret = OCSP_CB_REVOKED; - _mongoc_ocsp_cache_set_resp ( - id, cert_status, reason, this_update, next_update); + _mongoc_ocsp_cache_set_resp (id, cert_status, reason, this_update, next_update); GOTO (done); default: @@ -944,8 +884,7 @@ _mongoc_ocsp_tlsext_status (SSL *ssl, mongoc_openssl_ocsp_opt_t *opts) } /* Validate hostname matches cert */ - if (!_mongoc_openssl_check_peer_hostname ( - ssl, opts->host, opts->allow_invalid_hostname)) { + if (!_mongoc_openssl_check_peer_hostname (ssl, opts->host, opts->allow_invalid_hostname)) { ret = OCSP_CB_REVOKED; GOTO (done); } @@ -1036,8 +975,7 @@ _mongoc_openssl_ctx_new (mongoc_ssl_opt_t *opt) SSL_CTX_set_mode (ctx, SSL_MODE_AUTO_RETRY); /* Load my private keys to present to the server */ - if (opt->pem_file && - !_mongoc_openssl_setup_pem_file (ctx, opt->pem_file, opt->pem_pwd)) { + if (opt->pem_file && !_mongoc_openssl_setup_pem_file (ctx, opt->pem_file, opt->pem_pwd)) { SSL_CTX_free (ctx); return NULL; } @@ -1091,8 +1029,7 @@ _mongoc_openssl_extract_subject (const char *filename, const char *passphrase) BSON_ASSERT (strbio); - if (BIO_read_filename (certbio, filename) && - (cert = PEM_read_bio_X509 (certbio, NULL, 0, NULL))) { + if (BIO_read_filename (certbio, filename) && (cert = PEM_read_bio_X509 (certbio, NULL, 0, NULL))) { if ((subject = X509_get_subject_name (cert))) { ret = X509_NAME_print_ex (strbio, subject, 0, XN_FLAG_RFC2253); @@ -1145,10 +1082,7 @@ _mongoc_openssl_thread_id_callback (void) #endif static void -_mongoc_openssl_thread_locking_callback (int mode, - int type, - const char *file, - int line) +_mongoc_openssl_thread_locking_callback (int mode, int type, const char *file, int line) { if (mode & CRYPTO_LOCK) { bson_mutex_lock (&gMongocOpenSslThreadLocks[type]); @@ -1162,8 +1096,7 @@ _mongoc_openssl_thread_startup (void) { int i; - gMongocOpenSslThreadLocks = (bson_mutex_t *) OPENSSL_malloc ( - CRYPTO_num_locks () * sizeof (bson_mutex_t)); + gMongocOpenSslThreadLocks = (bson_mutex_t *) OPENSSL_malloc (CRYPTO_num_locks () * sizeof (bson_mutex_t)); for (i = 0; i < CRYPTO_num_locks (); i++) { bson_mutex_init (&gMongocOpenSslThreadLocks[i]); @@ -1180,8 +1113,7 @@ _mongoc_openssl_thread_cleanup (void) { int i; - if (CRYPTO_get_locking_callback () == - _mongoc_openssl_thread_locking_callback) { + if (CRYPTO_get_locking_callback () == _mongoc_openssl_thread_locking_callback) { CRYPTO_set_locking_callback (NULL); } diff --git a/src/libmongoc/src/mongoc/mongoc-opts-helpers-private.h b/src/libmongoc/src/mongoc/mongoc-opts-helpers-private.h index 500c8fd924..1a70af204e 100644 --- a/src/libmongoc/src/mongoc/mongoc-opts-helpers-private.h +++ b/src/libmongoc/src/mongoc/mongoc-opts-helpers-private.h @@ -38,52 +38,31 @@ void _mongoc_timestamp_set (mongoc_timestamp_t *dst, mongoc_timestamp_t *src); void -_mongoc_timestamp_set_from_bson (mongoc_timestamp_t *timestamp, - bson_iter_t *iter); +_mongoc_timestamp_set_from_bson (mongoc_timestamp_t *timestamp, bson_iter_t *iter); void -_mongoc_timestamp_append (mongoc_timestamp_t *timestamp, - bson_t *bson, - char *key); +_mongoc_timestamp_append (mongoc_timestamp_t *timestamp, bson_t *bson, char *key); void _mongoc_timestamp_clear (mongoc_timestamp_t *timestamp); bool -_mongoc_convert_document (mongoc_client_t *client, - const bson_iter_t *iter, - bson_t *doc, - bson_error_t *error); +_mongoc_convert_document (mongoc_client_t *client, const bson_iter_t *iter, bson_t *doc, bson_error_t *error); bool -_mongoc_convert_array (mongoc_client_t *client, - const bson_iter_t *iter, - bson_t *doc, - bson_error_t *error); +_mongoc_convert_array (mongoc_client_t *client, const bson_iter_t *iter, bson_t *doc, bson_error_t *error); bool -_mongoc_convert_int64_positive (mongoc_client_t *client, - const bson_iter_t *iter, - int64_t *num, - bson_error_t *error); +_mongoc_convert_int64_positive (mongoc_client_t *client, const bson_iter_t *iter, int64_t *num, bson_error_t *error); bool -_mongoc_convert_int32_t (mongoc_client_t *client, - const bson_iter_t *iter, - int32_t *num, - bson_error_t *error); +_mongoc_convert_int32_t (mongoc_client_t *client, const bson_iter_t *iter, int32_t *num, bson_error_t *error); bool -_mongoc_convert_int32_positive (mongoc_client_t *client, - const bson_iter_t *iter, - int32_t *num, - bson_error_t *error); +_mongoc_convert_int32_positive (mongoc_client_t *client, const bson_iter_t *iter, int32_t *num, bson_error_t *error); bool -_mongoc_convert_bool (mongoc_client_t *client, - const bson_iter_t *iter, - bool *flag, - bson_error_t *error); +_mongoc_convert_bool (mongoc_client_t *client, const bson_iter_t *iter, bool *flag, bson_error_t *error); bool _mongoc_convert_bson_value_t (mongoc_client_t *client, @@ -98,10 +77,7 @@ _mongoc_convert_timestamp (mongoc_client_t *client, bson_error_t *error); bool -_mongoc_convert_utf8 (mongoc_client_t *client, - const bson_iter_t *iter, - const char **comment, - bson_error_t *error); +_mongoc_convert_utf8 (mongoc_client_t *client, const bson_iter_t *iter, const char **comment, bson_error_t *error); bool _mongoc_convert_validate_flags (mongoc_client_t *client, @@ -110,11 +86,10 @@ _mongoc_convert_validate_flags (mongoc_client_t *client, bson_error_t *error); bool -_mongoc_convert_mongoc_write_bypass_document_validation_t ( - mongoc_client_t *client, - const bson_iter_t *iter, - bool *bdv, - bson_error_t *error); +_mongoc_convert_mongoc_write_bypass_document_validation_t (mongoc_client_t *client, + const bson_iter_t *iter, + bool *bdv, + bson_error_t *error); bool _mongoc_convert_write_concern (mongoc_client_t *client, @@ -123,10 +98,7 @@ _mongoc_convert_write_concern (mongoc_client_t *client, bson_error_t *error); bool -_mongoc_convert_server_id (mongoc_client_t *client, - const bson_iter_t *iter, - uint32_t *server_id, - bson_error_t *error); +_mongoc_convert_server_id (mongoc_client_t *client, const bson_iter_t *iter, uint32_t *server_id, bson_error_t *error); bool _mongoc_convert_read_concern (mongoc_client_t *client, @@ -135,9 +107,6 @@ _mongoc_convert_read_concern (mongoc_client_t *client, bson_error_t *error); bool -_mongoc_convert_hint (mongoc_client_t *client, - const bson_iter_t *iter, - bson_value_t *value, - bson_error_t *error); +_mongoc_convert_hint (mongoc_client_t *client, const bson_iter_t *iter, bson_value_t *value, bson_error_t *error); #endif diff --git a/src/libmongoc/src/mongoc/mongoc-opts-helpers.c b/src/libmongoc/src/mongoc/mongoc-opts-helpers.c index 32bff262ed..67f2b9ba29 100644 --- a/src/libmongoc/src/mongoc/mongoc-opts-helpers.c +++ b/src/libmongoc/src/mongoc/mongoc-opts-helpers.c @@ -20,21 +20,17 @@ #include "mongoc-util-private.h" #include "mongoc-read-concern-private.h" -#define BSON_ERR(...) \ - do { \ - bson_set_error ( \ - error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, __VA_ARGS__); \ - return false; \ +#define BSON_ERR(...) \ + do { \ + bson_set_error (error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, __VA_ARGS__); \ + return false; \ } while (0) -#define CONVERSION_ERR(...) \ - do { \ - bson_set_error (error, \ - MONGOC_ERROR_COMMAND, \ - MONGOC_ERROR_COMMAND_INVALID_ARG, \ - __VA_ARGS__); \ - return false; \ +#define CONVERSION_ERR(...) \ + do { \ + bson_set_error (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, __VA_ARGS__); \ + return false; \ } while (0) @@ -52,21 +48,17 @@ _mongoc_timestamp_set (mongoc_timestamp_t *dst, mongoc_timestamp_t *src) } void -_mongoc_timestamp_set_from_bson (mongoc_timestamp_t *timestamp, - bson_iter_t *iter) +_mongoc_timestamp_set_from_bson (mongoc_timestamp_t *timestamp, bson_iter_t *iter) { bson_iter_timestamp (iter, &(timestamp->timestamp), &(timestamp->increment)); } void -_mongoc_timestamp_append (mongoc_timestamp_t *timestamp, - bson_t *bson, - char *key) +_mongoc_timestamp_append (mongoc_timestamp_t *timestamp, bson_t *bson, char *key) { const size_t len = strlen (key); BSON_ASSERT (bson_in_range_unsigned (int, len)); - bson_append_timestamp ( - bson, key, (int) len, timestamp->timestamp, timestamp->increment); + bson_append_timestamp (bson, key, (int) len, timestamp->timestamp, timestamp->increment); } void @@ -77,10 +69,7 @@ _mongoc_timestamp_clear (mongoc_timestamp_t *timestamp) } bool -_mongoc_convert_document (mongoc_client_t *client, - const bson_iter_t *iter, - bson_t *doc, - bson_error_t *error) +_mongoc_convert_document (mongoc_client_t *client, const bson_iter_t *iter, bson_t *doc, bson_error_t *error) { uint32_t len; const uint8_t *data; @@ -107,10 +96,7 @@ _mongoc_convert_document (mongoc_client_t *client, } bool -_mongoc_convert_array (mongoc_client_t *client, - const bson_iter_t *iter, - bson_t *doc, - bson_error_t *error) +_mongoc_convert_array (mongoc_client_t *client, const bson_iter_t *iter, bson_t *doc, bson_error_t *error) { uint32_t len; const uint8_t *data; @@ -137,10 +123,7 @@ _mongoc_convert_array (mongoc_client_t *client, } bool -_mongoc_convert_int64_positive (mongoc_client_t *client, - const bson_iter_t *iter, - int64_t *num, - bson_error_t *error) +_mongoc_convert_int64_positive (mongoc_client_t *client, const bson_iter_t *iter, int64_t *num, bson_error_t *error) { int64_t i; @@ -166,10 +149,7 @@ _mongoc_convert_int64_positive (mongoc_client_t *client, } bool -_mongoc_convert_int32_t (mongoc_client_t *client, - const bson_iter_t *iter, - int32_t *num, - bson_error_t *error) +_mongoc_convert_int32_t (mongoc_client_t *client, const bson_iter_t *iter, int32_t *num, bson_error_t *error) { int64_t i; @@ -181,10 +161,7 @@ _mongoc_convert_int32_t (mongoc_client_t *client, i = bson_iter_as_int64 (iter); if (i > INT32_MAX || i < INT32_MIN) { - CONVERSION_ERR ("Invalid field \"%s\" in opts: %" PRId64 - " out of range for int32", - bson_iter_key (iter), - i); + CONVERSION_ERR ("Invalid field \"%s\" in opts: %" PRId64 " out of range for int32", bson_iter_key (iter), i); } *num = (int32_t) i; @@ -193,10 +170,7 @@ _mongoc_convert_int32_t (mongoc_client_t *client, } bool -_mongoc_convert_int32_positive (mongoc_client_t *client, - const bson_iter_t *iter, - int32_t *num, - bson_error_t *error) +_mongoc_convert_int32_positive (mongoc_client_t *client, const bson_iter_t *iter, int32_t *num, bson_error_t *error) { int32_t i; @@ -205,10 +179,7 @@ _mongoc_convert_int32_positive (mongoc_client_t *client, } if (i <= 0) { - CONVERSION_ERR ( - "Invalid field \"%s\" in opts, should be greater than 0, not %d", - bson_iter_key (iter), - i); + CONVERSION_ERR ("Invalid field \"%s\" in opts, should be greater than 0, not %d", bson_iter_key (iter), i); } *num = i; @@ -217,10 +188,7 @@ _mongoc_convert_int32_positive (mongoc_client_t *client, } bool -_mongoc_convert_bool (mongoc_client_t *client, - const bson_iter_t *iter, - bool *flag, - bson_error_t *error) +_mongoc_convert_bool (mongoc_client_t *client, const bson_iter_t *iter, bool *flag, bson_error_t *error) { BSON_UNUSED (client); @@ -264,10 +232,7 @@ _mongoc_convert_timestamp (mongoc_client_t *client, } bool -_mongoc_convert_utf8 (mongoc_client_t *client, - const bson_iter_t *iter, - const char **str, - bson_error_t *error) +_mongoc_convert_utf8 (mongoc_client_t *client, const bson_iter_t *iter, const char **str, bson_error_t *error) { BSON_UNUSED (client); @@ -338,10 +303,7 @@ _mongoc_convert_write_concern (mongoc_client_t *client, } bool -_mongoc_convert_server_id (mongoc_client_t *client, - const bson_iter_t *iter, - uint32_t *server_id, - bson_error_t *error) +_mongoc_convert_server_id (mongoc_client_t *client, const bson_iter_t *iter, uint32_t *server_id, bson_error_t *error) { int64_t tmp; @@ -376,10 +338,7 @@ _mongoc_convert_read_concern (mongoc_client_t *client, } bool -_mongoc_convert_hint (mongoc_client_t *client, - const bson_iter_t *iter, - bson_value_t *value, - bson_error_t *error) +_mongoc_convert_hint (mongoc_client_t *client, const bson_iter_t *iter, bson_value_t *value, bson_error_t *error) { BSON_UNUSED (client); diff --git a/src/libmongoc/src/mongoc/mongoc-rand-cng.c b/src/libmongoc/src/mongoc/mongoc-rand-cng.c index dd5ff76337..3384d7218d 100644 --- a/src/libmongoc/src/mongoc/mongoc-rand-cng.c +++ b/src/libmongoc/src/mongoc/mongoc-rand-cng.c @@ -37,8 +37,7 @@ _mongoc_rand_bytes (uint8_t *buf, int num) NTSTATUS status = 0; if (!algorithm) { - status = BCryptOpenAlgorithmProvider ( - &algorithm, BCRYPT_RNG_ALGORITHM, NULL, 0); + status = BCryptOpenAlgorithmProvider (&algorithm, BCRYPT_RNG_ALGORITHM, NULL, 0); if (!NT_SUCCESS (status)) { MONGOC_ERROR ("BCryptOpenAlgorithmProvider(): %ld", status); return 0; diff --git a/src/libmongoc/src/mongoc/mongoc-read-concern-private.h b/src/libmongoc/src/mongoc/mongoc-read-concern-private.h index 7984215178..ec421dd1bf 100644 --- a/src/libmongoc/src/mongoc/mongoc-read-concern-private.h +++ b/src/libmongoc/src/mongoc/mongoc-read-concern-private.h @@ -38,8 +38,7 @@ _mongoc_read_concern_get_bson (mongoc_read_concern_t *read_concern); mongoc_read_concern_t * -_mongoc_read_concern_new_from_iter (const bson_iter_t *iter, - bson_error_t *error); +_mongoc_read_concern_new_from_iter (const bson_iter_t *iter, bson_error_t *error); BSON_END_DECLS diff --git a/src/libmongoc/src/mongoc/mongoc-read-concern.c b/src/libmongoc/src/mongoc/mongoc-read-concern.c index 5e21dfda3b..85bff706ab 100644 --- a/src/libmongoc/src/mongoc/mongoc-read-concern.c +++ b/src/libmongoc/src/mongoc/mongoc-read-concern.c @@ -101,8 +101,7 @@ mongoc_read_concern_get_level (const mongoc_read_concern_t *read_concern) * See the MongoDB docs for more information on readConcernLevel */ bool -mongoc_read_concern_set_level (mongoc_read_concern_t *read_concern, - const char *level) +mongoc_read_concern_set_level (mongoc_read_concern_t *read_concern, const char *level) { BSON_ASSERT (read_concern); @@ -125,8 +124,7 @@ mongoc_read_concern_set_level (mongoc_read_concern_t *read_concern, * */ bool -mongoc_read_concern_append (mongoc_read_concern_t *read_concern, - bson_t *command) +mongoc_read_concern_append (mongoc_read_concern_t *read_concern, bson_t *command) { BSON_ASSERT (read_concern); @@ -134,10 +132,7 @@ mongoc_read_concern_append (mongoc_read_concern_t *read_concern, return true; } - if (!bson_append_document (command, - "readConcern", - 11, - _mongoc_read_concern_get_bson (read_concern))) { + if (!bson_append_document (command, "readConcern", 11, _mongoc_read_concern_get_bson (read_concern))) { MONGOC_ERROR ("Could not append readConcern to command."); return false; } @@ -189,8 +184,7 @@ _mongoc_read_concern_get_bson (mongoc_read_concern_t *read_concern) * with mongoc_read_concern_destroy(). */ mongoc_read_concern_t * -_mongoc_read_concern_new_from_iter (const bson_iter_t *iter, - bson_error_t *error) +_mongoc_read_concern_new_from_iter (const bson_iter_t *iter, bson_error_t *error) { bson_iter_t inner; mongoc_read_concern_t *read_concern; @@ -212,10 +206,7 @@ _mongoc_read_concern_new_from_iter (const bson_iter_t *iter, return read_concern; fail: - bson_set_error (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Invalid readConcern"); + bson_set_error (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid readConcern"); mongoc_read_concern_destroy (read_concern); return NULL; diff --git a/src/libmongoc/src/mongoc/mongoc-read-concern.h b/src/libmongoc/src/mongoc/mongoc-read-concern.h index ab4cb0a8da..2c4d68b0a8 100644 --- a/src/libmongoc/src/mongoc/mongoc-read-concern.h +++ b/src/libmongoc/src/mongoc/mongoc-read-concern.h @@ -38,15 +38,13 @@ typedef struct _mongoc_read_concern_t mongoc_read_concern_t; MONGOC_EXPORT (mongoc_read_concern_t *) mongoc_read_concern_new (void) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (mongoc_read_concern_t *) -mongoc_read_concern_copy (const mongoc_read_concern_t *read_concern) - BSON_GNUC_WARN_UNUSED_RESULT; +mongoc_read_concern_copy (const mongoc_read_concern_t *read_concern) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (void) mongoc_read_concern_destroy (mongoc_read_concern_t *read_concern); MONGOC_EXPORT (const char *) mongoc_read_concern_get_level (const mongoc_read_concern_t *read_concern); MONGOC_EXPORT (bool) -mongoc_read_concern_set_level (mongoc_read_concern_t *read_concern, - const char *level); +mongoc_read_concern_set_level (mongoc_read_concern_t *read_concern, const char *level); MONGOC_EXPORT (bool) mongoc_read_concern_append (mongoc_read_concern_t *read_concern, bson_t *doc); MONGOC_EXPORT (bool) diff --git a/src/libmongoc/src/mongoc/mongoc-read-prefs-private.h b/src/libmongoc/src/mongoc/mongoc-read-prefs-private.h index a0d9d787a3..4a10f9b136 100644 --- a/src/libmongoc/src/mongoc/mongoc-read-prefs-private.h +++ b/src/libmongoc/src/mongoc/mongoc-read-prefs-private.h @@ -61,11 +61,9 @@ void assemble_query_result_cleanup (mongoc_assemble_query_result_t *result); bool -_mongoc_read_prefs_validate (const mongoc_read_prefs_t *read_prefs, - bson_error_t *error); +_mongoc_read_prefs_validate (const mongoc_read_prefs_t *read_prefs, bson_error_t *error); -#define IS_PREF_PRIMARY(_pref) \ - (!(_pref) || ((_pref)->mode == MONGOC_READ_PRIMARY)) +#define IS_PREF_PRIMARY(_pref) (!(_pref) || ((_pref)->mode == MONGOC_READ_PRIMARY)) BSON_END_DECLS diff --git a/src/libmongoc/src/mongoc/mongoc-read-prefs.c b/src/libmongoc/src/mongoc/mongoc-read-prefs.c index 525f26b8fd..c7e44ed844 100644 --- a/src/libmongoc/src/mongoc/mongoc-read-prefs.c +++ b/src/libmongoc/src/mongoc/mongoc-read-prefs.c @@ -43,8 +43,7 @@ mongoc_read_prefs_get_mode (const mongoc_read_prefs_t *read_prefs) void -mongoc_read_prefs_set_mode (mongoc_read_prefs_t *read_prefs, - mongoc_read_mode_t mode) +mongoc_read_prefs_set_mode (mongoc_read_prefs_t *read_prefs, mongoc_read_mode_t mode) { BSON_ASSERT (read_prefs); BSON_ASSERT (mode <= MONGOC_READ_NEAREST); @@ -99,8 +98,7 @@ mongoc_read_prefs_add_tag (mongoc_read_prefs_t *read_prefs, const bson_t *tag) int64_t -mongoc_read_prefs_get_max_staleness_seconds ( - const mongoc_read_prefs_t *read_prefs) +mongoc_read_prefs_get_max_staleness_seconds (const mongoc_read_prefs_t *read_prefs) { BSON_ASSERT (read_prefs); @@ -109,8 +107,7 @@ mongoc_read_prefs_get_max_staleness_seconds ( void -mongoc_read_prefs_set_max_staleness_seconds (mongoc_read_prefs_t *read_prefs, - int64_t max_staleness_seconds) +mongoc_read_prefs_set_max_staleness_seconds (mongoc_read_prefs_t *read_prefs, int64_t max_staleness_seconds) { BSON_ASSERT (read_prefs); @@ -128,8 +125,7 @@ mongoc_read_prefs_get_hedge (const mongoc_read_prefs_t *read_prefs) void -mongoc_read_prefs_set_hedge (mongoc_read_prefs_t *read_prefs, - const bson_t *hedge) +mongoc_read_prefs_set_hedge (mongoc_read_prefs_t *read_prefs, const bson_t *hedge) { BSON_ASSERT (read_prefs); @@ -152,15 +148,13 @@ mongoc_read_prefs_is_valid (const mongoc_read_prefs_t *read_prefs) * Tags, maxStalenessSeconds, and hedge are not supported with PRIMARY mode. */ if (read_prefs->mode == MONGOC_READ_PRIMARY) { - if (!bson_empty (&read_prefs->tags) || - read_prefs->max_staleness_seconds != MONGOC_NO_MAX_STALENESS || + if (!bson_empty (&read_prefs->tags) || read_prefs->max_staleness_seconds != MONGOC_NO_MAX_STALENESS || !bson_empty (&read_prefs->hedge)) { return false; } } - if (read_prefs->max_staleness_seconds != MONGOC_NO_MAX_STALENESS && - read_prefs->max_staleness_seconds <= 0) { + if (read_prefs->max_staleness_seconds != MONGOC_NO_MAX_STALENESS && read_prefs->max_staleness_seconds <= 0) { return false; } @@ -222,10 +216,9 @@ _mongoc_read_mode_as_str (mongoc_read_mode_t mode) * The driver must have discovered the server is a mongos. */ static void -_apply_read_preferences_mongos ( - const mongoc_read_prefs_t *read_prefs, - const bson_t *query_bson, - mongoc_assemble_query_result_t *result /* OUT */) +_apply_read_preferences_mongos (const mongoc_read_prefs_t *read_prefs, + const bson_t *query_bson, + mongoc_assemble_query_result_t *result /* OUT */) { mongoc_read_mode_t mode; const bson_t *tags = NULL; @@ -236,8 +229,7 @@ _apply_read_preferences_mongos ( mode = mongoc_read_prefs_get_mode (read_prefs); if (read_prefs) { - max_staleness_seconds = - mongoc_read_prefs_get_max_staleness_seconds (read_prefs); + max_staleness_seconds = mongoc_read_prefs_get_max_staleness_seconds (read_prefs); tags = mongoc_read_prefs_get_tags (read_prefs); hedge = mongoc_read_prefs_get_hedge (read_prefs); @@ -264,8 +256,7 @@ _apply_read_preferences_mongos ( * and MUST also use $readPreference */ if (mode == MONGOC_READ_SECONDARY_PREFERRED && - (bson_empty0 (tags) && max_staleness_seconds <= 0 && - bson_empty0 (hedge))) { + (bson_empty0 (tags) && max_staleness_seconds <= 0 && bson_empty0 (hedge))) { result->flags |= MONGOC_QUERY_SECONDARY_OK; } else if (mode != MONGOC_READ_PRIMARY) { @@ -283,12 +274,10 @@ _apply_read_preferences_mongos ( if (bson_has_field (query_bson, "$query")) { bson_concat (result->assembled_query, query_bson); } else { - bson_append_document ( - result->assembled_query, "$query", 6, query_bson); + bson_append_document (result->assembled_query, "$query", 6, query_bson); } - bson_append_document_begin ( - result->assembled_query, "$readPreference", 15, &child); + bson_append_document_begin (result->assembled_query, "$readPreference", 15, &child); mode_str = _mongoc_read_mode_as_str (mode); bson_append_utf8 (&child, "mode", 4, mode_str, -1); if (!bson_empty0 (tags)) { @@ -296,8 +285,7 @@ _apply_read_preferences_mongos ( } if (max_staleness_seconds != MONGOC_NO_MAX_STALENESS) { - bson_append_int64 ( - &child, "maxStalenessSeconds", 19, max_staleness_seconds); + bson_append_int64 (&child, "maxStalenessSeconds", 19, max_staleness_seconds); } if (!bson_empty0 (hedge)) { @@ -410,14 +398,10 @@ assemble_query_result_cleanup (mongoc_assemble_query_result_t *result) } bool -_mongoc_read_prefs_validate (const mongoc_read_prefs_t *read_prefs, - bson_error_t *error) +_mongoc_read_prefs_validate (const mongoc_read_prefs_t *read_prefs, bson_error_t *error) { if (read_prefs && !mongoc_read_prefs_is_valid (read_prefs)) { - bson_set_error (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Invalid mongoc_read_prefs_t"); + bson_set_error (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid mongoc_read_prefs_t"); return false; } return true; diff --git a/src/libmongoc/src/mongoc/mongoc-read-prefs.h b/src/libmongoc/src/mongoc/mongoc-read-prefs.h index c378adbe57..cb0a7df5de 100644 --- a/src/libmongoc/src/mongoc/mongoc-read-prefs.h +++ b/src/libmongoc/src/mongoc/mongoc-read-prefs.h @@ -48,36 +48,29 @@ typedef enum { MONGOC_EXPORT (mongoc_read_prefs_t *) -mongoc_read_prefs_new (mongoc_read_mode_t read_mode) - BSON_GNUC_WARN_UNUSED_RESULT; +mongoc_read_prefs_new (mongoc_read_mode_t read_mode) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (mongoc_read_prefs_t *) -mongoc_read_prefs_copy (const mongoc_read_prefs_t *read_prefs) - BSON_GNUC_WARN_UNUSED_RESULT; +mongoc_read_prefs_copy (const mongoc_read_prefs_t *read_prefs) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (void) mongoc_read_prefs_destroy (mongoc_read_prefs_t *read_prefs); MONGOC_EXPORT (mongoc_read_mode_t) mongoc_read_prefs_get_mode (const mongoc_read_prefs_t *read_prefs); MONGOC_EXPORT (void) -mongoc_read_prefs_set_mode (mongoc_read_prefs_t *read_prefs, - mongoc_read_mode_t mode); +mongoc_read_prefs_set_mode (mongoc_read_prefs_t *read_prefs, mongoc_read_mode_t mode); MONGOC_EXPORT (const bson_t *) mongoc_read_prefs_get_tags (const mongoc_read_prefs_t *read_prefs); MONGOC_EXPORT (void) -mongoc_read_prefs_set_tags (mongoc_read_prefs_t *read_prefs, - const bson_t *tags); +mongoc_read_prefs_set_tags (mongoc_read_prefs_t *read_prefs, const bson_t *tags); MONGOC_EXPORT (void) mongoc_read_prefs_add_tag (mongoc_read_prefs_t *read_prefs, const bson_t *tag); MONGOC_EXPORT (int64_t) -mongoc_read_prefs_get_max_staleness_seconds ( - const mongoc_read_prefs_t *read_prefs); +mongoc_read_prefs_get_max_staleness_seconds (const mongoc_read_prefs_t *read_prefs); MONGOC_EXPORT (void) -mongoc_read_prefs_set_max_staleness_seconds (mongoc_read_prefs_t *read_prefs, - int64_t max_staleness_seconds); +mongoc_read_prefs_set_max_staleness_seconds (mongoc_read_prefs_t *read_prefs, int64_t max_staleness_seconds); MONGOC_EXPORT (const bson_t *) mongoc_read_prefs_get_hedge (const mongoc_read_prefs_t *read_prefs); MONGOC_EXPORT (void) -mongoc_read_prefs_set_hedge (mongoc_read_prefs_t *read_prefs, - const bson_t *hedge); +mongoc_read_prefs_set_hedge (mongoc_read_prefs_t *read_prefs, const bson_t *hedge); MONGOC_EXPORT (bool) mongoc_read_prefs_is_valid (const mongoc_read_prefs_t *read_prefs); diff --git a/src/libmongoc/src/mongoc/mongoc-rpc-private.h b/src/libmongoc/src/mongoc/mongoc-rpc-private.h index 79b3f9bc83..ce3f0ef338 100644 --- a/src/libmongoc/src/mongoc/mongoc-rpc-private.h +++ b/src/libmongoc/src/mongoc/mongoc-rpc-private.h @@ -37,14 +37,10 @@ mcd_rpc_message_check_ok (mcd_rpc_message *rpc, bson_error_t *error /* OUT */, bson_t *error_doc /* OUT */); bool -_mongoc_cmd_check_ok (const bson_t *doc, - int32_t error_api_version, - bson_error_t *error); +_mongoc_cmd_check_ok (const bson_t *doc, int32_t error_api_version, bson_error_t *error); bool -_mongoc_cmd_check_ok_no_wce (const bson_t *doc, - int32_t error_api_version, - bson_error_t *error); +_mongoc_cmd_check_ok_no_wce (const bson_t *doc, int32_t error_api_version, bson_error_t *error); void mcd_rpc_message_egress (const mcd_rpc_message *rpc); diff --git a/src/libmongoc/src/mongoc/mongoc-rpc.c b/src/libmongoc/src/mongoc/mongoc-rpc.c index 61edc44634..27a8d6042a 100644 --- a/src/libmongoc/src/mongoc/mongoc-rpc.c +++ b/src/libmongoc/src/mongoc/mongoc-rpc.c @@ -32,11 +32,9 @@ mcd_rpc_message_get_body (const mcd_rpc_message *rpc, bson_t *reply) for (size_t index = 0u; index < sections_count; ++index) { switch (mcd_rpc_op_msg_section_get_kind (rpc, index)) { case 0: { // Body. - const uint8_t *const body = - mcd_rpc_op_msg_section_get_body (rpc, index); + const uint8_t *const body = mcd_rpc_op_msg_section_get_body (rpc, index); - const int32_t body_len = - bson_iter_int32_unsafe (&(bson_iter_t){.raw = body}); + const int32_t body_len = bson_iter_int32_unsafe (&(bson_iter_t){.raw = body}); return bson_init_static (reply, body, (size_t) body_len); } @@ -60,10 +58,7 @@ mcd_rpc_message_get_body (const mcd_rpc_message *rpc, bson_t *reply) // Assume the first document in OP_REPLY is the body. const uint8_t *const body = mcd_rpc_op_reply_get_documents (rpc); - return bson_init_static ( - reply, - body, - (size_t) bson_iter_int32_unsafe (&(bson_iter_t){.raw = body})); + return bson_init_static (reply, body, (size_t) bson_iter_int32_unsafe (&(bson_iter_t){.raw = body})); } default: @@ -76,10 +71,7 @@ mcd_rpc_message_get_body (const mcd_rpc_message *rpc, bson_t *reply) /* returns true if an error was found. */ static bool -_parse_error_reply (const bson_t *doc, - bool check_wce, - uint32_t *code, - const char **msg) +_parse_error_reply (const bson_t *doc, bool check_wce, uint32_t *code, const char **msg) { bson_iter_t iter; bool found_error = false; @@ -93,19 +85,16 @@ _parse_error_reply (const bson_t *doc, /* The server only returns real error codes as int32. * But it may return as a double or int64 if a failpoint * based on how it is configured to error. */ - if (bson_iter_init_find (&iter, doc, "code") && - BSON_ITER_HOLDS_NUMBER (&iter)) { + if (bson_iter_init_find (&iter, doc, "code") && BSON_ITER_HOLDS_NUMBER (&iter)) { *code = (uint32_t) bson_iter_as_int64 (&iter); BSON_ASSERT (*code); found_error = true; } - if (bson_iter_init_find (&iter, doc, "errmsg") && - BSON_ITER_HOLDS_UTF8 (&iter)) { + if (bson_iter_init_find (&iter, doc, "errmsg") && BSON_ITER_HOLDS_UTF8 (&iter)) { *msg = bson_iter_utf8 (&iter, NULL); found_error = true; - } else if (bson_iter_init_find (&iter, doc, "$err") && - BSON_ITER_HOLDS_UTF8 (&iter)) { + } else if (bson_iter_init_find (&iter, doc, "$err") && BSON_ITER_HOLDS_UTF8 (&iter)) { *msg = bson_iter_utf8 (&iter, NULL); found_error = true; } @@ -117,19 +106,16 @@ _parse_error_reply (const bson_t *doc, if (check_wce) { /* check for a write concern error */ - if (bson_iter_init_find (&iter, doc, "writeConcernError") && - BSON_ITER_HOLDS_DOCUMENT (&iter)) { + if (bson_iter_init_find (&iter, doc, "writeConcernError") && BSON_ITER_HOLDS_DOCUMENT (&iter)) { bson_iter_t child; BSON_ASSERT (bson_iter_recurse (&iter, &child)); - if (bson_iter_find (&child, "code") && - BSON_ITER_HOLDS_NUMBER (&child)) { + if (bson_iter_find (&child, "code") && BSON_ITER_HOLDS_NUMBER (&child)) { *code = (uint32_t) bson_iter_as_int64 (&child); BSON_ASSERT (*code); found_error = true; } BSON_ASSERT (bson_iter_recurse (&iter, &child)); - if (bson_iter_find (&child, "errmsg") && - BSON_ITER_HOLDS_UTF8 (&child)) { + if (bson_iter_find (&child, "errmsg") && BSON_ITER_HOLDS_UTF8 (&child)) { *msg = bson_iter_utf8 (&child, NULL); found_error = true; } @@ -159,13 +145,10 @@ _parse_error_reply (const bson_t *doc, *-------------------------------------------------------------------------- */ bool -_mongoc_cmd_check_ok (const bson_t *doc, - int32_t error_api_version, - bson_error_t *error) +_mongoc_cmd_check_ok (const bson_t *doc, int32_t error_api_version, bson_error_t *error) { mongoc_error_domain_t domain = - error_api_version >= MONGOC_ERROR_API_VERSION_2 ? MONGOC_ERROR_SERVER - : MONGOC_ERROR_QUERY; + error_api_version >= MONGOC_ERROR_API_VERSION_2 ? MONGOC_ERROR_SERVER : MONGOC_ERROR_QUERY; uint32_t code; bson_iter_t iter; const char *msg = "Unknown command error"; @@ -215,13 +198,10 @@ _mongoc_cmd_check_ok (const bson_t *doc, *-------------------------------------------------------------------------- */ bool -_mongoc_cmd_check_ok_no_wce (const bson_t *doc, - int32_t error_api_version, - bson_error_t *error) +_mongoc_cmd_check_ok_no_wce (const bson_t *doc, int32_t error_api_version, bson_error_t *error) { mongoc_error_domain_t domain = - error_api_version >= MONGOC_ERROR_API_VERSION_2 ? MONGOC_ERROR_SERVER - : MONGOC_ERROR_QUERY; + error_api_version >= MONGOC_ERROR_API_VERSION_2 ? MONGOC_ERROR_SERVER : MONGOC_ERROR_QUERY; uint32_t code; const char *msg = "Unknown command error"; @@ -248,13 +228,10 @@ _mongoc_cmd_check_ok_no_wce (const bson_t *doc, /* helper function to parse error reply document to an OP_QUERY */ static void -_mongoc_populate_query_error (const bson_t *doc, - int32_t error_api_version, - bson_error_t *error) +_mongoc_populate_query_error (const bson_t *doc, int32_t error_api_version, bson_error_t *error) { mongoc_error_domain_t domain = - error_api_version >= MONGOC_ERROR_API_VERSION_2 ? MONGOC_ERROR_SERVER - : MONGOC_ERROR_QUERY; + error_api_version >= MONGOC_ERROR_API_VERSION_2 ? MONGOC_ERROR_SERVER : MONGOC_ERROR_QUERY; uint32_t code = MONGOC_ERROR_QUERY_FAILURE; bson_iter_t iter; const char *msg = "Unknown query failure"; @@ -263,14 +240,12 @@ _mongoc_populate_query_error (const bson_t *doc, BSON_ASSERT (doc); - if (bson_iter_init_find (&iter, doc, "code") && - BSON_ITER_HOLDS_NUMBER (&iter)) { + if (bson_iter_init_find (&iter, doc, "code") && BSON_ITER_HOLDS_NUMBER (&iter)) { code = (uint32_t) bson_iter_as_int64 (&iter); BSON_ASSERT (code); } - if (bson_iter_init_find (&iter, doc, "$err") && - BSON_ITER_HOLDS_UTF8 (&iter)) { + if (bson_iter_init_find (&iter, doc, "$err") && BSON_ITER_HOLDS_UTF8 (&iter)) { msg = bson_iter_utf8 (&iter, NULL); } @@ -290,10 +265,8 @@ mcd_rpc_message_check_ok (mcd_rpc_message *rpc, ENTRY; if (mcd_rpc_header_get_op_code (rpc) != MONGOC_OP_CODE_REPLY) { - bson_set_error (error, - MONGOC_ERROR_PROTOCOL, - MONGOC_ERROR_PROTOCOL_INVALID_REPLY, - "Received rpc other than OP_REPLY."); + bson_set_error ( + error, MONGOC_ERROR_PROTOCOL, MONGOC_ERROR_PROTOCOL_INVALID_REPLY, "Received rpc other than OP_REPLY."); RETURN (false); } @@ -312,20 +285,15 @@ mcd_rpc_message_check_ok (mcd_rpc_message *rpc, bson_destroy (&body); } else { - bson_set_error (error, - MONGOC_ERROR_QUERY, - MONGOC_ERROR_QUERY_FAILURE, - "Unknown query failure."); + bson_set_error (error, MONGOC_ERROR_QUERY, MONGOC_ERROR_QUERY_FAILURE, "Unknown query failure."); } RETURN (false); } if (flags & MONGOC_OP_REPLY_RESPONSE_FLAG_CURSOR_NOT_FOUND) { - bson_set_error (error, - MONGOC_ERROR_CURSOR, - MONGOC_ERROR_CURSOR_INVALID_CURSOR, - "The cursor is invalid or has expired."); + bson_set_error ( + error, MONGOC_ERROR_CURSOR, MONGOC_ERROR_CURSOR_INVALID_CURSOR, "The cursor is invalid or has expired."); RETURN (false); } @@ -341,16 +309,14 @@ mcd_rpc_message_egress (const mcd_rpc_message *rpc) // `mcd_rpc_message_to_iovecs`, which converts the opCode field to // little endian. int32_t op_code = mcd_rpc_header_get_op_code (rpc); - op_code = bson_iter_int32_unsafe ( - &(bson_iter_t){.raw = (const uint8_t *) &op_code}); + op_code = bson_iter_int32_unsafe (&(bson_iter_t){.raw = (const uint8_t *) &op_code}); if (op_code == MONGOC_OP_CODE_COMPRESSED) { mongoc_counter_op_egress_compressed_inc (); mongoc_counter_op_egress_total_inc (); op_code = mcd_rpc_op_compressed_get_original_opcode (rpc); - op_code = bson_iter_int32_unsafe ( - &(bson_iter_t){.raw = (const uint8_t *) &op_code}); + op_code = bson_iter_int32_unsafe (&(bson_iter_t){.raw = (const uint8_t *) &op_code}); } switch (op_code) { diff --git a/src/libmongoc/src/mongoc/mongoc-sasl.c b/src/libmongoc/src/mongoc/mongoc-sasl.c index 8f338a9686..94fefbf1cf 100644 --- a/src/libmongoc/src/mongoc/mongoc-sasl.c +++ b/src/libmongoc/src/mongoc/mongoc-sasl.c @@ -84,14 +84,11 @@ _mongoc_sasl_set_properties (mongoc_sasl_t *sasl, const mongoc_uri_t *uri) bson_init (&properties); } - if (bson_iter_init_find_case ( - &iter, options, MONGOC_URI_GSSAPISERVICENAME) && - BSON_ITER_HOLDS_UTF8 (&iter)) { + if (bson_iter_init_find_case (&iter, options, MONGOC_URI_GSSAPISERVICENAME) && BSON_ITER_HOLDS_UTF8 (&iter)) { service_name = bson_iter_utf8 (&iter, NULL); } - if (bson_iter_init_find_case (&iter, &properties, "SERVICE_NAME") && - BSON_ITER_HOLDS_UTF8 (&iter)) { + if (bson_iter_init_find_case (&iter, &properties, "SERVICE_NAME") && BSON_ITER_HOLDS_UTF8 (&iter)) { /* newer "authMechanismProperties" URI syntax takes precedence */ service_name = bson_iter_utf8 (&iter, NULL); } @@ -109,15 +106,11 @@ _mongoc_sasl_set_properties (mongoc_sasl_t *sasl, const mongoc_uri_t *uri) * * See CDRIVER-323 for more information. */ - if (bson_iter_init_find_case ( - &iter, options, MONGOC_URI_CANONICALIZEHOSTNAME) && - BSON_ITER_HOLDS_BOOL (&iter)) { + if (bson_iter_init_find_case (&iter, options, MONGOC_URI_CANONICALIZEHOSTNAME) && BSON_ITER_HOLDS_BOOL (&iter)) { canonicalize = bson_iter_bool (&iter); } - if (bson_iter_init_find_case ( - &iter, &properties, "CANONICALIZE_HOST_NAME") && - BSON_ITER_HOLDS_UTF8 (&iter)) { + if (bson_iter_init_find_case (&iter, &properties, "CANONICALIZE_HOST_NAME") && BSON_ITER_HOLDS_UTF8 (&iter)) { /* newer "authMechanismProperties" URI syntax takes precedence */ canonicalize = !strcasecmp (bson_iter_utf8 (&iter, NULL), "true"); } @@ -168,8 +161,7 @@ _mongoc_sasl_get_canonicalized_name (mongoc_stream_t *node_stream, /* IN */ BSON_ASSERT (stream); if (stream->type == MONGOC_STREAM_SOCKET) { - sock = - mongoc_stream_socket_get_socket ((mongoc_stream_socket_t *) stream); + sock = mongoc_stream_socket_get_socket ((mongoc_stream_socket_t *) stream); if (sock) { canonicalized = mongoc_socket_getnameinfo (sock); if (canonicalized) { diff --git a/src/libmongoc/src/mongoc/mongoc-scram-private.h b/src/libmongoc/src/mongoc/mongoc-scram-private.h index 6b1ca1363d..7e3b349e7b 100644 --- a/src/libmongoc/src/mongoc/mongoc-scram-private.h +++ b/src/libmongoc/src/mongoc/mongoc-scram-private.h @@ -35,8 +35,7 @@ BSON_BEGIN_DECLS #define MONGOC_SCRAM_B64_ENCODED_SIZE(n) (2 * n) -#define MONGOC_SCRAM_B64_HASH_MAX_SIZE \ - MONGOC_SCRAM_B64_ENCODED_SIZE (MONGOC_SCRAM_HASH_MAX_SIZE) +#define MONGOC_SCRAM_B64_HASH_MAX_SIZE MONGOC_SCRAM_B64_ENCODED_SIZE (MONGOC_SCRAM_HASH_MAX_SIZE) enum { /* It is unlikely that there will be more than 64 different user accounts @@ -76,14 +75,10 @@ void _mongoc_scram_set_user (mongoc_scram_t *scram, const char *user); void -_mongoc_scram_set_server_key (mongoc_scram_t *scram, - const uint8_t *server_key, - size_t len); +_mongoc_scram_set_server_key (mongoc_scram_t *scram, const uint8_t *server_key, size_t len); void -_mongoc_scram_set_salted_password (mongoc_scram_t *scram, - const uint8_t *salted_password, - size_t len); +_mongoc_scram_set_salted_password (mongoc_scram_t *scram, const uint8_t *salted_password, size_t len); void _mongoc_scram_destroy (mongoc_scram_t *scram); @@ -133,105 +128,67 @@ _mongoc_utf8_get_first_code_point (const char *c, size_t length); * these characters are not allowed for SASLPrep */ static const uint32_t unassigned_codepoint_ranges[] = { - 0x0221, 0x0221, 0x0234, 0x024F, 0x02AE, 0x02AF, 0x02EF, 0x02FF, - 0x0350, 0x035F, 0x0370, 0x0373, 0x0376, 0x0379, 0x037B, 0x037D, - 0x037F, 0x0383, 0x038B, 0x038B, 0x038D, 0x038D, 0x03A2, 0x03A2, - 0x03CF, 0x03CF, 0x03F7, 0x03FF, 0x0487, 0x0487, 0x04CF, 0x04CF, - 0x04F6, 0x04F7, 0x04FA, 0x04FF, 0x0510, 0x0530, 0x0557, 0x0558, - 0x0560, 0x0560, 0x0588, 0x0588, 0x058B, 0x0590, 0x05A2, 0x05A2, - 0x05BA, 0x05BA, 0x05C5, 0x05CF, 0x05EB, 0x05EF, 0x05F5, 0x060B, - 0x060D, 0x061A, 0x061C, 0x061E, 0x0620, 0x0620, 0x063B, 0x063F, - 0x0656, 0x065F, 0x06EE, 0x06EF, 0x06FF, 0x06FF, 0x070E, 0x070E, - 0x072D, 0x072F, 0x074B, 0x077F, 0x07B2, 0x0900, 0x0904, 0x0904, - 0x093A, 0x093B, 0x094E, 0x094F, 0x0955, 0x0957, 0x0971, 0x0980, - 0x0984, 0x0984, 0x098D, 0x098E, 0x0991, 0x0992, 0x09A9, 0x09A9, - 0x09B1, 0x09B1, 0x09B3, 0x09B5, 0x09BA, 0x09BB, 0x09BD, 0x09BD, - 0x09C5, 0x09C6, 0x09C9, 0x09CA, 0x09CE, 0x09D6, 0x09D8, 0x09DB, - 0x09DE, 0x09DE, 0x09E4, 0x09E5, 0x09FB, 0x0A01, 0x0A03, 0x0A04, - 0x0A0B, 0x0A0E, 0x0A11, 0x0A12, 0x0A29, 0x0A29, 0x0A31, 0x0A31, - 0x0A34, 0x0A34, 0x0A37, 0x0A37, 0x0A3A, 0x0A3B, 0x0A3D, 0x0A3D, - 0x0A43, 0x0A46, 0x0A49, 0x0A4A, 0x0A4E, 0x0A58, 0x0A5D, 0x0A5D, - 0x0A5F, 0x0A65, 0x0A75, 0x0A80, 0x0A84, 0x0A84, 0x0A8C, 0x0A8C, - 0x0A8E, 0x0A8E, 0x0A92, 0x0A92, 0x0AA9, 0x0AA9, 0x0AB1, 0x0AB1, - 0x0AB4, 0x0AB4, 0x0ABA, 0x0ABB, 0x0AC6, 0x0AC6, 0x0ACA, 0x0ACA, - 0x0ACE, 0x0ACF, 0x0AD1, 0x0ADF, 0x0AE1, 0x0AE5, 0x0AF0, 0x0B00, - 0x0B04, 0x0B04, 0x0B0D, 0x0B0E, 0x0B11, 0x0B12, 0x0B29, 0x0B29, - 0x0B31, 0x0B31, 0x0B34, 0x0B35, 0x0B3A, 0x0B3B, 0x0B44, 0x0B46, - 0x0B49, 0x0B4A, 0x0B4E, 0x0B55, 0x0B58, 0x0B5B, 0x0B5E, 0x0B5E, - 0x0B62, 0x0B65, 0x0B71, 0x0B81, 0x0B84, 0x0B84, 0x0B8B, 0x0B8D, - 0x0B91, 0x0B91, 0x0B96, 0x0B98, 0x0B9B, 0x0B9B, 0x0B9D, 0x0B9D, - 0x0BA0, 0x0BA2, 0x0BA5, 0x0BA7, 0x0BAB, 0x0BAD, 0x0BB6, 0x0BB6, - 0x0BBA, 0x0BBD, 0x0BC3, 0x0BC5, 0x0BC9, 0x0BC9, 0x0BCE, 0x0BD6, - 0x0BD8, 0x0BE6, 0x0BF3, 0x0C00, 0x0C04, 0x0C04, 0x0C0D, 0x0C0D, - 0x0C11, 0x0C11, 0x0C29, 0x0C29, 0x0C34, 0x0C34, 0x0C3A, 0x0C3D, - 0x0C45, 0x0C45, 0x0C49, 0x0C49, 0x0C4E, 0x0C54, 0x0C57, 0x0C5F, - 0x0C62, 0x0C65, 0x0C70, 0x0C81, 0x0C84, 0x0C84, 0x0C8D, 0x0C8D, - 0x0C91, 0x0C91, 0x0CA9, 0x0CA9, 0x0CB4, 0x0CB4, 0x0CBA, 0x0CBD, - 0x0CC5, 0x0CC5, 0x0CC9, 0x0CC9, 0x0CCE, 0x0CD4, 0x0CD7, 0x0CDD, - 0x0CDF, 0x0CDF, 0x0CE2, 0x0CE5, 0x0CF0, 0x0D01, 0x0D04, 0x0D04, - 0x0D0D, 0x0D0D, 0x0D11, 0x0D11, 0x0D29, 0x0D29, 0x0D3A, 0x0D3D, - 0x0D44, 0x0D45, 0x0D49, 0x0D49, 0x0D4E, 0x0D56, 0x0D58, 0x0D5F, - 0x0D62, 0x0D65, 0x0D70, 0x0D81, 0x0D84, 0x0D84, 0x0D97, 0x0D99, - 0x0DB2, 0x0DB2, 0x0DBC, 0x0DBC, 0x0DBE, 0x0DBF, 0x0DC7, 0x0DC9, - 0x0DCB, 0x0DCE, 0x0DD5, 0x0DD5, 0x0DD7, 0x0DD7, 0x0DE0, 0x0DF1, - 0x0DF5, 0x0E00, 0x0E3B, 0x0E3E, 0x0E5C, 0x0E80, 0x0E83, 0x0E83, - 0x0E85, 0x0E86, 0x0E89, 0x0E89, 0x0E8B, 0x0E8C, 0x0E8E, 0x0E93, - 0x0E98, 0x0E98, 0x0EA0, 0x0EA0, 0x0EA4, 0x0EA4, 0x0EA6, 0x0EA6, - 0x0EA8, 0x0EA9, 0x0EAC, 0x0EAC, 0x0EBA, 0x0EBA, 0x0EBE, 0x0EBF, - 0x0EC5, 0x0EC5, 0x0EC7, 0x0EC7, 0x0ECE, 0x0ECF, 0x0EDA, 0x0EDB, - 0x0EDE, 0x0EFF, 0x0F48, 0x0F48, 0x0F6B, 0x0F70, 0x0F8C, 0x0F8F, - 0x0F98, 0x0F98, 0x0FBD, 0x0FBD, 0x0FCD, 0x0FCE, 0x0FD0, 0x0FFF, - 0x1022, 0x1022, 0x1028, 0x1028, 0x102B, 0x102B, 0x1033, 0x1035, - 0x103A, 0x103F, 0x105A, 0x109F, 0x10C6, 0x10CF, 0x10F9, 0x10FA, - 0x10FC, 0x10FF, 0x115A, 0x115E, 0x11A3, 0x11A7, 0x11FA, 0x11FF, - 0x1207, 0x1207, 0x1247, 0x1247, 0x1249, 0x1249, 0x124E, 0x124F, - 0x1257, 0x1257, 0x1259, 0x1259, 0x125E, 0x125F, 0x1287, 0x1287, - 0x1289, 0x1289, 0x128E, 0x128F, 0x12AF, 0x12AF, 0x12B1, 0x12B1, - 0x12B6, 0x12B7, 0x12BF, 0x12BF, 0x12C1, 0x12C1, 0x12C6, 0x12C7, - 0x12CF, 0x12CF, 0x12D7, 0x12D7, 0x12EF, 0x12EF, 0x130F, 0x130F, - 0x1311, 0x1311, 0x1316, 0x1317, 0x131F, 0x131F, 0x1347, 0x1347, - 0x135B, 0x1360, 0x137D, 0x139F, 0x13F5, 0x1400, 0x1677, 0x167F, - 0x169D, 0x169F, 0x16F1, 0x16FF, 0x170D, 0x170D, 0x1715, 0x171F, - 0x1737, 0x173F, 0x1754, 0x175F, 0x176D, 0x176D, 0x1771, 0x1771, - 0x1774, 0x177F, 0x17DD, 0x17DF, 0x17EA, 0x17FF, 0x180F, 0x180F, - 0x181A, 0x181F, 0x1878, 0x187F, 0x18AA, 0x1DFF, 0x1E9C, 0x1E9F, - 0x1EFA, 0x1EFF, 0x1F16, 0x1F17, 0x1F1E, 0x1F1F, 0x1F46, 0x1F47, - 0x1F4E, 0x1F4F, 0x1F58, 0x1F58, 0x1F5A, 0x1F5A, 0x1F5C, 0x1F5C, - 0x1F5E, 0x1F5E, 0x1F7E, 0x1F7F, 0x1FB5, 0x1FB5, 0x1FC5, 0x1FC5, - 0x1FD4, 0x1FD5, 0x1FDC, 0x1FDC, 0x1FF0, 0x1FF1, 0x1FF5, 0x1FF5, - 0x1FFF, 0x1FFF, 0x2053, 0x2056, 0x2058, 0x205E, 0x2064, 0x2069, - 0x2072, 0x2073, 0x208F, 0x209F, 0x20B2, 0x20CF, 0x20EB, 0x20FF, - 0x213B, 0x213C, 0x214C, 0x2152, 0x2184, 0x218F, 0x23CF, 0x23FF, - 0x2427, 0x243F, 0x244B, 0x245F, 0x24FF, 0x24FF, 0x2614, 0x2615, - 0x2618, 0x2618, 0x267E, 0x267F, 0x268A, 0x2700, 0x2705, 0x2705, - 0x270A, 0x270B, 0x2728, 0x2728, 0x274C, 0x274C, 0x274E, 0x274E, - 0x2753, 0x2755, 0x2757, 0x2757, 0x275F, 0x2760, 0x2795, 0x2797, - 0x27B0, 0x27B0, 0x27BF, 0x27CF, 0x27EC, 0x27EF, 0x2B00, 0x2E7F, - 0x2E9A, 0x2E9A, 0x2EF4, 0x2EFF, 0x2FD6, 0x2FEF, 0x2FFC, 0x2FFF, - 0x3040, 0x3040, 0x3097, 0x3098, 0x3100, 0x3104, 0x312D, 0x3130, - 0x318F, 0x318F, 0x31B8, 0x31EF, 0x321D, 0x321F, 0x3244, 0x3250, - 0x327C, 0x327E, 0x32CC, 0x32CF, 0x32FF, 0x32FF, 0x3377, 0x337A, - 0x33DE, 0x33DF, 0x33FF, 0x33FF, 0x4DB6, 0x4DFF, 0x9FA6, 0x9FFF, - 0xA48D, 0xA48F, 0xA4C7, 0xABFF, 0xD7A4, 0xD7FF, 0xFA2E, 0xFA2F, - 0xFA6B, 0xFAFF, 0xFB07, 0xFB12, 0xFB18, 0xFB1C, 0xFB37, 0xFB37, - 0xFB3D, 0xFB3D, 0xFB3F, 0xFB3F, 0xFB42, 0xFB42, 0xFB45, 0xFB45, - 0xFBB2, 0xFBD2, 0xFD40, 0xFD4F, 0xFD90, 0xFD91, 0xFDC8, 0xFDCF, - 0xFDFD, 0xFDFF, 0xFE10, 0xFE1F, 0xFE24, 0xFE2F, 0xFE47, 0xFE48, - 0xFE53, 0xFE53, 0xFE67, 0xFE67, 0xFE6C, 0xFE6F, 0xFE75, 0xFE75, - 0xFEFD, 0xFEFE, 0xFF00, 0xFF00, 0xFFBF, 0xFFC1, 0xFFC8, 0xFFC9, - 0xFFD0, 0xFFD1, 0xFFD8, 0xFFD9, 0xFFDD, 0xFFDF, 0xFFE7, 0xFFE7, - 0xFFEF, 0xFFF8, 0x10000, 0x102FF, 0x1031F, 0x1031F, 0x10324, 0x1032F, - 0x1034B, 0x103FF, 0x10426, 0x10427, 0x1044E, 0x1CFFF, 0x1D0F6, 0x1D0FF, - 0x1D127, 0x1D129, 0x1D1DE, 0x1D3FF, 0x1D455, 0x1D455, 0x1D49D, 0x1D49D, - 0x1D4A0, 0x1D4A1, 0x1D4A3, 0x1D4A4, 0x1D4A7, 0x1D4A8, 0x1D4AD, 0x1D4AD, - 0x1D4BA, 0x1D4BA, 0x1D4BC, 0x1D4BC, 0x1D4C1, 0x1D4C1, 0x1D4C4, 0x1D4C4, - 0x1D506, 0x1D506, 0x1D50B, 0x1D50C, 0x1D515, 0x1D515, 0x1D51D, 0x1D51D, - 0x1D53A, 0x1D53A, 0x1D53F, 0x1D53F, 0x1D545, 0x1D545, 0x1D547, 0x1D549, - 0x1D551, 0x1D551, 0x1D6A4, 0x1D6A7, 0x1D7CA, 0x1D7CD, 0x1D800, 0x1FFFD, - 0x2A6D7, 0x2F7FF, 0x2FA1E, 0x2FFFD, 0x30000, 0x3FFFD, 0x40000, 0x4FFFD, - 0x50000, 0x5FFFD, 0x60000, 0x6FFFD, 0x70000, 0x7FFFD, 0x80000, 0x8FFFD, - 0x90000, 0x9FFFD, 0xA0000, 0xAFFFD, 0xB0000, 0xBFFFD, 0xC0000, 0xCFFFD, - 0xD0000, 0xDFFFD, 0xE0000, 0xE0000, 0xE0002, 0xE001F, 0xE0080, 0xEFFFD}; + 0x0221, 0x0221, 0x0234, 0x024F, 0x02AE, 0x02AF, 0x02EF, 0x02FF, 0x0350, 0x035F, 0x0370, 0x0373, 0x0376, + 0x0379, 0x037B, 0x037D, 0x037F, 0x0383, 0x038B, 0x038B, 0x038D, 0x038D, 0x03A2, 0x03A2, 0x03CF, 0x03CF, + 0x03F7, 0x03FF, 0x0487, 0x0487, 0x04CF, 0x04CF, 0x04F6, 0x04F7, 0x04FA, 0x04FF, 0x0510, 0x0530, 0x0557, + 0x0558, 0x0560, 0x0560, 0x0588, 0x0588, 0x058B, 0x0590, 0x05A2, 0x05A2, 0x05BA, 0x05BA, 0x05C5, 0x05CF, + 0x05EB, 0x05EF, 0x05F5, 0x060B, 0x060D, 0x061A, 0x061C, 0x061E, 0x0620, 0x0620, 0x063B, 0x063F, 0x0656, + 0x065F, 0x06EE, 0x06EF, 0x06FF, 0x06FF, 0x070E, 0x070E, 0x072D, 0x072F, 0x074B, 0x077F, 0x07B2, 0x0900, + 0x0904, 0x0904, 0x093A, 0x093B, 0x094E, 0x094F, 0x0955, 0x0957, 0x0971, 0x0980, 0x0984, 0x0984, 0x098D, + 0x098E, 0x0991, 0x0992, 0x09A9, 0x09A9, 0x09B1, 0x09B1, 0x09B3, 0x09B5, 0x09BA, 0x09BB, 0x09BD, 0x09BD, + 0x09C5, 0x09C6, 0x09C9, 0x09CA, 0x09CE, 0x09D6, 0x09D8, 0x09DB, 0x09DE, 0x09DE, 0x09E4, 0x09E5, 0x09FB, + 0x0A01, 0x0A03, 0x0A04, 0x0A0B, 0x0A0E, 0x0A11, 0x0A12, 0x0A29, 0x0A29, 0x0A31, 0x0A31, 0x0A34, 0x0A34, + 0x0A37, 0x0A37, 0x0A3A, 0x0A3B, 0x0A3D, 0x0A3D, 0x0A43, 0x0A46, 0x0A49, 0x0A4A, 0x0A4E, 0x0A58, 0x0A5D, + 0x0A5D, 0x0A5F, 0x0A65, 0x0A75, 0x0A80, 0x0A84, 0x0A84, 0x0A8C, 0x0A8C, 0x0A8E, 0x0A8E, 0x0A92, 0x0A92, + 0x0AA9, 0x0AA9, 0x0AB1, 0x0AB1, 0x0AB4, 0x0AB4, 0x0ABA, 0x0ABB, 0x0AC6, 0x0AC6, 0x0ACA, 0x0ACA, 0x0ACE, + 0x0ACF, 0x0AD1, 0x0ADF, 0x0AE1, 0x0AE5, 0x0AF0, 0x0B00, 0x0B04, 0x0B04, 0x0B0D, 0x0B0E, 0x0B11, 0x0B12, + 0x0B29, 0x0B29, 0x0B31, 0x0B31, 0x0B34, 0x0B35, 0x0B3A, 0x0B3B, 0x0B44, 0x0B46, 0x0B49, 0x0B4A, 0x0B4E, + 0x0B55, 0x0B58, 0x0B5B, 0x0B5E, 0x0B5E, 0x0B62, 0x0B65, 0x0B71, 0x0B81, 0x0B84, 0x0B84, 0x0B8B, 0x0B8D, + 0x0B91, 0x0B91, 0x0B96, 0x0B98, 0x0B9B, 0x0B9B, 0x0B9D, 0x0B9D, 0x0BA0, 0x0BA2, 0x0BA5, 0x0BA7, 0x0BAB, + 0x0BAD, 0x0BB6, 0x0BB6, 0x0BBA, 0x0BBD, 0x0BC3, 0x0BC5, 0x0BC9, 0x0BC9, 0x0BCE, 0x0BD6, 0x0BD8, 0x0BE6, + 0x0BF3, 0x0C00, 0x0C04, 0x0C04, 0x0C0D, 0x0C0D, 0x0C11, 0x0C11, 0x0C29, 0x0C29, 0x0C34, 0x0C34, 0x0C3A, + 0x0C3D, 0x0C45, 0x0C45, 0x0C49, 0x0C49, 0x0C4E, 0x0C54, 0x0C57, 0x0C5F, 0x0C62, 0x0C65, 0x0C70, 0x0C81, + 0x0C84, 0x0C84, 0x0C8D, 0x0C8D, 0x0C91, 0x0C91, 0x0CA9, 0x0CA9, 0x0CB4, 0x0CB4, 0x0CBA, 0x0CBD, 0x0CC5, + 0x0CC5, 0x0CC9, 0x0CC9, 0x0CCE, 0x0CD4, 0x0CD7, 0x0CDD, 0x0CDF, 0x0CDF, 0x0CE2, 0x0CE5, 0x0CF0, 0x0D01, + 0x0D04, 0x0D04, 0x0D0D, 0x0D0D, 0x0D11, 0x0D11, 0x0D29, 0x0D29, 0x0D3A, 0x0D3D, 0x0D44, 0x0D45, 0x0D49, + 0x0D49, 0x0D4E, 0x0D56, 0x0D58, 0x0D5F, 0x0D62, 0x0D65, 0x0D70, 0x0D81, 0x0D84, 0x0D84, 0x0D97, 0x0D99, + 0x0DB2, 0x0DB2, 0x0DBC, 0x0DBC, 0x0DBE, 0x0DBF, 0x0DC7, 0x0DC9, 0x0DCB, 0x0DCE, 0x0DD5, 0x0DD5, 0x0DD7, + 0x0DD7, 0x0DE0, 0x0DF1, 0x0DF5, 0x0E00, 0x0E3B, 0x0E3E, 0x0E5C, 0x0E80, 0x0E83, 0x0E83, 0x0E85, 0x0E86, + 0x0E89, 0x0E89, 0x0E8B, 0x0E8C, 0x0E8E, 0x0E93, 0x0E98, 0x0E98, 0x0EA0, 0x0EA0, 0x0EA4, 0x0EA4, 0x0EA6, + 0x0EA6, 0x0EA8, 0x0EA9, 0x0EAC, 0x0EAC, 0x0EBA, 0x0EBA, 0x0EBE, 0x0EBF, 0x0EC5, 0x0EC5, 0x0EC7, 0x0EC7, + 0x0ECE, 0x0ECF, 0x0EDA, 0x0EDB, 0x0EDE, 0x0EFF, 0x0F48, 0x0F48, 0x0F6B, 0x0F70, 0x0F8C, 0x0F8F, 0x0F98, + 0x0F98, 0x0FBD, 0x0FBD, 0x0FCD, 0x0FCE, 0x0FD0, 0x0FFF, 0x1022, 0x1022, 0x1028, 0x1028, 0x102B, 0x102B, + 0x1033, 0x1035, 0x103A, 0x103F, 0x105A, 0x109F, 0x10C6, 0x10CF, 0x10F9, 0x10FA, 0x10FC, 0x10FF, 0x115A, + 0x115E, 0x11A3, 0x11A7, 0x11FA, 0x11FF, 0x1207, 0x1207, 0x1247, 0x1247, 0x1249, 0x1249, 0x124E, 0x124F, + 0x1257, 0x1257, 0x1259, 0x1259, 0x125E, 0x125F, 0x1287, 0x1287, 0x1289, 0x1289, 0x128E, 0x128F, 0x12AF, + 0x12AF, 0x12B1, 0x12B1, 0x12B6, 0x12B7, 0x12BF, 0x12BF, 0x12C1, 0x12C1, 0x12C6, 0x12C7, 0x12CF, 0x12CF, + 0x12D7, 0x12D7, 0x12EF, 0x12EF, 0x130F, 0x130F, 0x1311, 0x1311, 0x1316, 0x1317, 0x131F, 0x131F, 0x1347, + 0x1347, 0x135B, 0x1360, 0x137D, 0x139F, 0x13F5, 0x1400, 0x1677, 0x167F, 0x169D, 0x169F, 0x16F1, 0x16FF, + 0x170D, 0x170D, 0x1715, 0x171F, 0x1737, 0x173F, 0x1754, 0x175F, 0x176D, 0x176D, 0x1771, 0x1771, 0x1774, + 0x177F, 0x17DD, 0x17DF, 0x17EA, 0x17FF, 0x180F, 0x180F, 0x181A, 0x181F, 0x1878, 0x187F, 0x18AA, 0x1DFF, + 0x1E9C, 0x1E9F, 0x1EFA, 0x1EFF, 0x1F16, 0x1F17, 0x1F1E, 0x1F1F, 0x1F46, 0x1F47, 0x1F4E, 0x1F4F, 0x1F58, + 0x1F58, 0x1F5A, 0x1F5A, 0x1F5C, 0x1F5C, 0x1F5E, 0x1F5E, 0x1F7E, 0x1F7F, 0x1FB5, 0x1FB5, 0x1FC5, 0x1FC5, + 0x1FD4, 0x1FD5, 0x1FDC, 0x1FDC, 0x1FF0, 0x1FF1, 0x1FF5, 0x1FF5, 0x1FFF, 0x1FFF, 0x2053, 0x2056, 0x2058, + 0x205E, 0x2064, 0x2069, 0x2072, 0x2073, 0x208F, 0x209F, 0x20B2, 0x20CF, 0x20EB, 0x20FF, 0x213B, 0x213C, + 0x214C, 0x2152, 0x2184, 0x218F, 0x23CF, 0x23FF, 0x2427, 0x243F, 0x244B, 0x245F, 0x24FF, 0x24FF, 0x2614, + 0x2615, 0x2618, 0x2618, 0x267E, 0x267F, 0x268A, 0x2700, 0x2705, 0x2705, 0x270A, 0x270B, 0x2728, 0x2728, + 0x274C, 0x274C, 0x274E, 0x274E, 0x2753, 0x2755, 0x2757, 0x2757, 0x275F, 0x2760, 0x2795, 0x2797, 0x27B0, + 0x27B0, 0x27BF, 0x27CF, 0x27EC, 0x27EF, 0x2B00, 0x2E7F, 0x2E9A, 0x2E9A, 0x2EF4, 0x2EFF, 0x2FD6, 0x2FEF, + 0x2FFC, 0x2FFF, 0x3040, 0x3040, 0x3097, 0x3098, 0x3100, 0x3104, 0x312D, 0x3130, 0x318F, 0x318F, 0x31B8, + 0x31EF, 0x321D, 0x321F, 0x3244, 0x3250, 0x327C, 0x327E, 0x32CC, 0x32CF, 0x32FF, 0x32FF, 0x3377, 0x337A, + 0x33DE, 0x33DF, 0x33FF, 0x33FF, 0x4DB6, 0x4DFF, 0x9FA6, 0x9FFF, 0xA48D, 0xA48F, 0xA4C7, 0xABFF, 0xD7A4, + 0xD7FF, 0xFA2E, 0xFA2F, 0xFA6B, 0xFAFF, 0xFB07, 0xFB12, 0xFB18, 0xFB1C, 0xFB37, 0xFB37, 0xFB3D, 0xFB3D, + 0xFB3F, 0xFB3F, 0xFB42, 0xFB42, 0xFB45, 0xFB45, 0xFBB2, 0xFBD2, 0xFD40, 0xFD4F, 0xFD90, 0xFD91, 0xFDC8, + 0xFDCF, 0xFDFD, 0xFDFF, 0xFE10, 0xFE1F, 0xFE24, 0xFE2F, 0xFE47, 0xFE48, 0xFE53, 0xFE53, 0xFE67, 0xFE67, + 0xFE6C, 0xFE6F, 0xFE75, 0xFE75, 0xFEFD, 0xFEFE, 0xFF00, 0xFF00, 0xFFBF, 0xFFC1, 0xFFC8, 0xFFC9, 0xFFD0, + 0xFFD1, 0xFFD8, 0xFFD9, 0xFFDD, 0xFFDF, 0xFFE7, 0xFFE7, 0xFFEF, 0xFFF8, 0x10000, 0x102FF, 0x1031F, 0x1031F, + 0x10324, 0x1032F, 0x1034B, 0x103FF, 0x10426, 0x10427, 0x1044E, 0x1CFFF, 0x1D0F6, 0x1D0FF, 0x1D127, 0x1D129, 0x1D1DE, + 0x1D3FF, 0x1D455, 0x1D455, 0x1D49D, 0x1D49D, 0x1D4A0, 0x1D4A1, 0x1D4A3, 0x1D4A4, 0x1D4A7, 0x1D4A8, 0x1D4AD, 0x1D4AD, + 0x1D4BA, 0x1D4BA, 0x1D4BC, 0x1D4BC, 0x1D4C1, 0x1D4C1, 0x1D4C4, 0x1D4C4, 0x1D506, 0x1D506, 0x1D50B, 0x1D50C, 0x1D515, + 0x1D515, 0x1D51D, 0x1D51D, 0x1D53A, 0x1D53A, 0x1D53F, 0x1D53F, 0x1D545, 0x1D545, 0x1D547, 0x1D549, 0x1D551, 0x1D551, + 0x1D6A4, 0x1D6A7, 0x1D7CA, 0x1D7CD, 0x1D800, 0x1FFFD, 0x2A6D7, 0x2F7FF, 0x2FA1E, 0x2FFFD, 0x30000, 0x3FFFD, 0x40000, + 0x4FFFD, 0x50000, 0x5FFFD, 0x60000, 0x6FFFD, 0x70000, 0x7FFFD, 0x80000, 0x8FFFD, 0x90000, 0x9FFFD, 0xA0000, 0xAFFFD, + 0xB0000, 0xBFFFD, 0xC0000, 0xCFFFD, 0xD0000, 0xDFFFD, 0xE0000, 0xE0000, 0xE0002, 0xE001F, 0xE0080, 0xEFFFD}; /* * Table B.1 Commonly mapped to nothing @@ -259,18 +216,8 @@ static const uint32_t commonly_mapped_to_nothing_ranges[] = {0x00AD, * these are all of the characters that will be mapped to the space character. * (0x0020) */ -static const uint32_t non_ascii_space_character_ranges[] = {0x00A0, - 0x00A0, - 0x1680, - 0x1680, - 0x2000, - 0x200B, - 0x202F, - 0x202F, - 0x205F, - 0x205F, - 0x3000, - 0x3000}; +static const uint32_t non_ascii_space_character_ranges[] = { + 0x00A0, 0x00A0, 0x1680, 0x1680, 0x2000, 0x200B, 0x202F, 0x202F, 0x205F, 0x205F, 0x3000, 0x3000}; /* * these are all of the characters that are "prohibited output" for SASLprep. @@ -321,110 +268,73 @@ static const uint32_t prohibited_output_ranges[] = { */ static const uint32_t RandALCat_bidi_ranges[] = { - 0x05BE, 0x05BE, 0x05C0, 0x05C0, 0x05C3, 0x05C3, 0x05D0, 0x05EA, 0x05F0, - 0x05F4, 0x061B, 0x061B, 0x061F, 0x061F, 0x0621, 0x063A, 0x0640, 0x064A, - 0x066D, 0x066F, 0x0671, 0x06D5, 0x06DD, 0x06DD, 0x06E5, 0x06E6, 0x06FA, - 0x06FE, 0x0700, 0x070D, 0x0710, 0x0710, 0x0712, 0x072C, 0x0780, 0x07A5, - 0x07B1, 0x07B1, 0x200F, 0x200F, 0xFB1D, 0xFB1D, 0xFB1F, 0xFB28, 0xFB2A, - 0xFB36, 0xFB38, 0xFB3C, 0xFB3E, 0xFB3E, 0xFB40, 0xFB41, 0xFB43, 0xFB44, - 0xFB46, 0xFBB1, 0xFBD3, 0xFD3D, 0xFD50, 0xFD8F, 0xFD92, 0xFDC7, 0xFDF0, - 0xFDFC, 0xFE70, 0xFE74, 0xFE76, 0xFEFC}; + 0x05BE, 0x05BE, 0x05C0, 0x05C0, 0x05C3, 0x05C3, 0x05D0, 0x05EA, 0x05F0, 0x05F4, 0x061B, 0x061B, 0x061F, 0x061F, + 0x0621, 0x063A, 0x0640, 0x064A, 0x066D, 0x066F, 0x0671, 0x06D5, 0x06DD, 0x06DD, 0x06E5, 0x06E6, 0x06FA, 0x06FE, + 0x0700, 0x070D, 0x0710, 0x0710, 0x0712, 0x072C, 0x0780, 0x07A5, 0x07B1, 0x07B1, 0x200F, 0x200F, 0xFB1D, 0xFB1D, + 0xFB1F, 0xFB28, 0xFB2A, 0xFB36, 0xFB38, 0xFB3C, 0xFB3E, 0xFB3E, 0xFB40, 0xFB41, 0xFB43, 0xFB44, 0xFB46, 0xFBB1, + 0xFBD3, 0xFD3D, 0xFD50, 0xFD8F, 0xFD92, 0xFDC7, 0xFDF0, 0xFDFC, 0xFE70, 0xFE74, 0xFE76, 0xFEFC}; /* D.2 Characters with bidirectional property "L" * any string that contains one of these characters cannot contain a character * with bidirectional property "R" or "AL". * */ static const uint32_t LCat_bidi_ranges[] = { - 0x0041, 0x005A, 0x0061, 0x007A, 0x00AA, 0x00AA, 0x00B5, 0x00B5, - 0x00BA, 0x00BA, 0x00C0, 0x00D6, 0x00D8, 0x00F6, 0x00F8, 0x0220, - 0x0222, 0x0233, 0x0250, 0x02AD, 0x02B0, 0x02B8, 0x02BB, 0x02C1, - 0x02D0, 0x02D1, 0x02E0, 0x02E4, 0x02EE, 0x02EE, 0x037A, 0x037A, - 0x0386, 0x0386, 0x0388, 0x038A, 0x038C, 0x038C, 0x038E, 0x03A1, - 0x03A3, 0x03CE, 0x03D0, 0x03F5, 0x0400, 0x0482, 0x048A, 0x04CE, - 0x04D0, 0x04F5, 0x04F8, 0x04F9, 0x0500, 0x050F, 0x0531, 0x0556, - 0x0559, 0x055F, 0x0561, 0x0587, 0x0589, 0x0589, 0x0903, 0x0903, - 0x0905, 0x0939, 0x093D, 0x0940, 0x0949, 0x094C, 0x0950, 0x0950, - 0x0958, 0x0961, 0x0964, 0x0970, 0x0982, 0x0983, 0x0985, 0x098C, - 0x098F, 0x0990, 0x0993, 0x09A8, 0x09AA, 0x09B0, 0x09B2, 0x09B2, - 0x09B6, 0x09B9, 0x09BE, 0x09C0, 0x09C7, 0x09C8, 0x09CB, 0x09CC, - 0x09D7, 0x09D7, 0x09DC, 0x09DD, 0x09DF, 0x09E1, 0x09E6, 0x09F1, - 0x09F4, 0x09FA, 0x0A05, 0x0A0A, 0x0A0F, 0x0A10, 0x0A13, 0x0A28, - 0x0A2A, 0x0A30, 0x0A32, 0x0A33, 0x0A35, 0x0A36, 0x0A38, 0x0A39, - 0x0A3E, 0x0A40, 0x0A59, 0x0A5C, 0x0A5E, 0x0A5E, 0x0A66, 0x0A6F, - 0x0A72, 0x0A74, 0x0A83, 0x0A83, 0x0A85, 0x0A8B, 0x0A8D, 0x0A8D, - 0x0A8F, 0x0A91, 0x0A93, 0x0AA8, 0x0AAA, 0x0AB0, 0x0AB2, 0x0AB3, - 0x0AB5, 0x0AB9, 0x0ABD, 0x0AC0, 0x0AC9, 0x0AC9, 0x0ACB, 0x0ACC, - 0x0AD0, 0x0AD0, 0x0AE0, 0x0AE0, 0x0AE6, 0x0AEF, 0x0B02, 0x0B03, - 0x0B05, 0x0B0C, 0x0B0F, 0x0B10, 0x0B13, 0x0B28, 0x0B2A, 0x0B30, - 0x0B32, 0x0B33, 0x0B36, 0x0B39, 0x0B3D, 0x0B3E, 0x0B40, 0x0B40, - 0x0B47, 0x0B48, 0x0B4B, 0x0B4C, 0x0B57, 0x0B57, 0x0B5C, 0x0B5D, - 0x0B5F, 0x0B61, 0x0B66, 0x0B70, 0x0B83, 0x0B83, 0x0B85, 0x0B8A, - 0x0B8E, 0x0B90, 0x0B92, 0x0B95, 0x0B99, 0x0B9A, 0x0B9C, 0x0B9C, - 0x0B9E, 0x0B9F, 0x0BA3, 0x0BA4, 0x0BA8, 0x0BAA, 0x0BAE, 0x0BB5, - 0x0BB7, 0x0BB9, 0x0BBE, 0x0BBF, 0x0BC1, 0x0BC2, 0x0BC6, 0x0BC8, - 0x0BCA, 0x0BCC, 0x0BD7, 0x0BD7, 0x0BE7, 0x0BF2, 0x0C01, 0x0C03, - 0x0C05, 0x0C0C, 0x0C0E, 0x0C10, 0x0C12, 0x0C28, 0x0C2A, 0x0C33, - 0x0C35, 0x0C39, 0x0C41, 0x0C44, 0x0C60, 0x0C61, 0x0C66, 0x0C6F, - 0x0C82, 0x0C83, 0x0C85, 0x0C8C, 0x0C8E, 0x0C90, 0x0C92, 0x0CA8, - 0x0CAA, 0x0CB3, 0x0CB5, 0x0CB9, 0x0CBE, 0x0CBE, 0x0CC0, 0x0CC4, - 0x0CC7, 0x0CC8, 0x0CCA, 0x0CCB, 0x0CD5, 0x0CD6, 0x0CDE, 0x0CDE, - 0x0CE0, 0x0CE1, 0x0CE6, 0x0CEF, 0x0D02, 0x0D03, 0x0D05, 0x0D0C, - 0x0D0E, 0x0D10, 0x0D12, 0x0D28, 0x0D2A, 0x0D39, 0x0D3E, 0x0D40, - 0x0D46, 0x0D48, 0x0D4A, 0x0D4C, 0x0D57, 0x0D57, 0x0D60, 0x0D61, - 0x0D66, 0x0D6F, 0x0D82, 0x0D83, 0x0D85, 0x0D96, 0x0D9A, 0x0DB1, - 0x0DB3, 0x0DBB, 0x0DBD, 0x0DBD, 0x0DC0, 0x0DC6, 0x0DCF, 0x0DD1, - 0x0DD8, 0x0DDF, 0x0DF2, 0x0DF4, 0x0E01, 0x0E30, 0x0E32, 0x0E33, - 0x0E40, 0x0E46, 0x0E4F, 0x0E5B, 0x0E81, 0x0E82, 0x0E84, 0x0E84, - 0x0E87, 0x0E88, 0x0E8A, 0x0E8A, 0x0E8D, 0x0E8D, 0x0E94, 0x0E97, - 0x0E99, 0x0E9F, 0x0EA1, 0x0EA3, 0x0EA5, 0x0EA5, 0x0EA7, 0x0EA7, - 0x0EAA, 0x0EAB, 0x0EAD, 0x0EB0, 0x0EB2, 0x0EB3, 0x0EBD, 0x0EBD, - 0x0EC0, 0x0EC4, 0x0EC6, 0x0EC6, 0x0ED0, 0x0ED9, 0x0EDC, 0x0EDD, - 0x0F00, 0x0F17, 0x0F1A, 0x0F34, 0x0F36, 0x0F36, 0x0F38, 0x0F38, - 0x0F3E, 0x0F47, 0x0F49, 0x0F6A, 0x0F7F, 0x0F7F, 0x0F85, 0x0F85, - 0x0F88, 0x0F8B, 0x0FBE, 0x0FC5, 0x0FC7, 0x0FCC, 0x0FCF, 0x0FCF, - 0x1000, 0x1021, 0x1023, 0x1027, 0x1029, 0x102A, 0x102C, 0x102C, - 0x1031, 0x1031, 0x1038, 0x1038, 0x1040, 0x1057, 0x10A0, 0x10C5, - 0x10D0, 0x10F8, 0x10FB, 0x10FB, 0x1100, 0x1159, 0x115F, 0x11A2, - 0x11A8, 0x11F9, 0x1200, 0x1206, 0x1208, 0x1246, 0x1248, 0x1248, - 0x124A, 0x124D, 0x1250, 0x1256, 0x1258, 0x1258, 0x125A, 0x125D, - 0x1260, 0x1286, 0x1288, 0x1288, 0x128A, 0x128D, 0x1290, 0x12AE, - 0x12B0, 0x12B0, 0x12B2, 0x12B5, 0x12B8, 0x12BE, 0x12C0, 0x12C0, - 0x12C2, 0x12C5, 0x12C8, 0x12CE, 0x12D0, 0x12D6, 0x12D8, 0x12EE, - 0x12F0, 0x130E, 0x1310, 0x1310, 0x1312, 0x1315, 0x1318, 0x131E, - 0x1320, 0x1346, 0x1348, 0x135A, 0x1361, 0x137C, 0x13A0, 0x13F4, - 0x1401, 0x1676, 0x1681, 0x169A, 0x16A0, 0x16F0, 0x1700, 0x170C, - 0x170E, 0x1711, 0x1720, 0x1731, 0x1735, 0x1736, 0x1740, 0x1751, - 0x1760, 0x176C, 0x176E, 0x1770, 0x1780, 0x17B6, 0x17BE, 0x17C5, - 0x17C7, 0x17C8, 0x17D4, 0x17DA, 0x17DC, 0x17DC, 0x17E0, 0x17E9, - 0x1810, 0x1819, 0x1820, 0x1877, 0x1880, 0x18A8, 0x1E00, 0x1E9B, - 0x1EA0, 0x1EF9, 0x1F00, 0x1F15, 0x1F18, 0x1F1D, 0x1F20, 0x1F45, - 0x1F48, 0x1F4D, 0x1F50, 0x1F57, 0x1F59, 0x1F59, 0x1F5B, 0x1F5B, - 0x1F5D, 0x1F5D, 0x1F5F, 0x1F7D, 0x1F80, 0x1FB4, 0x1FB6, 0x1FBC, - 0x1FBE, 0x1FBE, 0x1FC2, 0x1FC4, 0x1FC6, 0x1FCC, 0x1FD0, 0x1FD3, - 0x1FD6, 0x1FDB, 0x1FE0, 0x1FEC, 0x1FF2, 0x1FF4, 0x1FF6, 0x1FFC, - 0x200E, 0x200E, 0x2071, 0x2071, 0x207F, 0x207F, 0x2102, 0x2102, - 0x2107, 0x2107, 0x210A, 0x2113, 0x2115, 0x2115, 0x2119, 0x211D, - 0x2124, 0x2124, 0x2126, 0x2126, 0x2128, 0x2128, 0x212A, 0x212D, - 0x212F, 0x2131, 0x2133, 0x2139, 0x213D, 0x213F, 0x2145, 0x2149, - 0x2160, 0x2183, 0x2336, 0x237A, 0x2395, 0x2395, 0x249C, 0x24E9, - 0x3005, 0x3007, 0x3021, 0x3029, 0x3031, 0x3035, 0x3038, 0x303C, - 0x3041, 0x3096, 0x309D, 0x309F, 0x30A1, 0x30FA, 0x30FC, 0x30FF, - 0x3105, 0x312C, 0x3131, 0x318E, 0x3190, 0x31B7, 0x31F0, 0x321C, - 0x3220, 0x3243, 0x3260, 0x327B, 0x327F, 0x32B0, 0x32C0, 0x32CB, - 0x32D0, 0x32FE, 0x3300, 0x3376, 0x337B, 0x33DD, 0x33E0, 0x33FE, - 0x3400, 0x4DB5, 0x4E00, 0x9FA5, 0xA000, 0xA48C, 0xAC00, 0xD7A3, - 0xD800, 0xFA2D, 0xFA30, 0xFA6A, 0xFB00, 0xFB06, 0xFB13, 0xFB17, - 0xFF21, 0xFF3A, 0xFF41, 0xFF5A, 0xFF66, 0xFFBE, 0xFFC2, 0xFFC7, - 0xFFCA, 0xFFCF, 0xFFD2, 0xFFD7, 0xFFDA, 0xFFDC, 0x10300, 0x1031E, - 0x10320, 0x10323, 0x10330, 0x1034A, 0x10400, 0x10425, 0x10428, 0x1044D, - 0x1D000, 0x1D0F5, 0x1D100, 0x1D126, 0x1D12A, 0x1D166, 0x1D16A, 0x1D172, - 0x1D183, 0x1D184, 0x1D18C, 0x1D1A9, 0x1D1AE, 0x1D1DD, 0x1D400, 0x1D454, - 0x1D456, 0x1D49C, 0x1D49E, 0x1D49F, 0x1D4A2, 0x1D4A2, 0x1D4A5, 0x1D4A6, - 0x1D4A9, 0x1D4AC, 0x1D4AE, 0x1D4B9, 0x1D4BB, 0x1D4BB, 0x1D4BD, 0x1D4C0, - 0x1D4C2, 0x1D4C3, 0x1D4C5, 0x1D505, 0x1D507, 0x1D50A, 0x1D50D, 0x1D514, - 0x1D516, 0x1D51C, 0x1D51E, 0x1D539, 0x1D53B, 0x1D53E, 0x1D540, 0x1D544, - 0x1D546, 0x1D546, 0x1D54A, 0x1D550, 0x1D552, 0x1D6A3, 0x1D6A8, 0x1D7C9, - 0x20000, 0x2A6D6, 0x2F800, 0x2FA1D, 0xF0000, 0xFFFFD, 0x100000, 0x10FFFD}; + 0x0041, 0x005A, 0x0061, 0x007A, 0x00AA, 0x00AA, 0x00B5, 0x00B5, 0x00BA, 0x00BA, 0x00C0, 0x00D6, 0x00D8, + 0x00F6, 0x00F8, 0x0220, 0x0222, 0x0233, 0x0250, 0x02AD, 0x02B0, 0x02B8, 0x02BB, 0x02C1, 0x02D0, 0x02D1, + 0x02E0, 0x02E4, 0x02EE, 0x02EE, 0x037A, 0x037A, 0x0386, 0x0386, 0x0388, 0x038A, 0x038C, 0x038C, 0x038E, + 0x03A1, 0x03A3, 0x03CE, 0x03D0, 0x03F5, 0x0400, 0x0482, 0x048A, 0x04CE, 0x04D0, 0x04F5, 0x04F8, 0x04F9, + 0x0500, 0x050F, 0x0531, 0x0556, 0x0559, 0x055F, 0x0561, 0x0587, 0x0589, 0x0589, 0x0903, 0x0903, 0x0905, + 0x0939, 0x093D, 0x0940, 0x0949, 0x094C, 0x0950, 0x0950, 0x0958, 0x0961, 0x0964, 0x0970, 0x0982, 0x0983, + 0x0985, 0x098C, 0x098F, 0x0990, 0x0993, 0x09A8, 0x09AA, 0x09B0, 0x09B2, 0x09B2, 0x09B6, 0x09B9, 0x09BE, + 0x09C0, 0x09C7, 0x09C8, 0x09CB, 0x09CC, 0x09D7, 0x09D7, 0x09DC, 0x09DD, 0x09DF, 0x09E1, 0x09E6, 0x09F1, + 0x09F4, 0x09FA, 0x0A05, 0x0A0A, 0x0A0F, 0x0A10, 0x0A13, 0x0A28, 0x0A2A, 0x0A30, 0x0A32, 0x0A33, 0x0A35, + 0x0A36, 0x0A38, 0x0A39, 0x0A3E, 0x0A40, 0x0A59, 0x0A5C, 0x0A5E, 0x0A5E, 0x0A66, 0x0A6F, 0x0A72, 0x0A74, + 0x0A83, 0x0A83, 0x0A85, 0x0A8B, 0x0A8D, 0x0A8D, 0x0A8F, 0x0A91, 0x0A93, 0x0AA8, 0x0AAA, 0x0AB0, 0x0AB2, + 0x0AB3, 0x0AB5, 0x0AB9, 0x0ABD, 0x0AC0, 0x0AC9, 0x0AC9, 0x0ACB, 0x0ACC, 0x0AD0, 0x0AD0, 0x0AE0, 0x0AE0, + 0x0AE6, 0x0AEF, 0x0B02, 0x0B03, 0x0B05, 0x0B0C, 0x0B0F, 0x0B10, 0x0B13, 0x0B28, 0x0B2A, 0x0B30, 0x0B32, + 0x0B33, 0x0B36, 0x0B39, 0x0B3D, 0x0B3E, 0x0B40, 0x0B40, 0x0B47, 0x0B48, 0x0B4B, 0x0B4C, 0x0B57, 0x0B57, + 0x0B5C, 0x0B5D, 0x0B5F, 0x0B61, 0x0B66, 0x0B70, 0x0B83, 0x0B83, 0x0B85, 0x0B8A, 0x0B8E, 0x0B90, 0x0B92, + 0x0B95, 0x0B99, 0x0B9A, 0x0B9C, 0x0B9C, 0x0B9E, 0x0B9F, 0x0BA3, 0x0BA4, 0x0BA8, 0x0BAA, 0x0BAE, 0x0BB5, + 0x0BB7, 0x0BB9, 0x0BBE, 0x0BBF, 0x0BC1, 0x0BC2, 0x0BC6, 0x0BC8, 0x0BCA, 0x0BCC, 0x0BD7, 0x0BD7, 0x0BE7, + 0x0BF2, 0x0C01, 0x0C03, 0x0C05, 0x0C0C, 0x0C0E, 0x0C10, 0x0C12, 0x0C28, 0x0C2A, 0x0C33, 0x0C35, 0x0C39, + 0x0C41, 0x0C44, 0x0C60, 0x0C61, 0x0C66, 0x0C6F, 0x0C82, 0x0C83, 0x0C85, 0x0C8C, 0x0C8E, 0x0C90, 0x0C92, + 0x0CA8, 0x0CAA, 0x0CB3, 0x0CB5, 0x0CB9, 0x0CBE, 0x0CBE, 0x0CC0, 0x0CC4, 0x0CC7, 0x0CC8, 0x0CCA, 0x0CCB, + 0x0CD5, 0x0CD6, 0x0CDE, 0x0CDE, 0x0CE0, 0x0CE1, 0x0CE6, 0x0CEF, 0x0D02, 0x0D03, 0x0D05, 0x0D0C, 0x0D0E, + 0x0D10, 0x0D12, 0x0D28, 0x0D2A, 0x0D39, 0x0D3E, 0x0D40, 0x0D46, 0x0D48, 0x0D4A, 0x0D4C, 0x0D57, 0x0D57, + 0x0D60, 0x0D61, 0x0D66, 0x0D6F, 0x0D82, 0x0D83, 0x0D85, 0x0D96, 0x0D9A, 0x0DB1, 0x0DB3, 0x0DBB, 0x0DBD, + 0x0DBD, 0x0DC0, 0x0DC6, 0x0DCF, 0x0DD1, 0x0DD8, 0x0DDF, 0x0DF2, 0x0DF4, 0x0E01, 0x0E30, 0x0E32, 0x0E33, + 0x0E40, 0x0E46, 0x0E4F, 0x0E5B, 0x0E81, 0x0E82, 0x0E84, 0x0E84, 0x0E87, 0x0E88, 0x0E8A, 0x0E8A, 0x0E8D, + 0x0E8D, 0x0E94, 0x0E97, 0x0E99, 0x0E9F, 0x0EA1, 0x0EA3, 0x0EA5, 0x0EA5, 0x0EA7, 0x0EA7, 0x0EAA, 0x0EAB, + 0x0EAD, 0x0EB0, 0x0EB2, 0x0EB3, 0x0EBD, 0x0EBD, 0x0EC0, 0x0EC4, 0x0EC6, 0x0EC6, 0x0ED0, 0x0ED9, 0x0EDC, + 0x0EDD, 0x0F00, 0x0F17, 0x0F1A, 0x0F34, 0x0F36, 0x0F36, 0x0F38, 0x0F38, 0x0F3E, 0x0F47, 0x0F49, 0x0F6A, + 0x0F7F, 0x0F7F, 0x0F85, 0x0F85, 0x0F88, 0x0F8B, 0x0FBE, 0x0FC5, 0x0FC7, 0x0FCC, 0x0FCF, 0x0FCF, 0x1000, + 0x1021, 0x1023, 0x1027, 0x1029, 0x102A, 0x102C, 0x102C, 0x1031, 0x1031, 0x1038, 0x1038, 0x1040, 0x1057, + 0x10A0, 0x10C5, 0x10D0, 0x10F8, 0x10FB, 0x10FB, 0x1100, 0x1159, 0x115F, 0x11A2, 0x11A8, 0x11F9, 0x1200, + 0x1206, 0x1208, 0x1246, 0x1248, 0x1248, 0x124A, 0x124D, 0x1250, 0x1256, 0x1258, 0x1258, 0x125A, 0x125D, + 0x1260, 0x1286, 0x1288, 0x1288, 0x128A, 0x128D, 0x1290, 0x12AE, 0x12B0, 0x12B0, 0x12B2, 0x12B5, 0x12B8, + 0x12BE, 0x12C0, 0x12C0, 0x12C2, 0x12C5, 0x12C8, 0x12CE, 0x12D0, 0x12D6, 0x12D8, 0x12EE, 0x12F0, 0x130E, + 0x1310, 0x1310, 0x1312, 0x1315, 0x1318, 0x131E, 0x1320, 0x1346, 0x1348, 0x135A, 0x1361, 0x137C, 0x13A0, + 0x13F4, 0x1401, 0x1676, 0x1681, 0x169A, 0x16A0, 0x16F0, 0x1700, 0x170C, 0x170E, 0x1711, 0x1720, 0x1731, + 0x1735, 0x1736, 0x1740, 0x1751, 0x1760, 0x176C, 0x176E, 0x1770, 0x1780, 0x17B6, 0x17BE, 0x17C5, 0x17C7, + 0x17C8, 0x17D4, 0x17DA, 0x17DC, 0x17DC, 0x17E0, 0x17E9, 0x1810, 0x1819, 0x1820, 0x1877, 0x1880, 0x18A8, + 0x1E00, 0x1E9B, 0x1EA0, 0x1EF9, 0x1F00, 0x1F15, 0x1F18, 0x1F1D, 0x1F20, 0x1F45, 0x1F48, 0x1F4D, 0x1F50, + 0x1F57, 0x1F59, 0x1F59, 0x1F5B, 0x1F5B, 0x1F5D, 0x1F5D, 0x1F5F, 0x1F7D, 0x1F80, 0x1FB4, 0x1FB6, 0x1FBC, + 0x1FBE, 0x1FBE, 0x1FC2, 0x1FC4, 0x1FC6, 0x1FCC, 0x1FD0, 0x1FD3, 0x1FD6, 0x1FDB, 0x1FE0, 0x1FEC, 0x1FF2, + 0x1FF4, 0x1FF6, 0x1FFC, 0x200E, 0x200E, 0x2071, 0x2071, 0x207F, 0x207F, 0x2102, 0x2102, 0x2107, 0x2107, + 0x210A, 0x2113, 0x2115, 0x2115, 0x2119, 0x211D, 0x2124, 0x2124, 0x2126, 0x2126, 0x2128, 0x2128, 0x212A, + 0x212D, 0x212F, 0x2131, 0x2133, 0x2139, 0x213D, 0x213F, 0x2145, 0x2149, 0x2160, 0x2183, 0x2336, 0x237A, + 0x2395, 0x2395, 0x249C, 0x24E9, 0x3005, 0x3007, 0x3021, 0x3029, 0x3031, 0x3035, 0x3038, 0x303C, 0x3041, + 0x3096, 0x309D, 0x309F, 0x30A1, 0x30FA, 0x30FC, 0x30FF, 0x3105, 0x312C, 0x3131, 0x318E, 0x3190, 0x31B7, + 0x31F0, 0x321C, 0x3220, 0x3243, 0x3260, 0x327B, 0x327F, 0x32B0, 0x32C0, 0x32CB, 0x32D0, 0x32FE, 0x3300, + 0x3376, 0x337B, 0x33DD, 0x33E0, 0x33FE, 0x3400, 0x4DB5, 0x4E00, 0x9FA5, 0xA000, 0xA48C, 0xAC00, 0xD7A3, + 0xD800, 0xFA2D, 0xFA30, 0xFA6A, 0xFB00, 0xFB06, 0xFB13, 0xFB17, 0xFF21, 0xFF3A, 0xFF41, 0xFF5A, 0xFF66, + 0xFFBE, 0xFFC2, 0xFFC7, 0xFFCA, 0xFFCF, 0xFFD2, 0xFFD7, 0xFFDA, 0xFFDC, 0x10300, 0x1031E, 0x10320, 0x10323, + 0x10330, 0x1034A, 0x10400, 0x10425, 0x10428, 0x1044D, 0x1D000, 0x1D0F5, 0x1D100, 0x1D126, 0x1D12A, 0x1D166, 0x1D16A, + 0x1D172, 0x1D183, 0x1D184, 0x1D18C, 0x1D1A9, 0x1D1AE, 0x1D1DD, 0x1D400, 0x1D454, 0x1D456, 0x1D49C, 0x1D49E, 0x1D49F, + 0x1D4A2, 0x1D4A2, 0x1D4A5, 0x1D4A6, 0x1D4A9, 0x1D4AC, 0x1D4AE, 0x1D4B9, 0x1D4BB, 0x1D4BB, 0x1D4BD, 0x1D4C0, 0x1D4C2, + 0x1D4C3, 0x1D4C5, 0x1D505, 0x1D507, 0x1D50A, 0x1D50D, 0x1D514, 0x1D516, 0x1D51C, 0x1D51E, 0x1D539, 0x1D53B, 0x1D53E, + 0x1D540, 0x1D544, 0x1D546, 0x1D546, 0x1D54A, 0x1D550, 0x1D552, 0x1D6A3, 0x1D6A8, 0x1D7C9, 0x20000, 0x2A6D6, 0x2F800, + 0x2FA1D, 0xF0000, 0xFFFFD, 0x100000, 0x10FFFD}; BSON_END_DECLS diff --git a/src/libmongoc/src/mongoc/mongoc-scram.c b/src/libmongoc/src/mongoc/mongoc-scram.c index 2a148c711b..09a340e068 100644 --- a/src/libmongoc/src/mongoc/mongoc-scram.c +++ b/src/libmongoc/src/mongoc/mongoc-scram.c @@ -54,17 +54,13 @@ _mongoc_utf8_first_code_point_is_valid (const char *c, size_t length); /* returns whether a character is between two limits (inclusive). */ bool -_mongoc_utf8_code_unit_in_range (const uint8_t c, - const uint8_t lower, - const uint8_t upper); +_mongoc_utf8_code_unit_in_range (const uint8_t c, const uint8_t lower, const uint8_t upper); /* returns whether a codepoint exists in the specified table. The table format * is that the 2*n element is the lower bound and the 2*n + 1 is the upper bound * (both inclusive). */ bool -_mongoc_utf8_code_point_is_in_table (uint32_t code, - const uint32_t *table, - size_t size); +_mongoc_utf8_code_point_is_in_table (uint32_t code, const uint32_t *table, size_t size); /* returns the byte length of the UTF-8 code point. Returns -1 if `c` is not a * valid UTF-8 code point. */ @@ -129,17 +125,14 @@ _scram_hash_size (mongoc_scram_t *scram) /* Copies the cache's secrets to scram */ static void -_mongoc_scram_cache_apply_secrets (mongoc_scram_cache_entry_t *cache, - mongoc_scram_t *scram) +_mongoc_scram_cache_apply_secrets (mongoc_scram_cache_entry_t *cache, mongoc_scram_t *scram) { BSON_ASSERT (cache); BSON_ASSERT (scram); memcpy (scram->client_key, cache->client_key, sizeof (scram->client_key)); memcpy (scram->server_key, cache->server_key, sizeof (scram->server_key)); - memcpy (scram->salted_password, - cache->salted_password, - sizeof (scram->salted_password)); + memcpy (scram->salted_password, cache->salted_password, sizeof (scram->salted_password)); } @@ -156,8 +149,7 @@ _mongoc_scram_cache_destroy (mongoc_scram_cache_entry_t *cache) * Populate `cache` with the values found in the global cache if found. */ static bool -_mongoc_scram_cache_has_presecrets (mongoc_scram_cache_entry_t *cache /* out */, - const mongoc_scram_t *scram) +_mongoc_scram_cache_has_presecrets (mongoc_scram_cache_entry_t *cache /* out */, const mongoc_scram_t *scram) { bool cache_hit = false; @@ -178,23 +170,14 @@ _mongoc_scram_cache_has_presecrets (mongoc_scram_cache_entry_t *cache /* out */, for (size_t i = 0; i < MONGOC_SCRAM_CACHE_SIZE; i++) { if (g_scram_cache[i].taken) { mongoc_scram_cache_entry_t *cache_entry = &g_scram_cache[i]; - cache_hit = - !strcmp (cache_entry->hashed_password, scram->hashed_password) && - cache_entry->iterations == scram->iterations && - !memcmp (cache_entry->decoded_salt, - scram->decoded_salt, - sizeof (cache_entry->decoded_salt)); + cache_hit = !strcmp (cache_entry->hashed_password, scram->hashed_password) && + cache_entry->iterations == scram->iterations && + !memcmp (cache_entry->decoded_salt, scram->decoded_salt, sizeof (cache_entry->decoded_salt)); if (cache_hit) { /* copy the found cache items into the 'cache' output parameter */ - memcpy (cache->client_key, - cache_entry->client_key, - sizeof (cache->client_key)); - memcpy (cache->server_key, - cache_entry->server_key, - sizeof (cache->server_key)); - memcpy (cache->salted_password, - cache_entry->salted_password, - sizeof (cache->salted_password)); + memcpy (cache->client_key, cache_entry->client_key, sizeof (cache->client_key)); + memcpy (cache->server_key, cache_entry->server_key, sizeof (cache->server_key)); + memcpy (cache->salted_password, cache_entry->salted_password, sizeof (cache->salted_password)); goto done; } } @@ -269,18 +252,10 @@ _mongoc_scram_cache_insert (const mongoc_scram_t *scram) bool already_exists = !strcmp (cache_entry->hashed_password, scram->hashed_password) && cache_entry->iterations == scram->iterations && - !memcmp (cache_entry->decoded_salt, - scram->decoded_salt, - sizeof (cache_entry->decoded_salt)) && - !memcmp (cache_entry->client_key, - scram->client_key, - sizeof (cache_entry->client_key)) && - !memcmp (cache_entry->server_key, - scram->server_key, - sizeof (cache_entry->server_key)) && - !memcmp (cache_entry->salted_password, - scram->salted_password, - sizeof (cache_entry->salted_password)); + !memcmp (cache_entry->decoded_salt, scram->decoded_salt, sizeof (cache_entry->decoded_salt)) && + !memcmp (cache_entry->client_key, scram->client_key, sizeof (cache_entry->client_key)) && + !memcmp (cache_entry->server_key, scram->server_key, sizeof (cache_entry->server_key)) && + !memcmp (cache_entry->salted_password, scram->salted_password, sizeof (cache_entry->salted_password)); if (already_exists) { /* cache entry already populated between read and write lock @@ -290,21 +265,11 @@ _mongoc_scram_cache_insert (const mongoc_scram_t *scram) if (!cache_entry->taken) { /* found an empty slot */ - memcpy (cache_entry->client_key, - scram->client_key, - sizeof (cache_entry->client_key)); - memcpy (cache_entry->server_key, - scram->server_key, - sizeof (cache_entry->server_key)); - memcpy (cache_entry->salted_password, - scram->salted_password, - sizeof (cache_entry->salted_password)); - memcpy (cache_entry->decoded_salt, - scram->decoded_salt, - sizeof (cache_entry->decoded_salt)); - memcpy (cache_entry->hashed_password, - scram->hashed_password, - sizeof (cache_entry->hashed_password)); + memcpy (cache_entry->client_key, scram->client_key, sizeof (cache_entry->client_key)); + memcpy (cache_entry->server_key, scram->server_key, sizeof (cache_entry->server_key)); + memcpy (cache_entry->salted_password, scram->salted_password, sizeof (cache_entry->salted_password)); + memcpy (cache_entry->decoded_salt, scram->decoded_salt, sizeof (cache_entry->decoded_salt)); + memcpy (cache_entry->hashed_password, scram->hashed_password, sizeof (cache_entry->hashed_password)); cache_entry->iterations = scram->iterations; cache_entry->taken = true; break; @@ -334,11 +299,7 @@ _mongoc_scram_update_cache (const mongoc_scram_t *scram) static bool -_mongoc_scram_buf_write (const char *src, - int32_t src_len, - uint8_t *outbuf, - uint32_t outbufmax, - uint32_t *outbuflen) +_mongoc_scram_buf_write (const char *src, int32_t src_len, uint8_t *outbuf, uint32_t outbufmax, uint32_t *outbuflen) { if (src_len < 0) { src_len = (int32_t) strlen (src); @@ -362,11 +323,8 @@ _mongoc_scram_buf_write (const char *src, * note that a= is optional, so we aren't dealing with that here */ static bool -_mongoc_scram_start (mongoc_scram_t *scram, - uint8_t *outbuf, - uint32_t outbufmax, - uint32_t *outbuflen, - bson_error_t *error) +_mongoc_scram_start ( + mongoc_scram_t *scram, uint8_t *outbuf, uint32_t outbufmax, uint32_t *outbuflen, bson_error_t *error) { uint8_t nonce[24]; const char *ptr; @@ -378,10 +336,8 @@ _mongoc_scram_start (mongoc_scram_t *scram, BSON_ASSERT (outbuflen); if (!scram->user) { - bson_set_error (error, - MONGOC_ERROR_SCRAM, - MONGOC_ERROR_SCRAM_PROTOCOL_ERROR, - "SCRAM Failure: username is not set"); + bson_set_error ( + error, MONGOC_ERROR_SCRAM, MONGOC_ERROR_SCRAM_PROTOCOL_ERROR, "SCRAM Failure: username is not set"); goto FAIL; } @@ -399,16 +355,12 @@ _mongoc_scram_start (mongoc_scram_t *scram, goto FAIL; } - scram->encoded_nonce_len = mcommon_b64_ntop (nonce, - sizeof (nonce), - scram->encoded_nonce, - sizeof (scram->encoded_nonce)); + scram->encoded_nonce_len = + mcommon_b64_ntop (nonce, sizeof (nonce), scram->encoded_nonce, sizeof (scram->encoded_nonce)); if (-1 == scram->encoded_nonce_len) { - bson_set_error (error, - MONGOC_ERROR_SCRAM, - MONGOC_ERROR_SCRAM_PROTOCOL_ERROR, - "SCRAM Failure: could not encode nonce"); + bson_set_error ( + error, MONGOC_ERROR_SCRAM, MONGOC_ERROR_SCRAM_PROTOCOL_ERROR, "SCRAM Failure: could not encode nonce"); goto FAIL; } @@ -422,16 +374,14 @@ _mongoc_scram_start (mongoc_scram_t *scram, switch (*ptr) { case ',': - if (!_mongoc_scram_buf_write ( - "=2C", -1, outbuf, outbufmax, outbuflen)) { + if (!_mongoc_scram_buf_write ("=2C", -1, outbuf, outbufmax, outbuflen)) { goto BUFFER; } break; case '=': - if (!_mongoc_scram_buf_write ( - "=3D", -1, outbuf, outbufmax, outbuflen)) { + if (!_mongoc_scram_buf_write ("=3D", -1, outbuf, outbufmax, outbuflen)) { goto BUFFER; } @@ -450,49 +400,35 @@ _mongoc_scram_start (mongoc_scram_t *scram, goto BUFFER; } - if (!_mongoc_scram_buf_write (scram->encoded_nonce, - scram->encoded_nonce_len, - outbuf, - outbufmax, - outbuflen)) { + if (!_mongoc_scram_buf_write (scram->encoded_nonce, scram->encoded_nonce_len, outbuf, outbufmax, outbuflen)) { goto BUFFER; } /* we have to keep track of the conversation to create a client proof later * on. This copies the message we're crafting from the 'n=' portion onwards * into a buffer we're managing */ - if (!_mongoc_scram_buf_write ((char *) outbuf + 3, - *outbuflen - 3, - scram->auth_message, - scram->auth_messagemax, - &scram->auth_messagelen)) { + if (!_mongoc_scram_buf_write ( + (char *) outbuf + 3, *outbuflen - 3, 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)) { + if (!_mongoc_scram_buf_write (",", -1, scram->auth_message, scram->auth_messagemax, &scram->auth_messagelen)) { goto BUFFER_AUTH; } 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 step1"); + bson_set_error (error, + MONGOC_ERROR_SCRAM, + MONGOC_ERROR_SCRAM_PROTOCOL_ERROR, + "SCRAM Failure: could not buffer auth message in sasl step1"); goto FAIL; BUFFER: - bson_set_error (error, - MONGOC_ERROR_SCRAM, - MONGOC_ERROR_SCRAM_PROTOCOL_ERROR, - "SCRAM Failure: could not buffer sasl step1"); + bson_set_error ( + error, MONGOC_ERROR_SCRAM, MONGOC_ERROR_SCRAM_PROTOCOL_ERROR, "SCRAM Failure: could not buffer sasl step1"); goto FAIL; @@ -526,12 +462,7 @@ _mongoc_scram_salt_password (mongoc_scram_t *scram, start_key[salt_len + 2] = 0; start_key[salt_len + 3] = 1; - mongoc_crypto_hmac (&scram->crypto, - password, - password_len, - start_key, - _scram_hash_size (scram), - output); + mongoc_crypto_hmac (&scram->crypto, password, password_len, start_key, _scram_hash_size (scram), output); memcpy (intermediate_digest, output, _scram_hash_size (scram)); @@ -540,12 +471,7 @@ _mongoc_scram_salt_password (mongoc_scram_t *scram, for (uint32_t i = 2u; i <= iterations; i++) { const int hash_size = _scram_hash_size (scram); - mongoc_crypto_hmac (&scram->crypto, - password, - password_len, - intermediate_digest, - hash_size, - intermediate_digest); + mongoc_crypto_hmac (&scram->crypto, password, password_len, intermediate_digest, hash_size, intermediate_digest); for (int k = 0; k < hash_size; k++) { output[k] ^= intermediate_digest[k]; @@ -555,10 +481,7 @@ _mongoc_scram_salt_password (mongoc_scram_t *scram, static bool -_mongoc_scram_generate_client_proof (mongoc_scram_t *scram, - uint8_t *outbuf, - uint32_t outbufmax, - uint32_t *outbuflen) +_mongoc_scram_generate_client_proof (mongoc_scram_t *scram, uint8_t *outbuf, uint32_t outbufmax, uint32_t *outbuflen) { uint8_t stored_key[MONGOC_SCRAM_HASH_MAX_SIZE]; uint8_t client_signature[MONGOC_SCRAM_HASH_MAX_SIZE]; @@ -577,10 +500,7 @@ _mongoc_scram_generate_client_proof (mongoc_scram_t *scram, } /* StoredKey := H(client_key) */ - mongoc_crypto_hash (&scram->crypto, - scram->client_key, - (size_t) _scram_hash_size (scram), - stored_key); + mongoc_crypto_hash (&scram->crypto, scram->client_key, (size_t) _scram_hash_size (scram), stored_key); /* ClientSignature := HMAC(StoredKey, AuthMessage) */ mongoc_crypto_hmac (&scram->crypto, @@ -596,10 +516,7 @@ _mongoc_scram_generate_client_proof (mongoc_scram_t *scram, client_proof[i] = scram->client_key[i] ^ client_signature[i]; } - r = mcommon_b64_ntop (client_proof, - _scram_hash_size (scram), - (char *) outbuf + *outbuflen, - outbufmax - *outbuflen); + r = mcommon_b64_ntop (client_proof, _scram_hash_size (scram), (char *) outbuf + *outbuflen, outbufmax - *outbuflen); if (-1 == r) { return false; @@ -673,19 +590,12 @@ _mongoc_scram_step2 (mongoc_scram_t *scram, } /* 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)) { + 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)) { + if (!_mongoc_scram_buf_write (",", -1, scram->auth_message, scram->auth_messagemax, &scram->auth_messagelen)) { goto BUFFER_AUTH; } @@ -725,8 +635,7 @@ _mongoc_scram_step2 (mongoc_scram_t *scram, ptr++; - const uint8_t *const next_comma = - (const uint8_t *) memchr (ptr, ',', (inbuf + inbuflen) - ptr); + const uint8_t *const next_comma = (const uint8_t *) memchr (ptr, ',', (inbuf + inbuflen) - ptr); if (next_comma) { *current_val_len = (uint32_t) (next_comma - ptr); @@ -746,28 +655,22 @@ _mongoc_scram_step2 (mongoc_scram_t *scram, } if (!val_r) { - bson_set_error (error, - MONGOC_ERROR_SCRAM, - MONGOC_ERROR_SCRAM_PROTOCOL_ERROR, - "SCRAM Failure: no r param in sasl step 2"); + 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"); + 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"); + bson_set_error ( + error, MONGOC_ERROR_SCRAM, MONGOC_ERROR_SCRAM_PROTOCOL_ERROR, "SCRAM Failure: no i param in sasl step 2"); goto FAIL; } @@ -775,30 +678,24 @@ _mongoc_scram_step2 (mongoc_scram_t *scram, /* verify our nonce */ if (bson_cmp_less_us (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"); + 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)) { + 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)) { + 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)) { + if (!_mongoc_scram_buf_write ( + (char *) outbuf, *outbuflen, scram->auth_message, scram->auth_messagemax, &scram->auth_messagelen)) { goto BUFFER_AUTH; } @@ -806,8 +703,7 @@ _mongoc_scram_step2 (mongoc_scram_t *scram, goto BUFFER; } - decoded_salt_len = - mcommon_b64_pton ((char *) val_s, decoded_salt, sizeof (decoded_salt)); + decoded_salt_len = mcommon_b64_pton ((char *) val_s, decoded_salt, sizeof (decoded_salt)); if (-1 == decoded_salt_len) { bson_set_error (error, @@ -831,11 +727,10 @@ _mongoc_scram_step2 (mongoc_scram_t *scram, * 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"); + bson_set_error (error, + MONGOC_ERROR_SCRAM, + MONGOC_ERROR_SCRAM_PROTOCOL_ERROR, + "SCRAM Failure: unable to parse iterations in sasl step2"); goto FAIL; } @@ -860,9 +755,7 @@ _mongoc_scram_step2 (mongoc_scram_t *scram, /* Save the presecrets for caching */ if (hashed_password) { - bson_strncpy (scram->hashed_password, - hashed_password, - sizeof (scram->hashed_password)); + bson_strncpy (scram->hashed_password, hashed_password, sizeof (scram->hashed_password)); } scram->iterations = iterations; @@ -887,19 +780,16 @@ _mongoc_scram_step2 (mongoc_scram_t *scram, 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"); + 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"); + bson_set_error ( + error, MONGOC_ERROR_SCRAM, MONGOC_ERROR_SCRAM_PROTOCOL_ERROR, "SCRAM Failure: could not buffer sasl step2"); goto FAIL; @@ -920,9 +810,7 @@ _mongoc_scram_step2 (mongoc_scram_t *scram, static bool -_mongoc_scram_verify_server_signature (mongoc_scram_t *scram, - uint8_t *verification, - uint32_t len) +_mongoc_scram_verify_server_signature (mongoc_scram_t *scram, uint8_t *verification, uint32_t len) { char encoded_server_signature[MONGOC_SCRAM_B64_HASH_MAX_SIZE]; int32_t encoded_server_signature_len; @@ -949,17 +837,13 @@ _mongoc_scram_verify_server_signature (mongoc_scram_t *scram, scram->auth_messagelen, server_signature); - encoded_server_signature_len = - mcommon_b64_ntop (server_signature, - _scram_hash_size (scram), - encoded_server_signature, - sizeof (encoded_server_signature)); + encoded_server_signature_len = mcommon_b64_ntop ( + server_signature, _scram_hash_size (scram), encoded_server_signature, sizeof (encoded_server_signature)); if (encoded_server_signature_len == -1) { return false; } - return (len == encoded_server_signature_len) && - (mongoc_memcmp (verification, encoded_server_signature, len) == 0); + return (len == encoded_server_signature_len) && (mongoc_memcmp (verification, encoded_server_signature, len) == 0); } @@ -1018,8 +902,7 @@ _mongoc_scram_step3 (mongoc_scram_t *scram, ptr++; - const uint8_t *const next_comma = - (const uint8_t *) memchr (ptr, ',', (inbuf + inbuflen) - ptr); + const uint8_t *const next_comma = (const uint8_t *) memchr (ptr, ',', (inbuf + inbuflen) - ptr); if (next_comma) { *current_val_len = (uint32_t) (next_comma - ptr); @@ -1041,29 +924,25 @@ _mongoc_scram_step3 (mongoc_scram_t *scram, *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); + 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"); + 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"); + 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; } @@ -1103,16 +982,11 @@ _mongoc_scram_step (mongoc_scram_t *scram, case 1: return _mongoc_scram_start (scram, outbuf, outbufmax, outbuflen, error); case 2: - return _mongoc_scram_step2 ( - scram, inbuf, inbuflen, outbuf, outbufmax, outbuflen, error); + return _mongoc_scram_step2 (scram, inbuf, inbuflen, outbuf, outbufmax, outbuflen, error); case 3: - return _mongoc_scram_step3 ( - scram, inbuf, inbuflen, outbuf, outbufmax, outbuflen, error); + return _mongoc_scram_step3 (scram, inbuf, inbuflen, outbuf, outbufmax, outbuflen, error); default: - bson_set_error (error, - MONGOC_ERROR_SCRAM, - MONGOC_ERROR_SCRAM_NOT_DONE, - "SCRAM Failure: maximum steps detected"); + bson_set_error (error, MONGOC_ERROR_SCRAM, MONGOC_ERROR_SCRAM_NOT_DONE, "SCRAM Failure: maximum steps detected"); return false; } } @@ -1135,9 +1009,7 @@ _mongoc_sasl_prep_required (const char *str) } char * -_mongoc_sasl_prep_impl (const char *name, - const char *in_utf8, - bson_error_t *err) +_mongoc_sasl_prep_impl (const char *name, const char *in_utf8, bson_error_t *err) { BSON_ASSERT_PARAM (name); BSON_ASSERT_PARAM (in_utf8); @@ -1146,14 +1018,10 @@ _mongoc_sasl_prep_impl (const char *name, ssize_t num_chars; uint8_t *out_utf8; -#define SASL_PREP_ERR_RETURN(msg) \ - do { \ - bson_set_error (err, \ - MONGOC_ERROR_SCRAM, \ - MONGOC_ERROR_SCRAM_PROTOCOL_ERROR, \ - (msg), \ - name); \ - return NULL; \ +#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 Unicode codepoints. */ @@ -1164,14 +1032,12 @@ _mongoc_sasl_prep_impl (const char *name, } /* convert to unicode. */ - utf8_codepoints = bson_malloc ( - sizeof (uint32_t) * (num_chars + 1)); /* add one for trailing 0 value. */ + utf8_codepoints = bson_malloc (sizeof (uint32_t) * (num_chars + 1)); /* add one for trailing 0 value. */ const char *c = in_utf8; for (size_t i = 0; i < num_chars; ++i) { const size_t utf8_char_length = _mongoc_utf8_char_length (c); - utf8_codepoints[i] = - _mongoc_utf8_get_first_code_point (c, utf8_char_length); + utf8_codepoints[i] = _mongoc_utf8_get_first_code_point (c, utf8_char_length); c += utf8_char_length; } @@ -1189,16 +1055,13 @@ _mongoc_sasl_prep_impl (const char *name, // the new characters (curr). i will always be >= curr. size_t curr = 0; for (size_t i = 0; i < num_chars; ++i) { - if (_mongoc_utf8_code_point_is_in_table ( - utf8_codepoints[i], - non_ascii_space_character_ranges, - sizeof (non_ascii_space_character_ranges) / sizeof (uint32_t))) + if (_mongoc_utf8_code_point_is_in_table (utf8_codepoints[i], + non_ascii_space_character_ranges, + sizeof (non_ascii_space_character_ranges) / sizeof (uint32_t))) utf8_codepoints[curr++] = 0x0020; - else if (_mongoc_utf8_code_point_is_in_table ( - utf8_codepoints[i], - commonly_mapped_to_nothing_ranges, - sizeof (commonly_mapped_to_nothing_ranges) / - sizeof (uint32_t))) { + else if (_mongoc_utf8_code_point_is_in_table (utf8_codepoints[i], + commonly_mapped_to_nothing_ranges, + sizeof (commonly_mapped_to_nothing_ranges) / sizeof (uint32_t))) { // effectively skip over the character because we don't increment curr. } else utf8_codepoints[curr++] = utf8_codepoints[i]; @@ -1226,13 +1089,11 @@ _mongoc_sasl_prep_impl (const char *name, utf8_pre_norm_len += len; } } - char *utf8_pre_norm = - (char *) bson_malloc (sizeof (char) * (utf8_pre_norm_len + 1)); + char *utf8_pre_norm = (char *) bson_malloc (sizeof (char) * (utf8_pre_norm_len + 1)); char *loc = utf8_pre_norm; for (size_t i = 0; i < num_chars; ++i) { - const ssize_t utf8_char_length = - _mongoc_utf8_code_point_to_str (utf8_codepoints[i], loc); + const ssize_t utf8_char_length = _mongoc_utf8_code_point_to_str (utf8_codepoints[i], loc); if (utf8_char_length == -1) { bson_free (utf8_pre_norm); bson_free (utf8_codepoints); @@ -1255,13 +1116,10 @@ _mongoc_sasl_prep_impl (const char *name, for (size_t i = 0; i < num_chars; ++i) { if (_mongoc_utf8_code_point_is_in_table ( - utf8_codepoints[i], - prohibited_output_ranges, - sizeof (prohibited_output_ranges) / sizeof (uint32_t)) || - _mongoc_utf8_code_point_is_in_table ( - utf8_codepoints[i], - unassigned_codepoint_ranges, - sizeof (unassigned_codepoint_ranges) / sizeof (uint32_t))) { + utf8_codepoints[i], prohibited_output_ranges, sizeof (prohibited_output_ranges) / sizeof (uint32_t)) || + _mongoc_utf8_code_point_is_in_table (utf8_codepoints[i], + unassigned_codepoint_ranges, + sizeof (unassigned_codepoint_ranges) / sizeof (uint32_t))) { bson_free (out_utf8); bson_free (utf8_pre_norm); bson_free (utf8_codepoints); @@ -1288,16 +1146,12 @@ _mongoc_sasl_prep_impl (const char *name, for (size_t i = 0; i < num_chars; ++i) { - if (_mongoc_utf8_code_point_is_in_table (utf8_codepoints[i], - LCat_bidi_ranges, - sizeof (LCat_bidi_ranges) / - sizeof (uint32_t))) { + if (_mongoc_utf8_code_point_is_in_table ( + utf8_codepoints[i], LCat_bidi_ranges, sizeof (LCat_bidi_ranges) / sizeof (uint32_t))) { contains_LCat = true; } - if (_mongoc_utf8_code_point_is_in_table (utf8_codepoints[i], - RandALCat_bidi_ranges, - sizeof (RandALCat_bidi_ranges) / - sizeof (uint32_t))) + if (_mongoc_utf8_code_point_is_in_table ( + utf8_codepoints[i], RandALCat_bidi_ranges, sizeof (RandALCat_bidi_ranges) / sizeof (uint32_t))) contains_RandALCar = true; } @@ -1306,14 +1160,11 @@ _mongoc_sasl_prep_impl (const char *name, (contains_RandALCar && contains_LCat) || // requirement 2 (contains_RandALCar && - (!_mongoc_utf8_code_point_is_in_table (utf8_codepoints[0], - RandALCat_bidi_ranges, - sizeof (RandALCat_bidi_ranges) / - sizeof (uint32_t)) || + (!_mongoc_utf8_code_point_is_in_table ( + utf8_codepoints[0], RandALCat_bidi_ranges, sizeof (RandALCat_bidi_ranges) / sizeof (uint32_t)) || !_mongoc_utf8_code_point_is_in_table (utf8_codepoints[num_chars - 1], RandALCat_bidi_ranges, - sizeof (RandALCat_bidi_ranges) / - sizeof (uint32_t))))) { + sizeof (RandALCat_bidi_ranges) / sizeof (uint32_t))))) { bson_free (out_utf8); bson_free (utf8_pre_norm); bson_free (utf8_codepoints); @@ -1368,8 +1219,7 @@ _mongoc_utf8_string_length (const char *s) while (*c) { const size_t utf8_char_length = _mongoc_utf8_char_length ((char *) c); - if (!_mongoc_utf8_first_code_point_is_valid ((char *) c, - utf8_char_length)) + if (!_mongoc_utf8_first_code_point_is_valid ((char *) c, utf8_char_length)) return -1; str_length++; @@ -1390,65 +1240,38 @@ _mongoc_utf8_first_code_point_is_valid (const char *c, size_t length) // https://lemire.me/blog/2018/05/09/how-quickly-can-you-check-that-a-string-is-valid-unicode-utf-8/ switch (length) { case 1: - return _mongoc_utf8_code_unit_in_range ( - temp_c[0], UINT8_C (0x00), UINT8_C (0x7F)); + return _mongoc_utf8_code_unit_in_range (temp_c[0], UINT8_C (0x00), UINT8_C (0x7F)); case 2: - return _mongoc_utf8_code_unit_in_range ( - temp_c[0], UINT8_C (0xC2), UINT8_C (0xDF)) && - _mongoc_utf8_code_unit_in_range ( - temp_c[1], UINT8_C (0x80), UINT8_C (0xBF)); + return _mongoc_utf8_code_unit_in_range (temp_c[0], UINT8_C (0xC2), UINT8_C (0xDF)) && + _mongoc_utf8_code_unit_in_range (temp_c[1], UINT8_C (0x80), UINT8_C (0xBF)); case 3: // Four options, separated by || - return (_mongoc_utf8_code_unit_in_range ( - temp_c[0], UINT8_C (0xE0), UINT8_C (0xE0)) && - _mongoc_utf8_code_unit_in_range ( - temp_c[1], UINT8_C (0xA0), UINT8_C (0xBF)) && - _mongoc_utf8_code_unit_in_range ( - temp_c[2], UINT8_C (0x80), UINT8_C (0xBF))) || - (_mongoc_utf8_code_unit_in_range ( - temp_c[0], UINT8_C (0xE1), UINT8_C (0xEC)) && - _mongoc_utf8_code_unit_in_range ( - temp_c[1], UINT8_C (0x80), UINT8_C (0xBF)) && - _mongoc_utf8_code_unit_in_range ( - temp_c[2], UINT8_C (0x80), UINT8_C (0xBF))) || - (_mongoc_utf8_code_unit_in_range ( - temp_c[0], UINT8_C (0xED), UINT8_C (0xED)) && - _mongoc_utf8_code_unit_in_range ( - temp_c[1], UINT8_C (0x80), UINT8_C (0x9F)) && - _mongoc_utf8_code_unit_in_range ( - temp_c[2], UINT8_C (0x80), UINT8_C (0xBF))) || - (_mongoc_utf8_code_unit_in_range ( - temp_c[0], UINT8_C (0xEE), UINT8_C (0xEF)) && - _mongoc_utf8_code_unit_in_range ( - temp_c[1], UINT8_C (0x80), UINT8_C (0xBF)) && - _mongoc_utf8_code_unit_in_range ( - temp_c[2], UINT8_C (0x80), UINT8_C (0xBF))); + return (_mongoc_utf8_code_unit_in_range (temp_c[0], UINT8_C (0xE0), UINT8_C (0xE0)) && + _mongoc_utf8_code_unit_in_range (temp_c[1], UINT8_C (0xA0), UINT8_C (0xBF)) && + _mongoc_utf8_code_unit_in_range (temp_c[2], UINT8_C (0x80), UINT8_C (0xBF))) || + (_mongoc_utf8_code_unit_in_range (temp_c[0], UINT8_C (0xE1), UINT8_C (0xEC)) && + _mongoc_utf8_code_unit_in_range (temp_c[1], UINT8_C (0x80), UINT8_C (0xBF)) && + _mongoc_utf8_code_unit_in_range (temp_c[2], UINT8_C (0x80), UINT8_C (0xBF))) || + (_mongoc_utf8_code_unit_in_range (temp_c[0], UINT8_C (0xED), UINT8_C (0xED)) && + _mongoc_utf8_code_unit_in_range (temp_c[1], UINT8_C (0x80), UINT8_C (0x9F)) && + _mongoc_utf8_code_unit_in_range (temp_c[2], UINT8_C (0x80), UINT8_C (0xBF))) || + (_mongoc_utf8_code_unit_in_range (temp_c[0], UINT8_C (0xEE), UINT8_C (0xEF)) && + _mongoc_utf8_code_unit_in_range (temp_c[1], UINT8_C (0x80), UINT8_C (0xBF)) && + _mongoc_utf8_code_unit_in_range (temp_c[2], UINT8_C (0x80), UINT8_C (0xBF))); case 4: // Three options, separated by || - return (_mongoc_utf8_code_unit_in_range ( - temp_c[0], UINT8_C (0xF0), UINT8_C (0xF0)) && - _mongoc_utf8_code_unit_in_range ( - temp_c[1], UINT8_C (0x90), UINT8_C (0xBF)) && - _mongoc_utf8_code_unit_in_range ( - temp_c[2], UINT8_C (0x80), UINT8_C (0xBF)) && - _mongoc_utf8_code_unit_in_range ( - temp_c[3], UINT8_C (0x80), UINT8_C (0xBF))) || - (_mongoc_utf8_code_unit_in_range ( - temp_c[0], UINT8_C (0xF1), UINT8_C (0xF3)) && - _mongoc_utf8_code_unit_in_range ( - temp_c[1], UINT8_C (0x80), UINT8_C (0xBF)) && - _mongoc_utf8_code_unit_in_range ( - temp_c[2], UINT8_C (0x80), UINT8_C (0xBF)) && - _mongoc_utf8_code_unit_in_range ( - temp_c[3], UINT8_C (0x80), UINT8_C (0xBF))) || - (_mongoc_utf8_code_unit_in_range ( - temp_c[0], UINT8_C (0xF4), UINT8_C (0xF4)) && - _mongoc_utf8_code_unit_in_range ( - temp_c[1], UINT8_C (0x80), UINT8_C (0x8F)) && - _mongoc_utf8_code_unit_in_range ( - temp_c[2], UINT8_C (0x80), UINT8_C (0xBF)) && - _mongoc_utf8_code_unit_in_range ( - temp_c[3], UINT8_C (0x80), UINT8_C (0xBF))); + return (_mongoc_utf8_code_unit_in_range (temp_c[0], UINT8_C (0xF0), UINT8_C (0xF0)) && + _mongoc_utf8_code_unit_in_range (temp_c[1], UINT8_C (0x90), UINT8_C (0xBF)) && + _mongoc_utf8_code_unit_in_range (temp_c[2], UINT8_C (0x80), UINT8_C (0xBF)) && + _mongoc_utf8_code_unit_in_range (temp_c[3], UINT8_C (0x80), UINT8_C (0xBF))) || + (_mongoc_utf8_code_unit_in_range (temp_c[0], UINT8_C (0xF1), UINT8_C (0xF3)) && + _mongoc_utf8_code_unit_in_range (temp_c[1], UINT8_C (0x80), UINT8_C (0xBF)) && + _mongoc_utf8_code_unit_in_range (temp_c[2], UINT8_C (0x80), UINT8_C (0xBF)) && + _mongoc_utf8_code_unit_in_range (temp_c[3], UINT8_C (0x80), UINT8_C (0xBF))) || + (_mongoc_utf8_code_unit_in_range (temp_c[0], UINT8_C (0xF4), UINT8_C (0xF4)) && + _mongoc_utf8_code_unit_in_range (temp_c[1], UINT8_C (0x80), UINT8_C (0x8F)) && + _mongoc_utf8_code_unit_in_range (temp_c[2], UINT8_C (0x80), UINT8_C (0xBF)) && + _mongoc_utf8_code_unit_in_range (temp_c[3], UINT8_C (0x80), UINT8_C (0xBF))); default: return true; } @@ -1456,17 +1279,13 @@ _mongoc_utf8_first_code_point_is_valid (const char *c, size_t length) bool -_mongoc_utf8_code_unit_in_range (const uint8_t c, - const uint8_t lower, - const uint8_t upper) +_mongoc_utf8_code_unit_in_range (const uint8_t c, const uint8_t lower, const uint8_t upper) { return (c >= lower && c <= upper); } bool -_mongoc_utf8_code_point_is_in_table (uint32_t code, - const uint32_t *table, - size_t size) +_mongoc_utf8_code_point_is_in_table (uint32_t code, const uint32_t *table, size_t size) { BSON_ASSERT_PARAM (table); @@ -1489,17 +1308,13 @@ _mongoc_utf8_get_first_code_point (const char *c, size_t length) case 1: return (uint32_t) temp_c[0]; case 2: - return (uint32_t) (((temp_c[0] & UINT8_C (0x1f)) << 6) | - (temp_c[1] & UINT8_C (0x3f))); + return (uint32_t) (((temp_c[0] & UINT8_C (0x1f)) << 6) | (temp_c[1] & UINT8_C (0x3f))); case 3: - return (uint32_t) (((temp_c[0] & UINT8_C (0x0f)) << 12) | - ((temp_c[1] & UINT8_C (0x3f)) << 6) | + return (uint32_t) (((temp_c[0] & UINT8_C (0x0f)) << 12) | ((temp_c[1] & UINT8_C (0x3f)) << 6) | (temp_c[2] & UINT8_C (0x3f))); case 4: - return (uint32_t) (((temp_c[0] & UINT8_C (0x07)) << 18) | - ((temp_c[1] & UINT8_C (0x3f)) << 12) | - ((temp_c[2] & UINT8_C (0x3f)) << 6) | - (temp_c[3] & UINT8_C (0x3f))); + return (uint32_t) (((temp_c[0] & UINT8_C (0x07)) << 18) | ((temp_c[1] & UINT8_C (0x3f)) << 12) | + ((temp_c[2] & UINT8_C (0x3f)) << 6) | (temp_c[3] & UINT8_C (0x3f))); default: return 0; } diff --git a/src/libmongoc/src/mongoc/mongoc-secure-channel-private.h b/src/libmongoc/src/mongoc/mongoc-secure-channel-private.h index 78e6b0458f..5628aec048 100644 --- a/src/libmongoc/src/mongoc/mongoc-secure-channel-private.h +++ b/src/libmongoc/src/mongoc/mongoc-secure-channel-private.h @@ -34,30 +34,22 @@ BSON_BEGIN_DECLS char * -_mongoc_secure_channel_extract_subject (const char *filename, - const char *passphrase); +_mongoc_secure_channel_extract_subject (const char *filename, const char *passphrase); bool -mongoc_secure_channel_setup_ca ( - mongoc_stream_tls_secure_channel_t *secure_channel, mongoc_ssl_opt_t *opt); +mongoc_secure_channel_setup_ca (mongoc_stream_tls_secure_channel_t *secure_channel, mongoc_ssl_opt_t *opt); bool -mongoc_secure_channel_setup_crl ( - mongoc_stream_tls_secure_channel_t *secure_channel, mongoc_ssl_opt_t *opt); +mongoc_secure_channel_setup_crl (mongoc_stream_tls_secure_channel_t *secure_channel, mongoc_ssl_opt_t *opt); ssize_t -mongoc_secure_channel_read (mongoc_stream_tls_t *tls, - void *data, - size_t data_length); +mongoc_secure_channel_read (mongoc_stream_tls_t *tls, void *data, size_t data_length); ssize_t -mongoc_secure_channel_write (mongoc_stream_tls_t *tls, - const void *data, - size_t data_length); +mongoc_secure_channel_write (mongoc_stream_tls_t *tls, const void *data, size_t data_length); PCCERT_CONTEXT -mongoc_secure_channel_setup_certificate ( - mongoc_stream_tls_secure_channel_t *secure_channel, mongoc_ssl_opt_t *opt); +mongoc_secure_channel_setup_certificate (mongoc_stream_tls_secure_channel_t *secure_channel, mongoc_ssl_opt_t *opt); /* it may require 16k + some overhead to hold one decryptable block of data - do @@ -71,27 +63,17 @@ _mongoc_secure_channel_init_sec_buffer (SecBuffer *buffer, unsigned long buf_byte_size); void -_mongoc_secure_channel_init_sec_buffer_desc (SecBufferDesc *desc, - SecBuffer *buffer_array, - unsigned long buffer_count); +_mongoc_secure_channel_init_sec_buffer_desc (SecBufferDesc *desc, SecBuffer *buffer_array, unsigned long buffer_count); void -mongoc_secure_channel_realloc_buf (size_t *size, - uint8_t **buf, - size_t new_size); +mongoc_secure_channel_realloc_buf (size_t *size, uint8_t **buf, size_t new_size); bool -mongoc_secure_channel_handshake_step_1 (mongoc_stream_tls_t *tls, - char *hostname, - bson_error_t *error); +mongoc_secure_channel_handshake_step_1 (mongoc_stream_tls_t *tls, char *hostname, bson_error_t *error); bool -mongoc_secure_channel_handshake_step_2 (mongoc_stream_tls_t *tls, - char *hostname, - bson_error_t *error); +mongoc_secure_channel_handshake_step_2 (mongoc_stream_tls_t *tls, char *hostname, bson_error_t *error); bool -mongoc_secure_channel_handshake_step_3 (mongoc_stream_tls_t *tls, - char *hostname, - bson_error_t *error); +mongoc_secure_channel_handshake_step_3 (mongoc_stream_tls_t *tls, char *hostname, bson_error_t *error); BSON_END_DECLS diff --git a/src/libmongoc/src/mongoc/mongoc-secure-channel.c b/src/libmongoc/src/mongoc/mongoc-secure-channel.c index fd2007a59c..319613c59d 100644 --- a/src/libmongoc/src/mongoc/mongoc-secure-channel.c +++ b/src/libmongoc/src/mongoc/mongoc-secure-channel.c @@ -100,82 +100,66 @@ mongoc_secure_channel_setup_certificate_from_file (const char *filename) /* https://msdn.microsoft.com/en-us/library/windows/desktop/aa380264%28v=vs.85%29.aspx */ - CryptQueryObject ( - CERT_QUERY_OBJECT_BLOB, /* dwObjectType, blob or file */ - &public_blob, /* pvObject, Unicode filename */ - CERT_QUERY_CONTENT_FLAG_ALL, /* dwExpectedContentTypeFlags */ - CERT_QUERY_FORMAT_FLAG_ALL, /* dwExpectedFormatTypeFlags */ - 0, /* dwFlags, reserved for "future use" */ - NULL, /* pdwMsgAndCertEncodingType, OUT, unused */ - NULL, /* pdwContentType (dwExpectedContentTypeFlags), OUT, unused */ - NULL, /* pdwFormatType (dwExpectedFormatTypeFlags,), OUT, unused */ - NULL, /* phCertStore, OUT, HCERTSTORE.., unused, for now */ - NULL, /* phMsg, OUT, HCRYPTMSG, only for PKC7, unused */ - (const void **) &cert /* ppvContext, OUT, the Certificate Context */ + CryptQueryObject (CERT_QUERY_OBJECT_BLOB, /* dwObjectType, blob or file */ + &public_blob, /* pvObject, Unicode filename */ + CERT_QUERY_CONTENT_FLAG_ALL, /* dwExpectedContentTypeFlags */ + CERT_QUERY_FORMAT_FLAG_ALL, /* dwExpectedFormatTypeFlags */ + 0, /* dwFlags, reserved for "future use" */ + NULL, /* pdwMsgAndCertEncodingType, OUT, unused */ + NULL, /* pdwContentType (dwExpectedContentTypeFlags), OUT, unused */ + NULL, /* pdwFormatType (dwExpectedFormatTypeFlags,), OUT, unused */ + NULL, /* phCertStore, OUT, HCERTSTORE.., unused, for now */ + NULL, /* phMsg, OUT, HCRYPTMSG, only for PKC7, unused */ + (const void **) &cert /* ppvContext, OUT, the Certificate Context */ ); if (!cert) { - MONGOC_ERROR ("Failed to extract public key from '%s'. Error 0x%.8X", - filename, - (unsigned int) GetLastError ()); + MONGOC_ERROR ("Failed to extract public key from '%s'. Error 0x%.8X", filename, (unsigned int) GetLastError ()); goto fail; } /* https://msdn.microsoft.com/en-us/library/windows/desktop/aa380285%28v=vs.85%29.aspx */ - success = - CryptStringToBinaryA (pem_private, /* pszString */ - 0, /* cchString */ - CRYPT_STRING_BASE64HEADER, /* dwFlags */ - NULL, /* pbBinary */ - &encrypted_private_len, /* pcBinary, IN/OUT */ - NULL, /* pdwSkip */ - NULL); /* pdwFlags */ + success = CryptStringToBinaryA (pem_private, /* pszString */ + 0, /* cchString */ + CRYPT_STRING_BASE64HEADER, /* dwFlags */ + NULL, /* pbBinary */ + &encrypted_private_len, /* pcBinary, IN/OUT */ + NULL, /* pdwSkip */ + NULL); /* pdwFlags */ if (!success) { - MONGOC_ERROR ("Failed to convert base64 private key. Error 0x%.8X", - (unsigned int) GetLastError ()); + MONGOC_ERROR ("Failed to convert base64 private key. Error 0x%.8X", (unsigned int) GetLastError ()); goto fail; } encrypted_private = (LPBYTE) bson_malloc0 (encrypted_private_len); - success = CryptStringToBinaryA (pem_private, - 0, - CRYPT_STRING_BASE64HEADER, - encrypted_private, - &encrypted_private_len, - NULL, - NULL); + success = CryptStringToBinaryA ( + pem_private, 0, CRYPT_STRING_BASE64HEADER, encrypted_private, &encrypted_private_len, NULL, NULL); if (!success) { - MONGOC_ERROR ("Failed to convert base64 private key. Error 0x%.8X", - (unsigned int) GetLastError ()); + MONGOC_ERROR ("Failed to convert base64 private key. Error 0x%.8X", (unsigned int) GetLastError ()); goto fail; } /* https://msdn.microsoft.com/en-us/library/windows/desktop/aa379912%28v=vs.85%29.aspx */ - success = CryptDecodeObjectEx ( - X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, /* dwCertEncodingType */ - PKCS_RSA_PRIVATE_KEY, /* lpszStructType */ - encrypted_private, /* pbEncoded */ - encrypted_private_len, /* cbEncoded */ - 0, /* dwFlags */ - NULL, /* pDecodePara */ - NULL, /* pvStructInfo */ - &blob_private_len); /* pcbStructInfo */ + success = CryptDecodeObjectEx (X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, /* dwCertEncodingType */ + PKCS_RSA_PRIVATE_KEY, /* lpszStructType */ + encrypted_private, /* pbEncoded */ + encrypted_private_len, /* cbEncoded */ + 0, /* dwFlags */ + NULL, /* pDecodePara */ + NULL, /* pvStructInfo */ + &blob_private_len); /* pcbStructInfo */ if (!success) { LPTSTR msg = NULL; - FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_ARGUMENT_ARRAY, + FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY, NULL, GetLastError (), LANG_NEUTRAL, (LPTSTR) &msg, 0, NULL); - MONGOC_ERROR ("Failed to parse private key. %s (0x%.8X)", - msg, - (unsigned int) GetLastError ()); + MONGOC_ERROR ("Failed to parse private key. %s (0x%.8X)", msg, (unsigned int) GetLastError ()); LocalFree (msg); goto fail; } @@ -190,8 +174,7 @@ mongoc_secure_channel_setup_certificate_from_file (const char *filename) blob_private, &blob_private_len); if (!success) { - MONGOC_ERROR ("Failed to parse private key. Error 0x%.8X", - (unsigned int) GetLastError ()); + MONGOC_ERROR ("Failed to parse private key. Error 0x%.8X", (unsigned int) GetLastError ()); goto fail; } @@ -203,8 +186,7 @@ mongoc_secure_channel_setup_certificate_from_file (const char *filename) PROV_RSA_FULL, /* dwProvType */ CRYPT_VERIFYCONTEXT); /* dwFlags */ if (!success) { - MONGOC_ERROR ("CryptAcquireContext failed with error 0x%.8X", - (unsigned int) GetLastError ()); + MONGOC_ERROR ("CryptAcquireContext failed with error 0x%.8X", (unsigned int) GetLastError ()); goto fail; } @@ -217,25 +199,22 @@ mongoc_secure_channel_setup_certificate_from_file (const char *filename) 0, /* dwFlags */ &hKey); /* phKey, OUT */ if (!success) { - MONGOC_ERROR ("CryptImportKey for private key failed with error 0x%.8X", - (unsigned int) GetLastError ()); + MONGOC_ERROR ("CryptImportKey for private key failed with error 0x%.8X", (unsigned int) GetLastError ()); goto fail; } /* https://msdn.microsoft.com/en-us/library/windows/desktop/aa376573%28v=vs.85%29.aspx */ - success = CertSetCertificateContextProperty ( - cert, /* pCertContext */ - CERT_KEY_PROV_HANDLE_PROP_ID, /* dwPropId */ - 0, /* dwFlags */ - (const void *) provider); /* pvData */ + success = CertSetCertificateContextProperty (cert, /* pCertContext */ + CERT_KEY_PROV_HANDLE_PROP_ID, /* dwPropId */ + 0, /* dwFlags */ + (const void *) provider); /* pvData */ if (success) { TRACE ("%s", "Successfully loaded client certificate"); return cert; } - MONGOC_ERROR ("Can't associate private key with public key: 0x%.8X", - (unsigned int) GetLastError ()); + MONGOC_ERROR ("Can't associate private key with public key: 0x%.8X", (unsigned int) GetLastError ()); fail: SecureZeroMemory (pem, pem_length); @@ -254,20 +233,15 @@ mongoc_secure_channel_setup_certificate_from_file (const char *filename) } PCCERT_CONTEXT -mongoc_secure_channel_setup_certificate ( - mongoc_stream_tls_secure_channel_t *secure_channel, mongoc_ssl_opt_t *opt) +mongoc_secure_channel_setup_certificate (mongoc_stream_tls_secure_channel_t *secure_channel, mongoc_ssl_opt_t *opt) { return mongoc_secure_channel_setup_certificate_from_file (opt->pem_file); } void -_bson_append_szoid (bson_string_t *retval, - PCCERT_CONTEXT cert, - const char *label, - void *oid) +_bson_append_szoid (bson_string_t *retval, PCCERT_CONTEXT cert, const char *label, void *oid) { - DWORD oid_len = - CertGetNameString (cert, CERT_NAME_ATTR_TYPE, 0, oid, NULL, 0); + DWORD oid_len = CertGetNameString (cert, CERT_NAME_ATTR_TYPE, 0, oid, NULL, 0); if (oid_len > 1) { char *tmp = bson_malloc0 (oid_len); @@ -278,8 +252,7 @@ _bson_append_szoid (bson_string_t *retval, } } char * -_mongoc_secure_channel_extract_subject (const char *filename, - const char *passphrase) +_mongoc_secure_channel_extract_subject (const char *filename, const char *passphrase) { bson_string_t *retval; PCCERT_CONTEXT cert; @@ -303,8 +276,7 @@ _mongoc_secure_channel_extract_subject (const char *filename, } bool -mongoc_secure_channel_setup_ca ( - mongoc_stream_tls_secure_channel_t *secure_channel, mongoc_ssl_opt_t *opt) +mongoc_secure_channel_setup_ca (mongoc_stream_tls_secure_channel_t *secure_channel, mongoc_ssl_opt_t *opt) { FILE *file; long length; @@ -341,53 +313,36 @@ mongoc_secure_channel_setup_ca ( return false; } - if (!CryptStringToBinaryA (pem_key, - 0, - CRYPT_STRING_BASE64HEADER, - NULL, - &encrypted_cert_len, - NULL, - NULL)) { - MONGOC_ERROR ("Failed to convert BASE64 public key. Error 0x%.8X", - (unsigned int) GetLastError ()); + if (!CryptStringToBinaryA (pem_key, 0, CRYPT_STRING_BASE64HEADER, NULL, &encrypted_cert_len, NULL, NULL)) { + MONGOC_ERROR ("Failed to convert BASE64 public key. Error 0x%.8X", (unsigned int) GetLastError ()); return false; } encrypted_cert = (LPBYTE) LocalAlloc (0, encrypted_cert_len); - if (!CryptStringToBinaryA (pem_key, - 0, - CRYPT_STRING_BASE64HEADER, - encrypted_cert, - &encrypted_cert_len, - NULL, - NULL)) { - MONGOC_ERROR ("Failed to convert BASE64 public key. Error 0x%.8X", - (unsigned int) GetLastError ()); + if (!CryptStringToBinaryA (pem_key, 0, CRYPT_STRING_BASE64HEADER, encrypted_cert, &encrypted_cert_len, NULL, NULL)) { + MONGOC_ERROR ("Failed to convert BASE64 public key. Error 0x%.8X", (unsigned int) GetLastError ()); return false; } - cert = CertCreateCertificateContext ( - X509_ASN_ENCODING, encrypted_cert, encrypted_cert_len); + cert = CertCreateCertificateContext (X509_ASN_ENCODING, encrypted_cert, encrypted_cert_len); if (!cert) { MONGOC_WARNING ("Could not convert certificate"); return false; } - cert_store = CertOpenStore ( - CERT_STORE_PROV_SYSTEM, /* provider */ - X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, /* certificate encoding */ - 0, /* unused */ - CERT_SYSTEM_STORE_LOCAL_MACHINE, /* dwFlags */ - L"Root"); /* system store name. "My" or "Root" */ + cert_store = CertOpenStore (CERT_STORE_PROV_SYSTEM, /* provider */ + X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, /* certificate encoding */ + 0, /* unused */ + CERT_SYSTEM_STORE_LOCAL_MACHINE, /* dwFlags */ + L"Root"); /* system store name. "My" or "Root" */ if (cert_store == NULL) { MONGOC_ERROR ("Error opening certificate store"); return false; } - if (CertAddCertificateContextToStore ( - cert_store, cert, CERT_STORE_ADD_USE_EXISTING, NULL)) { + if (CertAddCertificateContextToStore (cert_store, cert, CERT_STORE_ADD_USE_EXISTING, NULL)) { TRACE ("%s", "Added the certificate !"); CertCloseStore (cert_store, 0); return true; @@ -399,8 +354,7 @@ mongoc_secure_channel_setup_ca ( } bool -mongoc_secure_channel_setup_crl ( - mongoc_stream_tls_secure_channel_t *secure_channel, mongoc_ssl_opt_t *opt) +mongoc_secure_channel_setup_crl (mongoc_stream_tls_secure_channel_t *secure_channel, mongoc_ssl_opt_t *opt) { HCERTSTORE cert_store = NULL; PCCERT_CONTEXT cert = NULL; @@ -418,18 +372,17 @@ mongoc_secure_channel_setup_crl ( /* https://msdn.microsoft.com/en-us/library/windows/desktop/aa380264%28v=vs.85%29.aspx */ - CryptQueryObject ( - CERT_QUERY_OBJECT_FILE, /* dwObjectType, blob or file */ - str, /* pvObject, Unicode filename */ - CERT_QUERY_CONTENT_FLAG_CRL, /* dwExpectedContentTypeFlags */ - CERT_QUERY_FORMAT_FLAG_ALL, /* dwExpectedFormatTypeFlags */ - 0, /* dwFlags, reserved for "future use" */ - NULL, /* pdwMsgAndCertEncodingType, OUT, unused */ - NULL, /* pdwContentType (dwExpectedContentTypeFlags), OUT, unused */ - NULL, /* pdwFormatType (dwExpectedFormatTypeFlags,), OUT, unused */ - NULL, /* phCertStore, OUT, HCERTSTORE.., unused, for now */ - NULL, /* phMsg, OUT, HCRYPTMSG, only for PKC7, unused */ - (const void **) &cert /* ppvContext, OUT, the Certificate Context */ + CryptQueryObject (CERT_QUERY_OBJECT_FILE, /* dwObjectType, blob or file */ + str, /* pvObject, Unicode filename */ + CERT_QUERY_CONTENT_FLAG_CRL, /* dwExpectedContentTypeFlags */ + CERT_QUERY_FORMAT_FLAG_ALL, /* dwExpectedFormatTypeFlags */ + 0, /* dwFlags, reserved for "future use" */ + NULL, /* pdwMsgAndCertEncodingType, OUT, unused */ + NULL, /* pdwContentType (dwExpectedContentTypeFlags), OUT, unused */ + NULL, /* pdwFormatType (dwExpectedFormatTypeFlags,), OUT, unused */ + NULL, /* phCertStore, OUT, HCERTSTORE.., unused, for now */ + NULL, /* phMsg, OUT, HCRYPTMSG, only for PKC7, unused */ + (const void **) &cert /* ppvContext, OUT, the Certificate Context */ ); bson_free (str); @@ -439,12 +392,11 @@ mongoc_secure_channel_setup_crl ( } - cert_store = CertOpenStore ( - CERT_STORE_PROV_SYSTEM, /* provider */ - X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, /* certificate encoding */ - 0, /* unused */ - CERT_SYSTEM_STORE_LOCAL_MACHINE, /* dwFlags */ - L"Root"); /* system store name. "My" or "Root" */ + cert_store = CertOpenStore (CERT_STORE_PROV_SYSTEM, /* provider */ + X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, /* certificate encoding */ + 0, /* unused */ + CERT_SYSTEM_STORE_LOCAL_MACHINE, /* dwFlags */ + L"Root"); /* system store name. "My" or "Root" */ if (cert_store == NULL) { MONGOC_ERROR ("Error opening certificate store"); @@ -452,8 +404,7 @@ mongoc_secure_channel_setup_crl ( return false; } - if (CertAddCertificateContextToStore ( - cert_store, cert, CERT_STORE_ADD_USE_EXISTING, NULL)) { + if (CertAddCertificateContextToStore (cert_store, cert, CERT_STORE_ADD_USE_EXISTING, NULL)) { TRACE ("%s", "Added the certificate !"); CertFreeCertificateContext (cert); CertCloseStore (cert_store, 0); @@ -468,30 +419,23 @@ mongoc_secure_channel_setup_crl ( } ssize_t -mongoc_secure_channel_read (mongoc_stream_tls_t *tls, - void *data, - size_t data_length) +mongoc_secure_channel_read (mongoc_stream_tls_t *tls, void *data, size_t data_length) { BSON_ASSERT_PARAM (tls); if (BSON_UNLIKELY (!bson_in_range_signed (int32_t, tls->timeout_msec))) { // CDRIVER-4589 - MONGOC_ERROR ("timeout_msec value %" PRId64 - " exceeds supported 32-bit range", - tls->timeout_msec); + MONGOC_ERROR ("timeout_msec value %" PRId64 " exceeds supported 32-bit range", tls->timeout_msec); return -1; } errno = 0; - TRACE ("Wanting to read: %zu, timeout is %" PRIu64, - data_length, - tls->timeout_msec); + TRACE ("Wanting to read: %zu, timeout is %" PRIu64, data_length, tls->timeout_msec); /* 4th argument is minimum bytes, while the data_length is the * size of the buffer. We are totally fine with just one TLS record (few *bytes) **/ - const ssize_t length = mongoc_stream_read ( - tls->base_stream, data, data_length, 0, (int32_t) tls->timeout_msec); + const ssize_t length = mongoc_stream_read (tls->base_stream, data, data_length, 0, (int32_t) tls->timeout_msec); TRACE ("Got %zd", length); @@ -503,26 +447,20 @@ mongoc_secure_channel_read (mongoc_stream_tls_t *tls, } ssize_t -mongoc_secure_channel_write (mongoc_stream_tls_t *tls, - const void *data, - size_t data_length) +mongoc_secure_channel_write (mongoc_stream_tls_t *tls, const void *data, size_t data_length) { BSON_ASSERT_PARAM (tls); if (BSON_UNLIKELY (!bson_in_range_signed (int32_t, tls->timeout_msec))) { // CDRIVER-4589 - MONGOC_ERROR ("timeout_msec value %" PRId64 - " exceeds supported 32-bit range", - tls->timeout_msec); + MONGOC_ERROR ("timeout_msec value %" PRId64 " exceeds supported 32-bit range", tls->timeout_msec); return -1; } errno = 0; TRACE ("Wanting to write: %zu", data_length); - const ssize_t length = mongoc_stream_write (tls->base_stream, - (void *) data, - data_length, - (int32_t) tls->timeout_msec); + const ssize_t length = + mongoc_stream_write (tls->base_stream, (void *) data, data_length, (int32_t) tls->timeout_msec); TRACE ("Wrote: %zd", length); return length; @@ -579,9 +517,7 @@ _mongoc_secure_channel_init_sec_buffer (SecBuffer *buffer, } void -_mongoc_secure_channel_init_sec_buffer_desc (SecBufferDesc *desc, - SecBuffer *buffer_array, - unsigned long buffer_count) +_mongoc_secure_channel_init_sec_buffer_desc (SecBufferDesc *desc, SecBuffer *buffer_array, unsigned long buffer_count) { desc->ulVersion = SECBUFFER_VERSION; desc->pBuffers = buffer_array; @@ -596,16 +532,13 @@ _mongoc_secure_channel_init_sec_buffer_desc (SecBufferDesc *desc, } while (0) bool -mongoc_secure_channel_handshake_step_1 (mongoc_stream_tls_t *tls, - char *hostname, - bson_error_t *error) +mongoc_secure_channel_handshake_step_1 (mongoc_stream_tls_t *tls, char *hostname, bson_error_t *error) { SecBuffer outbuf; ssize_t written = -1; SecBufferDesc outbuf_desc; SECURITY_STATUS sspi_status = SEC_E_OK; - mongoc_stream_tls_secure_channel_t *secure_channel = - (mongoc_stream_tls_secure_channel_t *) tls->ctx; + mongoc_stream_tls_secure_channel_t *secure_channel = (mongoc_stream_tls_secure_channel_t *) tls->ctx; TRACE ("SSL/TLS connection with '%s' (step 1/3)", hostname); @@ -614,28 +547,25 @@ mongoc_secure_channel_handshake_step_1 (mongoc_stream_tls_t *tls, _mongoc_secure_channel_init_sec_buffer_desc (&outbuf_desc, &outbuf, 1); /* setup request flags */ - secure_channel->req_flags = ISC_REQ_SEQUENCE_DETECT | ISC_REQ_REPLAY_DETECT | - ISC_REQ_CONFIDENTIALITY | + secure_channel->req_flags = ISC_REQ_SEQUENCE_DETECT | ISC_REQ_REPLAY_DETECT | ISC_REQ_CONFIDENTIALITY | ISC_REQ_ALLOCATE_MEMORY | ISC_REQ_STREAM; /* allocate memory for the security context handle */ - secure_channel->ctxt = (mongoc_secure_channel_ctxt *) bson_malloc0 ( - sizeof (mongoc_secure_channel_ctxt)); + secure_channel->ctxt = (mongoc_secure_channel_ctxt *) bson_malloc0 (sizeof (mongoc_secure_channel_ctxt)); /* https://msdn.microsoft.com/en-us/library/windows/desktop/aa375924.aspx */ - sspi_status = InitializeSecurityContext ( - &secure_channel->cred->cred_handle, /* phCredential */ - NULL, /* phContext */ - hostname, /* pszTargetName */ - secure_channel->req_flags, /* fContextReq */ - 0, /* Reserved1, must be 0 */ - 0, /* TargetDataRep, unused */ - NULL, /* pInput */ - 0, /* Reserved2, must be 0 */ - &secure_channel->ctxt->ctxt_handle, /* phNewContext OUT param */ - &outbuf_desc, /* pOutput OUT param */ - &secure_channel->ret_flags, /* pfContextAttr OUT param */ - &secure_channel->ctxt->time_stamp /* ptsExpiry OUT param */ + sspi_status = InitializeSecurityContext (&secure_channel->cred->cred_handle, /* phCredential */ + NULL, /* phContext */ + hostname, /* pszTargetName */ + secure_channel->req_flags, /* fContextReq */ + 0, /* Reserved1, must be 0 */ + 0, /* TargetDataRep, unused */ + NULL, /* pInput */ + 0, /* Reserved2, must be 0 */ + &secure_channel->ctxt->ctxt_handle, /* phNewContext OUT param */ + &outbuf_desc, /* pOutput OUT param */ + &secure_channel->ret_flags, /* pfContextAttr OUT param */ + &secure_channel->ctxt->time_stamp /* ptsExpiry OUT param */ ); if (sspi_status != SEC_I_CONTINUE_NEEDED) { @@ -647,12 +577,10 @@ mongoc_secure_channel_handshake_step_1 (mongoc_stream_tls_t *tls, return false; } - TRACE ("sending initial handshake data: sending %lu bytes...", - outbuf.cbBuffer); + TRACE ("sending initial handshake data: sending %lu bytes...", outbuf.cbBuffer); /* send initial handshake data which is now stored in output buffer */ - written = - mongoc_secure_channel_write (tls, outbuf.pvBuffer, outbuf.cbBuffer); + written = mongoc_secure_channel_write (tls, outbuf.pvBuffer, outbuf.cbBuffer); FreeContextBuffer (outbuf.pvBuffer); if (outbuf.cbBuffer != (size_t) written) { @@ -679,12 +607,9 @@ mongoc_secure_channel_handshake_step_1 (mongoc_stream_tls_t *tls, } bool -mongoc_secure_channel_handshake_step_2 (mongoc_stream_tls_t *tls, - char *hostname, - bson_error_t *error) +mongoc_secure_channel_handshake_step_2 (mongoc_stream_tls_t *tls, char *hostname, bson_error_t *error) { - mongoc_stream_tls_secure_channel_t *secure_channel = - (mongoc_stream_tls_secure_channel_t *) tls->ctx; + mongoc_stream_tls_secure_channel_t *secure_channel = (mongoc_stream_tls_secure_channel_t *) tls->ctx; SECURITY_STATUS sspi_status = SEC_E_OK; ssize_t nread = -1, written = -1; SecBufferDesc outbuf_desc; @@ -694,36 +619,29 @@ mongoc_secure_channel_handshake_step_2 (mongoc_stream_tls_t *tls, bool doread; int i; - doread = (secure_channel->connecting_state != ssl_connect_2_writing) ? true - : false; + doread = (secure_channel->connecting_state != ssl_connect_2_writing) ? true : false; TRACE ("%s", "SSL/TLS connection with endpoint (step 2/3)"); if (!secure_channel->cred || !secure_channel->ctxt) { MONGOC_LOG_AND_SET_ERROR ( - error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_SOCKET, - "required TLS credentials or context not provided"); + error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "required TLS credentials or context not provided"); return false; } /* grow the buffer if necessary */ if (secure_channel->encdata_length == secure_channel->encdata_offset) { - mongoc_secure_channel_realloc_buf (&secure_channel->encdata_length, - &secure_channel->encdata_buffer, - secure_channel->encdata_length + 1); + mongoc_secure_channel_realloc_buf ( + &secure_channel->encdata_length, &secure_channel->encdata_buffer, secure_channel->encdata_length + 1); } for (;;) { if (doread) { /* read encrypted handshake data from socket */ - nread = mongoc_secure_channel_read ( - tls, - (char *) (secure_channel->encdata_buffer + - secure_channel->encdata_offset), - secure_channel->encdata_length - secure_channel->encdata_offset); + nread = mongoc_secure_channel_read (tls, + (char *) (secure_channel->encdata_buffer + secure_channel->encdata_offset), + secure_channel->encdata_length - secure_channel->encdata_offset); if (!nread) { if (MONGOC_ERRNO_IS_AGAIN (errno)) { @@ -735,11 +653,10 @@ mongoc_secure_channel_handshake_step_2 (mongoc_stream_tls_t *tls, return true; } - MONGOC_LOG_AND_SET_ERROR ( - error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_SOCKET, - "failed to receive handshake, SSL/TLS connection failed"); + MONGOC_LOG_AND_SET_ERROR (error, + MONGOC_ERROR_STREAM, + MONGOC_ERROR_STREAM_SOCKET, + "failed to receive handshake, SSL/TLS connection failed"); return false; } @@ -753,53 +670,41 @@ mongoc_secure_channel_handshake_step_2 (mongoc_stream_tls_t *tls, (int) secure_channel->encdata_length); /* setup input buffers */ - _mongoc_secure_channel_init_sec_buffer ( - &inbuf[0], - SECBUFFER_TOKEN, - bson_malloc (secure_channel->encdata_offset), - (unsigned long) (secure_channel->encdata_offset & - (size_t) 0xFFFFFFFFUL)); - _mongoc_secure_channel_init_sec_buffer ( - &inbuf[1], SECBUFFER_EMPTY, NULL, 0); + _mongoc_secure_channel_init_sec_buffer (&inbuf[0], + SECBUFFER_TOKEN, + bson_malloc (secure_channel->encdata_offset), + (unsigned long) (secure_channel->encdata_offset & (size_t) 0xFFFFFFFFUL)); + _mongoc_secure_channel_init_sec_buffer (&inbuf[1], SECBUFFER_EMPTY, NULL, 0); _mongoc_secure_channel_init_sec_buffer_desc (&inbuf_desc, inbuf, 2); /* setup output buffers */ - _mongoc_secure_channel_init_sec_buffer ( - &outbuf[0], SECBUFFER_TOKEN, NULL, 0); - _mongoc_secure_channel_init_sec_buffer ( - &outbuf[1], SECBUFFER_ALERT, NULL, 0); - _mongoc_secure_channel_init_sec_buffer ( - &outbuf[2], SECBUFFER_EMPTY, NULL, 0); + _mongoc_secure_channel_init_sec_buffer (&outbuf[0], SECBUFFER_TOKEN, NULL, 0); + _mongoc_secure_channel_init_sec_buffer (&outbuf[1], SECBUFFER_ALERT, NULL, 0); + _mongoc_secure_channel_init_sec_buffer (&outbuf[2], SECBUFFER_EMPTY, NULL, 0); _mongoc_secure_channel_init_sec_buffer_desc (&outbuf_desc, outbuf, 3); if (inbuf[0].pvBuffer == NULL) { - MONGOC_LOG_AND_SET_ERROR (error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_SOCKET, - "unable to allocate memory"); + MONGOC_LOG_AND_SET_ERROR (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "unable to allocate memory"); return false; } /* copy received handshake data into input buffer */ - memcpy (inbuf[0].pvBuffer, - secure_channel->encdata_buffer, - secure_channel->encdata_offset); + memcpy (inbuf[0].pvBuffer, secure_channel->encdata_buffer, secure_channel->encdata_offset); /* https://msdn.microsoft.com/en-us/library/windows/desktop/aa375924.aspx */ - sspi_status = - InitializeSecurityContext (&secure_channel->cred->cred_handle, - &secure_channel->ctxt->ctxt_handle, - hostname, - secure_channel->req_flags, - 0, - 0, - &inbuf_desc, - 0, - NULL, - &outbuf_desc, - &secure_channel->ret_flags, - &secure_channel->ctxt->time_stamp); + sspi_status = InitializeSecurityContext (&secure_channel->cred->cred_handle, + &secure_channel->ctxt->ctxt_handle, + hostname, + secure_channel->req_flags, + 0, + 0, + &inbuf_desc, + 0, + NULL, + &outbuf_desc, + &secure_channel->ret_flags, + &secure_channel->ctxt->time_stamp); /* free buffer for received handshake data */ bson_free (inbuf[0].pvBuffer); @@ -814,8 +719,7 @@ mongoc_secure_channel_handshake_step_2 (mongoc_stream_tls_t *tls, /* If the server has requested a client certificate, attempt to continue * the handshake without one. This will allow connections to servers which * request a client certificate but do not require it. */ - if (sspi_status == SEC_I_INCOMPLETE_CREDENTIALS && - !(secure_channel->req_flags & ISC_REQ_USE_SUPPLIED_CREDS)) { + if (sspi_status == SEC_I_INCOMPLETE_CREDENTIALS && !(secure_channel->req_flags & ISC_REQ_USE_SUPPLIED_CREDS)) { secure_channel->req_flags |= ISC_REQ_USE_SUPPLIED_CREDS; secure_channel->connecting_state = ssl_connect_2_writing; TRACE ("%s", "A client certificate has been requested"); @@ -826,24 +730,20 @@ mongoc_secure_channel_handshake_step_2 (mongoc_stream_tls_t *tls, if (sspi_status == SEC_I_CONTINUE_NEEDED || sspi_status == SEC_E_OK) { for (i = 0; i < 3; i++) { /* search for handshake tokens that need to be send */ - if (outbuf[i].BufferType == SECBUFFER_TOKEN && - outbuf[i].cbBuffer > 0) { - TRACE ("sending next handshake data: sending %lu bytes...", - outbuf[i].cbBuffer); + if (outbuf[i].BufferType == SECBUFFER_TOKEN && outbuf[i].cbBuffer > 0) { + TRACE ("sending next handshake data: sending %lu bytes...", outbuf[i].cbBuffer); /* send handshake token to server */ - written = mongoc_secure_channel_write ( - tls, outbuf[i].pvBuffer, outbuf[i].cbBuffer); + written = mongoc_secure_channel_write (tls, outbuf[i].pvBuffer, outbuf[i].cbBuffer); if (outbuf[i].cbBuffer != (size_t) written) { - MONGOC_LOG_AND_SET_ERROR ( - error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_SOCKET, - "failed to send next handshake data: " - "sent %zd of %lu bytes", - written, - outbuf[i].cbBuffer); + MONGOC_LOG_AND_SET_ERROR (error, + MONGOC_ERROR_STREAM, + MONGOC_ERROR_STREAM_SOCKET, + "failed to send next handshake data: " + "sent %zd of %lu bytes", + written, + outbuf[i].cbBuffer); return false; } } @@ -856,38 +756,34 @@ mongoc_secure_channel_handshake_step_2 (mongoc_stream_tls_t *tls, } else { switch (sspi_status) { case SEC_E_WRONG_PRINCIPAL: - MONGOC_LOG_AND_SET_ERROR ( - error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_SOCKET, - "SSL Certification verification failed: hostname " - "doesn't match certificate"); + MONGOC_LOG_AND_SET_ERROR (error, + MONGOC_ERROR_STREAM, + MONGOC_ERROR_STREAM_SOCKET, + "SSL Certification verification failed: hostname " + "doesn't match certificate"); break; case SEC_E_UNTRUSTED_ROOT: - MONGOC_LOG_AND_SET_ERROR ( - error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_SOCKET, - "SSL Certification verification failed: Untrusted " - "root certificate"); + MONGOC_LOG_AND_SET_ERROR (error, + MONGOC_ERROR_STREAM, + MONGOC_ERROR_STREAM_SOCKET, + "SSL Certification verification failed: Untrusted " + "root certificate"); break; case SEC_E_CERT_EXPIRED: - MONGOC_LOG_AND_SET_ERROR ( - error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_SOCKET, - "SSL Certification verification failed: certificate " - "has expired"); + MONGOC_LOG_AND_SET_ERROR (error, + MONGOC_ERROR_STREAM, + MONGOC_ERROR_STREAM_SOCKET, + "SSL Certification verification failed: certificate " + "has expired"); break; case CRYPT_E_NO_REVOCATION_CHECK: - MONGOC_LOG_AND_SET_ERROR ( - error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_SOCKET, - "SSL Certification verification failed: certificate " - "does not include revocation check."); + MONGOC_LOG_AND_SET_ERROR (error, + MONGOC_ERROR_STREAM, + MONGOC_ERROR_STREAM_SOCKET, + "SSL Certification verification failed: certificate " + "does not include revocation check."); break; case SEC_E_INSUFFICIENT_MEMORY: @@ -908,24 +804,21 @@ mongoc_secure_channel_handshake_step_2 (mongoc_stream_tls_t *tls, default: { LPTSTR msg = NULL; - FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_ARGUMENT_ARRAY, + FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY, NULL, GetLastError (), LANG_NEUTRAL, (LPTSTR) &msg, 0, NULL); - MONGOC_LOG_AND_SET_ERROR ( - error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_SOCKET, - "Failed to initialize security context, error code: " - "0x%04X%04X: %s", - (unsigned int) (sspi_status >> 16) & 0xffff, - (unsigned int) sspi_status & 0xffff, - msg); + MONGOC_LOG_AND_SET_ERROR (error, + MONGOC_ERROR_STREAM, + MONGOC_ERROR_STREAM_SOCKET, + "Failed to initialize security context, error code: " + "0x%04X%04X: %s", + (unsigned int) (sspi_status >> 16) & 0xffff, + (unsigned int) sspi_status & 0xffff, + msg); LocalFree (msg); } } @@ -950,9 +843,7 @@ mongoc_secure_channel_handshake_step_2 (mongoc_stream_tls_t *tls, * and therefore begins after the already processed data */ if (secure_channel->encdata_offset > inbuf[1].cbBuffer) { memmove (secure_channel->encdata_buffer, - (secure_channel->encdata_buffer + - secure_channel->encdata_offset) - - inbuf[1].cbBuffer, + (secure_channel->encdata_buffer + secure_channel->encdata_offset) - inbuf[1].cbBuffer, inbuf[1].cbBuffer); secure_channel->encdata_offset = inbuf[1].cbBuffer; @@ -984,31 +875,23 @@ mongoc_secure_channel_handshake_step_2 (mongoc_stream_tls_t *tls, } bool -mongoc_secure_channel_handshake_step_3 (mongoc_stream_tls_t *tls, - char *hostname, - bson_error_t *error) +mongoc_secure_channel_handshake_step_3 (mongoc_stream_tls_t *tls, char *hostname, bson_error_t *error) { - mongoc_stream_tls_secure_channel_t *secure_channel = - (mongoc_stream_tls_secure_channel_t *) tls->ctx; + mongoc_stream_tls_secure_channel_t *secure_channel = (mongoc_stream_tls_secure_channel_t *) tls->ctx; BSON_ASSERT (ssl_connect_3 == secure_channel->connecting_state); TRACE ("SSL/TLS connection with %s (step 3/3)", hostname); if (!secure_channel->cred) { - MONGOC_LOG_AND_SET_ERROR (error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_SOCKET, - "required TLS credentials not provided"); + MONGOC_LOG_AND_SET_ERROR ( + error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "required TLS credentials not provided"); return false; } /* check if the required context attributes are met */ if (secure_channel->ret_flags != secure_channel->req_flags) { - MONGOC_LOG_AND_SET_ERROR (error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_SOCKET, - "Failed handshake"); + MONGOC_LOG_AND_SET_ERROR (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "Failed handshake"); return false; } diff --git a/src/libmongoc/src/mongoc/mongoc-secure-transport-private.h b/src/libmongoc/src/mongoc/mongoc-secure-transport-private.h index c54038373a..0fbb922555 100644 --- a/src/libmongoc/src/mongoc/mongoc-secure-transport-private.h +++ b/src/libmongoc/src/mongoc/mongoc-secure-transport-private.h @@ -32,27 +32,19 @@ char * _mongoc_cfstringref_to_cstring (CFStringRef ref); char * -_mongoc_secure_transport_extract_subject (const char *filename, - const char *passphrase); +_mongoc_secure_transport_extract_subject (const char *filename, const char *passphrase); OSStatus -mongoc_secure_transport_write (SSLConnectionRef connection, - const void *data, - size_t *data_length); +mongoc_secure_transport_write (SSLConnectionRef connection, const void *data, size_t *data_length); OSStatus -mongoc_secure_transport_read (SSLConnectionRef connection, - void *data, - size_t *data_length); +mongoc_secure_transport_read (SSLConnectionRef connection, void *data, size_t *data_length); bool -mongoc_secure_transport_setup_ca ( - mongoc_stream_tls_secure_transport_t *secure_transport, - mongoc_ssl_opt_t *opt); +mongoc_secure_transport_setup_ca (mongoc_stream_tls_secure_transport_t *secure_transport, mongoc_ssl_opt_t *opt); bool -mongoc_secure_transport_setup_certificate ( - mongoc_stream_tls_secure_transport_t *secure_transport, - mongoc_ssl_opt_t *opt); +mongoc_secure_transport_setup_certificate (mongoc_stream_tls_secure_transport_t *secure_transport, + mongoc_ssl_opt_t *opt); void CFReleaseSafe (CFTypeRef cf); diff --git a/src/libmongoc/src/mongoc/mongoc-secure-transport.c b/src/libmongoc/src/mongoc/mongoc-secure-transport.c index 97437e0d78..cdaab6d479 100644 --- a/src/libmongoc/src/mongoc/mongoc-secure-transport.c +++ b/src/libmongoc/src/mongoc/mongoc-secure-transport.c @@ -45,9 +45,7 @@ * best solution. */ SecIdentityRef -SecIdentityCreate (CFAllocatorRef allocator, - SecCertificateRef certificate, - SecKeyRef privateKey); +SecIdentityCreate (CFAllocatorRef allocator, SecCertificateRef certificate, SecKeyRef privateKey); #undef MONGOC_LOG_DOMAIN #define MONGOC_LOG_DOMAIN "stream-secure_transport" @@ -114,8 +112,7 @@ _mongoc_secure_transport_dict_get (CFArrayRef values, CFStringRef label) } item_label = CFDictionaryGetValue (item, kSecPropertyKeyLabel); - if (item_label && - CFStringCompare (item_label, label, 0) == kCFCompareEqualTo) { + if (item_label && CFStringCompare (item_label, label, 0) == kCFCompareEqualTo) { return CFDictionaryGetValue (item, kSecPropertyKeyValue); } } @@ -154,20 +151,16 @@ _mongoc_secure_transport_RFC2253_from_cert (SecCertificateRef cert) value = _mongoc_secure_transport_dict_get (subject_name, kSecOIDCountryName); _bson_append_cftyperef (retval, "C=", value); - value = _mongoc_secure_transport_dict_get (subject_name, - kSecOIDStateProvinceName); + value = _mongoc_secure_transport_dict_get (subject_name, kSecOIDStateProvinceName); _bson_append_cftyperef (retval, ",ST=", value); - value = - _mongoc_secure_transport_dict_get (subject_name, kSecOIDLocalityName); + value = _mongoc_secure_transport_dict_get (subject_name, kSecOIDLocalityName); _bson_append_cftyperef (retval, ",L=", value); - value = - _mongoc_secure_transport_dict_get (subject_name, kSecOIDOrganizationName); + value = _mongoc_secure_transport_dict_get (subject_name, kSecOIDOrganizationName); _bson_append_cftyperef (retval, ",O=", value); - value = _mongoc_secure_transport_dict_get (subject_name, - kSecOIDOrganizationalUnitName); + value = _mongoc_secure_transport_dict_get (subject_name, kSecOIDOrganizationalUnitName); if (value) { /* Can be either one unit name, or array of unit names */ if (CFGetTypeID (value) == CFStringGetTypeID ()) { @@ -176,16 +169,13 @@ _mongoc_secure_transport_RFC2253_from_cert (SecCertificateRef cert) CFIndex len = CFArrayGetCount (value); if (len > 0) { - _bson_append_cftyperef ( - retval, ",OU=", CFArrayGetValueAtIndex (value, 0)); + _bson_append_cftyperef (retval, ",OU=", CFArrayGetValueAtIndex (value, 0)); } if (len > 1) { - _bson_append_cftyperef ( - retval, ",", CFArrayGetValueAtIndex (value, 1)); + _bson_append_cftyperef (retval, ",", CFArrayGetValueAtIndex (value, 1)); } if (len > 2) { - _bson_append_cftyperef ( - retval, ",", CFArrayGetValueAtIndex (value, 2)); + _bson_append_cftyperef (retval, ",", CFArrayGetValueAtIndex (value, 2)); } } } @@ -193,8 +183,7 @@ _mongoc_secure_transport_RFC2253_from_cert (SecCertificateRef cert) value = _mongoc_secure_transport_dict_get (subject_name, kSecOIDCommonName); _bson_append_cftyperef (retval, ",CN=", value); - value = - _mongoc_secure_transport_dict_get (subject_name, kSecOIDStreetAddress); + value = _mongoc_secure_transport_dict_get (subject_name, kSecOIDStreetAddress); _bson_append_cftyperef (retval, ",STREET", value); CFRelease (cert_dict); @@ -242,16 +231,14 @@ _mongoc_secure_transport_import_pem (const char *filename, params.keyAttributes = NULL; if (passphrase) { - params.passphrase = CFStringCreateWithCString ( - kCFAllocatorDefault, passphrase, kCFStringEncodingUTF8); + params.passphrase = CFStringCreateWithCString (kCFAllocatorDefault, passphrase, kCFStringEncodingUTF8); } - url = CFURLCreateFromFileSystemRepresentation ( - kCFAllocatorDefault, (const UInt8 *) filename, strlen (filename), false); + url = + CFURLCreateFromFileSystemRepresentation (kCFAllocatorDefault, (const UInt8 *) filename, strlen (filename), false); read_stream = CFReadStreamCreateWithFile (kCFAllocatorDefault, url); if (!CFReadStreamOpen (read_stream)) { - MONGOC_ERROR ("Cannot find certificate in '%s', error reading file", - filename); + MONGOC_ERROR ("Cannot find certificate in '%s', error reading file", filename); goto done; } @@ -261,16 +248,13 @@ _mongoc_secure_transport_import_pem (const char *filename, if (error) { CFStringRef str = CFErrorCopyDescription (error); MONGOC_ERROR ( - "Failed importing PEM '%s': %s", - filename, - CFStringGetCStringPtr (str, CFStringGetFastestEncoding (str))); + "Failed importing PEM '%s': %s", filename, CFStringGetCStringPtr (str, CFStringGetFastestEncoding (str))); CFRelease (str); goto done; } - res = SecItemImport ( - dataref, CFSTR (".pem"), &format, type, 0, ¶ms, NULL, items); + res = SecItemImport (dataref, CFSTR (".pem"), &format, type, 0, ¶ms, NULL, items); if (res) { MONGOC_ERROR ("Failed importing PEM '%s' (code: %d)", filename, res); @@ -290,8 +274,7 @@ _mongoc_secure_transport_import_pem (const char *filename, } char * -_mongoc_secure_transport_extract_subject (const char *filename, - const char *passphrase) +_mongoc_secure_transport_extract_subject (const char *filename, const char *passphrase) { bool success; char *retval = NULL; @@ -299,8 +282,7 @@ _mongoc_secure_transport_extract_subject (const char *filename, SecExternalItemType type = kSecItemTypeCertificate; - success = - _mongoc_secure_transport_import_pem (filename, passphrase, &items, &type); + success = _mongoc_secure_transport_import_pem (filename, passphrase, &items, &type); if (!success) { return NULL; @@ -311,14 +293,12 @@ _mongoc_secure_transport_extract_subject (const char *filename, CFTypeID item_id = CFGetTypeID (CFArrayGetValueAtIndex (items, i)); if (item_id == SecCertificateGetTypeID ()) { - retval = _mongoc_secure_transport_RFC2253_from_cert ( - (SecCertificateRef) CFArrayGetValueAtIndex (items, i)); + retval = _mongoc_secure_transport_RFC2253_from_cert ((SecCertificateRef) CFArrayGetValueAtIndex (items, i)); break; } } } else if (type == kSecItemTypeCertificate) { - retval = - _mongoc_secure_transport_RFC2253_from_cert ((SecCertificateRef) items); + retval = _mongoc_secure_transport_RFC2253_from_cert ((SecCertificateRef) items); } if (items) { @@ -329,9 +309,8 @@ _mongoc_secure_transport_extract_subject (const char *filename, } bool -mongoc_secure_transport_setup_certificate ( - mongoc_stream_tls_secure_transport_t *secure_transport, - mongoc_ssl_opt_t *opt) +mongoc_secure_transport_setup_certificate (mongoc_stream_tls_secure_transport_t *secure_transport, + mongoc_ssl_opt_t *opt) { bool success; CFArrayRef items; @@ -341,21 +320,18 @@ mongoc_secure_transport_setup_certificate ( SecExternalItemType type = kSecItemTypeCertificate; if (!opt->pem_file) { - TRACE ("%s", - "No private key provided, the server won't be able to verify us"); + TRACE ("%s", "No private key provided, the server won't be able to verify us"); return false; } - success = _mongoc_secure_transport_import_pem ( - opt->pem_file, opt->pem_pwd, &items, &type); + success = _mongoc_secure_transport_import_pem (opt->pem_file, opt->pem_pwd, &items, &type); if (!success) { /* caller will log an error */ return false; } if (type != kSecItemTypeAggregate) { - MONGOC_ERROR ("Cannot work with keys of type \"%d\". Please file a JIRA", - type); + MONGOC_ERROR ("Cannot work with keys of type \"%d\". Please file a JIRA", type); CFRelease (items); return false; } @@ -377,8 +353,7 @@ mongoc_secure_transport_setup_certificate ( } id = SecIdentityCreate (kCFAllocatorDefault, cert, key); - secure_transport->my_cert = - CFArrayCreateMutable (kCFAllocatorDefault, 2, &kCFTypeArrayCallBacks); + secure_transport->my_cert = CFArrayCreateMutable (kCFAllocatorDefault, 2, &kCFTypeArrayCallBacks); CFArrayAppendValue (secure_transport->my_cert, id); CFArrayAppendValue (secure_transport->my_cert, cert); @@ -390,8 +365,7 @@ mongoc_secure_transport_setup_certificate ( * session. * * The identity specified in certRefs[0] is capable of signing. */ - success = !SSLSetCertificate (secure_transport->ssl_ctx_ref, - secure_transport->my_cert); + success = !SSLSetCertificate (secure_transport->ssl_ctx_ref, secure_transport->my_cert); TRACE ("Setting client certificate %s", success ? "succeeded" : "failed"); CFRelease (items); @@ -399,9 +373,7 @@ mongoc_secure_transport_setup_certificate ( } bool -mongoc_secure_transport_setup_ca ( - mongoc_stream_tls_secure_transport_t *secure_transport, - mongoc_ssl_opt_t *opt) +mongoc_secure_transport_setup_ca (mongoc_stream_tls_secure_transport_t *secure_transport, mongoc_ssl_opt_t *opt) { CFArrayRef items; SecExternalItemType type = kSecItemTypeCertificate; @@ -412,18 +384,15 @@ mongoc_secure_transport_setup_ca ( return false; } - success = - _mongoc_secure_transport_import_pem (opt->ca_file, NULL, &items, &type); + success = _mongoc_secure_transport_import_pem (opt->ca_file, NULL, &items, &type); if (!success) { - MONGOC_ERROR ("Cannot load Certificate Authorities from file \'%s\'", - opt->ca_file); + MONGOC_ERROR ("Cannot load Certificate Authorities from file \'%s\'", opt->ca_file); return false; } if (type == kSecItemTypeAggregate) { - CFMutableArrayRef anchors = - CFArrayCreateMutable (kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks); + CFMutableArrayRef anchors = CFArrayCreateMutable (kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks); for (CFIndex i = 0; i < CFArrayGetCount (items); ++i) { CFTypeID item_id = CFGetTypeID (CFArrayGetValueAtIndex (items, i)); @@ -442,18 +411,13 @@ mongoc_secure_transport_setup_ca ( /* This should be SSLSetCertificateAuthorities But the /TLS/ tests fail * when it is */ - success = !SSLSetTrustedRoots ( - secure_transport->ssl_ctx_ref, secure_transport->anchors, true); - TRACE ("Setting certificate authority %s (%s)", - success ? "succeeded" : "failed", - opt->ca_file); + success = !SSLSetTrustedRoots (secure_transport->ssl_ctx_ref, secure_transport->anchors, true); + TRACE ("Setting certificate authority %s (%s)", success ? "succeeded" : "failed", opt->ca_file); return success; } OSStatus -mongoc_secure_transport_read (SSLConnectionRef connection, - void *data, - size_t *data_length) +mongoc_secure_transport_read (SSLConnectionRef connection, void *data, size_t *data_length) { mongoc_stream_tls_t *tls = (mongoc_stream_tls_t *) connection; ssize_t length; @@ -463,8 +427,7 @@ mongoc_secure_transport_read (SSLConnectionRef connection, /* 4 arguments is *min_bytes* -- This is not a negotiation. * Secure Transport wants all or nothing. We must continue reading until * we get this amount, or timeout */ - length = mongoc_stream_read ( - tls->base_stream, data, *data_length, *data_length, tls->timeout_msec); + length = mongoc_stream_read (tls->base_stream, data, *data_length, *data_length, tls->timeout_msec); if (length > 0) { *data_length = length; @@ -492,17 +455,14 @@ mongoc_secure_transport_read (SSLConnectionRef connection, } OSStatus -mongoc_secure_transport_write (SSLConnectionRef connection, - const void *data, - size_t *data_length) +mongoc_secure_transport_write (SSLConnectionRef connection, const void *data, size_t *data_length) { mongoc_stream_tls_t *tls = (mongoc_stream_tls_t *) connection; ssize_t length; ENTRY; errno = 0; - length = mongoc_stream_write ( - tls->base_stream, (void *) data, *data_length, tls->timeout_msec); + length = mongoc_stream_write (tls->base_stream, (void *) data, *data_length, tls->timeout_msec); if (length >= 0) { *data_length = length; diff --git a/src/libmongoc/src/mongoc/mongoc-server-api.c b/src/libmongoc/src/mongoc/mongoc-server-api.c index b35d9db560..7b8a03230c 100644 --- a/src/libmongoc/src/mongoc/mongoc-server-api.c +++ b/src/libmongoc/src/mongoc/mongoc-server-api.c @@ -30,8 +30,7 @@ mongoc_server_api_version_to_string (mongoc_server_api_version_t version) } bool -mongoc_server_api_version_from_string (const char *version, - mongoc_server_api_version_t *out) +mongoc_server_api_version_from_string (const char *version, mongoc_server_api_version_t *out) { if (strcmp (version, "1") == 0) { *out = MONGOC_SERVER_API_V1; @@ -89,8 +88,7 @@ mongoc_server_api_strict (mongoc_server_api_t *api, bool strict) } void -mongoc_server_api_deprecation_errors (mongoc_server_api_t *api, - bool deprecation_errors) +mongoc_server_api_deprecation_errors (mongoc_server_api_t *api, bool deprecation_errors) { BSON_ASSERT (api); mongoc_optional_set_value (&api->deprecation_errors, deprecation_errors); diff --git a/src/libmongoc/src/mongoc/mongoc-server-api.h b/src/libmongoc/src/mongoc/mongoc-server-api.h index a0e3f37043..a8602c3eba 100644 --- a/src/libmongoc/src/mongoc/mongoc-server-api.h +++ b/src/libmongoc/src/mongoc/mongoc-server-api.h @@ -34,16 +34,13 @@ MONGOC_EXPORT (const char *) mongoc_server_api_version_to_string (mongoc_server_api_version_t version); MONGOC_EXPORT (bool) -mongoc_server_api_version_from_string (const char *version, - mongoc_server_api_version_t *out); +mongoc_server_api_version_from_string (const char *version, mongoc_server_api_version_t *out); MONGOC_EXPORT (mongoc_server_api_t *) -mongoc_server_api_new (mongoc_server_api_version_t version) - BSON_GNUC_WARN_UNUSED_RESULT; +mongoc_server_api_new (mongoc_server_api_version_t version) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (mongoc_server_api_t *) -mongoc_server_api_copy (const mongoc_server_api_t *api) - BSON_GNUC_WARN_UNUSED_RESULT; +mongoc_server_api_copy (const mongoc_server_api_t *api) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (void) mongoc_server_api_destroy (mongoc_server_api_t *api); @@ -52,8 +49,7 @@ MONGOC_EXPORT (void) mongoc_server_api_strict (mongoc_server_api_t *api, bool strict); MONGOC_EXPORT (void) -mongoc_server_api_deprecation_errors (mongoc_server_api_t *api, - bool deprecation_errors); +mongoc_server_api_deprecation_errors (mongoc_server_api_t *api, bool deprecation_errors); MONGOC_EXPORT (const mongoc_optional_t *) mongoc_server_api_get_deprecation_errors (const mongoc_server_api_t *api); diff --git a/src/libmongoc/src/mongoc/mongoc-server-description-private.h b/src/libmongoc/src/mongoc/mongoc-server-description-private.h index 58cfbb6570..33812c9d6e 100644 --- a/src/libmongoc/src/mongoc/mongoc-server-description-private.h +++ b/src/libmongoc/src/mongoc/mongoc-server-description-private.h @@ -147,8 +147,7 @@ mc_tpl_sd_generation_map_const (const mongoc_server_description_t *sd) * service ID. */ static BSON_INLINE void -mc_tpl_sd_increment_generation (mongoc_server_description_t *sd, - const bson_oid_t *service_id) +mc_tpl_sd_increment_generation (mongoc_server_description_t *sd, const bson_oid_t *service_id) { mongoc_generation_map_increment (mc_tpl_sd_generation_map (sd), service_id); } @@ -158,29 +157,22 @@ mc_tpl_sd_increment_generation (mongoc_server_description_t *sd, * associated service ID. */ static BSON_INLINE uint32_t -mc_tpl_sd_get_generation (const mongoc_server_description_t *sd, - const bson_oid_t *service_id) +mc_tpl_sd_get_generation (const mongoc_server_description_t *sd, const bson_oid_t *service_id) { - return mongoc_generation_map_get (mc_tpl_sd_generation_map_const (sd), - service_id); + return mongoc_generation_map_get (mc_tpl_sd_generation_map_const (sd), service_id); } void -mongoc_server_description_init (mongoc_server_description_t *sd, - const char *address, - uint32_t id); +mongoc_server_description_init (mongoc_server_description_t *sd, const char *address, uint32_t id); bool -mongoc_server_description_has_rs_member ( - const mongoc_server_description_t *description, const char *address); +mongoc_server_description_has_rs_member (const mongoc_server_description_t *description, const char *address); bool -mongoc_server_description_has_set_version ( - const mongoc_server_description_t *description); +mongoc_server_description_has_set_version (const mongoc_server_description_t *description); bool -mongoc_server_description_has_election_id ( - const mongoc_server_description_t *description); +mongoc_server_description_has_election_id (const mongoc_server_description_t *description); void mongoc_server_description_cleanup (mongoc_server_description_t *sd); @@ -189,17 +181,13 @@ void mongoc_server_description_reset (mongoc_server_description_t *sd); void -mongoc_server_description_set_state (mongoc_server_description_t *description, - mongoc_server_description_type_t type); +mongoc_server_description_set_state (mongoc_server_description_t *description, mongoc_server_description_type_t type); void -mongoc_server_description_set_set_version ( - mongoc_server_description_t *description, int64_t set_version); +mongoc_server_description_set_set_version (mongoc_server_description_t *description, int64_t set_version); void -mongoc_server_description_set_election_id ( - mongoc_server_description_t *description, const bson_oid_t *election_id); +mongoc_server_description_set_election_id (mongoc_server_description_t *description, const bson_oid_t *election_id); void -mongoc_server_description_update_rtt (mongoc_server_description_t *server, - int64_t rtt_msec); +mongoc_server_description_update_rtt (mongoc_server_description_t *server, int64_t rtt_msec); void mongoc_server_description_handle_hello (mongoc_server_description_t *sd, @@ -208,37 +196,31 @@ mongoc_server_description_handle_hello (mongoc_server_description_t *sd, const bson_error_t *error /* IN */); void -mongoc_server_description_filter_stale ( - const mongoc_server_description_t **sds, - size_t sds_len, - const mongoc_server_description_t *primary, - int64_t heartbeat_frequency_ms, - const mongoc_read_prefs_t *read_prefs); +mongoc_server_description_filter_stale (const mongoc_server_description_t **sds, + size_t sds_len, + const mongoc_server_description_t *primary, + int64_t heartbeat_frequency_ms, + const mongoc_read_prefs_t *read_prefs); void -mongoc_server_description_filter_tags ( - const mongoc_server_description_t **descriptions, - size_t description_len, - const mongoc_read_prefs_t *read_prefs); +mongoc_server_description_filter_tags (const mongoc_server_description_t **descriptions, + size_t description_len, + const mongoc_read_prefs_t *read_prefs); /* Compares server descriptions following the "Server Description Equality" * rules. Not all fields are considered. */ bool -_mongoc_server_description_equal (mongoc_server_description_t *sd1, - mongoc_server_description_t *sd2); +_mongoc_server_description_equal (mongoc_server_description_t *sd1, mongoc_server_description_t *sd2); int -mongoc_server_description_topology_version_cmp (const bson_t *tv1, - const bson_t *tv2); +mongoc_server_description_topology_version_cmp (const bson_t *tv1, const bson_t *tv2); void -mongoc_server_description_set_topology_version (mongoc_server_description_t *sd, - const bson_t *tv); +mongoc_server_description_set_topology_version (mongoc_server_description_t *sd, const bson_t *tv); extern const bson_oid_t kZeroServiceId; bool -mongoc_server_description_has_service_id ( - const mongoc_server_description_t *description); +mongoc_server_description_has_service_id (const mongoc_server_description_t *description); #endif diff --git a/src/libmongoc/src/mongoc/mongoc-server-description.c b/src/libmongoc/src/mongoc/mongoc-server-description.c index b1de91f9e9..e0ae4fa276 100644 --- a/src/libmongoc/src/mongoc/mongoc-server-description.c +++ b/src/libmongoc/src/mongoc/mongoc-server-description.c @@ -36,8 +36,7 @@ static bson_oid_t kObjectIdZero = {{0}}; const bson_oid_t kZeroServiceId = {{0}}; static bool -_match_tag_set (const mongoc_server_description_t *sd, - bson_iter_t *tag_set_iter); +_match_tag_set (const mongoc_server_description_t *sd, bson_iter_t *tag_set_iter); /* Destroy allocated resources within @description, but don't free it */ void @@ -117,9 +116,7 @@ mongoc_server_description_reset (mongoc_server_description_t *sd) *-------------------------------------------------------------------------- */ void -mongoc_server_description_init (mongoc_server_description_t *sd, - const char *address, - uint32_t id) +mongoc_server_description_init (mongoc_server_description_t *sd, const char *address, uint32_t id) { ENTRY; @@ -201,8 +198,7 @@ mongoc_server_description_destroy (mongoc_server_description_t *description) *-------------------------------------------------------------------------- */ bool -mongoc_server_description_has_rs_member ( - const mongoc_server_description_t *server, const char *address) +mongoc_server_description_has_rs_member (const mongoc_server_description_t *server, const char *address) { bson_iter_t member_iter; const bson_t *rs_members[3]; @@ -217,8 +213,7 @@ mongoc_server_description_has_rs_member ( BSON_ASSERT (bson_iter_init (&member_iter, rs_members[i])); while (bson_iter_next (&member_iter)) { - if (strcasecmp (address, bson_iter_utf8 (&member_iter, NULL)) == - 0) { + if (strcasecmp (address, bson_iter_utf8 (&member_iter, NULL)) == 0) { return true; } } @@ -242,8 +237,7 @@ mongoc_server_description_has_rs_member ( */ bool -mongoc_server_description_has_set_version ( - const mongoc_server_description_t *description) +mongoc_server_description_has_set_version (const mongoc_server_description_t *description) { return description->set_version != MONGOC_NO_SET_VERSION; } @@ -262,8 +256,7 @@ mongoc_server_description_has_set_version ( */ bool -mongoc_server_description_has_election_id ( - const mongoc_server_description_t *description) +mongoc_server_description_has_election_id (const mongoc_server_description_t *description) { return 0 != bson_oid_compare (&description->election_id, &kObjectIdZero); } @@ -308,8 +301,7 @@ mongoc_server_description_host (const mongoc_server_description_t *description) } int64_t -mongoc_server_description_last_update_time ( - const mongoc_server_description_t *description) +mongoc_server_description_last_update_time (const mongoc_server_description_t *description) { return description->last_update_time_usec; } @@ -329,8 +321,7 @@ mongoc_server_description_last_update_time ( */ int64_t -mongoc_server_description_round_trip_time ( - const mongoc_server_description_t *description) +mongoc_server_description_round_trip_time (const mongoc_server_description_t *description) { return description->round_trip_time_msec; } @@ -394,8 +385,7 @@ mongoc_server_description_type (const mongoc_server_description_t *description) */ const bson_t * -mongoc_server_description_hello_response ( - const mongoc_server_description_t *description) +mongoc_server_description_hello_response (const mongoc_server_description_t *description) { return &description->last_hello_response; } @@ -414,8 +404,7 @@ mongoc_server_description_hello_response ( */ const bson_t * -mongoc_server_description_ismaster ( - const mongoc_server_description_t *description) +mongoc_server_description_ismaster (const mongoc_server_description_t *description) { return mongoc_server_description_hello_response (description); } @@ -430,8 +419,7 @@ mongoc_server_description_ismaster ( *-------------------------------------------------------------------------- */ void -mongoc_server_description_set_state (mongoc_server_description_t *description, - mongoc_server_description_type_t type) +mongoc_server_description_set_state (mongoc_server_description_t *description, mongoc_server_description_type_t type) { description->type = type; } @@ -449,8 +437,7 @@ mongoc_server_description_set_state (mongoc_server_description_t *description, *-------------------------------------------------------------------------- */ void -mongoc_server_description_set_set_version ( - mongoc_server_description_t *description, int64_t set_version) +mongoc_server_description_set_set_version (mongoc_server_description_t *description, int64_t set_version) { description->set_version = set_version; } @@ -469,8 +456,7 @@ mongoc_server_description_set_set_version ( *-------------------------------------------------------------------------- */ void -mongoc_server_description_set_election_id ( - mongoc_server_description_t *description, const bson_oid_t *election_id) +mongoc_server_description_set_election_id (mongoc_server_description_t *description, const bson_oid_t *election_id) { if (election_id) { bson_oid_copy_unsafe (election_id, &description->election_id); @@ -495,36 +481,28 @@ mongoc_server_description_set_election_id ( *------------------------------------------------------------------------- */ void -mongoc_server_description_update_rtt (mongoc_server_description_t *server, - int64_t rtt_msec) +mongoc_server_description_update_rtt (mongoc_server_description_t *server, int64_t rtt_msec) { if (rtt_msec == MONGOC_RTT_UNSET) { return; } if (server->round_trip_time_msec == MONGOC_RTT_UNSET) { - bson_atomic_int64_exchange ( - &server->round_trip_time_msec, rtt_msec, bson_memory_order_relaxed); + bson_atomic_int64_exchange (&server->round_trip_time_msec, rtt_msec, bson_memory_order_relaxed); } else { - bson_atomic_int64_exchange ( - &server->round_trip_time_msec, - (int64_t) (ALPHA * rtt_msec + - (1 - ALPHA) * server->round_trip_time_msec), - bson_memory_order_relaxed); + bson_atomic_int64_exchange (&server->round_trip_time_msec, + (int64_t) (ALPHA * rtt_msec + (1 - ALPHA) * server->round_trip_time_msec), + bson_memory_order_relaxed); } } static void -_mongoc_server_description_set_error (mongoc_server_description_t *sd, - const bson_error_t *error) +_mongoc_server_description_set_error (mongoc_server_description_t *sd, const bson_error_t *error) { if (error && error->code) { memcpy (&sd->error, error, sizeof (bson_error_t)); } else { - bson_set_error (&sd->error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_CONNECT, - "unknown error calling hello"); + bson_set_error (&sd->error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_CONNECT, "unknown error calling hello"); } /* Server Discovery and Monitoring Spec: if the server type changes from a @@ -572,8 +550,7 @@ mongoc_server_description_handle_hello (mongoc_server_description_t *sd, } bson_destroy (&sd->last_hello_response); - bsonBuild (sd->last_hello_response, - insert (*hello_response, not(key ("speculativeAuthenticate")))); + bsonBuild (sd->last_hello_response, insert (*hello_response, not(key ("speculativeAuthenticate")))); sd->has_hello_response = true; /* Only reinitialize the topology version if we have a hello response. @@ -588,8 +565,7 @@ mongoc_server_description_handle_hello (mongoc_server_description_t *sd, if (!bson_iter_as_bool (&iter)) { /* it doesn't really matter what error API we use. the code and * domain will be overwritten. */ - (void) _mongoc_cmd_check_ok ( - hello_response, MONGOC_ERROR_API_VERSION_2, &sd->error); + (void) _mongoc_cmd_check_ok (hello_response, MONGOC_ERROR_API_VERSION_2, &sd->error); /* TODO CDRIVER-3696: this is an existing bug. If this is handling * a hello reply that is NOT from a handshake, this should not * be considered an auth error. */ @@ -601,8 +577,7 @@ mongoc_server_description_handle_hello (mongoc_server_description_t *sd, GOTO (authfailure); } } else if (strcmp ("isWritablePrimary", bson_iter_key (&iter)) == 0 || - strcmp (HANDSHAKE_RESPONSE_LEGACY_HELLO, - bson_iter_key (&iter)) == 0) { + strcmp (HANDSHAKE_RESPONSE_LEGACY_HELLO, bson_iter_key (&iter)) == 0) { if (!BSON_ITER_HOLDS_BOOL (&iter)) GOTO (typefailure); is_primary = bson_iter_bool (&iter); @@ -626,8 +601,7 @@ mongoc_server_description_handle_hello (mongoc_server_description_t *sd, if (!BSON_ITER_HOLDS_INT32 (&iter)) GOTO (typefailure); sd->max_write_batch_size = bson_iter_int32 (&iter); - } else if (strcmp ("logicalSessionTimeoutMinutes", - bson_iter_key (&iter)) == 0) { + } else if (strcmp ("logicalSessionTimeoutMinutes", bson_iter_key (&iter)) == 0) { if (BSON_ITER_HOLDS_NUMBER (&iter)) { sd->session_timeout_minutes = bson_iter_as_int64 (&iter); } else if (BSON_ITER_HOLDS_NULL (&iter)) { @@ -657,8 +631,7 @@ mongoc_server_description_handle_hello (mongoc_server_description_t *sd, GOTO (typefailure); sd->set_name = bson_iter_utf8 (&iter, NULL); } else if (strcmp ("setVersion", bson_iter_key (&iter)) == 0) { - mongoc_server_description_set_set_version (sd, - bson_iter_as_int64 (&iter)); + mongoc_server_description_set_set_version (sd, bson_iter_as_int64 (&iter)); } else if (strcmp ("electionId", bson_iter_key (&iter)) == 0) { if (!BSON_ITER_HOLDS_OID (&iter)) GOTO (typefailure); @@ -706,10 +679,8 @@ mongoc_server_description_handle_hello (mongoc_server_description_t *sd, } else if (strcmp ("hidden", bson_iter_key (&iter)) == 0) { is_hidden = bson_iter_bool (&iter); } else if (strcmp ("lastWrite", bson_iter_key (&iter)) == 0) { - if (!BSON_ITER_HOLDS_DOCUMENT (&iter) || - !bson_iter_recurse (&iter, &child) || - !bson_iter_find (&child, "lastWriteDate") || - !BSON_ITER_HOLDS_DATE_TIME (&child)) { + if (!BSON_ITER_HOLDS_DOCUMENT (&iter) || !bson_iter_recurse (&iter, &child) || + !bson_iter_find (&child, "lastWriteDate") || !BSON_ITER_HOLDS_DATE_TIME (&child)) { GOTO (typefailure); } @@ -728,10 +699,8 @@ mongoc_server_description_handle_hello (mongoc_server_description_t *sd, } bson_iter_document (&iter, &len, &bytes); - BSON_ASSERT ( - bson_init_static (&incoming_topology_version, bytes, len)); - mongoc_server_description_set_topology_version ( - sd, &incoming_topology_version); + BSON_ASSERT (bson_init_static (&incoming_topology_version, bytes, len)); + mongoc_server_description_set_topology_version (sd, &incoming_topology_version); bson_destroy (&incoming_topology_version); } else if (strcmp ("serviceId", bson_iter_key (&iter)) == 0) { if (!BSON_ITER_HOLDS_OID (&iter)) @@ -799,8 +768,7 @@ mongoc_server_description_handle_hello (mongoc_server_description_t *sd, *------------------------------------------------------------------------- */ mongoc_server_description_t * -mongoc_server_description_new_copy ( - const mongoc_server_description_t *description) +mongoc_server_description_new_copy (const mongoc_server_description_t *description) { mongoc_server_description_t *copy; @@ -828,12 +796,9 @@ mongoc_server_description_new_copy ( if (description->has_hello_response) { /* calls mongoc_server_description_reset */ - int64_t last_rtt_ms = bson_atomic_int64_fetch ( - &description->round_trip_time_msec, bson_memory_order_relaxed); - mongoc_server_description_handle_hello (copy, - &description->last_hello_response, - last_rtt_ms, - &description->error); + int64_t last_rtt_ms = bson_atomic_int64_fetch (&description->round_trip_time_msec, bson_memory_order_relaxed); + mongoc_server_description_handle_hello ( + copy, &description->last_hello_response, last_rtt_ms, &description->error); } else { mongoc_server_description_reset (copy); /* preserve the original server description type, which is manually set @@ -845,8 +810,7 @@ mongoc_server_description_new_copy ( memcpy (©->error, &description->error, sizeof copy->error); copy->generation = description->generation; - copy->_generation_map_ = - mongoc_generation_map_copy (mc_tpl_sd_generation_map_const (description)); + copy->_generation_map_ = mongoc_generation_map_copy (mc_tpl_sd_generation_map_const (description)); return copy; } @@ -864,12 +828,11 @@ mongoc_server_description_new_copy ( */ void -mongoc_server_description_filter_stale ( - const mongoc_server_description_t **sds, - size_t sds_len, - const mongoc_server_description_t *primary, - int64_t heartbeat_frequency_ms, - const mongoc_read_prefs_t *read_prefs) +mongoc_server_description_filter_stale (const mongoc_server_description_t **sds, + size_t sds_len, + const mongoc_server_description_t *primary, + int64_t heartbeat_frequency_ms, + const mongoc_read_prefs_t *read_prefs) { int64_t max_staleness_seconds; size_t i; @@ -884,8 +847,7 @@ mongoc_server_description_filter_stale ( return; } - max_staleness_seconds = - mongoc_read_prefs_get_max_staleness_seconds (read_prefs); + max_staleness_seconds = mongoc_read_prefs_get_max_staleness_seconds (read_prefs); if (max_staleness_seconds == MONGOC_NO_MAX_STALENESS) { return; @@ -902,14 +864,12 @@ mongoc_server_description_filter_stale ( } /* See max-staleness.rst for explanation of these formulae. */ - staleness_usec = - primary->last_write_date_ms * 1000 + - (sds[i]->last_update_time_usec - primary->last_update_time_usec) - - sds[i]->last_write_date_ms * 1000 + heartbeat_frequency_usec; + staleness_usec = primary->last_write_date_ms * 1000 + + (sds[i]->last_update_time_usec - primary->last_update_time_usec) - + sds[i]->last_write_date_ms * 1000 + heartbeat_frequency_usec; if (staleness_usec > max_staleness_usec) { - TRACE ("Rejected stale RSSecondary [%s]", - sds[i]->host.host_and_port); + TRACE ("Rejected stale RSSecondary [%s]", sds[i]->host.host_and_port); sds[i] = NULL; } } @@ -918,8 +878,7 @@ mongoc_server_description_filter_stale ( max_last_write_date_usec = 0; for (i = 0; i < sds_len; i++) { if (sds[i] && sds[i]->type == MONGOC_SERVER_RS_SECONDARY) { - max_last_write_date_usec = BSON_MAX ( - max_last_write_date_usec, sds[i]->last_write_date_ms * 1000); + max_last_write_date_usec = BSON_MAX (max_last_write_date_usec, sds[i]->last_write_date_ms * 1000); } } @@ -929,13 +888,10 @@ mongoc_server_description_filter_stale ( continue; } - staleness_usec = max_last_write_date_usec - - sds[i]->last_write_date_ms * 1000 + - heartbeat_frequency_usec; + staleness_usec = max_last_write_date_usec - sds[i]->last_write_date_ms * 1000 + heartbeat_frequency_usec; if (staleness_usec > max_staleness_usec) { - TRACE ("Rejected stale RSSecondary [%s]", - sds[i]->host.host_and_port); + TRACE ("Rejected stale RSSecondary [%s]", sds[i]->host.host_and_port); sds[i] = NULL; } } @@ -957,10 +913,9 @@ mongoc_server_description_filter_stale ( */ void -mongoc_server_description_filter_tags ( - const mongoc_server_description_t **descriptions, - size_t description_len, - const mongoc_read_prefs_t *read_prefs) +mongoc_server_description_filter_tags (const mongoc_server_description_t **descriptions, + size_t description_len, + const mongoc_read_prefs_t *read_prefs) { const bson_t *rp_tags; bson_iter_t rp_tagset_iter; @@ -1043,8 +998,7 @@ mongoc_server_description_filter_tags ( *------------------------------------------------------------------------- */ static bool -_match_tag_set (const mongoc_server_description_t *sd, - bson_iter_t *tag_set_iter) +_match_tag_set (const mongoc_server_description_t *sd, bson_iter_t *tag_set_iter) { bson_iter_t sd_iter; uint32_t read_pref_tag_len; @@ -1061,8 +1015,7 @@ _match_tag_set (const mongoc_server_description_t *sd, if (bson_iter_init_find (&sd_iter, &sd->tags, read_pref_tag)) { /* The server has this tag - does it have the right value? */ server_val = bson_iter_utf8 (&sd_iter, &sd_len); - if (sd_len != read_pref_tag_len || - memcmp (read_pref_val, server_val, read_pref_tag_len)) { + if (sd_len != read_pref_tag_len || memcmp (read_pref_val, server_val, read_pref_tag_len)) { /* If the values don't match, no match */ return false; } @@ -1089,8 +1042,7 @@ _match_tag_set (const mongoc_server_description_t *sd, */ int32_t -mongoc_server_description_compressor_id ( - const mongoc_server_description_t *description) +mongoc_server_description_compressor_id (const mongoc_server_description_t *description) { int id; bson_iter_t iter; @@ -1141,8 +1093,7 @@ _nullable_strcmp (const char *a, const char *b) } bool -_mongoc_server_description_equal (mongoc_server_description_t *sd1, - mongoc_server_description_t *sd2) +_mongoc_server_description_equal (mongoc_server_description_t *sd1, mongoc_server_description_t *sd2) { if (sd1->type != sd2->type) { return false; @@ -1210,8 +1161,7 @@ _mongoc_server_description_equal (mongoc_server_description_t *sd1, } int -mongoc_server_description_topology_version_cmp (const bson_t *tv1, - const bson_t *tv2) +mongoc_server_description_topology_version_cmp (const bson_t *tv1, const bson_t *tv2) { const bson_oid_t *pid1; const bson_oid_t *pid2; @@ -1226,14 +1176,12 @@ mongoc_server_description_topology_version_cmp (const bson_t *tv1, return -1; } - if (!bson_iter_init_find (&iter, tv1, "processId") || - !BSON_ITER_HOLDS_OID (&iter)) { + if (!bson_iter_init_find (&iter, tv1, "processId") || !BSON_ITER_HOLDS_OID (&iter)) { return -1; } pid1 = bson_iter_oid (&iter); - if (!bson_iter_init_find (&iter, tv2, "processId") || - !BSON_ITER_HOLDS_OID (&iter)) { + if (!bson_iter_init_find (&iter, tv2, "processId") || !BSON_ITER_HOLDS_OID (&iter)) { return -1; } pid2 = bson_iter_oid (&iter); @@ -1243,14 +1191,12 @@ mongoc_server_description_topology_version_cmp (const bson_t *tv1, return -1; } - if (!bson_iter_init_find (&iter, tv1, "counter") || - !BSON_ITER_HOLDS_INT (&iter)) { + if (!bson_iter_init_find (&iter, tv1, "counter") || !BSON_ITER_HOLDS_INT (&iter)) { return -1; } counter1 = bson_iter_as_int64 (&iter); - if (!bson_iter_init_find (&iter, tv2, "counter") || - !BSON_ITER_HOLDS_INT (&iter)) { + if (!bson_iter_init_find (&iter, tv2, "counter") || !BSON_ITER_HOLDS_INT (&iter)) { return -1; } counter2 = bson_iter_as_int64 (&iter); @@ -1264,8 +1210,7 @@ mongoc_server_description_topology_version_cmp (const bson_t *tv1, } void -mongoc_server_description_set_topology_version (mongoc_server_description_t *sd, - const bson_t *tv) +mongoc_server_description_set_topology_version (mongoc_server_description_t *sd, const bson_t *tv) { BSON_ASSERT (tv); bson_destroy (&sd->topology_version); @@ -1273,8 +1218,7 @@ mongoc_server_description_set_topology_version (mongoc_server_description_t *sd, } bool -mongoc_server_description_has_service_id ( - const mongoc_server_description_t *description) +mongoc_server_description_has_service_id (const mongoc_server_description_t *description) { if (0 == bson_oid_compare (&description->service_id, &kZeroServiceId)) { return false; diff --git a/src/libmongoc/src/mongoc/mongoc-server-description.h b/src/libmongoc/src/mongoc/mongoc-server-description.h index 79ab4af646..f780e44b38 100644 --- a/src/libmongoc/src/mongoc/mongoc-server-description.h +++ b/src/libmongoc/src/mongoc/mongoc-server-description.h @@ -33,8 +33,7 @@ MONGOC_EXPORT (void) mongoc_server_description_destroy (mongoc_server_description_t *description); MONGOC_EXPORT (mongoc_server_description_t *) -mongoc_server_description_new_copy ( - const mongoc_server_description_t *description) BSON_GNUC_WARN_UNUSED_RESULT; +mongoc_server_description_new_copy (const mongoc_server_description_t *description) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (uint32_t) mongoc_server_description_id (const mongoc_server_description_t *description); @@ -43,28 +42,23 @@ MONGOC_EXPORT (mongoc_host_list_t *) mongoc_server_description_host (const mongoc_server_description_t *description); MONGOC_EXPORT (int64_t) -mongoc_server_description_last_update_time ( - const mongoc_server_description_t *description); +mongoc_server_description_last_update_time (const mongoc_server_description_t *description); MONGOC_EXPORT (int64_t) -mongoc_server_description_round_trip_time ( - const mongoc_server_description_t *description); +mongoc_server_description_round_trip_time (const mongoc_server_description_t *description); MONGOC_EXPORT (const char *) mongoc_server_description_type (const mongoc_server_description_t *description); MONGOC_EXPORT (const bson_t *) -mongoc_server_description_hello_response ( - const mongoc_server_description_t *description); +mongoc_server_description_hello_response (const mongoc_server_description_t *description); MONGOC_EXPORT (const bson_t *) -mongoc_server_description_ismaster ( - const mongoc_server_description_t *description) +mongoc_server_description_ismaster (const mongoc_server_description_t *description) BSON_GNUC_DEPRECATED_FOR (mongoc_server_description_hello_response); MONGOC_EXPORT (int32_t) -mongoc_server_description_compressor_id ( - const mongoc_server_description_t *description); +mongoc_server_description_compressor_id (const mongoc_server_description_t *description); BSON_END_DECLS diff --git a/src/libmongoc/src/mongoc/mongoc-server-monitor-private.h b/src/libmongoc/src/mongoc/mongoc-server-monitor-private.h index 49d45c08ff..bb9469a317 100644 --- a/src/libmongoc/src/mongoc/mongoc-server-monitor-private.h +++ b/src/libmongoc/src/mongoc/mongoc-server-monitor-private.h @@ -39,12 +39,10 @@ void mongoc_server_monitor_request_scan (mongoc_server_monitor_t *server_monitor); bool -mongoc_server_monitor_request_shutdown ( - mongoc_server_monitor_t *server_monitor); +mongoc_server_monitor_request_shutdown (mongoc_server_monitor_t *server_monitor); void -mongoc_server_monitor_wait_for_shutdown ( - mongoc_server_monitor_t *server_monitor); +mongoc_server_monitor_wait_for_shutdown (mongoc_server_monitor_t *server_monitor); void mongoc_server_monitor_destroy (mongoc_server_monitor_t *server_monitor); diff --git a/src/libmongoc/src/mongoc/mongoc-server-monitor.c b/src/libmongoc/src/mongoc/mongoc-server-monitor.c index 861fa4161e..fe9b5cabb9 100644 --- a/src/libmongoc/src/mongoc/mongoc-server-monitor.c +++ b/src/libmongoc/src/mongoc/mongoc-server-monitor.c @@ -90,11 +90,10 @@ struct _mongoc_server_monitor_t { bool is_rtt; }; -static BSON_GNUC_PRINTF (3, 4) void _server_monitor_log ( - mongoc_server_monitor_t *server_monitor, - mongoc_log_level_t level, - const char *format, - ...) +static BSON_GNUC_PRINTF (3, 4) void _server_monitor_log (mongoc_server_monitor_t *server_monitor, + mongoc_log_level_t level, + const char *format, + ...) { va_list ap; char *msg; @@ -120,19 +119,15 @@ static BSON_GNUC_PRINTF (3, 4) void _server_monitor_log ( } while (0) /* TODO CDRIVER-3710 use MONGOC_LOG_LEVEL_ERROR */ -#define MONITOR_LOG_ERROR(sm, ...) \ - _server_monitor_log (sm, MONGOC_LOG_LEVEL_DEBUG, __VA_ARGS__) +#define MONITOR_LOG_ERROR(sm, ...) _server_monitor_log (sm, MONGOC_LOG_LEVEL_DEBUG, __VA_ARGS__) /* TODO CDRIVER-3710 use MONGOC_LOG_LEVEL_WARNING */ -#define MONITOR_LOG_WARNING(sm, ...) \ - _server_monitor_log (sm, MONGOC_LOG_LEVEL_DEBUG, __VA_ARGS__) +#define MONITOR_LOG_WARNING(sm, ...) _server_monitor_log (sm, MONGOC_LOG_LEVEL_DEBUG, __VA_ARGS__) static void -_server_monitor_heartbeat_started (mongoc_server_monitor_t *server_monitor, - bool awaited) +_server_monitor_heartbeat_started (mongoc_server_monitor_t *server_monitor, bool awaited) { mongoc_apm_server_heartbeat_started_t event; - MONGOC_DEBUG_ASSERT ( - !mcommon_mutex_is_locked (&server_monitor->topology->apm_mutex)); + MONGOC_DEBUG_ASSERT (!mcommon_mutex_is_locked (&server_monitor->topology->apm_mutex)); if (!server_monitor->apm_callbacks.server_heartbeat_started) { return; @@ -140,9 +135,7 @@ _server_monitor_heartbeat_started (mongoc_server_monitor_t *server_monitor, event.host = &server_monitor->description->host; event.context = server_monitor->apm_context; - MONITOR_LOG (server_monitor, - "%s heartbeat started", - awaited ? "awaitable" : "regular"); + MONITOR_LOG (server_monitor, "%s heartbeat started", awaited ? "awaitable" : "regular"); event.awaited = awaited; bson_mutex_lock (&server_monitor->topology->apm_mutex); server_monitor->apm_callbacks.server_heartbeat_started (&event); @@ -165,9 +158,7 @@ _server_monitor_heartbeat_succeeded (mongoc_server_monitor_t *server_monitor, event.context = server_monitor->apm_context; event.reply = reply; event.duration_usec = duration_usec; - MONITOR_LOG (server_monitor, - "%s heartbeat succeeded", - awaited ? "awaitable" : "regular"); + MONITOR_LOG (server_monitor, "%s heartbeat succeeded", awaited ? "awaitable" : "regular"); event.awaited = awaited; bson_mutex_lock (&server_monitor->topology->apm_mutex); server_monitor->apm_callbacks.server_heartbeat_succeeded (&event); @@ -190,8 +181,7 @@ _server_monitor_heartbeat_failed (mongoc_server_monitor_t *server_monitor, event.context = server_monitor->apm_context; event.error = error; event.duration_usec = duration_usec; - MONITOR_LOG ( - server_monitor, "%s heartbeat failed", awaited ? "awaitable" : "regular"); + MONITOR_LOG (server_monitor, "%s heartbeat failed", awaited ? "awaitable" : "regular"); event.awaited = awaited; bson_mutex_lock (&server_monitor->topology->apm_mutex); server_monitor->apm_callbacks.server_heartbeat_failed (&event); @@ -199,11 +189,9 @@ _server_monitor_heartbeat_failed (mongoc_server_monitor_t *server_monitor, } static void -_server_monitor_append_cluster_time (mongoc_server_monitor_t *server_monitor, - bson_t *cmd) +_server_monitor_append_cluster_time (mongoc_server_monitor_t *server_monitor, bson_t *cmd) { - mc_shared_tpld td = - mc_tpld_take_ref (BSON_ASSERT_PTR_INLINE (server_monitor)->topology); + mc_shared_tpld td = mc_tpld_take_ref (BSON_ASSERT_PTR_INLINE (server_monitor)->topology); /* Cluster time is updated on every reply. */ if (!bson_empty (&td.ptr->cluster_time)) { @@ -220,11 +208,10 @@ _int32_from_le (const void *data) } static bool -_server_monitor_send_and_recv_hello_opmsg ( - mongoc_server_monitor_t *server_monitor, - const bson_t *cmd, - bson_t *reply, - bson_error_t *error) +_server_monitor_send_and_recv_hello_opmsg (mongoc_server_monitor_t *server_monitor, + const bson_t *cmd, + bson_t *reply, + bson_error_t *error) { bool ret = false; @@ -239,18 +226,15 @@ _server_monitor_send_and_recv_hello_opmsg ( int32_t message_length = 0; message_length += mcd_rpc_header_set_message_length (rpc, 0); - message_length += - mcd_rpc_header_set_request_id (rpc, server_monitor->request_id++); + message_length += mcd_rpc_header_set_request_id (rpc, server_monitor->request_id++); message_length += mcd_rpc_header_set_response_to (rpc, 0); message_length += mcd_rpc_header_set_op_code (rpc, MONGOC_OP_CODE_MSG); mcd_rpc_op_msg_set_sections_count (rpc, 1u); - message_length += - mcd_rpc_op_msg_set_flag_bits (rpc, MONGOC_OP_MSG_FLAG_NONE); + message_length += mcd_rpc_op_msg_set_flag_bits (rpc, MONGOC_OP_MSG_FLAG_NONE); message_length += mcd_rpc_op_msg_section_set_kind (rpc, 0u, 0); - message_length += - mcd_rpc_op_msg_section_set_body (rpc, 0u, bson_get_data (cmd)); + message_length += mcd_rpc_op_msg_section_set_body (rpc, 0u, bson_get_data (cmd)); mcd_rpc_message_set_length (rpc, message_length); } @@ -259,27 +243,18 @@ _server_monitor_send_and_recv_hello_opmsg ( mongoc_iovec_t *const iovecs = mcd_rpc_message_to_iovecs (rpc, &num_iovecs); BSON_ASSERT (iovecs); - MONITOR_LOG (server_monitor, - "sending with timeout %" PRId64, - server_monitor->connect_timeout_ms); + MONITOR_LOG (server_monitor, "sending with timeout %" PRId64, server_monitor->connect_timeout_ms); mcd_rpc_message_egress (rpc); - if (!_mongoc_stream_writev_full (server_monitor->stream, - iovecs, - num_iovecs, - server_monitor->connect_timeout_ms, - error)) { - MONITOR_LOG_ERROR ( - server_monitor, "failed to write polling hello: %s", error->message); + if (!_mongoc_stream_writev_full ( + server_monitor->stream, iovecs, num_iovecs, server_monitor->connect_timeout_ms, error)) { + MONITOR_LOG_ERROR (server_monitor, "failed to write polling hello: %s", error->message); goto fail; } /* Done sending! Now, receive the reply: */ - if (!_mongoc_buffer_append_from_stream (&buffer, - server_monitor->stream, - sizeof (int32_t), - server_monitor->connect_timeout_ms, - error)) { + if (!_mongoc_buffer_append_from_stream ( + &buffer, server_monitor->stream, sizeof (int32_t), server_monitor->connect_timeout_ms, error)) { goto fail; } @@ -298,17 +273,13 @@ _server_monitor_send_and_recv_hello_opmsg ( const size_t remaining_bytes = (size_t) message_length - sizeof (int32_t); - if (!_mongoc_buffer_append_from_stream (&buffer, - server_monitor->stream, - remaining_bytes, - server_monitor->connect_timeout_ms, - error)) { + if (!_mongoc_buffer_append_from_stream ( + &buffer, server_monitor->stream, remaining_bytes, server_monitor->connect_timeout_ms, error)) { goto fail; } mcd_rpc_message_reset (rpc); - if (!mcd_rpc_message_from_data_in_place ( - rpc, buffer.data, buffer.len, NULL)) { + if (!mcd_rpc_message_from_data_in_place (rpc, buffer.data, buffer.len, NULL)) { bson_set_error (error, MONGOC_ERROR_PROTOCOL, MONGOC_ERROR_PROTOCOL_INVALID_REPLY, @@ -318,8 +289,7 @@ _server_monitor_send_and_recv_hello_opmsg ( mcd_rpc_message_ingress (rpc); - if (!mcd_rpc_message_decompress_if_necessary ( - rpc, &decompressed_data, &decompressed_data_len)) { + if (!mcd_rpc_message_decompress_if_necessary (rpc, &decompressed_data, &decompressed_data_len)) { bson_set_error (error, MONGOC_ERROR_PROTOCOL, MONGOC_ERROR_PROTOCOL_INVALID_REPLY, @@ -374,15 +344,12 @@ _server_monitor_send_and_recv_opquery (mongoc_server_monitor_t *server_monitor, int32_t message_length = 0; message_length += mcd_rpc_header_set_message_length (rpc, 0); - message_length += - mcd_rpc_header_set_request_id (rpc, server_monitor->request_id++); + message_length += mcd_rpc_header_set_request_id (rpc, server_monitor->request_id++); message_length += mcd_rpc_header_set_response_to (rpc, 0); message_length += mcd_rpc_header_set_op_code (rpc, MONGOC_OP_CODE_QUERY); - message_length += - mcd_rpc_op_query_set_flags (rpc, MONGOC_OP_QUERY_FLAG_SECONDARY_OK); - message_length += - mcd_rpc_op_query_set_full_collection_name (rpc, "admin.$cmd"); + message_length += mcd_rpc_op_query_set_flags (rpc, MONGOC_OP_QUERY_FLAG_SECONDARY_OK); + message_length += mcd_rpc_op_query_set_full_collection_name (rpc, "admin.$cmd"); message_length += mcd_rpc_op_query_set_number_to_skip (rpc, 0); message_length += mcd_rpc_op_query_set_number_to_return (rpc, -1); message_length += mcd_rpc_op_query_set_query (rpc, bson_get_data (cmd)); @@ -394,19 +361,13 @@ _server_monitor_send_and_recv_opquery (mongoc_server_monitor_t *server_monitor, BSON_ASSERT (iovecs); mcd_rpc_message_egress (rpc); - if (!_mongoc_stream_writev_full (server_monitor->stream, - iovecs, - num_iovecs, - server_monitor->connect_timeout_ms, - error)) { + if (!_mongoc_stream_writev_full ( + server_monitor->stream, iovecs, num_iovecs, server_monitor->connect_timeout_ms, error)) { goto fail; } - if (!_mongoc_buffer_append_from_stream (&buffer, - server_monitor->stream, - sizeof (int32_t), - server_monitor->connect_timeout_ms, - error)) { + if (!_mongoc_buffer_append_from_stream ( + &buffer, server_monitor->stream, sizeof (int32_t), server_monitor->connect_timeout_ms, error)) { goto fail; } @@ -425,17 +386,13 @@ _server_monitor_send_and_recv_opquery (mongoc_server_monitor_t *server_monitor, const size_t remaining_bytes = (size_t) message_length - sizeof (int32_t); - if (!_mongoc_buffer_append_from_stream (&buffer, - server_monitor->stream, - remaining_bytes, - server_monitor->connect_timeout_ms, - error)) { + if (!_mongoc_buffer_append_from_stream ( + &buffer, server_monitor->stream, remaining_bytes, server_monitor->connect_timeout_ms, error)) { goto fail; } mcd_rpc_message_reset (rpc); - if (!mcd_rpc_message_from_data_in_place ( - rpc, buffer.data, buffer.len, NULL)) { + if (!mcd_rpc_message_from_data_in_place (rpc, buffer.data, buffer.len, NULL)) { bson_set_error (error, MONGOC_ERROR_PROTOCOL, MONGOC_ERROR_PROTOCOL_INVALID_REPLY, @@ -445,8 +402,7 @@ _server_monitor_send_and_recv_opquery (mongoc_server_monitor_t *server_monitor, mcd_rpc_message_ingress (rpc); - if (!mcd_rpc_message_decompress_if_necessary ( - rpc, &decompressed_data, &decompressed_data_len)) { + if (!mcd_rpc_message_decompress_if_necessary (rpc, &decompressed_data, &decompressed_data_len)) { bson_set_error (error, MONGOC_ERROR_PROTOCOL, MONGOC_ERROR_PROTOCOL_INVALID_REPLY, @@ -482,21 +438,16 @@ _server_monitor_send_and_recv_opquery (mongoc_server_monitor_t *server_monitor, } static bool -_server_monitor_send_and_recv (mongoc_server_monitor_t *server_monitor, - bson_t *cmd, - bson_t *reply, - bson_error_t *error) +_server_monitor_send_and_recv (mongoc_server_monitor_t *server_monitor, bson_t *cmd, bson_t *reply, bson_error_t *error) { if (mongoc_topology_uses_server_api (server_monitor->topology) || mongoc_topology_uses_loadbalanced (server_monitor->topology)) { /* OP_MSG requires a "db" parameter: */ bson_append_utf8 (cmd, "$db", 3, "admin", 5); - return _server_monitor_send_and_recv_hello_opmsg ( - server_monitor, cmd, reply, error); + return _server_monitor_send_and_recv_hello_opmsg (server_monitor, cmd, reply, error); } else { - return _server_monitor_send_and_recv_opquery ( - server_monitor, cmd, reply, error); + return _server_monitor_send_and_recv_opquery (server_monitor, cmd, reply, error); } } @@ -510,23 +461,19 @@ _server_monitor_polling_hello (mongoc_server_monitor_t *server_monitor, const bson_t *hello; bool ret; - hello = _mongoc_topology_scanner_get_monitoring_cmd ( - server_monitor->topology->scanner, hello_ok); + hello = _mongoc_topology_scanner_get_monitoring_cmd (server_monitor->topology->scanner, hello_ok); bson_copy_to (hello, &cmd); _server_monitor_append_cluster_time (server_monitor, &cmd); - ret = _server_monitor_send_and_recv ( - server_monitor, &cmd, hello_response, error); + ret = _server_monitor_send_and_recv (server_monitor, &cmd, hello_response, error); bson_destroy (&cmd); return ret; } static bool -_server_monitor_awaitable_hello_send (mongoc_server_monitor_t *server_monitor, - bson_t *cmd, - bson_error_t *error) +_server_monitor_awaitable_hello_send (mongoc_server_monitor_t *server_monitor, bson_t *cmd, bson_error_t *error) { bool ret = false; @@ -536,18 +483,15 @@ _server_monitor_awaitable_hello_send (mongoc_server_monitor_t *server_monitor, int32_t message_length = 0; message_length += mcd_rpc_header_set_message_length (rpc, 0); - message_length += - mcd_rpc_header_set_request_id (rpc, server_monitor->request_id++); + message_length += mcd_rpc_header_set_request_id (rpc, server_monitor->request_id++); message_length += mcd_rpc_header_set_response_to (rpc, 0); message_length += mcd_rpc_header_set_op_code (rpc, MONGOC_OP_CODE_MSG); mcd_rpc_op_msg_set_sections_count (rpc, 1); - message_length += - mcd_rpc_op_msg_set_flag_bits (rpc, MONGOC_OP_MSG_FLAG_EXHAUST_ALLOWED); + message_length += mcd_rpc_op_msg_set_flag_bits (rpc, MONGOC_OP_MSG_FLAG_EXHAUST_ALLOWED); message_length += mcd_rpc_op_msg_section_set_kind (rpc, 0u, 0); - message_length += - mcd_rpc_op_msg_section_set_body (rpc, 0u, bson_get_data (cmd)); + message_length += mcd_rpc_op_msg_section_set_body (rpc, 0u, bson_get_data (cmd)); mcd_rpc_message_set_length (rpc, message_length); } @@ -556,18 +500,12 @@ _server_monitor_awaitable_hello_send (mongoc_server_monitor_t *server_monitor, mongoc_iovec_t *const iovecs = mcd_rpc_message_to_iovecs (rpc, &num_iovecs); BSON_ASSERT (iovecs); - MONITOR_LOG (server_monitor, - "sending with timeout %" PRId64, - server_monitor->connect_timeout_ms); + MONITOR_LOG (server_monitor, "sending with timeout %" PRId64, server_monitor->connect_timeout_ms); mcd_rpc_message_egress (rpc); - if (!_mongoc_stream_writev_full (server_monitor->stream, - iovecs, - num_iovecs, - server_monitor->connect_timeout_ms, - error)) { - MONITOR_LOG_ERROR ( - server_monitor, "failed to write awaitable hello: %s", error->message); + if (!_mongoc_stream_writev_full ( + server_monitor->stream, iovecs, num_iovecs, server_monitor->connect_timeout_ms, error)) { + MONITOR_LOG_ERROR (server_monitor, "failed to write awaitable hello: %s", error->message); goto done; } @@ -602,35 +540,21 @@ _server_monitor_poll_with_interrupt (mongoc_server_monitor_t *server_monitor, ssize_t ret; mongoc_stream_poll_t poller[1]; - MONITOR_LOG (server_monitor, - "_server_monitor_poll_with_interrupt expires in: %" PRIu64 - "ms", - timeleft_ms); + MONITOR_LOG (server_monitor, "_server_monitor_poll_with_interrupt expires in: %" PRIu64 "ms", timeleft_ms); poller[0].stream = server_monitor->stream; - poller[0].events = - POLLIN; /* POLLERR and POLLHUP are added in mongoc_socket_poll. */ + poller[0].events = POLLIN; /* POLLERR and POLLHUP are added in mongoc_socket_poll. */ poller[0].revents = 0; - MONITOR_LOG ( - server_monitor, - "polling for awaitable hello reply with timeleft_ms: %" PRId64, - timeleft_ms); - ret = mongoc_stream_poll ( - poller, 1, (int32_t) BSON_MIN (timeleft_ms, monitor_tick_ms)); + MONITOR_LOG (server_monitor, "polling for awaitable hello reply with timeleft_ms: %" PRId64, timeleft_ms); + ret = mongoc_stream_poll (poller, 1, (int32_t) BSON_MIN (timeleft_ms, monitor_tick_ms)); if (ret == -1) { MONITOR_LOG (server_monitor, "mongoc_stream_poll error"); - bson_set_error (error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_SOCKET, - "poll error"); + bson_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "poll error"); return false; } if (poller[0].revents & (POLLERR | POLLHUP)) { - bson_set_error (error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_SOCKET, - "connection closed while polling"); + bson_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "connection closed while polling"); return false; } @@ -650,10 +574,7 @@ _server_monitor_poll_with_interrupt (mongoc_server_monitor_t *server_monitor, return true; } } - bson_set_error (error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_SOCKET, - "connection timeout while polling"); + bson_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "connection timeout while polling"); return false; } @@ -669,10 +590,8 @@ _get_timeout_ms (int64_t expire_at_ms, bson_error_t *error) timeout_ms = expire_at_ms - _now_ms (); if (timeout_ms <= 0) { - bson_set_error (error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_SOCKET, - "connection timed out reading message length"); + bson_set_error ( + error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "connection timed out reading message length"); return 0; } return timeout_ms; @@ -703,12 +622,10 @@ _server_monitor_awaitable_hello_recv (mongoc_server_monitor_t *server_monitor, void *decompressed_data = NULL; size_t decompressed_data_len = 0u; - const int64_t expire_at_ms = _now_ms () + - server_monitor->heartbeat_frequency_ms + - server_monitor->connect_timeout_ms; + const int64_t expire_at_ms = + _now_ms () + server_monitor->heartbeat_frequency_ms + server_monitor->connect_timeout_ms; - if (!_server_monitor_poll_with_interrupt ( - server_monitor, expire_at_ms, cancelled, error)) { + if (!_server_monitor_poll_with_interrupt (server_monitor, expire_at_ms, cancelled, error)) { GOTO (fail); } @@ -717,14 +634,9 @@ _server_monitor_awaitable_hello_recv (mongoc_server_monitor_t *server_monitor, GOTO (fail); } - MONITOR_LOG (server_monitor, - "reading first 4 bytes with timeout: %" PRId64, - timeout_ms); - if (!_mongoc_buffer_append_from_stream (&buffer, - server_monitor->stream, - sizeof (int32_t), - (int32_t) timeout_ms, - error)) { + MONITOR_LOG (server_monitor, "reading first 4 bytes with timeout: %" PRId64, timeout_ms); + if (!_mongoc_buffer_append_from_stream ( + &buffer, server_monitor->stream, sizeof (int32_t), (int32_t) timeout_ms, error)) { GOTO (fail); } @@ -733,13 +645,11 @@ _server_monitor_awaitable_hello_recv (mongoc_server_monitor_t *server_monitor, // msgHeader consists of four int32 fields. const int32_t message_header_length = 4u * sizeof (int32_t); - if ((message_length < message_header_length) || - (message_length > server_monitor->description->max_msg_size)) { + if ((message_length < message_header_length) || (message_length > server_monitor->description->max_msg_size)) { bson_set_error (error, MONGOC_ERROR_PROTOCOL, MONGOC_ERROR_PROTOCOL_INVALID_REPLY, - "message size %" PRId32 - " is not within expected range 16-%" PRId32 " bytes", + "message size %" PRId32 " is not within expected range 16-%" PRId32 " bytes", message_length, server_monitor->description->max_msg_size); GOTO (fail); @@ -752,52 +662,35 @@ _server_monitor_awaitable_hello_recv (mongoc_server_monitor_t *server_monitor, const size_t remaining_bytes = (size_t) message_length - sizeof (int32_t); - MONITOR_LOG (server_monitor, - "reading remaining %zu bytes. Timeout %" PRId64, - remaining_bytes, - timeout_ms); - if (!_mongoc_buffer_append_from_stream (&buffer, - server_monitor->stream, - remaining_bytes, - timeout_ms, - error)) { + MONITOR_LOG (server_monitor, "reading remaining %zu bytes. Timeout %" PRId64, remaining_bytes, timeout_ms); + if (!_mongoc_buffer_append_from_stream (&buffer, server_monitor->stream, remaining_bytes, timeout_ms, error)) { GOTO (fail); } - if (!mcd_rpc_message_from_data_in_place ( - rpc, buffer.data, buffer.len, NULL)) { - bson_set_error (error, - MONGOC_ERROR_PROTOCOL, - MONGOC_ERROR_PROTOCOL_INVALID_REPLY, - "malformed message from server"); + if (!mcd_rpc_message_from_data_in_place (rpc, buffer.data, buffer.len, NULL)) { + bson_set_error ( + error, MONGOC_ERROR_PROTOCOL, MONGOC_ERROR_PROTOCOL_INVALID_REPLY, "malformed message from server"); GOTO (fail); } mcd_rpc_message_ingress (rpc); - if (!mcd_rpc_message_decompress_if_necessary ( - rpc, &decompressed_data, &decompressed_data_len)) { - bson_set_error (error, - MONGOC_ERROR_PROTOCOL, - MONGOC_ERROR_PROTOCOL_INVALID_REPLY, - "decompression failure"); + if (!mcd_rpc_message_decompress_if_necessary (rpc, &decompressed_data, &decompressed_data_len)) { + bson_set_error (error, MONGOC_ERROR_PROTOCOL, MONGOC_ERROR_PROTOCOL_INVALID_REPLY, "decompression failure"); GOTO (fail); } bson_t body; if (!mcd_rpc_message_get_body (rpc, &body)) { - bson_set_error (error, - MONGOC_ERROR_PROTOCOL, - MONGOC_ERROR_PROTOCOL_INVALID_REPLY, - "malformed BSON payload from server"); + bson_set_error ( + error, MONGOC_ERROR_PROTOCOL, MONGOC_ERROR_PROTOCOL_INVALID_REPLY, "malformed BSON payload from server"); GOTO (fail); } bson_copy_to (&body, hello_response); bson_destroy (&body); - server_monitor->more_to_come = (mcd_rpc_op_msg_get_flag_bits (rpc) & - MONGOC_OP_MSG_FLAG_MORE_TO_COME) != 0; + server_monitor->more_to_come = (mcd_rpc_op_msg_get_flag_bits (rpc) & MONGOC_OP_MSG_FLAG_MORE_TO_COME) != 0; ret = true; @@ -830,23 +723,19 @@ _server_monitor_awaitable_hello (mongoc_server_monitor_t *server_monitor, const bson_t *hello; bool ret = false; - hello = _mongoc_topology_scanner_get_monitoring_cmd ( - server_monitor->topology->scanner, description->hello_ok); + hello = _mongoc_topology_scanner_get_monitoring_cmd (server_monitor->topology->scanner, description->hello_ok); bson_copy_to (hello, &cmd); _server_monitor_append_cluster_time (server_monitor, &cmd); - bson_append_document ( - &cmd, "topologyVersion", 15, &description->topology_version); - bson_append_int64 ( - &cmd, "maxAwaitTimeMS", 14, server_monitor->heartbeat_frequency_ms); + bson_append_document (&cmd, "topologyVersion", 15, &description->topology_version); + bson_append_int64 (&cmd, "maxAwaitTimeMS", 14, server_monitor->heartbeat_frequency_ms); bson_append_utf8 (&cmd, "$db", 3, "admin", 5); if (!_server_monitor_awaitable_hello_send (server_monitor, &cmd, error)) { GOTO (fail); } - if (!_server_monitor_awaitable_hello_recv ( - server_monitor, hello_response, cancelled, error)) { + if (!_server_monitor_awaitable_hello_recv (server_monitor, hello_response, cancelled, error)) { bson_destroy (hello_response); GOTO (fail); } @@ -867,8 +756,7 @@ _server_monitor_awaitable_hello (mongoc_server_monitor_t *server_monitor, * Locks server monitor mutex. */ static void -_update_topology_description (mongoc_server_monitor_t *server_monitor, - mongoc_server_description_t *description) +_update_topology_description (mongoc_server_monitor_t *server_monitor, mongoc_server_description_t *description) { mongoc_topology_t *topology; bson_t *hello_response = NULL; @@ -883,8 +771,7 @@ _update_topology_description (mongoc_server_monitor_t *server_monitor, _mongoc_topology_update_cluster_time (topology, hello_response); } - if (bson_atomic_int_fetch (&topology->scanner_state, - bson_memory_order_relaxed) == + if (bson_atomic_int_fetch (&topology->scanner_state, bson_memory_order_relaxed) == MONGOC_TOPOLOGY_SCANNER_SHUTTING_DOWN) { return; } @@ -893,11 +780,8 @@ _update_topology_description (mongoc_server_monitor_t *server_monitor, bson_mutex_lock (&server_monitor->shared.mutex); server_monitor->shared.scan_requested = false; bson_mutex_unlock (&server_monitor->shared.mutex); - mongoc_topology_description_handle_hello (tdmod.new_td, - server_monitor->server_id, - hello_response, - description->round_trip_time_msec, - &description->error); + mongoc_topology_description_handle_hello ( + tdmod.new_td, server_monitor->server_id, hello_response, description->round_trip_time_msec, &description->error); /* Reconcile server monitors. */ _mongoc_topology_background_monitoring_reconcile (topology, tdmod.new_td); /* Wake threads performing server selection. */ @@ -915,15 +799,12 @@ mongoc_server_monitor_new (mongoc_topology_t *topology, mongoc_topology_description_t *td, mongoc_server_description_t *init_description) { - mongoc_server_monitor_t *server_monitor = - bson_malloc0 (sizeof (*server_monitor)); - server_monitor->description = - mongoc_server_description_new_copy (init_description); + mongoc_server_monitor_t *server_monitor = bson_malloc0 (sizeof (*server_monitor)); + server_monitor->description = mongoc_server_description_new_copy (init_description); server_monitor->server_id = init_description->id; server_monitor->topology = topology; server_monitor->heartbeat_frequency_ms = td->heartbeat_msec; - server_monitor->min_heartbeat_frequency_ms = - topology->min_heartbeat_frequency_msec; + server_monitor->min_heartbeat_frequency_ms = topology->min_heartbeat_frequency_msec; server_monitor->connect_timeout_ms = topology->connect_timeout_msec; server_monitor->uri = mongoc_uri_copy (topology->uri); /* TODO CDRIVER-3682: Do not retrieve ssl opts from topology scanner. They @@ -932,13 +813,10 @@ mongoc_server_monitor_new (mongoc_topology_t *topology, if (topology->scanner->ssl_opts) { server_monitor->ssl_opts = bson_malloc0 (sizeof (mongoc_ssl_opt_t)); - _mongoc_ssl_opts_copy_to ( - topology->scanner->ssl_opts, server_monitor->ssl_opts, true); + _mongoc_ssl_opts_copy_to (topology->scanner->ssl_opts, server_monitor->ssl_opts, true); } #endif - memcpy (&server_monitor->apm_callbacks, - &td->apm_callbacks, - sizeof (mongoc_apm_callbacks_t)); + memcpy (&server_monitor->apm_callbacks, &td->apm_callbacks, sizeof (mongoc_apm_callbacks_t)); server_monitor->apm_context = td->apm_context; server_monitor->initiator = topology->scanner->initiator; server_monitor->initiator_context = topology->scanner->initiator_context; @@ -973,24 +851,16 @@ _server_monitor_setup_connection (mongoc_server_monitor_t *server_monitor, /* Using an initiator isn't really necessary. Users can't set them on * pools. But it is used for tests. */ if (server_monitor->initiator) { - server_monitor->stream = - server_monitor->initiator (server_monitor->uri, - &server_monitor->description->host, - server_monitor->initiator_context, - error); + server_monitor->stream = server_monitor->initiator ( + server_monitor->uri, &server_monitor->description->host, server_monitor->initiator_context, error); } else { void *ssl_opts_void = NULL; #ifdef MONGOC_ENABLE_SSL ssl_opts_void = server_monitor->ssl_opts; #endif - server_monitor->stream = - mongoc_client_connect (false, - ssl_opts_void != NULL, - ssl_opts_void, - server_monitor->uri, - &server_monitor->description->host, - error); + server_monitor->stream = mongoc_client_connect ( + false, ssl_opts_void != NULL, ssl_opts_void, server_monitor->uri, &server_monitor->description->host, error); } if (!server_monitor->stream) { @@ -1005,8 +875,7 @@ _server_monitor_setup_connection (mongoc_server_monitor_t *server_monitor, _server_monitor_append_cluster_time (server_monitor, &cmd); bson_destroy (hello_response); - ret = _server_monitor_send_and_recv ( - server_monitor, &cmd, hello_response, error); + ret = _server_monitor_send_and_recv (server_monitor, &cmd, hello_response, error); fail: bson_destroy (&cmd); @@ -1029,10 +898,9 @@ _server_monitor_setup_connection (mongoc_server_monitor_t *server_monitor, * information, but with no hello reply. */ static mongoc_server_description_t * -_server_monitor_check_server ( - mongoc_server_monitor_t *server_monitor, - const mongoc_server_description_t *previous_description, - bool *cancelled) +_server_monitor_check_server (mongoc_server_monitor_t *server_monitor, + const mongoc_server_description_t *previous_description, + bool *cancelled) { bool ret = false; bson_error_t error; @@ -1050,17 +918,14 @@ _server_monitor_check_server ( memset (&error, 0, sizeof (bson_error_t)); description = BSON_ALIGNED_ALLOC0 (mongoc_server_description_t); mongoc_server_description_init ( - description, - server_monitor->description->connection_address, - server_monitor->description->id); + description, server_monitor->description->connection_address, server_monitor->description->id); start_us = _now_us (); if (!server_monitor->stream) { MONITOR_LOG (server_monitor, "setting up connection"); awaited = false; _server_monitor_heartbeat_started (server_monitor, awaited); - ret = _server_monitor_setup_connection ( - server_monitor, &hello_response, &start_us, &error); + ret = _server_monitor_setup_connection (server_monitor, &hello_response, &start_us, &error); GOTO (exit); } @@ -1069,8 +934,7 @@ _server_monitor_check_server ( /* Publish a heartbeat started for each additional response read. */ _server_monitor_heartbeat_started (server_monitor, awaited); MONITOR_LOG (server_monitor, "more to come"); - ret = _server_monitor_awaitable_hello_recv ( - server_monitor, &hello_response, cancelled, &error); + ret = _server_monitor_awaitable_hello_recv (server_monitor, &hello_response, cancelled, &error); GOTO (exit); } @@ -1082,28 +946,21 @@ _server_monitor_check_server ( awaited = true; _server_monitor_heartbeat_started (server_monitor, awaited); MONITOR_LOG (server_monitor, "awaitable hello"); - ret = _server_monitor_awaitable_hello (server_monitor, - previous_description, - &hello_response, - cancelled, - &error); + ret = _server_monitor_awaitable_hello (server_monitor, previous_description, &hello_response, cancelled, &error); GOTO (exit); } MONITOR_LOG (server_monitor, "polling hello"); awaited = false; _server_monitor_heartbeat_started (server_monitor, awaited); - ret = _server_monitor_polling_hello ( - server_monitor, previous_description->hello_ok, &hello_response, &error); + ret = _server_monitor_polling_hello (server_monitor, previous_description->hello_ok, &hello_response, &error); exit: duration_us = _now_us () - start_us; - MONITOR_LOG ( - server_monitor, "server check duration (us): %" PRId64, duration_us); + MONITOR_LOG (server_monitor, "server check duration (us): %" PRId64, duration_us); /* If ret is true, we have a reply. Check if "ok": 1. */ - if (ret && _mongoc_cmd_check_ok ( - &hello_response, MONGOC_ERROR_API_VERSION_2, &error)) { + if (ret && _mongoc_cmd_check_ok (&hello_response, MONGOC_ERROR_API_VERSION_2, &error)) { int64_t rtt_ms = MONGOC_RTT_UNSET; /* rtt remains MONGOC_RTT_UNSET if awaited. */ @@ -1111,20 +968,15 @@ _server_monitor_check_server ( rtt_ms = duration_us / 1000; } - mongoc_server_description_handle_hello ( - description, &hello_response, rtt_ms, NULL); + mongoc_server_description_handle_hello (description, &hello_response, rtt_ms, NULL); /* If the hello reply could not be parsed, consider this a command * error. */ if (description->error.code) { - MONITOR_LOG_ERROR (server_monitor, - "error parsing server reply: %s", - description->error.message); + MONITOR_LOG_ERROR (server_monitor, "error parsing server reply: %s", description->error.message); command_or_network_error = true; - _server_monitor_heartbeat_failed ( - server_monitor, &description->error, duration_us, awaited); + _server_monitor_heartbeat_failed (server_monitor, &description->error, duration_us, awaited); } else { - _server_monitor_heartbeat_succeeded ( - server_monitor, &hello_response, duration_us, awaited); + _server_monitor_heartbeat_succeeded (server_monitor, &hello_response, duration_us, awaited); } } else if (*cancelled) { MONITOR_LOG (server_monitor, "server monitor cancelled"); @@ -1133,18 +985,13 @@ _server_monitor_check_server ( } server_monitor->stream = NULL; server_monitor->more_to_come = false; - _server_monitor_heartbeat_failed ( - server_monitor, &description->error, duration_us, awaited); + _server_monitor_heartbeat_failed (server_monitor, &description->error, duration_us, awaited); } else { /* The hello reply had "ok":0 or a network error occurred. */ - MONITOR_LOG_ERROR (server_monitor, - "command or network error occurred: %s", - error.message); + MONITOR_LOG_ERROR (server_monitor, "command or network error occurred: %s", error.message); command_or_network_error = true; - mongoc_server_description_handle_hello ( - description, NULL, MONGOC_RTT_UNSET, &error); - _server_monitor_heartbeat_failed ( - server_monitor, &description->error, duration_us, awaited); + mongoc_server_description_handle_hello (description, NULL, MONGOC_RTT_UNSET, &error); + _server_monitor_heartbeat_failed (server_monitor, &description->error, duration_us, awaited); } if (command_or_network_error) { @@ -1157,9 +1004,7 @@ _server_monitor_check_server ( /* clear_connection_pool() is a no-op if 'description->id' was already * removed. */ _mongoc_topology_description_clear_connection_pool ( - tdmod.new_td, - server_monitor->description->id, - &server_monitor->description->service_id); + tdmod.new_td, server_monitor->description->id, &server_monitor->description->service_id); mc_tpld_modify_commit (tdmod); } @@ -1231,9 +1076,7 @@ mongoc_server_monitor_wait (mongoc_server_monitor_t *server_monitor) } MONITOR_LOG (server_monitor, "sleeping for %" PRId64, sleep_duration_ms); - cond_ret = mongoc_cond_timedwait (&server_monitor->shared.cond, - &server_monitor->shared.mutex, - sleep_duration_ms); + cond_ret = mongoc_cond_timedwait (&server_monitor->shared.cond, &server_monitor->shared.mutex, sleep_duration_ms); if (mongo_cond_ret_is_timedout (cond_ret)) { break; } @@ -1252,8 +1095,7 @@ static BSON_THREAD_FUN (_server_monitor_thread, server_monitor_void) mongoc_server_description_t *previous_description; server_monitor = (mongoc_server_monitor_t *) server_monitor_void; - description = - mongoc_server_description_new_copy (server_monitor->description); + description = mongoc_server_description_new_copy (server_monitor->description); previous_description = NULL; while (true) { @@ -1269,8 +1111,7 @@ static BSON_THREAD_FUN (_server_monitor_thread, server_monitor_void) mongoc_server_description_destroy (previous_description); previous_description = mongoc_server_description_new_copy (description); mongoc_server_description_destroy (description); - description = _server_monitor_check_server ( - server_monitor, previous_description, &cancelled); + description = _server_monitor_check_server (server_monitor, previous_description, &cancelled); if (cancelled) { mongoc_server_monitor_wait (server_monitor); @@ -1281,26 +1122,21 @@ static BSON_THREAD_FUN (_server_monitor_thread, server_monitor_void) /* Immediately proceed to the next check if the previous response was * successful and included the topologyVersion field. */ - if (description->type != MONGOC_SERVER_UNKNOWN && - !bson_empty (&description->topology_version)) { - MONITOR_LOG (server_monitor, - "immediately proceeding due to topologyVersion"); + if (description->type != MONGOC_SERVER_UNKNOWN && !bson_empty (&description->topology_version)) { + MONITOR_LOG (server_monitor, "immediately proceeding due to topologyVersion"); continue; } /* ... or the previous response included the moreToCome flag */ if (server_monitor->more_to_come) { - MONITOR_LOG (server_monitor, - "immediately proceeding due to moreToCome"); + MONITOR_LOG (server_monitor, "immediately proceeding due to moreToCome"); continue; } /* ... or the server has just transitioned to Unknown due to a network * error. */ - if (_mongoc_error_is_network (&description->error) && - previous_description->type != MONGOC_SERVER_UNKNOWN) { - MONITOR_LOG (server_monitor, - "immediately proceeding due to network error"); + if (_mongoc_error_is_network (&description->error) && previous_description->type != MONGOC_SERVER_UNKNOWN) { + MONITOR_LOG (server_monitor, "immediately proceeding due to network error"); continue; } @@ -1316,9 +1152,7 @@ static BSON_THREAD_FUN (_server_monitor_thread, server_monitor_void) } static bool -_server_monitor_ping_server (mongoc_server_monitor_t *server_monitor, - bool hello_ok, - int64_t *rtt_ms) +_server_monitor_ping_server (mongoc_server_monitor_t *server_monitor, bool hello_ok, int64_t *rtt_ms) { bool ret = false; int64_t start_us = _now_us (); @@ -1329,15 +1163,13 @@ _server_monitor_ping_server (mongoc_server_monitor_t *server_monitor, if (!server_monitor->stream) { MONITOR_LOG (server_monitor, "rtt setting up connection"); - ret = _server_monitor_setup_connection ( - server_monitor, &hello_response, &start_us, &error); + ret = _server_monitor_setup_connection (server_monitor, &hello_response, &start_us, &error); bson_destroy (&hello_response); } if (server_monitor->stream) { MONITOR_LOG (server_monitor, "rtt polling hello"); - ret = _server_monitor_polling_hello ( - server_monitor, hello_ok, &hello_response, &error); + ret = _server_monitor_polling_hello (server_monitor, hello_ok, &hello_response, &error); if (ret) { *rtt_ms = (_now_us () - start_us) / 1000; } @@ -1369,19 +1201,16 @@ static BSON_THREAD_FUN (_server_monitor_rtt_thread, server_monitor_void) { mc_shared_tpld td = mc_tpld_take_ref (server_monitor->topology); const mongoc_server_description_t *sd = - mongoc_topology_description_server_by_id_const ( - td.ptr, server_monitor->description->id, &error); + mongoc_topology_description_server_by_id_const (td.ptr, server_monitor->description->id, &error); hello_ok = sd ? sd->hello_ok : false; mc_tpld_drop_ref (&td); } _server_monitor_ping_server (server_monitor, hello_ok, &rtt_ms); if (rtt_ms != MONGOC_RTT_UNSET) { - mc_tpld_modification tdmod = - mc_tpld_modify_begin (server_monitor->topology); + mc_tpld_modification tdmod = mc_tpld_modify_begin (server_monitor->topology); mongoc_server_description_t *const mut_sd = - mongoc_topology_description_server_by_id ( - tdmod.new_td, server_monitor->description->id, &error); + mongoc_topology_description_server_by_id (tdmod.new_td, server_monitor->description->id, &error); if (mut_sd) { mongoc_server_description_update_rtt (mut_sd, rtt_ms); mc_tpld_modify_commit (tdmod); @@ -1407,8 +1236,7 @@ mongoc_server_monitor_run (mongoc_server_monitor_t *server_monitor) bson_mutex_lock (&server_monitor->shared.mutex); if (server_monitor->shared.state == MONGOC_THREAD_OFF) { server_monitor->is_rtt = false; - int ret = mcommon_thread_create ( - &server_monitor->thread, _server_monitor_thread, server_monitor); + int ret = mcommon_thread_create (&server_monitor->thread, _server_monitor_thread, server_monitor); if (ret == 0) { server_monitor->shared.state = MONGOC_THREAD_RUNNING; } else { @@ -1430,18 +1258,16 @@ mongoc_server_monitor_run_as_rtt (mongoc_server_monitor_t *server_monitor) bson_mutex_lock (&server_monitor->shared.mutex); if (server_monitor->shared.state == MONGOC_THREAD_OFF) { server_monitor->is_rtt = true; - int ret = mcommon_thread_create ( - &server_monitor->thread, _server_monitor_rtt_thread, server_monitor); + int ret = mcommon_thread_create (&server_monitor->thread, _server_monitor_rtt_thread, server_monitor); if (ret == 0) { server_monitor->shared.state = MONGOC_THREAD_RUNNING; } else { char errmsg_buf[BSON_ERROR_BUFFER_SIZE]; char *errmsg = bson_strerror_r (ret, errmsg_buf, sizeof errmsg_buf); - _server_monitor_log ( - server_monitor, - MONGOC_LOG_LEVEL_ERROR, - "Failed to start Round-Trip Time monitoring thread. Error: %s", - errmsg); + _server_monitor_log (server_monitor, + MONGOC_LOG_LEVEL_ERROR, + "Failed to start Round-Trip Time monitoring thread. Error: %s", + errmsg); } } bson_mutex_unlock (&server_monitor->shared.mutex); @@ -1485,8 +1311,7 @@ mongoc_server_monitor_request_shutdown (mongoc_server_monitor_t *server_monitor) * Locks the server monitor mutex. */ void -mongoc_server_monitor_wait_for_shutdown ( - mongoc_server_monitor_t *server_monitor) +mongoc_server_monitor_wait_for_shutdown (mongoc_server_monitor_t *server_monitor) { if (mongoc_server_monitor_request_shutdown (server_monitor)) { return; diff --git a/src/libmongoc/src/mongoc/mongoc-server-stream-private.h b/src/libmongoc/src/mongoc/mongoc-server-stream-private.h index 0dfab75744..f6042a7931 100644 --- a/src/libmongoc/src/mongoc/mongoc-server-stream-private.h +++ b/src/libmongoc/src/mongoc/mongoc-server-stream-private.h @@ -56,8 +56,7 @@ int32_t mongoc_server_stream_max_msg_size (mongoc_server_stream_t *server_stream); int32_t -mongoc_server_stream_max_write_batch_size ( - mongoc_server_stream_t *server_stream); +mongoc_server_stream_max_write_batch_size (mongoc_server_stream_t *server_stream); void mongoc_server_stream_cleanup (mongoc_server_stream_t *server_stream); diff --git a/src/libmongoc/src/mongoc/mongoc-server-stream.c b/src/libmongoc/src/mongoc/mongoc-server-stream.c index 7c03ebd8b0..a94f8fffa1 100644 --- a/src/libmongoc/src/mongoc/mongoc-server-stream.c +++ b/src/libmongoc/src/mongoc/mongoc-server-stream.c @@ -66,8 +66,7 @@ mongoc_server_stream_cleanup (mongoc_server_stream_t *server_stream) int32_t mongoc_server_stream_max_bson_obj_size (mongoc_server_stream_t *server_stream) { - return COALESCE (server_stream->sd->max_bson_obj_size, - MONGOC_DEFAULT_BSON_OBJ_SIZE); + return COALESCE (server_stream->sd->max_bson_obj_size, MONGOC_DEFAULT_BSON_OBJ_SIZE); } /* @@ -83,8 +82,7 @@ mongoc_server_stream_max_bson_obj_size (mongoc_server_stream_t *server_stream) int32_t mongoc_server_stream_max_msg_size (mongoc_server_stream_t *server_stream) { - return COALESCE (server_stream->sd->max_msg_size, - MONGOC_DEFAULT_MAX_MSG_SIZE); + return COALESCE (server_stream->sd->max_msg_size, MONGOC_DEFAULT_MAX_MSG_SIZE); } /* @@ -98,9 +96,7 @@ mongoc_server_stream_max_msg_size (mongoc_server_stream_t *server_stream) */ int32_t -mongoc_server_stream_max_write_batch_size ( - mongoc_server_stream_t *server_stream) +mongoc_server_stream_max_write_batch_size (mongoc_server_stream_t *server_stream) { - return COALESCE (server_stream->sd->max_write_batch_size, - MONGOC_DEFAULT_WRITE_BATCH_SIZE); + return COALESCE (server_stream->sd->max_write_batch_size, MONGOC_DEFAULT_WRITE_BATCH_SIZE); } diff --git a/src/libmongoc/src/mongoc/mongoc-set-private.h b/src/libmongoc/src/mongoc/mongoc-set-private.h index abef64095a..41556abffa 100644 --- a/src/libmongoc/src/mongoc/mongoc-set-private.h +++ b/src/libmongoc/src/mongoc/mongoc-set-private.h @@ -28,9 +28,7 @@ typedef void (*mongoc_set_item_dtor) (void *item, void *ctx); /* return true to continue iteration, false to stop */ typedef bool (*mongoc_set_for_each_cb_t) (void *item, void *ctx); typedef bool (*mongoc_set_for_each_const_cb_t) (const void *item, void *ctx); -typedef bool (*mongoc_set_for_each_with_id_cb_t) (uint32_t id, - void *item, - void *ctx); +typedef bool (*mongoc_set_for_each_with_id_cb_t) (uint32_t id, void *item, void *ctx); typedef struct { uint32_t id; @@ -73,14 +71,10 @@ mongoc_set_get_item_const (const mongoc_set_t *set, size_t idx) } void * -mongoc_set_get_item_and_id (mongoc_set_t *set, - size_t idx, - uint32_t *id /* OUT */); +mongoc_set_get_item_and_id (mongoc_set_t *set, size_t idx, uint32_t *id /* OUT */); static BSON_INLINE const void * -mongoc_set_get_item_and_id_const (const mongoc_set_t *set, - size_t idx, - uint32_t *id) +mongoc_set_get_item_and_id_const (const mongoc_set_t *set, size_t idx, uint32_t *id) { return mongoc_set_get_item_and_id ((mongoc_set_t *) set, idx, id); } @@ -99,30 +93,21 @@ void mongoc_set_for_each (mongoc_set_t *set, mongoc_set_for_each_cb_t cb, void *ctx); static BSON_INLINE void -mongoc_set_for_each_const (const mongoc_set_t *set, - mongoc_set_for_each_const_cb_t cb, - void *ctx) +mongoc_set_for_each_const (const mongoc_set_t *set, mongoc_set_for_each_const_cb_t cb, void *ctx) { - mongoc_set_for_each ( - (mongoc_set_t *) set, (mongoc_set_for_each_cb_t) cb, ctx); + mongoc_set_for_each ((mongoc_set_t *) set, (mongoc_set_for_each_cb_t) cb, ctx); } void -mongoc_set_for_each_with_id (mongoc_set_t *set, - mongoc_set_for_each_with_id_cb_t cb, - void *ctx); +mongoc_set_for_each_with_id (mongoc_set_t *set, mongoc_set_for_each_with_id_cb_t cb, void *ctx); /* first item in set for which "cb" returns true */ void * -mongoc_set_find_item (mongoc_set_t *set, - mongoc_set_for_each_cb_t cb, - void *ctx); +mongoc_set_find_item (mongoc_set_t *set, mongoc_set_for_each_cb_t cb, void *ctx); /* id of first item in set for which "cb" returns true, or 0. */ uint32_t -mongoc_set_find_id (const mongoc_set_t *set, - mongoc_set_for_each_const_cb_t cb, - void *ctx); +mongoc_set_find_id (const mongoc_set_t *set, mongoc_set_for_each_const_cb_t cb, void *ctx); BSON_END_DECLS diff --git a/src/libmongoc/src/mongoc/mongoc-set.c b/src/libmongoc/src/mongoc/mongoc-set.c index df99d074d9..7462921d23 100644 --- a/src/libmongoc/src/mongoc/mongoc-set.c +++ b/src/libmongoc/src/mongoc/mongoc-set.c @@ -28,8 +28,7 @@ mongoc_set_new (size_t nitems, mongoc_set_item_dtor dtor, void *dtor_ctx) mongoc_set_t *set = (mongoc_set_t *) bson_malloc (sizeof (*set)); set->items_allocated = BSON_MAX (nitems, 1); - set->items = (mongoc_set_item_t *) bson_malloc (sizeof (*set->items) * - set->items_allocated); + set->items = (mongoc_set_item_t *) bson_malloc (sizeof (*set->items) * set->items_allocated); set->items_len = 0; set->dtor = dtor; @@ -56,8 +55,7 @@ mongoc_set_add (mongoc_set_t *set, uint32_t id, void *item) { if (set->items_len >= set->items_allocated) { set->items_allocated *= 2; - set->items = (mongoc_set_item_t *) bson_realloc ( - set->items, sizeof (*set->items) * set->items_allocated); + set->items = (mongoc_set_item_t *) bson_realloc (set->items, sizeof (*set->items) * set->items_allocated); } set->items[set->items_len].id = id; @@ -66,8 +64,7 @@ mongoc_set_add (mongoc_set_t *set, uint32_t id, void *item) set->items_len++; if (set->items_len > 1 && set->items[set->items_len - 2].id > id) { - qsort ( - set->items, set->items_len, sizeof (*set->items), mongoc_set_id_cmp); + qsort (set->items, set->items_len, sizeof (*set->items), mongoc_set_id_cmp); } } @@ -76,8 +73,8 @@ mongoc_set_rm (mongoc_set_t *set, uint32_t id) { const mongoc_set_item_t key = {.id = id}; - mongoc_set_item_t *const ptr = (mongoc_set_item_t *) bsearch ( - &key, set->items, set->items_len, sizeof (key), mongoc_set_id_cmp); + mongoc_set_item_t *const ptr = + (mongoc_set_item_t *) bsearch (&key, set->items, set->items_len, sizeof (key), mongoc_set_id_cmp); if (ptr) { if (set->dtor) { @@ -87,9 +84,7 @@ mongoc_set_rm (mongoc_set_t *set, uint32_t id) const size_t index = (size_t) (ptr - set->items); if (index != set->items_len - 1u) { - memmove (set->items + index, - set->items + index + 1u, - (set->items_len - (index + 1u)) * sizeof (key)); + memmove (set->items + index, set->items + index + 1u, (set->items_len - (index + 1u)) * sizeof (key)); } set->items_len--; @@ -104,8 +99,7 @@ mongoc_set_get (mongoc_set_t *set, uint32_t id) key.id = id; - ptr = (mongoc_set_item_t *) bsearch ( - &key, set->items, set->items_len, sizeof (key), mongoc_set_id_cmp); + ptr = (mongoc_set_item_t *) bsearch (&key, set->items, set->items_len, sizeof (key), mongoc_set_id_cmp); return ptr ? ptr->item : NULL; } @@ -121,9 +115,7 @@ mongoc_set_get_item (mongoc_set_t *set, size_t idx) void * -mongoc_set_get_item_and_id (mongoc_set_t *set, - size_t idx, - uint32_t *id /* OUT */) +mongoc_set_get_item_and_id (mongoc_set_t *set, size_t idx, uint32_t *id /* OUT */) { BSON_ASSERT (set); BSON_ASSERT (id); @@ -158,8 +150,7 @@ typedef struct { static bool _mongoc_set_for_each_helper (uint32_t id, void *item, void *ctx) { - _mongoc_set_for_each_helper_t *helper = - (_mongoc_set_for_each_helper_t *) ctx; + _mongoc_set_for_each_helper_t *helper = (_mongoc_set_for_each_helper_t *) ctx; BSON_UNUSED (id); @@ -178,9 +169,7 @@ mongoc_set_for_each (mongoc_set_t *set, mongoc_set_for_each_cb_t cb, void *ctx) } void -mongoc_set_for_each_with_id (mongoc_set_t *set, - mongoc_set_for_each_with_id_cb_t cb, - void *ctx) +mongoc_set_for_each_with_id (mongoc_set_t *set, mongoc_set_for_each_with_id_cb_t cb, void *ctx) { mongoc_set_item_t *old_set; @@ -206,9 +195,7 @@ mongoc_set_for_each_with_id (mongoc_set_t *set, static mongoc_set_item_t * -_mongoc_set_find (const mongoc_set_t *set, - mongoc_set_for_each_const_cb_t cb, - void *ctx) +_mongoc_set_find (const mongoc_set_t *set, mongoc_set_for_each_const_cb_t cb, void *ctx) { size_t i; size_t items_len; @@ -232,8 +219,7 @@ mongoc_set_find_item (mongoc_set_t *set, mongoc_set_for_each_cb_t cb, void *ctx) { mongoc_set_item_t *item; - if ((item = - _mongoc_set_find (set, (mongoc_set_for_each_const_cb_t) cb, ctx))) { + if ((item = _mongoc_set_find (set, (mongoc_set_for_each_const_cb_t) cb, ctx))) { return item->item; } @@ -242,9 +228,7 @@ mongoc_set_find_item (mongoc_set_t *set, mongoc_set_for_each_cb_t cb, void *ctx) uint32_t -mongoc_set_find_id (const mongoc_set_t *set, - mongoc_set_for_each_const_cb_t cb, - void *ctx) +mongoc_set_find_id (const mongoc_set_t *set, mongoc_set_for_each_const_cb_t cb, void *ctx) { const mongoc_set_item_t *item; diff --git a/src/libmongoc/src/mongoc/mongoc-shared-private.h b/src/libmongoc/src/mongoc/mongoc-shared-private.h index bd9493cf44..1769ec58ab 100644 --- a/src/libmongoc/src/mongoc/mongoc-shared-private.h +++ b/src/libmongoc/src/mongoc/mongoc-shared-private.h @@ -80,9 +80,7 @@ typedef struct mongoc_shared_ptr { * *ptr = mongoc_shared_ptr_create(pointee, deleter); */ extern void -mongoc_shared_ptr_reset (mongoc_shared_ptr *ptr, - void *pointee, - void (*deleter) (void *)); +mongoc_shared_ptr_reset (mongoc_shared_ptr *ptr, void *pointee, void (*deleter) (void *)); /** * @brief Reassign the given shared pointer to manage the same resource as @@ -119,8 +117,7 @@ mongoc_shared_ptr_assign (mongoc_shared_ptr *dest, mongoc_shared_ptr from); * Thread-safe equivalent of `mongoc_shared_ptr_assign` */ extern void -mongoc_atomic_shared_ptr_store (mongoc_shared_ptr *dest, - mongoc_shared_ptr from); +mongoc_atomic_shared_ptr_store (mongoc_shared_ptr *dest, mongoc_shared_ptr from); /** * @brief Create a copy of the given shared pointer. Increases the reference diff --git a/src/libmongoc/src/mongoc/mongoc-shared.c b/src/libmongoc/src/mongoc/mongoc-shared.c index a93824e36d..103ac2118a 100644 --- a/src/libmongoc/src/mongoc/mongoc-shared.c +++ b/src/libmongoc/src/mongoc/mongoc-shared.c @@ -42,9 +42,7 @@ static BSON_ONCE_FUN (_init_mtx) } void -mongoc_shared_ptr_reset (mongoc_shared_ptr *ptr, - void *pointee, - void (*deleter) (void *)) +mongoc_shared_ptr_reset (mongoc_shared_ptr *ptr, void *pointee, void (*deleter) (void *)) { BSON_ASSERT_PARAM (ptr); if (!mongoc_shared_ptr_is_null (*ptr)) { @@ -117,8 +115,7 @@ mongoc_shared_ptr_copy (mongoc_shared_ptr ptr) { mongoc_shared_ptr ret = ptr; if (!mongoc_shared_ptr_is_null (ptr)) { - bson_atomic_int_fetch_add ( - &ret._aux->refcount, 1, bson_memory_order_acquire); + bson_atomic_int_fetch_add (&ret._aux->refcount, 1, bson_memory_order_acquire); } return ret; } @@ -133,8 +130,7 @@ mongoc_shared_ptr_reset_null (mongoc_shared_ptr *ptr) return; } /* Decrement the reference count by one */ - prevcount = bson_atomic_int_fetch_sub ( - &ptr->_aux->refcount, 1, bson_memory_order_acq_rel); + prevcount = bson_atomic_int_fetch_sub (&ptr->_aux->refcount, 1, bson_memory_order_acq_rel); if (prevcount == 1) { /* We just decremented from one to zero, so this is the last instance. * Release the managed data. */ @@ -147,9 +143,6 @@ mongoc_shared_ptr_reset_null (mongoc_shared_ptr *ptr) int mongoc_shared_ptr_use_count (mongoc_shared_ptr ptr) { - BSON_ASSERT ( - !mongoc_shared_ptr_is_null (ptr) && - "Unbound mongoc_shared_ptr given to mongoc_shared_ptr_use_count"); - return bson_atomic_int_fetch (&ptr._aux->refcount, - bson_memory_order_relaxed); + BSON_ASSERT (!mongoc_shared_ptr_is_null (ptr) && "Unbound mongoc_shared_ptr given to mongoc_shared_ptr_use_count"); + return bson_atomic_int_fetch (&ptr._aux->refcount, bson_memory_order_relaxed); } diff --git a/src/libmongoc/src/mongoc/mongoc-sleep.h b/src/libmongoc/src/mongoc/mongoc-sleep.h index db64535df3..fd0b93a309 100644 --- a/src/libmongoc/src/mongoc/mongoc-sleep.h +++ b/src/libmongoc/src/mongoc/mongoc-sleep.h @@ -28,9 +28,7 @@ typedef void (*mongoc_usleep_func_t) (int64_t usec, void *user_data); * not supported. Doing so is at the user's own risk. */ MONGOC_EXPORT (void) -mongoc_client_set_usleep_impl (mongoc_client_t *client, - mongoc_usleep_func_t usleep_func, - void *user_data); +mongoc_client_set_usleep_impl (mongoc_client_t *client, mongoc_usleep_func_t usleep_func, void *user_data); MONGOC_EXPORT (void) mongoc_usleep_default_impl (int64_t usec, void *user_data); diff --git a/src/libmongoc/src/mongoc/mongoc-socket-private.h b/src/libmongoc/src/mongoc/mongoc-socket-private.h index 84eee6a730..f9b12f71e1 100644 --- a/src/libmongoc/src/mongoc/mongoc-socket-private.h +++ b/src/libmongoc/src/mongoc/mongoc-socket-private.h @@ -35,9 +35,7 @@ struct _mongoc_socket_t { }; mongoc_socket_t * -mongoc_socket_accept_ex (mongoc_socket_t *sock, - int64_t expire_at, - uint16_t *port); +mongoc_socket_accept_ex (mongoc_socket_t *sock, int64_t expire_at, uint16_t *port); BSON_END_DECLS diff --git a/src/libmongoc/src/mongoc/mongoc-socket.c b/src/libmongoc/src/mongoc/mongoc-socket.c index 2446aa662d..0c7efc748f 100644 --- a/src/libmongoc/src/mongoc/mongoc-socket.c +++ b/src/libmongoc/src/mongoc/mongoc-socket.c @@ -33,8 +33,7 @@ #define MONGOC_LOG_DOMAIN "socket" -#define OPERATION_EXPIRED(expire_at) \ - ((expire_at >= 0) && (expire_at < (bson_get_monotonic_time ()))) +#define OPERATION_EXPIRED(expire_at) ((expire_at >= 0) && (expire_at < (bson_get_monotonic_time ()))) /* either struct sockaddr or void, depending on platform */ @@ -203,8 +202,7 @@ _mongoc_socket_wait (mongoc_socket_t *sock, /* IN */ } else { timeout_tv.tv_sec = timeout / 1000; timeout_tv.tv_usec = (timeout % 1000) * 1000; - ret = select ( - 0 /*unused*/, &read_fds, &write_fds, &error_fds, &timeout_tv); + ret = select (0 /*unused*/, &read_fds, &write_fds, &error_fds, &timeout_tv); } if (ret == SOCKET_ERROR) { _mongoc_socket_capture_errno (sock); @@ -220,8 +218,7 @@ _mongoc_socket_wait (mongoc_socket_t *sock, /* IN */ if (ret > 0) { /* Something happened, so return that */ #ifdef _WIN32 - return (FD_ISSET (sock->sd, &read_fds) || - FD_ISSET (sock->sd, &write_fds)); + return (FD_ISSET (sock->sd, &read_fds) || FD_ISSET (sock->sd, &write_fds)); #else RETURN (0 != (pfd.revents & events)); #endif @@ -371,8 +368,7 @@ _mongoc_socket_setkeepalive_windows (SOCKET sd) DWORD type; DWORD data; DWORD data_size = sizeof data; - const char *reg_key = - "SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters"; + const char *reg_key = "SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters"; keepalive.onoff = true; keepalive.keepalivetime = MONGODB_KEEPIDLE * 1000; keepalive.keepaliveinterval = MONGODB_KEEPALIVEINTVL * 1000; @@ -388,16 +384,13 @@ _mongoc_socket_setkeepalive_windows (SOCKET sd) * change the default value by setting the registry values. */ - if (RegOpenKeyExA (HKEY_LOCAL_MACHINE, reg_key, 0, KEY_QUERY_VALUE, &hKey) == - ERROR_SUCCESS) { + if (RegOpenKeyExA (HKEY_LOCAL_MACHINE, reg_key, 0, KEY_QUERY_VALUE, &hKey) == ERROR_SUCCESS) { /* https://technet.microsoft.com/en-us/library/cc957549.aspx */ DWORD default_keepalivetime = 7200000; /* 2 hours */ /* https://technet.microsoft.com/en-us/library/cc957548.aspx */ DWORD default_keepaliveinterval = 1000; /* 1 second */ - if (RegQueryValueEx ( - hKey, "KeepAliveTime", NULL, &type, (LPBYTE) &data, &data_size) == - ERROR_SUCCESS) { + if (RegQueryValueEx (hKey, "KeepAliveTime", NULL, &type, (LPBYTE) &data, &data_size) == ERROR_SUCCESS) { if (type == REG_DWORD && data < keepalive.keepalivetime) { keepalive.keepalivetime = data; } @@ -405,12 +398,7 @@ _mongoc_socket_setkeepalive_windows (SOCKET sd) keepalive.keepalivetime = default_keepalivetime; } - if (RegQueryValueEx (hKey, - "KeepAliveInterval", - NULL, - &type, - (LPBYTE) &data, - &data_size) == ERROR_SUCCESS) { + if (RegQueryValueEx (hKey, "KeepAliveInterval", NULL, &type, (LPBYTE) &data, &data_size) == ERROR_SUCCESS) { if (type == REG_DWORD && data < keepalive.keepaliveinterval) { keepalive.keepaliveinterval = data; } @@ -419,15 +407,8 @@ _mongoc_socket_setkeepalive_windows (SOCKET sd) } RegCloseKey (hKey); } - if (WSAIoctl (sd, - SIO_KEEPALIVE_VALS, - &keepalive, - sizeof keepalive, - NULL, - 0, - &lpcbBytesReturned, - NULL, - NULL) == SOCKET_ERROR) { + if (WSAIoctl (sd, SIO_KEEPALIVE_VALS, &keepalive, sizeof keepalive, NULL, 0, &lpcbBytesReturned, NULL, NULL) == + SOCKET_ERROR) { TRACE ("%s", "Could not set keepalive values"); } else { TRACE ("%s", "KeepAlive values updated"); @@ -471,25 +452,15 @@ _mongoc_socket_set_sockopt_if_less (int sd, int name, int value) optlen = sizeof optval; if (getsockopt (sd, IPPROTO_TCP, name, (char *) &optval, &optlen)) { - TRACE ("Getting '%s' failed, errno: %d", - _mongoc_socket_sockopt_value_to_name (name), - errno); + TRACE ("Getting '%s' failed, errno: %d", _mongoc_socket_sockopt_value_to_name (name), errno); } else { - TRACE ("'%s' is %d, target value is %d", - _mongoc_socket_sockopt_value_to_name (name), - optval, - value); + TRACE ("'%s' is %d, target value is %d", _mongoc_socket_sockopt_value_to_name (name), optval, value); if (optval > value) { optval = value; - if (setsockopt ( - sd, IPPROTO_TCP, name, (char *) &optval, sizeof optval)) { - TRACE ("Setting '%s' failed, errno: %d", - _mongoc_socket_sockopt_value_to_name (name), - errno); + if (setsockopt (sd, IPPROTO_TCP, name, (char *) &optval, sizeof optval)) { + TRACE ("Setting '%s' failed, errno: %d", _mongoc_socket_sockopt_value_to_name (name), errno); } else { - TRACE ("'%s' value changed to %d", - _mongoc_socket_sockopt_value_to_name (name), - optval); + TRACE ("'%s' value changed to %d", _mongoc_socket_sockopt_value_to_name (name), optval); } } } @@ -507,8 +478,7 @@ _mongoc_socket_setkeepalive_nix (int sd) #endif #ifdef TCP_KEEPINTVL - _mongoc_socket_set_sockopt_if_less ( - sd, TCP_KEEPINTVL, MONGODB_KEEPALIVEINTVL); + _mongoc_socket_set_sockopt_if_less (sd, TCP_KEEPINTVL, MONGODB_KEEPALIVEINTVL); #else TRACE ("%s", "TCP_KEEPINTVL not available"); #endif @@ -533,8 +503,7 @@ _mongoc_socket_setkeepalive (int sd) /* IN */ ENTRY; #ifdef SO_KEEPALIVE - if (!setsockopt ( - sd, SOL_SOCKET, SO_KEEPALIVE, (char *) &optval, sizeof optval)) { + if (!setsockopt (sd, SOL_SOCKET, SO_KEEPALIVE, (char *) &optval, sizeof optval)) { TRACE ("%s", "Setting SO_KEEPALIVE"); #ifdef _WIN32 _mongoc_socket_setkeepalive_windows (sd); @@ -569,8 +538,7 @@ _mongoc_socket_setnodelay (int sd) /* IN */ ENTRY; errno = 0; - ret = setsockopt ( - sd, IPPROTO_TCP, TCP_NODELAY, (char *) &optval, sizeof optval); + ret = setsockopt (sd, IPPROTO_TCP, TCP_NODELAY, (char *) &optval, sizeof optval); #ifdef _WIN32 if (ret == SOCKET_ERROR) { @@ -878,8 +846,7 @@ mongoc_socket_connect (mongoc_socket_t *sock, /* IN */ if (failed && try_again) { if (_mongoc_socket_wait (sock, POLLOUT, expire_at)) { optval = -1; - ret = getsockopt ( - sock->sd, SOL_SOCKET, SO_ERROR, (char *) &optval, &optlen); + ret = getsockopt (sock->sd, SOL_SOCKET, SO_ERROR, (char *) &optval, &optlen); if ((ret == 0) && (optval == 0)) { RETURN (0); } else { @@ -1097,8 +1064,7 @@ mongoc_socket_recv (mongoc_socket_t *sock, /* IN */ #endif if (failed) { _mongoc_socket_capture_errno (sock); - if (_mongoc_socket_errno_is_again (sock) && - _mongoc_socket_wait (sock, POLLIN, expire_at)) { + if (_mongoc_socket_errno_is_again (sock) && _mongoc_socket_wait (sock, POLLIN, expire_at)) { GOTO (again); } } @@ -1224,8 +1190,7 @@ _mongoc_socket_try_sendv_slow (mongoc_socket_t *sock, /* IN */ for (size_t i = 0u; i < iovcnt; i++) { #ifdef _WIN32 BSON_ASSERT (bson_in_range_unsigned (int, iov[i].iov_len)); - const int wrote = - send (sock->sd, iov[i].iov_base, (int) iov[i].iov_len, 0); + const int wrote = send (sock->sd, iov[i].iov_base, (int) iov[i].iov_len, 0); if (wrote == SOCKET_ERROR) { #else const ssize_t wrote = send (sock->sd, iov[i].iov_base, iov[i].iov_len, 0); @@ -1292,17 +1257,8 @@ _mongoc_socket_try_sendv (mongoc_socket_t *sock, /* IN */ #ifdef _WIN32 BSON_ASSERT (bson_in_range_unsigned (unsigned_long, iovcnt)); - ret = WSASend (sock->sd, - (LPWSABUF) iov, - (DWORD) iovcnt, - &dwNumberofBytesSent, - 0, - NULL, - NULL); - TRACE ("WSASend sent: %ld (out of: %zu), ret: %d", - dwNumberofBytesSent, - iov->iov_len, - ret); + ret = WSASend (sock->sd, (LPWSABUF) iov, (DWORD) iovcnt, &dwNumberofBytesSent, 0, NULL, NULL); + TRACE ("WSASend sent: %ld (out of: %zu), ret: %d", dwNumberofBytesSent, iov->iov_len, ret); #else memset (&msg, 0, sizeof msg); msg.msg_iov = iov; @@ -1394,8 +1350,7 @@ mongoc_socket_sendv (mongoc_socket_t *sock, /* IN */ for (;;) { sent = _mongoc_socket_try_sendv (sock, &iov[cur], iovcnt - cur); - TRACE ( - "Sent %zd (of %zu) out of iovcnt=%zu", sent, iov[cur].iov_len, iovcnt); + TRACE ("Sent %zd (of %zu) out of iovcnt=%zu", sent, iov[cur].iov_len, iovcnt); /* * If we failed with anything other than EAGAIN or EWOULDBLOCK, @@ -1420,9 +1375,7 @@ mongoc_socket_sendv (mongoc_socket_t *sock, /* IN */ * Subtract the sent amount from what we still need to send. */ while ((cur < iovcnt) && (sent >= (ssize_t) iov[cur].iov_len)) { - TRACE ("still got bytes left: sent -= iov_len: %zd -= %zu", - sent, - iov[cur].iov_len); + TRACE ("still got bytes left: sent -= iov_len: %zd -= %zu", sent, iov[cur].iov_len); sent -= iov[cur++].iov_len; } @@ -1440,8 +1393,7 @@ mongoc_socket_sendv (mongoc_socket_t *sock, /* IN */ * the number of bytes to write. */ TRACE ("Seeked io_base+%zd", sent); - TRACE ( - "Subtracting iov_len -= sent; %zu -= %zd", iov[cur].iov_len, sent); + TRACE ("Subtracting iov_len -= sent; %zu -= %zd", iov[cur].iov_len, sent); iov[cur].iov_base = ((char *) iov[cur].iov_base) + sent; iov[cur].iov_len -= sent; TRACE ("iov_len remaining %zu", iov[cur].iov_len); @@ -1506,8 +1458,7 @@ mongoc_socket_getnameinfo (mongoc_socket_t *sock) /* IN */ RETURN (NULL); } - if (getnameinfo ( - (struct sockaddr *) &addr, len, host, sizeof host, NULL, 0, 0)) { + if (getnameinfo ((struct sockaddr *) &addr, len, host, sizeof host, NULL, 0, 0)) { RETURN (NULL); } diff --git a/src/libmongoc/src/mongoc/mongoc-socket.h b/src/libmongoc/src/mongoc/mongoc-socket.h index 44be989545..e465b5acc7 100644 --- a/src/libmongoc/src/mongoc/mongoc-socket.h +++ b/src/libmongoc/src/mongoc/mongoc-socket.h @@ -59,19 +59,13 @@ typedef struct { } mongoc_socket_poll_t; MONGOC_EXPORT (mongoc_socket_t *) -mongoc_socket_accept (mongoc_socket_t *sock, - int64_t expire_at) BSON_GNUC_WARN_UNUSED_RESULT; +mongoc_socket_accept (mongoc_socket_t *sock, int64_t expire_at) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (int) -mongoc_socket_bind (mongoc_socket_t *sock, - const struct sockaddr *addr, - mongoc_socklen_t addrlen); +mongoc_socket_bind (mongoc_socket_t *sock, const struct sockaddr *addr, mongoc_socklen_t addrlen); MONGOC_EXPORT (int) mongoc_socket_close (mongoc_socket_t *socket); MONGOC_EXPORT (int) -mongoc_socket_connect (mongoc_socket_t *sock, - const struct sockaddr *addr, - mongoc_socklen_t addrlen, - int64_t expire_at); +mongoc_socket_connect (mongoc_socket_t *sock, const struct sockaddr *addr, mongoc_socklen_t addrlen, int64_t expire_at); MONGOC_EXPORT (char *) mongoc_socket_getnameinfo (mongoc_socket_t *sock) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (void) @@ -79,37 +73,19 @@ mongoc_socket_destroy (mongoc_socket_t *sock); MONGOC_EXPORT (int) mongoc_socket_errno (mongoc_socket_t *sock); MONGOC_EXPORT (int) -mongoc_socket_getsockname (mongoc_socket_t *sock, - struct sockaddr *addr, - mongoc_socklen_t *addrlen); +mongoc_socket_getsockname (mongoc_socket_t *sock, struct sockaddr *addr, mongoc_socklen_t *addrlen); MONGOC_EXPORT (int) mongoc_socket_listen (mongoc_socket_t *sock, unsigned int backlog); MONGOC_EXPORT (mongoc_socket_t *) -mongoc_socket_new (int domain, - int type, - int protocol) BSON_GNUC_WARN_UNUSED_RESULT; +mongoc_socket_new (int domain, int type, int protocol) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (ssize_t) -mongoc_socket_recv (mongoc_socket_t *sock, - void *buf, - size_t buflen, - int flags, - int64_t expire_at); +mongoc_socket_recv (mongoc_socket_t *sock, void *buf, size_t buflen, int flags, int64_t expire_at); MONGOC_EXPORT (int) -mongoc_socket_setsockopt (mongoc_socket_t *sock, - int level, - int optname, - const void *optval, - mongoc_socklen_t optlen); +mongoc_socket_setsockopt (mongoc_socket_t *sock, int level, int optname, const void *optval, mongoc_socklen_t optlen); MONGOC_EXPORT (ssize_t) -mongoc_socket_send (mongoc_socket_t *sock, - const void *buf, - size_t buflen, - int64_t expire_at); +mongoc_socket_send (mongoc_socket_t *sock, const void *buf, size_t buflen, int64_t expire_at); MONGOC_EXPORT (ssize_t) -mongoc_socket_sendv (mongoc_socket_t *sock, - mongoc_iovec_t *iov, - size_t iovcnt, - int64_t expire_at); +mongoc_socket_sendv (mongoc_socket_t *sock, mongoc_iovec_t *iov, size_t iovcnt, int64_t expire_at); MONGOC_EXPORT (bool) mongoc_socket_check_closed (mongoc_socket_t *sock); MONGOC_EXPORT (void) diff --git a/src/libmongoc/src/mongoc/mongoc-ssl-private.h b/src/libmongoc/src/mongoc/mongoc-ssl-private.h index e64f68b78b..ea6db94d4b 100644 --- a/src/libmongoc/src/mongoc/mongoc-ssl-private.h +++ b/src/libmongoc/src/mongoc/mongoc-ssl-private.h @@ -34,17 +34,12 @@ char * mongoc_ssl_extract_subject (const char *filename, const char *passphrase); void -_mongoc_ssl_opts_from_uri (mongoc_ssl_opt_t *ssl_opt, - _mongoc_internal_tls_opts_t *internal, - mongoc_uri_t *uri); +_mongoc_ssl_opts_from_uri (mongoc_ssl_opt_t *ssl_opt, _mongoc_internal_tls_opts_t *internal, mongoc_uri_t *uri); void -_mongoc_ssl_opts_copy_to (const mongoc_ssl_opt_t *src, - mongoc_ssl_opt_t *dst, - bool copy_internal); +_mongoc_ssl_opts_copy_to (const mongoc_ssl_opt_t *src, mongoc_ssl_opt_t *dst, bool copy_internal); bool -_mongoc_ssl_opts_disable_certificate_revocation_check ( - const mongoc_ssl_opt_t *ssl_opt); +_mongoc_ssl_opts_disable_certificate_revocation_check (const mongoc_ssl_opt_t *ssl_opt); bool _mongoc_ssl_opts_disable_ocsp_endpoint_check (const mongoc_ssl_opt_t *ssl_opt); @@ -59,9 +54,7 @@ _mongoc_ssl_opts_cleanup (mongoc_ssl_opt_t *opt, bool free_internal); * - errmsg must be an initialized bson_string_t. * - Returns false on error and appends to errmsg. */ bool -_mongoc_ssl_opts_from_bson (mongoc_ssl_opt_t *ssl_opt, - const bson_t *bson, - bson_string_t *errmsg); +_mongoc_ssl_opts_from_bson (mongoc_ssl_opt_t *ssl_opt, const bson_t *bson, bson_string_t *errmsg); BSON_END_DECLS diff --git a/src/libmongoc/src/mongoc/mongoc-ssl.c b/src/libmongoc/src/mongoc/mongoc-ssl.c index 8976b12c21..275736cddb 100644 --- a/src/libmongoc/src/mongoc/mongoc-ssl.c +++ b/src/libmongoc/src/mongoc/mongoc-ssl.c @@ -72,17 +72,15 @@ mongoc_ssl_extract_subject (const char *filename, const char *passphrase) #else if (access (filename, R_OK) != 0) { #endif - MONGOC_ERROR ("Can't extract subject from unreadable file: '%s'", - filename); + MONGOC_ERROR ("Can't extract subject from unreadable file: '%s'", filename); return NULL; } #if defined(MONGOC_ENABLE_SSL_OPENSSL) retval = _mongoc_openssl_extract_subject (filename, passphrase); #elif defined(MONGOC_ENABLE_SSL_LIBRESSL) - MONGOC_WARNING ( - "libtls doesn't support automatically extracting subject from " - "certificate to use with authentication"); + MONGOC_WARNING ("libtls doesn't support automatically extracting subject from " + "certificate to use with authentication"); retval = NULL; #elif defined(MONGOC_ENABLE_SSL_SECURE_TRANSPORT) retval = _mongoc_secure_transport_extract_subject (filename, passphrase); @@ -98,35 +96,25 @@ retval = _mongoc_secure_channel_extract_subject (filename, passphrase); } void -_mongoc_ssl_opts_from_uri (mongoc_ssl_opt_t *ssl_opt, - _mongoc_internal_tls_opts_t *internal, - mongoc_uri_t *uri) +_mongoc_ssl_opts_from_uri (mongoc_ssl_opt_t *ssl_opt, _mongoc_internal_tls_opts_t *internal, mongoc_uri_t *uri) { - bool insecure = - mongoc_uri_get_option_as_bool (uri, MONGOC_URI_TLSINSECURE, false); - - ssl_opt->pem_file = mongoc_uri_get_option_as_utf8 ( - uri, MONGOC_URI_TLSCERTIFICATEKEYFILE, NULL); - ssl_opt->pem_pwd = mongoc_uri_get_option_as_utf8 ( - uri, MONGOC_URI_TLSCERTIFICATEKEYFILEPASSWORD, NULL); - ssl_opt->ca_file = - mongoc_uri_get_option_as_utf8 (uri, MONGOC_URI_TLSCAFILE, NULL); - ssl_opt->weak_cert_validation = mongoc_uri_get_option_as_bool ( - uri, MONGOC_URI_TLSALLOWINVALIDCERTIFICATES, insecure); - ssl_opt->allow_invalid_hostname = mongoc_uri_get_option_as_bool ( - uri, MONGOC_URI_TLSALLOWINVALIDHOSTNAMES, insecure); + bool insecure = mongoc_uri_get_option_as_bool (uri, MONGOC_URI_TLSINSECURE, false); + + ssl_opt->pem_file = mongoc_uri_get_option_as_utf8 (uri, MONGOC_URI_TLSCERTIFICATEKEYFILE, NULL); + ssl_opt->pem_pwd = mongoc_uri_get_option_as_utf8 (uri, MONGOC_URI_TLSCERTIFICATEKEYFILEPASSWORD, NULL); + ssl_opt->ca_file = mongoc_uri_get_option_as_utf8 (uri, MONGOC_URI_TLSCAFILE, NULL); + ssl_opt->weak_cert_validation = + mongoc_uri_get_option_as_bool (uri, MONGOC_URI_TLSALLOWINVALIDCERTIFICATES, insecure); + ssl_opt->allow_invalid_hostname = mongoc_uri_get_option_as_bool (uri, MONGOC_URI_TLSALLOWINVALIDHOSTNAMES, insecure); ssl_opt->internal = internal; internal->tls_disable_certificate_revocation_check = - mongoc_uri_get_option_as_bool ( - uri, MONGOC_URI_TLSDISABLECERTIFICATEREVOCATIONCHECK, false); - internal->tls_disable_ocsp_endpoint_check = mongoc_uri_get_option_as_bool ( - uri, MONGOC_URI_TLSDISABLEOCSPENDPOINTCHECK, false); + mongoc_uri_get_option_as_bool (uri, MONGOC_URI_TLSDISABLECERTIFICATEREVOCATIONCHECK, false); + internal->tls_disable_ocsp_endpoint_check = + mongoc_uri_get_option_as_bool (uri, MONGOC_URI_TLSDISABLEOCSPENDPOINTCHECK, false); } void -_mongoc_ssl_opts_copy_to (const mongoc_ssl_opt_t *src, - mongoc_ssl_opt_t *dst, - bool copy_internal) +_mongoc_ssl_opts_copy_to (const mongoc_ssl_opt_t *src, mongoc_ssl_opt_t *dst, bool copy_internal) { BSON_ASSERT (src); BSON_ASSERT (dst); @@ -142,8 +130,7 @@ _mongoc_ssl_opts_copy_to (const mongoc_ssl_opt_t *src, dst->internal = NULL; if (src->internal) { dst->internal = bson_malloc (sizeof (_mongoc_internal_tls_opts_t)); - memcpy ( - dst->internal, src->internal, sizeof (_mongoc_internal_tls_opts_t)); + memcpy (dst->internal, src->internal, sizeof (_mongoc_internal_tls_opts_t)); } } } @@ -162,14 +149,12 @@ _mongoc_ssl_opts_cleanup (mongoc_ssl_opt_t *opt, bool free_internal) } bool -_mongoc_ssl_opts_disable_certificate_revocation_check ( - const mongoc_ssl_opt_t *ssl_opt) +_mongoc_ssl_opts_disable_certificate_revocation_check (const mongoc_ssl_opt_t *ssl_opt) { if (!ssl_opt->internal) { return false; } - return ((_mongoc_internal_tls_opts_t *) ssl_opt->internal) - ->tls_disable_certificate_revocation_check; + return ((_mongoc_internal_tls_opts_t *) ssl_opt->internal)->tls_disable_certificate_revocation_check; } bool @@ -178,28 +163,23 @@ _mongoc_ssl_opts_disable_ocsp_endpoint_check (const mongoc_ssl_opt_t *ssl_opt) if (!ssl_opt->internal) { return false; } - return ((_mongoc_internal_tls_opts_t *) ssl_opt->internal) - ->tls_disable_ocsp_endpoint_check; + return ((_mongoc_internal_tls_opts_t *) ssl_opt->internal)->tls_disable_ocsp_endpoint_check; } bool -_mongoc_ssl_opts_from_bson (mongoc_ssl_opt_t *ssl_opt, - const bson_t *bson, - bson_string_t *errmsg) +_mongoc_ssl_opts_from_bson (mongoc_ssl_opt_t *ssl_opt, const bson_t *bson, bson_string_t *errmsg) { bson_iter_t iter; if (ssl_opt->internal) { - bson_string_append (errmsg, - "SSL options must not have internal state set"); + bson_string_append (errmsg, "SSL options must not have internal state set"); return false; } ssl_opt->internal = bson_malloc0 (sizeof (_mongoc_internal_tls_opts_t)); if (!bson_iter_init (&iter, bson)) { - bson_string_append (errmsg, - "error initializing iterator to BSON SSL options"); + bson_string_append (errmsg, "error initializing iterator to BSON SSL options"); return false; } @@ -210,8 +190,7 @@ _mongoc_ssl_opts_from_bson (mongoc_ssl_opt_t *ssl_opt, if (0 == bson_strcasecmp (key, MONGOC_URI_TLSCERTIFICATEKEYFILE)) { ssl_opt->pem_file = bson_strdup (bson_iter_utf8 (&iter, NULL)); continue; - } else if (0 == bson_strcasecmp ( - key, MONGOC_URI_TLSCERTIFICATEKEYFILEPASSWORD)) { + } else if (0 == bson_strcasecmp (key, MONGOC_URI_TLSCERTIFICATEKEYFILEPASSWORD)) { ssl_opt->pem_pwd = bson_strdup (bson_iter_utf8 (&iter, NULL)); continue; } else if (0 == bson_strcasecmp (key, MONGOC_URI_TLSCAFILE)) { @@ -221,19 +200,15 @@ _mongoc_ssl_opts_from_bson (mongoc_ssl_opt_t *ssl_opt, } if (BSON_ITER_HOLDS_BOOL (&iter)) { - if (0 == - bson_strcasecmp (key, MONGOC_URI_TLSALLOWINVALIDCERTIFICATES)) { + if (0 == bson_strcasecmp (key, MONGOC_URI_TLSALLOWINVALIDCERTIFICATES)) { /* If MONGOC_URI_TLSINSECURE was parsed, weak_cert_validation must * remain true. */ - ssl_opt->weak_cert_validation = - ssl_opt->weak_cert_validation || bson_iter_bool (&iter); + ssl_opt->weak_cert_validation = ssl_opt->weak_cert_validation || bson_iter_bool (&iter); continue; - } else if (0 == bson_strcasecmp ( - key, MONGOC_URI_TLSALLOWINVALIDHOSTNAMES)) { + } else if (0 == bson_strcasecmp (key, MONGOC_URI_TLSALLOWINVALIDHOSTNAMES)) { /* If MONGOC_URI_TLSINSECURE was parsed, allow_invalid_hostname must * remain true. */ - ssl_opt->allow_invalid_hostname = - ssl_opt->allow_invalid_hostname || bson_iter_bool (&iter); + ssl_opt->allow_invalid_hostname = ssl_opt->allow_invalid_hostname || bson_iter_bool (&iter); continue; } else if (0 == bson_strcasecmp (key, MONGOC_URI_TLSINSECURE)) { if (bson_iter_bool (&iter)) { @@ -241,26 +216,19 @@ _mongoc_ssl_opts_from_bson (mongoc_ssl_opt_t *ssl_opt, ssl_opt->allow_invalid_hostname = true; } continue; - } else if (0 == - bson_strcasecmp ( - key, MONGOC_URI_TLSDISABLECERTIFICATEREVOCATIONCHECK)) { - ((_mongoc_internal_tls_opts_t *) ssl_opt->internal) - ->tls_disable_certificate_revocation_check = + } else if (0 == bson_strcasecmp (key, MONGOC_URI_TLSDISABLECERTIFICATEREVOCATIONCHECK)) { + ((_mongoc_internal_tls_opts_t *) ssl_opt->internal)->tls_disable_certificate_revocation_check = bson_iter_bool (&iter); continue; - } else if (0 == bson_strcasecmp ( - key, MONGOC_URI_TLSDISABLEOCSPENDPOINTCHECK)) { - ((_mongoc_internal_tls_opts_t *) ssl_opt->internal) - ->tls_disable_ocsp_endpoint_check = bson_iter_bool (&iter); + } else if (0 == bson_strcasecmp (key, MONGOC_URI_TLSDISABLEOCSPENDPOINTCHECK)) { + ((_mongoc_internal_tls_opts_t *) ssl_opt->internal)->tls_disable_ocsp_endpoint_check = + bson_iter_bool (&iter); continue; } } bson_string_append_printf ( - errmsg, - "unexpected %s option: %s", - _mongoc_bson_type_to_str (bson_iter_type (&iter)), - key); + errmsg, "unexpected %s option: %s", _mongoc_bson_type_to_str (bson_iter_type (&iter)), key); return false; } diff --git a/src/libmongoc/src/mongoc/mongoc-sspi-private.h b/src/libmongoc/src/mongoc/mongoc-sspi-private.h index 60996fcace..dbd337ac8d 100644 --- a/src/libmongoc/src/mongoc/mongoc-sspi-private.h +++ b/src/libmongoc/src/mongoc/mongoc-sspi-private.h @@ -67,19 +67,14 @@ _mongoc_sspi_auth_sspi_client_init (WCHAR *service, ULONG plen, mongoc_sspi_client_state_t *state); int -_mongoc_sspi_auth_sspi_client_step (mongoc_sspi_client_state_t *state, - SEC_CHAR *challenge); +_mongoc_sspi_auth_sspi_client_step (mongoc_sspi_client_state_t *state, SEC_CHAR *challenge); int -_mongoc_sspi_auth_sspi_client_unwrap (mongoc_sspi_client_state_t *state, - SEC_CHAR *challenge); +_mongoc_sspi_auth_sspi_client_unwrap (mongoc_sspi_client_state_t *state, SEC_CHAR *challenge); int -_mongoc_sspi_auth_sspi_client_wrap (mongoc_sspi_client_state_t *state, - SEC_CHAR *data, - SEC_CHAR *user, - ULONG ulen, - INT protect); +_mongoc_sspi_auth_sspi_client_wrap ( + mongoc_sspi_client_state_t *state, SEC_CHAR *data, SEC_CHAR *user, ULONG ulen, INT protect); BSON_END_DECLS diff --git a/src/libmongoc/src/mongoc/mongoc-sspi.c b/src/libmongoc/src/mongoc/mongoc-sspi.c index e9deb94fed..cd2ccca213 100644 --- a/src/libmongoc/src/mongoc/mongoc-sspi.c +++ b/src/libmongoc/src/mongoc/mongoc-sspi.c @@ -58,15 +58,8 @@ _mongoc_sspi_set_gsserror (DWORD errCode, const SEC_CHAR *msg) { SEC_CHAR *err; DWORD status; - DWORD flags = FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS; - status = FormatMessageA (flags, - NULL, - errCode, - MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT), - (LPTSTR) &err, - 0, - NULL); + DWORD flags = FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS; + status = FormatMessageA (flags, NULL, errCode, MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &err, 0, NULL); if (status) { MONGOC_ERROR ("SSPI: %s: %s", msg, err); LocalFree (err); @@ -81,19 +74,11 @@ _mongoc_sspi_base64_encode (const SEC_CHAR *value, DWORD vlen) SEC_CHAR *out = NULL; DWORD len; /* Get the correct size for the out buffer. */ - if (CryptBinaryToStringA ((BYTE *) value, - vlen, - CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF, - NULL, - &len)) { + if (CryptBinaryToStringA ((BYTE *) value, vlen, CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF, NULL, &len)) { out = (SEC_CHAR *) bson_malloc (sizeof (SEC_CHAR) * len); if (out) { /* Encode to the out buffer. */ - if (CryptBinaryToStringA ((BYTE *) value, - vlen, - CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF, - out, - &len)) { + if (CryptBinaryToStringA ((BYTE *) value, vlen, CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF, out, &len)) { return out; } else { bson_free (out); @@ -109,18 +94,11 @@ _mongoc_sspi_base64_decode (const SEC_CHAR *value, DWORD *rlen) { SEC_CHAR *out = NULL; /* Get the correct size for the out buffer. */ - if (CryptStringToBinaryA ( - value, 0, CRYPT_STRING_BASE64, NULL, rlen, NULL, NULL)) { + if (CryptStringToBinaryA (value, 0, CRYPT_STRING_BASE64, NULL, rlen, NULL, NULL)) { out = (SEC_CHAR *) bson_malloc (sizeof (SEC_CHAR) * *rlen); if (out) { /* Decode to the out buffer. */ - if (CryptStringToBinaryA (value, - 0, - CRYPT_STRING_BASE64, - (BYTE *) out, - rlen, - NULL, - NULL)) { + if (CryptStringToBinaryA (value, 0, CRYPT_STRING_BASE64, (BYTE *) out, rlen, NULL, NULL)) { return out; } else { bson_free (out); @@ -222,8 +200,7 @@ _mongoc_sspi_auth_sspi_client_init (WCHAR *service, } int -_mongoc_sspi_auth_sspi_client_step (mongoc_sspi_client_state_t *state, - SEC_CHAR *challenge) +_mongoc_sspi_auth_sspi_client_step (mongoc_sspi_client_state_t *state, SEC_CHAR *challenge) { SecBufferDesc inbuf; SecBuffer inBufs[1]; @@ -290,8 +267,7 @@ _mongoc_sspi_auth_sspi_client_step (mongoc_sspi_client_state_t *state, } state->haveCtx = 1; if (outBufs[0].cbBuffer) { - state->response = - _mongoc_sspi_base64_encode (outBufs[0].pvBuffer, outBufs[0].cbBuffer); + state->response = _mongoc_sspi_base64_encode (outBufs[0].pvBuffer, outBufs[0].cbBuffer); if (!state->response) { status = MONGOC_SSPI_AUTH_GSS_ERROR; goto done; @@ -328,8 +304,7 @@ _mongoc_sspi_auth_sspi_client_step (mongoc_sspi_client_state_t *state, } int -_mongoc_sspi_auth_sspi_client_unwrap (mongoc_sspi_client_state_t *state, - SEC_CHAR *challenge) +_mongoc_sspi_auth_sspi_client_unwrap (mongoc_sspi_client_state_t *state, SEC_CHAR *challenge) { SECURITY_STATUS status; DWORD len; @@ -369,8 +344,7 @@ _mongoc_sspi_auth_sspi_client_unwrap (mongoc_sspi_client_state_t *state, goto done; } if (wrapBufs[1].cbBuffer) { - state->response = _mongoc_sspi_base64_encode (wrapBufs[1].pvBuffer, - wrapBufs[1].cbBuffer); + state->response = _mongoc_sspi_base64_encode (wrapBufs[1].pvBuffer, wrapBufs[1].cbBuffer); if (!state->response) { status = MONGOC_SSPI_AUTH_GSS_ERROR; } @@ -383,11 +357,8 @@ _mongoc_sspi_auth_sspi_client_unwrap (mongoc_sspi_client_state_t *state, } int -_mongoc_sspi_auth_sspi_client_wrap (mongoc_sspi_client_state_t *state, - SEC_CHAR *data, - SEC_CHAR *user, - ULONG ulen, - int protect) +_mongoc_sspi_auth_sspi_client_wrap ( + mongoc_sspi_client_state_t *state, SEC_CHAR *data, SEC_CHAR *user, ULONG ulen, int protect) { SECURITY_STATUS status; SecPkgContext_Sizes sizes; @@ -426,8 +397,7 @@ _mongoc_sspi_auth_sspi_client_wrap (mongoc_sspi_client_state_t *state, } } - inbufSize = - sizes.cbSecurityTrailer + plaintextMessageSize + sizes.cbBlockSize; + inbufSize = sizes.cbSecurityTrailer + plaintextMessageSize + sizes.cbBlockSize; inbuf = (SEC_CHAR *) bson_malloc (inbufSize); if (inbuf == NULL) { bson_free (decodedData); @@ -443,16 +413,10 @@ _mongoc_sspi_auth_sspi_client_wrap (mongoc_sspi_client_state_t *state, plaintextMessage[1] = 0; plaintextMessage[2] = 0; plaintextMessage[3] = 0; - memcpy_s (plaintextMessage + 4, - inbufSize - sizes.cbSecurityTrailer - 4, - user, - strlen (user)); + memcpy_s (plaintextMessage + 4, inbufSize - sizes.cbSecurityTrailer - 4, user, strlen (user)); } else { /* No user provided. Just rewrap data. */ - memcpy_s (plaintextMessage, - inbufSize - sizes.cbSecurityTrailer, - decodedData, - plaintextMessageSize); + memcpy_s (plaintextMessage, inbufSize - sizes.cbSecurityTrailer, decodedData, plaintextMessageSize); bson_free (decodedData); } @@ -470,25 +434,20 @@ _mongoc_sspi_auth_sspi_client_wrap (mongoc_sspi_client_state_t *state, wrapBufs[2].cbBuffer = sizes.cbBlockSize; wrapBufs[2].BufferType = SECBUFFER_PADDING; - wrapBufs[2].pvBuffer = - inbuf + (sizes.cbSecurityTrailer + plaintextMessageSize); + wrapBufs[2].pvBuffer = inbuf + (sizes.cbSecurityTrailer + plaintextMessageSize); - status = EncryptMessage ( - &state->ctx, protect ? 0 : SECQOP_WRAP_NO_ENCRYPT, &wrapBufDesc, 0); + status = EncryptMessage (&state->ctx, protect ? 0 : SECQOP_WRAP_NO_ENCRYPT, &wrapBufDesc, 0); if (status != SEC_E_OK) { bson_free (inbuf); _mongoc_sspi_set_gsserror (status, "EncryptMessage"); return MONGOC_SSPI_AUTH_GSS_ERROR; } - outbufSize = - wrapBufs[0].cbBuffer + wrapBufs[1].cbBuffer + wrapBufs[2].cbBuffer; + outbufSize = wrapBufs[0].cbBuffer + wrapBufs[1].cbBuffer + wrapBufs[2].cbBuffer; outbuf = (SEC_CHAR *) bson_malloc (sizeof (SEC_CHAR) * outbufSize); memcpy_s (outbuf, outbufSize, wrapBufs[0].pvBuffer, wrapBufs[0].cbBuffer); - memcpy_s (outbuf + wrapBufs[0].cbBuffer, - outbufSize - wrapBufs[0].cbBuffer, - wrapBufs[1].pvBuffer, - wrapBufs[1].cbBuffer); + memcpy_s ( + outbuf + wrapBufs[0].cbBuffer, outbufSize - wrapBufs[0].cbBuffer, wrapBufs[1].pvBuffer, wrapBufs[1].cbBuffer); memcpy_s (outbuf + wrapBufs[0].cbBuffer + wrapBufs[1].cbBuffer, outbufSize - wrapBufs[0].cbBuffer - wrapBufs[1].cbBuffer, wrapBufs[2].pvBuffer, diff --git a/src/libmongoc/src/mongoc/mongoc-stream-buffered.c b/src/libmongoc/src/mongoc/mongoc-stream-buffered.c index d5e8cd54db..406275f9a8 100644 --- a/src/libmongoc/src/mongoc/mongoc-stream-buffered.c +++ b/src/libmongoc/src/mongoc/mongoc-stream-buffered.c @@ -182,8 +182,7 @@ mongoc_stream_buffered_writev (mongoc_stream_t *stream, /* IN */ BSON_ASSERT (buffered); - ret = - mongoc_stream_writev (buffered->base_stream, iov, iovcnt, timeout_msec); + ret = mongoc_stream_writev (buffered->base_stream, iov, iovcnt, timeout_msec); RETURN (ret); } @@ -239,11 +238,7 @@ mongoc_stream_buffered_readv (mongoc_stream_t *stream, /* IN */ total_bytes += iov[i].iov_len; } - if (-1 == _mongoc_buffer_fill (&buffered->buffer, - buffered->base_stream, - total_bytes, - timeout_msec, - &error)) { + if (-1 == _mongoc_buffer_fill (&buffered->buffer, buffered->base_stream, total_bytes, timeout_msec, &error)) { MONGOC_WARNING ("%s", error.message); RETURN (-1); } @@ -256,8 +251,7 @@ mongoc_stream_buffered_readv (mongoc_stream_t *stream, /* IN */ buffered->buffer.len -= iov[i].iov_len; } - memmove ( - buffered->buffer.data, buffered->buffer.data + off, buffered->buffer.len); + memmove (buffered->buffer.data, buffered->buffer.data + off, buffered->buffer.len); RETURN (total_bytes); } diff --git a/src/libmongoc/src/mongoc/mongoc-stream-buffered.h b/src/libmongoc/src/mongoc/mongoc-stream-buffered.h index 6bbf2cb06c..7053a63e90 100644 --- a/src/libmongoc/src/mongoc/mongoc-stream-buffered.h +++ b/src/libmongoc/src/mongoc/mongoc-stream-buffered.h @@ -29,8 +29,7 @@ BSON_BEGIN_DECLS MONGOC_EXPORT (mongoc_stream_t *) -mongoc_stream_buffered_new (mongoc_stream_t *base_stream, - size_t buffer_size) BSON_GNUC_WARN_UNUSED_RESULT; +mongoc_stream_buffered_new (mongoc_stream_t *base_stream, size_t buffer_size) BSON_GNUC_WARN_UNUSED_RESULT; BSON_END_DECLS diff --git a/src/libmongoc/src/mongoc/mongoc-stream-file.c b/src/libmongoc/src/mongoc/mongoc-stream-file.c index 104078df41..d0c9ba28b2 100644 --- a/src/libmongoc/src/mongoc/mongoc-stream-file.c +++ b/src/libmongoc/src/mongoc/mongoc-stream-file.c @@ -132,8 +132,7 @@ _mongoc_stream_file_readv (mongoc_stream_t *stream, /* IN */ for (size_t i = 0u; i < iovcnt; i++) { BSON_ASSERT (bson_in_range_unsigned (unsigned_int, iov[i].iov_len)); - const int nread = - _read (file->fd, iov[i].iov_base, (unsigned int) iov[i].iov_len); + const int nread = _read (file->fd, iov[i].iov_base, (unsigned int) iov[i].iov_len); if (nread < 0) { ret = ret ? ret : -1; GOTO (done); @@ -182,8 +181,7 @@ _mongoc_stream_file_writev (mongoc_stream_t *stream, /* IN */ { for (size_t i = 0; i < iovcnt; i++) { BSON_ASSERT (bson_in_range_unsigned (unsigned_int, iov[i].iov_len)); - const int nwrite = - _write (file->fd, iov[i].iov_base, (unsigned int) iov[i].iov_len); + const int nwrite = _write (file->fd, iov[i].iov_base, (unsigned int) iov[i].iov_len); if (bson_cmp_not_equal_su (nwrite, iov[i].iov_len)) { ret = ret ? ret : -1; goto done; diff --git a/src/libmongoc/src/mongoc/mongoc-stream-file.h b/src/libmongoc/src/mongoc/mongoc-stream-file.h index 8887e116ab..9bb128d90d 100644 --- a/src/libmongoc/src/mongoc/mongoc-stream-file.h +++ b/src/libmongoc/src/mongoc/mongoc-stream-file.h @@ -32,9 +32,7 @@ typedef struct _mongoc_stream_file_t mongoc_stream_file_t; MONGOC_EXPORT (mongoc_stream_t *) mongoc_stream_file_new (int fd) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (mongoc_stream_t *) -mongoc_stream_file_new_for_path (const char *path, - int flags, - int mode) BSON_GNUC_WARN_UNUSED_RESULT; +mongoc_stream_file_new_for_path (const char *path, int flags, int mode) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (int) mongoc_stream_file_get_fd (mongoc_stream_file_t *stream); diff --git a/src/libmongoc/src/mongoc/mongoc-stream-gridfs-download.c b/src/libmongoc/src/mongoc/mongoc-stream-gridfs-download.c index 458bac1af8..e57c0fb1d4 100644 --- a/src/libmongoc/src/mongoc/mongoc-stream-gridfs-download.c +++ b/src/libmongoc/src/mongoc/mongoc-stream-gridfs-download.c @@ -26,8 +26,7 @@ static void _mongoc_download_stream_gridfs_destroy (mongoc_stream_t *stream) { - mongoc_gridfs_download_stream_t *gridfs = - (mongoc_gridfs_download_stream_t *) stream; + mongoc_gridfs_download_stream_t *gridfs = (mongoc_gridfs_download_stream_t *) stream; ENTRY; @@ -57,8 +56,7 @@ _mongoc_download_stream_gridfs_failed (mongoc_stream_t *stream) static int _mongoc_download_stream_gridfs_close (mongoc_stream_t *stream) { - mongoc_gridfs_download_stream_t *gridfs = - (mongoc_gridfs_download_stream_t *) stream; + mongoc_gridfs_download_stream_t *gridfs = (mongoc_gridfs_download_stream_t *) stream; int ret = 0; ENTRY; @@ -71,14 +69,10 @@ _mongoc_download_stream_gridfs_close (mongoc_stream_t *stream) } static ssize_t -_mongoc_download_stream_gridfs_readv (mongoc_stream_t *stream, - mongoc_iovec_t *iov, - size_t iovcnt, - size_t min_bytes, - int32_t timeout_msec) +_mongoc_download_stream_gridfs_readv ( + mongoc_stream_t *stream, mongoc_iovec_t *iov, size_t iovcnt, size_t min_bytes, int32_t timeout_msec) { - mongoc_gridfs_download_stream_t *gridfs = - (mongoc_gridfs_download_stream_t *) stream; + mongoc_gridfs_download_stream_t *gridfs = (mongoc_gridfs_download_stream_t *) stream; ssize_t ret = 0; ENTRY; @@ -102,8 +96,7 @@ _mongoc_download_stream_gridfs_readv (mongoc_stream_t *stream, static bool _mongoc_download_stream_gridfs_check_closed (mongoc_stream_t *stream) /* IN */ { - mongoc_gridfs_download_stream_t *gridfs = - (mongoc_gridfs_download_stream_t *) stream; + mongoc_gridfs_download_stream_t *gridfs = (mongoc_gridfs_download_stream_t *) stream; ENTRY; diff --git a/src/libmongoc/src/mongoc/mongoc-stream-gridfs-upload.c b/src/libmongoc/src/mongoc/mongoc-stream-gridfs-upload.c index 4fae7c3155..3914ba7179 100644 --- a/src/libmongoc/src/mongoc/mongoc-stream-gridfs-upload.c +++ b/src/libmongoc/src/mongoc/mongoc-stream-gridfs-upload.c @@ -26,8 +26,7 @@ static void _mongoc_upload_stream_gridfs_destroy (mongoc_stream_t *stream) { - mongoc_gridfs_upload_stream_t *gridfs = - (mongoc_gridfs_upload_stream_t *) stream; + mongoc_gridfs_upload_stream_t *gridfs = (mongoc_gridfs_upload_stream_t *) stream; ENTRY; @@ -57,8 +56,7 @@ _mongoc_upload_stream_gridfs_failed (mongoc_stream_t *stream) static int _mongoc_upload_stream_gridfs_close (mongoc_stream_t *stream) { - mongoc_gridfs_upload_stream_t *gridfs = - (mongoc_gridfs_upload_stream_t *) stream; + mongoc_gridfs_upload_stream_t *gridfs = (mongoc_gridfs_upload_stream_t *) stream; int ret = 0; ENTRY; @@ -71,13 +69,9 @@ _mongoc_upload_stream_gridfs_close (mongoc_stream_t *stream) } static ssize_t -_mongoc_upload_stream_gridfs_writev (mongoc_stream_t *stream, - mongoc_iovec_t *iov, - size_t iovcnt, - int32_t timeout_msec) +_mongoc_upload_stream_gridfs_writev (mongoc_stream_t *stream, mongoc_iovec_t *iov, size_t iovcnt, int32_t timeout_msec) { - mongoc_gridfs_upload_stream_t *gridfs = - (mongoc_gridfs_upload_stream_t *) stream; + mongoc_gridfs_upload_stream_t *gridfs = (mongoc_gridfs_upload_stream_t *) stream; ssize_t ret = 0; ENTRY; @@ -101,8 +95,7 @@ _mongoc_upload_stream_gridfs_writev (mongoc_stream_t *stream, static bool _mongoc_upload_stream_gridfs_check_closed (mongoc_stream_t *stream) /* IN */ { - mongoc_gridfs_upload_stream_t *gridfs = - (mongoc_gridfs_upload_stream_t *) stream; + mongoc_gridfs_upload_stream_t *gridfs = (mongoc_gridfs_upload_stream_t *) stream; ENTRY; diff --git a/src/libmongoc/src/mongoc/mongoc-stream-gridfs.c b/src/libmongoc/src/mongoc/mongoc-stream-gridfs.c index 3e097eac35..f5a819d41a 100644 --- a/src/libmongoc/src/mongoc/mongoc-stream-gridfs.c +++ b/src/libmongoc/src/mongoc/mongoc-stream-gridfs.c @@ -97,11 +97,8 @@ _mongoc_stream_gridfs_flush (mongoc_stream_t *stream) static ssize_t -_mongoc_stream_gridfs_readv (mongoc_stream_t *stream, - mongoc_iovec_t *iov, - size_t iovcnt, - size_t min_bytes, - int32_t timeout_msec) +_mongoc_stream_gridfs_readv ( + mongoc_stream_t *stream, mongoc_iovec_t *iov, size_t iovcnt, size_t min_bytes, int32_t timeout_msec) { mongoc_stream_gridfs_t *file = (mongoc_stream_gridfs_t *) stream; ssize_t ret = 0; @@ -124,10 +121,7 @@ _mongoc_stream_gridfs_readv (mongoc_stream_t *stream, static ssize_t -_mongoc_stream_gridfs_writev (mongoc_stream_t *stream, - mongoc_iovec_t *iov, - size_t iovcnt, - int32_t timeout_msec) +_mongoc_stream_gridfs_writev (mongoc_stream_t *stream, mongoc_iovec_t *iov, size_t iovcnt, int32_t timeout_msec) { mongoc_stream_gridfs_t *file = (mongoc_stream_gridfs_t *) stream; ssize_t ret = 0; diff --git a/src/libmongoc/src/mongoc/mongoc-stream-gridfs.h b/src/libmongoc/src/mongoc/mongoc-stream-gridfs.h index 9513f93d59..47306940f3 100644 --- a/src/libmongoc/src/mongoc/mongoc-stream-gridfs.h +++ b/src/libmongoc/src/mongoc/mongoc-stream-gridfs.h @@ -30,8 +30,7 @@ BSON_BEGIN_DECLS MONGOC_EXPORT (mongoc_stream_t *) -mongoc_stream_gridfs_new (mongoc_gridfs_file_t *file) - BSON_GNUC_WARN_UNUSED_RESULT; +mongoc_stream_gridfs_new (mongoc_gridfs_file_t *file) BSON_GNUC_WARN_UNUSED_RESULT; BSON_END_DECLS diff --git a/src/libmongoc/src/mongoc/mongoc-stream-private.h b/src/libmongoc/src/mongoc/mongoc-stream-private.h index c2223b0315..bbd131e1f0 100644 --- a/src/libmongoc/src/mongoc/mongoc-stream-private.h +++ b/src/libmongoc/src/mongoc/mongoc-stream-private.h @@ -38,11 +38,8 @@ bool mongoc_stream_wait (mongoc_stream_t *stream, int64_t expire_at); bool -_mongoc_stream_writev_full (mongoc_stream_t *stream, - mongoc_iovec_t *iov, - size_t iovcnt, - int64_t timeout_msec, - bson_error_t *error); +_mongoc_stream_writev_full ( + mongoc_stream_t *stream, mongoc_iovec_t *iov, size_t iovcnt, int64_t timeout_msec, bson_error_t *error); mongoc_stream_t * mongoc_stream_get_root_stream (mongoc_stream_t *stream); diff --git a/src/libmongoc/src/mongoc/mongoc-stream-socket.c b/src/libmongoc/src/mongoc/mongoc-stream-socket.c index dfdbf0af6c..525763fb50 100644 --- a/src/libmongoc/src/mongoc/mongoc-stream-socket.c +++ b/src/libmongoc/src/mongoc/mongoc-stream-socket.c @@ -99,11 +99,8 @@ _mongoc_stream_socket_failed (mongoc_stream_t *stream) static int -_mongoc_stream_socket_setsockopt (mongoc_stream_t *stream, - int level, - int optname, - void *optval, - mongoc_socklen_t optlen) +_mongoc_stream_socket_setsockopt ( + mongoc_stream_t *stream, int level, int optname, void *optval, mongoc_socklen_t optlen) { mongoc_stream_socket_t *ss = (mongoc_stream_socket_t *) stream; int ret; @@ -129,11 +126,8 @@ _mongoc_stream_socket_flush (mongoc_stream_t *stream) static ssize_t -_mongoc_stream_socket_readv (mongoc_stream_t *stream, - mongoc_iovec_t *iov, - size_t iovcnt, - size_t min_bytes, - int32_t timeout_msec) +_mongoc_stream_socket_readv ( + mongoc_stream_t *stream, mongoc_iovec_t *iov, size_t iovcnt, size_t min_bytes, int32_t timeout_msec) { mongoc_stream_socket_t *ss = (mongoc_stream_socket_t *) stream; int64_t expire_at; @@ -155,8 +149,7 @@ _mongoc_stream_socket_readv (mongoc_stream_t *stream, */ for (;;) { - nread = mongoc_socket_recv ( - ss->sock, iov[cur].iov_base, iov[cur].iov_len, 0, expire_at); + nread = mongoc_socket_recv (ss->sock, iov[cur].iov_base, iov[cur].iov_len, 0, expire_at); if (nread <= 0) { if (ret >= (ssize_t) min_bytes) { @@ -192,10 +185,7 @@ _mongoc_stream_socket_readv (mongoc_stream_t *stream, static ssize_t -_mongoc_stream_socket_writev (mongoc_stream_t *stream, - mongoc_iovec_t *iov, - size_t iovcnt, - int32_t timeout_msec) +_mongoc_stream_socket_writev (mongoc_stream_t *stream, mongoc_iovec_t *iov, size_t iovcnt, int32_t timeout_msec) { mongoc_stream_socket_t *ss = (mongoc_stream_socket_t *) stream; int64_t expire_at; @@ -215,9 +205,7 @@ _mongoc_stream_socket_writev (mongoc_stream_t *stream, static ssize_t -_mongoc_stream_socket_poll (mongoc_stream_poll_t *streams, - size_t nstreams, - int32_t timeout_msec) +_mongoc_stream_socket_poll (mongoc_stream_poll_t *streams, size_t nstreams, int32_t timeout_msec) { ssize_t ret = -1; diff --git a/src/libmongoc/src/mongoc/mongoc-stream-tls-libressl.c b/src/libmongoc/src/mongoc/mongoc-stream-tls-libressl.c index 82289b6325..384cd5fa16 100644 --- a/src/libmongoc/src/mongoc/mongoc-stream-tls-libressl.c +++ b/src/libmongoc/src/mongoc/mongoc-stream-tls-libressl.c @@ -43,8 +43,7 @@ static void _mongoc_stream_tls_libressl_destroy (mongoc_stream_t *stream) { mongoc_stream_tls_t *tls = (mongoc_stream_tls_t *) stream; - mongoc_stream_tls_libressl_t *libressl = - (mongoc_stream_tls_libressl_t *) tls->ctx; + mongoc_stream_tls_libressl_t *libressl = (mongoc_stream_tls_libressl_t *) tls->ctx; ENTRY; BSON_ASSERT (libressl); @@ -76,8 +75,7 @@ _mongoc_stream_tls_libressl_close (mongoc_stream_t *stream) { int ret = 0; mongoc_stream_tls_t *tls = (mongoc_stream_tls_t *) stream; - mongoc_stream_tls_libressl_t *libressl = - (mongoc_stream_tls_libressl_t *) tls->ctx; + mongoc_stream_tls_libressl_t *libressl = (mongoc_stream_tls_libressl_t *) tls->ctx; ENTRY; BSON_ASSERT (libressl); @@ -90,8 +88,7 @@ static int _mongoc_stream_tls_libressl_flush (mongoc_stream_t *stream) { mongoc_stream_tls_t *tls = (mongoc_stream_tls_t *) stream; - mongoc_stream_tls_libressl_t *libressl = - (mongoc_stream_tls_libressl_t *) tls->ctx; + mongoc_stream_tls_libressl_t *libressl = (mongoc_stream_tls_libressl_t *) tls->ctx; ENTRY; BSON_ASSERT (libressl); @@ -99,13 +96,10 @@ _mongoc_stream_tls_libressl_flush (mongoc_stream_t *stream) } static ssize_t -_mongoc_stream_tls_libressl_write (mongoc_stream_t *stream, - char *buf, - size_t buf_len) +_mongoc_stream_tls_libressl_write (mongoc_stream_t *stream, char *buf, size_t buf_len) { mongoc_stream_tls_t *tls = (mongoc_stream_tls_t *) stream; - mongoc_stream_tls_libressl_t *libressl = - (mongoc_stream_tls_libressl_t *) tls->ctx; + mongoc_stream_tls_libressl_t *libressl = (mongoc_stream_tls_libressl_t *) tls->ctx; mongoc_stream_poll_t poller; ssize_t total_write = 0; ssize_t ret; @@ -161,14 +155,10 @@ _mongoc_stream_tls_libressl_write (mongoc_stream_t *stream, /* This is copypasta from _mongoc_stream_tls_openssl_writev */ #define MONGOC_STREAM_TLS_BUFFER_SIZE 4096 static ssize_t -_mongoc_stream_tls_libressl_writev (mongoc_stream_t *stream, - mongoc_iovec_t *iov, - size_t iovcnt, - int32_t timeout_msec) +_mongoc_stream_tls_libressl_writev (mongoc_stream_t *stream, mongoc_iovec_t *iov, size_t iovcnt, int32_t timeout_msec) { mongoc_stream_tls_t *tls = (mongoc_stream_tls_t *) stream; - mongoc_stream_tls_libressl_t *libressl = - (mongoc_stream_tls_libressl_t *) tls->ctx; + mongoc_stream_tls_libressl_t *libressl = (mongoc_stream_tls_libressl_t *) tls->ctx; char buf[MONGOC_STREAM_TLS_BUFFER_SIZE]; ssize_t ret = 0; ssize_t child_ret; @@ -204,9 +194,7 @@ _mongoc_stream_tls_libressl_writev (mongoc_stream_t *stream, iov_pos = 0; while (iov_pos < iov[i].iov_len) { - if (buf_head != buf_tail || - ((i + 1 < iovcnt) && - ((buf_end - buf_tail) > (iov[i].iov_len - iov_pos)))) { + if (buf_head != buf_tail || ((i + 1 < iovcnt) && ((buf_end - buf_tail) > (iov[i].iov_len - iov_pos)))) { /* If we have either of: * - buffered bytes already * - another iovec to send after this one and we don't have more @@ -241,8 +229,7 @@ _mongoc_stream_tls_libressl_writev (mongoc_stream_t *stream, /* We get here if we buffered some bytes and filled the buffer, or * if we didn't buffer and have to send out of the iovec */ - child_ret = _mongoc_stream_tls_libressl_write ( - stream, to_write, to_write_len); + child_ret = _mongoc_stream_tls_libressl_write (stream, to_write, to_write_len); if (child_ret < 0) { RETURN (ret); @@ -264,8 +251,7 @@ _mongoc_stream_tls_libressl_writev (mongoc_stream_t *stream, if (buf_head != buf_tail) { /* If we have any bytes buffered, send */ - child_ret = _mongoc_stream_tls_libressl_write ( - stream, buf_head, buf_tail - buf_head); + child_ret = _mongoc_stream_tls_libressl_write (stream, buf_head, buf_tail - buf_head); if (child_ret < 0) { RETURN (child_ret); @@ -284,15 +270,11 @@ _mongoc_stream_tls_libressl_writev (mongoc_stream_t *stream, /* This function is copypasta of _mongoc_stream_tls_openssl_readv */ static ssize_t -_mongoc_stream_tls_libressl_readv (mongoc_stream_t *stream, - mongoc_iovec_t *iov, - size_t iovcnt, - size_t min_bytes, - int32_t timeout_msec) +_mongoc_stream_tls_libressl_readv ( + mongoc_stream_t *stream, mongoc_iovec_t *iov, size_t iovcnt, size_t min_bytes, int32_t timeout_msec) { mongoc_stream_tls_t *tls = (mongoc_stream_tls_t *) stream; - mongoc_stream_tls_libressl_t *libressl = - (mongoc_stream_tls_libressl_t *) tls->ctx; + mongoc_stream_tls_libressl_t *libressl = (mongoc_stream_tls_libressl_t *) tls->ctx; ssize_t ret = 0; ssize_t read_ret; size_t i; @@ -319,9 +301,7 @@ _mongoc_stream_tls_libressl_readv (mongoc_stream_t *stream, poller.stream = stream; poller.revents = 0; poller.events = POLLIN; - read_ret = tls_read (libressl->ctx, - (char *) iov[i].iov_base + iov_pos, - (int) (iov[i].iov_len - iov_pos)); + read_ret = tls_read (libressl->ctx, (char *) iov[i].iov_base + iov_pos, (int) (iov[i].iov_len - iov_pos)); if (read_ret == TLS_WANT_POLLIN) { poller.events = POLLIN; @@ -367,28 +347,22 @@ _mongoc_stream_tls_libressl_readv (mongoc_stream_t *stream, } static int -_mongoc_stream_tls_libressl_setsockopt (mongoc_stream_t *stream, - int level, - int optname, - void *optval, - mongoc_socklen_t optlen) +_mongoc_stream_tls_libressl_setsockopt ( + mongoc_stream_t *stream, int level, int optname, void *optval, mongoc_socklen_t optlen) { mongoc_stream_tls_t *tls = (mongoc_stream_tls_t *) stream; - mongoc_stream_tls_libressl_t *libressl = - (mongoc_stream_tls_libressl_t *) tls->ctx; + mongoc_stream_tls_libressl_t *libressl = (mongoc_stream_tls_libressl_t *) tls->ctx; ENTRY; BSON_ASSERT (libressl); - RETURN (mongoc_stream_setsockopt ( - tls->base_stream, level, optname, optval, optlen)); + RETURN (mongoc_stream_setsockopt (tls->base_stream, level, optname, optval, optlen)); } static mongoc_stream_t * _mongoc_stream_tls_libressl_get_base_stream (mongoc_stream_t *stream) { mongoc_stream_tls_t *tls = (mongoc_stream_tls_t *) stream; - mongoc_stream_tls_libressl_t *libressl = - (mongoc_stream_tls_libressl_t *) tls->ctx; + mongoc_stream_tls_libressl_t *libressl = (mongoc_stream_tls_libressl_t *) tls->ctx; ENTRY; BSON_ASSERT (libressl); @@ -400,8 +374,7 @@ static bool _mongoc_stream_tls_libressl_check_closed (mongoc_stream_t *stream) { mongoc_stream_tls_t *tls = (mongoc_stream_tls_t *) stream; - mongoc_stream_tls_libressl_t *libressl = - (mongoc_stream_tls_libressl_t *) tls->ctx; + mongoc_stream_tls_libressl_t *libressl = (mongoc_stream_tls_libressl_t *) tls->ctx; ENTRY; BSON_ASSERT (libressl); @@ -409,14 +382,10 @@ _mongoc_stream_tls_libressl_check_closed (mongoc_stream_t *stream) } bool -mongoc_stream_tls_libressl_handshake (mongoc_stream_t *stream, - const char *host, - int *events, - bson_error_t *error) +mongoc_stream_tls_libressl_handshake (mongoc_stream_t *stream, const char *host, int *events, bson_error_t *error) { mongoc_stream_tls_t *tls = (mongoc_stream_tls_t *) stream; - mongoc_stream_tls_libressl_t *libressl = - (mongoc_stream_tls_libressl_t *) tls->ctx; + mongoc_stream_tls_libressl_t *libressl = (mongoc_stream_tls_libressl_t *) tls->ctx; int ret; ENTRY; @@ -430,11 +399,8 @@ mongoc_stream_tls_libressl_handshake (mongoc_stream_t *stream, *events = POLLOUT; } else if (ret < 0) { *events = 0; - bson_set_error (error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_SOCKET, - "TLS handshake failed: %s", - tls_error (libressl->ctx)); + bson_set_error ( + error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "TLS handshake failed: %s", tls_error (libressl->ctx)); RETURN (false); } else { RETURN (true); @@ -463,10 +429,7 @@ _mongoc_stream_tls_libressl_should_retry (mongoc_stream_t *stream) } mongoc_stream_t * -mongoc_stream_tls_libressl_new (mongoc_stream_t *base_stream, - const char *host, - mongoc_ssl_opt_t *opt, - int client) +mongoc_stream_tls_libressl_new (mongoc_stream_t *base_stream, const char *host, mongoc_ssl_opt_t *opt, int client) { mongoc_stream_tls_t *tls; mongoc_stream_tls_libressl_t *libressl; @@ -477,9 +440,8 @@ mongoc_stream_tls_libressl_new (mongoc_stream_t *base_stream, if (opt->crl_file) { - MONGOC_ERROR ( - "Setting mongoc_ssl_opt_t.crl_file has no effect when built " - "against libtls"); + MONGOC_ERROR ("Setting mongoc_ssl_opt_t.crl_file has no effect when built " + "against libtls"); RETURN (false); } libressl = (mongoc_stream_tls_libressl_t *) bson_malloc0 (sizeof *libressl); @@ -522,9 +484,7 @@ mongoc_stream_tls_libressl_new (mongoc_stream_t *base_stream, do { if (stream->type == MONGOC_STREAM_SOCKET) { - int socket = mongoc_stream_socket_get_socket ( - (mongoc_stream_socket_t *) stream) - ->sd; + int socket = mongoc_stream_socket_get_socket ((mongoc_stream_socket_t *) stream)->sd; if (tls_configure (libressl->ctx, libressl->config) == -1) { MONGOC_ERROR ("%s", tls_config_error (libressl->config)); RETURN (false); diff --git a/src/libmongoc/src/mongoc/mongoc-stream-tls-libressl.h b/src/libmongoc/src/mongoc/mongoc-stream-tls-libressl.h index ca70a95ebf..c6acdeb223 100644 --- a/src/libmongoc/src/mongoc/mongoc-stream-tls-libressl.h +++ b/src/libmongoc/src/mongoc/mongoc-stream-tls-libressl.h @@ -28,10 +28,8 @@ BSON_BEGIN_DECLS MONGOC_EXPORT (mongoc_stream_t *) -mongoc_stream_tls_libressl_new (mongoc_stream_t *base_stream, - const char *host, - mongoc_ssl_opt_t *opt, - int client) BSON_GNUC_WARN_UNUSED_RESULT; +mongoc_stream_tls_libressl_new (mongoc_stream_t *base_stream, const char *host, mongoc_ssl_opt_t *opt, int client) + BSON_GNUC_WARN_UNUSED_RESULT; BSON_END_DECLS diff --git a/src/libmongoc/src/mongoc/mongoc-stream-tls-openssl-bio.c b/src/libmongoc/src/mongoc/mongoc-stream-tls-openssl-bio.c index 45f2ef8af4..bc55b273c5 100644 --- a/src/libmongoc/src/mongoc/mongoc-stream-tls-openssl-bio.c +++ b/src/libmongoc/src/mongoc/mongoc-stream-tls-openssl-bio.c @@ -39,21 +39,19 @@ #define MONGOC_LOG_DOMAIN "stream-tls-openssl-bio" -#if OPENSSL_VERSION_NUMBER < 0x10100000L || \ - (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x20700000L) +#if OPENSSL_VERSION_NUMBER < 0x10100000L || (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x20700000L) /* Magic vtable to make our BIO shim */ -static BIO_METHOD gMongocStreamTlsOpenSslRawMethods = { - BIO_TYPE_FILTER, - "mongoc-stream-tls-glue", - mongoc_stream_tls_openssl_bio_write, - mongoc_stream_tls_openssl_bio_read, - mongoc_stream_tls_openssl_bio_puts, - mongoc_stream_tls_openssl_bio_gets, - mongoc_stream_tls_openssl_bio_ctrl, - mongoc_stream_tls_openssl_bio_create, - mongoc_stream_tls_openssl_bio_destroy, - NULL}; +static BIO_METHOD gMongocStreamTlsOpenSslRawMethods = {BIO_TYPE_FILTER, + "mongoc-stream-tls-glue", + mongoc_stream_tls_openssl_bio_write, + mongoc_stream_tls_openssl_bio_read, + mongoc_stream_tls_openssl_bio_puts, + mongoc_stream_tls_openssl_bio_gets, + mongoc_stream_tls_openssl_bio_ctrl, + mongoc_stream_tls_openssl_bio_create, + mongoc_stream_tls_openssl_bio_destroy, + NULL}; static void BIO_set_data (BIO *b, void *ptr) @@ -218,17 +216,14 @@ mongoc_stream_tls_openssl_bio_read (BIO *b, char *buf, int len) if (BSON_UNLIKELY (!bson_in_range_signed (int32_t, tls->timeout_msec))) { // CDRIVER-4589 - MONGOC_ERROR ("timeout_msec value %" PRId64 - " exceeds supported 32-bit range", - tls->timeout_msec); + MONGOC_ERROR ("timeout_msec value %" PRId64 " exceeds supported 32-bit range", tls->timeout_msec); return -1; } openssl = (mongoc_stream_tls_openssl_t *) tls->ctx; errno = 0; - const ssize_t ret = mongoc_stream_read ( - tls->base_stream, buf, (size_t) len, 0, (int32_t) tls->timeout_msec); + const ssize_t ret = mongoc_stream_read (tls->base_stream, buf, (size_t) len, 0, (int32_t) tls->timeout_msec); BIO_clear_retry_flags (b); if ((ret <= 0) && MONGOC_ERRNO_IS_AGAIN (errno)) { @@ -289,16 +284,13 @@ mongoc_stream_tls_openssl_bio_write (BIO *b, const char *buf, int len) if (BSON_UNLIKELY (!bson_in_range_signed (int32_t, tls->timeout_msec))) { // CDRIVER-4589 - MONGOC_ERROR ("timeout_msec value %" PRId64 - " exceeds supported 32-bit range", - tls->timeout_msec); + MONGOC_ERROR ("timeout_msec value %" PRId64 " exceeds supported 32-bit range", tls->timeout_msec); RETURN (-1); } errno = 0; TRACE ("mongoc_stream_writev is expected to write: %d", len); - const ssize_t ret = mongoc_stream_writev ( - tls->base_stream, &iov, 1, (int32_t) tls->timeout_msec); + const ssize_t ret = mongoc_stream_writev (tls->base_stream, &iov, 1, (int32_t) tls->timeout_msec); BIO_clear_retry_flags (b); if (len > ret) { diff --git a/src/libmongoc/src/mongoc/mongoc-stream-tls-openssl.c b/src/libmongoc/src/mongoc/mongoc-stream-tls-openssl.c index 21e6fa3fe5..a4551fcac1 100644 --- a/src/libmongoc/src/mongoc/mongoc-stream-tls-openssl.c +++ b/src/libmongoc/src/mongoc/mongoc-stream-tls-openssl.c @@ -47,8 +47,7 @@ #define MONGOC_STREAM_TLS_OPENSSL_BUFFER_SIZE 4096 -#if OPENSSL_VERSION_NUMBER < 0x10100000L || \ - (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x20700000L) +#if OPENSSL_VERSION_NUMBER < 0x10100000L || (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x20700000L) static void BIO_meth_free (BIO_METHOD *meth) { @@ -79,8 +78,7 @@ static void _mongoc_stream_tls_openssl_destroy (mongoc_stream_t *stream) { mongoc_stream_tls_t *tls = (mongoc_stream_tls_t *) stream; - mongoc_stream_tls_openssl_t *openssl = - (mongoc_stream_tls_openssl_t *) tls->ctx; + mongoc_stream_tls_openssl_t *openssl = (mongoc_stream_tls_openssl_t *) tls->ctx; BSON_ASSERT (tls); @@ -184,8 +182,7 @@ static int _mongoc_stream_tls_openssl_flush (mongoc_stream_t *stream) { mongoc_stream_tls_t *tls = (mongoc_stream_tls_t *) stream; - mongoc_stream_tls_openssl_t *openssl = - (mongoc_stream_tls_openssl_t *) tls->ctx; + mongoc_stream_tls_openssl_t *openssl = (mongoc_stream_tls_openssl_t *) tls->ctx; BSON_ASSERT (openssl); @@ -194,12 +191,9 @@ _mongoc_stream_tls_openssl_flush (mongoc_stream_t *stream) static ssize_t -_mongoc_stream_tls_openssl_write (mongoc_stream_tls_t *tls, - char *buf, - size_t buf_len) +_mongoc_stream_tls_openssl_write (mongoc_stream_tls_t *tls, char *buf, size_t buf_len) { - mongoc_stream_tls_openssl_t *openssl = - (mongoc_stream_tls_openssl_t *) tls->ctx; + mongoc_stream_tls_openssl_t *openssl = (mongoc_stream_tls_openssl_t *) tls->ctx; ssize_t ret; int64_t now; int64_t expire = 0; @@ -258,10 +252,7 @@ _mongoc_stream_tls_openssl_write (mongoc_stream_tls_t *tls, */ static ssize_t -_mongoc_stream_tls_openssl_writev (mongoc_stream_t *stream, - mongoc_iovec_t *iov, - size_t iovcnt, - int32_t timeout_msec) +_mongoc_stream_tls_openssl_writev (mongoc_stream_t *stream, mongoc_iovec_t *iov, size_t iovcnt, int32_t timeout_msec) { mongoc_stream_tls_t *tls = (mongoc_stream_tls_t *) stream; char buf[MONGOC_STREAM_TLS_OPENSSL_BUFFER_SIZE]; @@ -302,9 +293,7 @@ _mongoc_stream_tls_openssl_writev (mongoc_stream_t *stream, BSON_ASSERT (buf_end >= buf_tail); const size_t buf_remaining = (size_t) (buf_end - buf_tail); - if (buf_head != buf_tail || - ((i + 1 < iovcnt) && - (buf_remaining > (iov[i].iov_len - iov_pos)))) { + if (buf_head != buf_tail || ((i + 1 < iovcnt) && (buf_remaining > (iov[i].iov_len - iov_pos)))) { /* If we have either of: * - buffered bytes already * - another iovec to send after this one and we don't have more @@ -339,12 +328,9 @@ _mongoc_stream_tls_openssl_writev (mongoc_stream_t *stream, /* We get here if we buffered some bytes and filled the buffer, or * if we didn't buffer and have to send out of the iovec */ - child_ret = - _mongoc_stream_tls_openssl_write (tls, to_write, to_write_len); + child_ret = _mongoc_stream_tls_openssl_write (tls, to_write, to_write_len); if (bson_cmp_not_equal_su (child_ret, to_write_len)) { - TRACE ("Got child_ret: %zu while to_write_len is: %zu", - child_ret, - to_write_len); + TRACE ("Got child_ret: %zu while to_write_len is: %zu", child_ret, to_write_len); } if (child_ret < 0) { @@ -372,8 +358,7 @@ _mongoc_stream_tls_openssl_writev (mongoc_stream_t *stream, if (buf_head != buf_tail) { /* If we have any bytes buffered, send */ - child_ret = - _mongoc_stream_tls_openssl_write (tls, buf_head, buf_tail - buf_head); + child_ret = _mongoc_stream_tls_openssl_write (tls, buf_head, buf_tail - buf_head); if (child_ret < 0) { RETURN (child_ret); @@ -411,15 +396,11 @@ _mongoc_stream_tls_openssl_writev (mongoc_stream_t *stream, */ static ssize_t -_mongoc_stream_tls_openssl_readv (mongoc_stream_t *stream, - mongoc_iovec_t *iov, - size_t iovcnt, - size_t min_bytes, - int32_t timeout_msec) +_mongoc_stream_tls_openssl_readv ( + mongoc_stream_t *stream, mongoc_iovec_t *iov, size_t iovcnt, size_t min_bytes, int32_t timeout_msec) { mongoc_stream_tls_t *tls = (mongoc_stream_tls_t *) stream; - mongoc_stream_tls_openssl_t *openssl = - (mongoc_stream_tls_openssl_t *) tls->ctx; + mongoc_stream_tls_openssl_t *openssl = (mongoc_stream_tls_openssl_t *) tls->ctx; ssize_t ret = 0; size_t i; int read_ret; @@ -442,9 +423,7 @@ _mongoc_stream_tls_openssl_readv (mongoc_stream_t *stream, iov_pos = 0; while (iov_pos < iov[i].iov_len) { - read_ret = BIO_read (openssl->bio, - (char *) iov[i].iov_base + iov_pos, - (int) (iov[i].iov_len - iov_pos)); + read_ret = BIO_read (openssl->bio, (char *) iov[i].iov_base + iov_pos, (int) (iov[i].iov_len - iov_pos)); /* https://www.openssl.org/docs/crypto/BIO_should_retry.html: * @@ -454,8 +433,7 @@ _mongoc_stream_tls_openssl_readv (mongoc_stream_t *stream, * socket BIO returns 0 and BIO_should_retry() is false then the cause * will be that the connection closed. */ - if (read_ret < 0 || - (read_ret == 0 && !BIO_should_retry (openssl->bio))) { + if (read_ret < 0 || (read_ret == 0 && !BIO_should_retry (openssl->bio))) { return -1; } @@ -515,18 +493,14 @@ _mongoc_stream_tls_openssl_readv (mongoc_stream_t *stream, */ static int -_mongoc_stream_tls_openssl_setsockopt (mongoc_stream_t *stream, - int level, - int optname, - void *optval, - mongoc_socklen_t optlen) +_mongoc_stream_tls_openssl_setsockopt ( + mongoc_stream_t *stream, int level, int optname, void *optval, mongoc_socklen_t optlen) { mongoc_stream_tls_t *tls = (mongoc_stream_tls_t *) stream; BSON_ASSERT (tls); - return mongoc_stream_setsockopt ( - tls->base_stream, level, optname, optval, optlen); + return mongoc_stream_setsockopt (tls->base_stream, level, optname, optval, optlen); } @@ -575,14 +549,10 @@ _mongoc_stream_tls_openssl_set_verify_cert_error (SSL *ssl, bson_error_t *error) * mongoc_stream_tls_openssl_handshake: */ static bool -_mongoc_stream_tls_openssl_handshake (mongoc_stream_t *stream, - const char *host, - int *events, - bson_error_t *error) +_mongoc_stream_tls_openssl_handshake (mongoc_stream_t *stream, const char *host, int *events, bson_error_t *error) { mongoc_stream_tls_t *tls = (mongoc_stream_tls_t *) stream; - mongoc_stream_tls_openssl_t *openssl = - (mongoc_stream_tls_openssl_t *) tls->ctx; + mongoc_stream_tls_openssl_t *openssl = (mongoc_stream_tls_openssl_t *) tls->ctx; SSL *ssl; BSON_ASSERT (tls); @@ -596,18 +566,14 @@ _mongoc_stream_tls_openssl_handshake (mongoc_stream_t *stream, #ifdef MONGOC_ENABLE_OCSP_OPENSSL /* Validate OCSP */ - if (openssl->ocsp_opts && - 1 != _mongoc_ocsp_tlsext_status (ssl, openssl->ocsp_opts)) { - bson_set_error (error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_SOCKET, - "TLS handshake failed: Failed OCSP verification"); + if (openssl->ocsp_opts && 1 != _mongoc_ocsp_tlsext_status (ssl, openssl->ocsp_opts)) { + bson_set_error ( + error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "TLS handshake failed: Failed OCSP verification"); RETURN (false); } #endif - if (_mongoc_openssl_check_peer_hostname ( - ssl, host, tls->ssl_opts.allow_invalid_hostname)) { + if (_mongoc_openssl_check_peer_hostname (ssl, host, tls->ssl_opts.allow_invalid_hostname)) { RETURN (true); } @@ -659,9 +625,7 @@ _mongoc_stream_tls_openssl_handshake (mongoc_stream_t *stream, { #ifdef _WIN32 LPTSTR msg = NULL; - FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_ARGUMENT_ARRAY, + FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY, NULL, errno, /* WSAETIMEDOUT */ LANG_NEUTRAL, @@ -672,11 +636,7 @@ _mongoc_stream_tls_openssl_handshake (mongoc_stream_t *stream, const char *msg = strerror (errno); /* ETIMEDOUT */ #endif - bson_set_error (error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_SOCKET, - "TLS handshake failed: %s", - msg); + bson_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "TLS handshake failed: %s", msg); #ifdef _WIN32 LocalFree (msg); @@ -724,8 +684,7 @@ static bool _mongoc_stream_tls_openssl_should_retry (mongoc_stream_t *stream) { mongoc_stream_tls_t *tls = (mongoc_stream_tls_t *) stream; - mongoc_stream_tls_openssl_t *openssl = - (mongoc_stream_tls_openssl_t *) tls->ctx; + mongoc_stream_tls_openssl_t *openssl = (mongoc_stream_tls_openssl_t *) tls->ctx; ENTRY; @@ -760,10 +719,7 @@ _mongoc_stream_tls_openssl_should_retry (mongoc_stream_t *stream) */ mongoc_stream_t * -mongoc_stream_tls_openssl_new (mongoc_stream_t *base_stream, - const char *host, - mongoc_ssl_opt_t *opt, - int client) +mongoc_stream_tls_openssl_new (mongoc_stream_t *base_stream, const char *host, mongoc_ssl_opt_t *opt, int client) { mongoc_stream_tls_t *tls; mongoc_stream_tls_openssl_t *openssl; @@ -789,10 +745,8 @@ mongoc_stream_tls_openssl_new (mongoc_stream_t *base_stream, struct in6_addr addr6; X509_VERIFY_PARAM *param = X509_VERIFY_PARAM_new (); - X509_VERIFY_PARAM_set_hostflags (param, - X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS); - if (inet_pton (AF_INET, host, &addr) || - inet_pton (AF_INET6, host, &addr6)) { + X509_VERIFY_PARAM_set_hostflags (param, X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS); + if (inet_pton (AF_INET, host, &addr) || inet_pton (AF_INET6, host, &addr6)) { X509_VERIFY_PARAM_set1_ip_asc (param, host); } else { X509_VERIFY_PARAM_set1_host (param, host, 0); @@ -805,8 +759,7 @@ mongoc_stream_tls_openssl_new (mongoc_stream_t *base_stream, if (!client) { /* Only used by the Mock Server. * Set a callback to get the SNI, if provided */ - SSL_CTX_set_tlsext_servername_callback (ssl_ctx, - _mongoc_stream_tls_openssl_sni); + SSL_CTX_set_tlsext_servername_callback (ssl_ctx, _mongoc_stream_tls_openssl_sni); } if (opt->weak_cert_validation) { @@ -842,8 +795,7 @@ mongoc_stream_tls_openssl_new (mongoc_stream_t *base_stream, BIO_push (bio_ssl, bio_mongoc_shim); #ifdef MONGOC_ENABLE_OCSP_OPENSSL - if (client && !opt->weak_cert_validation && - !_mongoc_ssl_opts_disable_certificate_revocation_check (opt)) { + if (client && !opt->weak_cert_validation && !_mongoc_ssl_opts_disable_certificate_revocation_check (opt)) { SSL *ssl; BIO_get_ssl (bio_ssl, &ssl); @@ -864,8 +816,7 @@ mongoc_stream_tls_openssl_new (mongoc_stream_t *base_stream, ocsp_opts = bson_malloc0 (sizeof (mongoc_openssl_ocsp_opt_t)); ocsp_opts->allow_invalid_hostname = opt->allow_invalid_hostname; ocsp_opts->weak_cert_validation = opt->weak_cert_validation; - ocsp_opts->disable_endpoint_check = - _mongoc_ssl_opts_disable_ocsp_endpoint_check (opt); + ocsp_opts->disable_endpoint_check = _mongoc_ssl_opts_disable_ocsp_endpoint_check (opt); ocsp_opts->host = bson_strdup (host); _mongoc_ssl_opts_copy_to (opt, &ocsp_opts->ssl_opts, true); } diff --git a/src/libmongoc/src/mongoc/mongoc-stream-tls-openssl.h b/src/libmongoc/src/mongoc/mongoc-stream-tls-openssl.h index 2ddf8a6428..78a18d20dc 100644 --- a/src/libmongoc/src/mongoc/mongoc-stream-tls-openssl.h +++ b/src/libmongoc/src/mongoc/mongoc-stream-tls-openssl.h @@ -27,10 +27,8 @@ BSON_BEGIN_DECLS MONGOC_EXPORT (mongoc_stream_t *) -mongoc_stream_tls_openssl_new (mongoc_stream_t *base_stream, - const char *host, - mongoc_ssl_opt_t *opt, - int client) BSON_GNUC_WARN_UNUSED_RESULT; +mongoc_stream_tls_openssl_new (mongoc_stream_t *base_stream, const char *host, mongoc_ssl_opt_t *opt, int client) + BSON_GNUC_WARN_UNUSED_RESULT; BSON_END_DECLS diff --git a/src/libmongoc/src/mongoc/mongoc-stream-tls-private.h b/src/libmongoc/src/mongoc/mongoc-stream-tls-private.h index e3da5f2649..410aed462f 100644 --- a/src/libmongoc/src/mongoc/mongoc-stream-tls-private.h +++ b/src/libmongoc/src/mongoc/mongoc-stream-tls-private.h @@ -36,13 +36,10 @@ BSON_BEGIN_DECLS struct _mongoc_stream_tls_t { mongoc_stream_t parent; /* The TLS stream wrapper */ mongoc_stream_t *base_stream; /* The underlying actual stream */ - void *ctx; /* TLS lib specific configuration or wrappers */ + void *ctx; /* TLS lib specific configuration or wrappers */ int64_t timeout_msec; mongoc_ssl_opt_t ssl_opts; - bool (*handshake) (mongoc_stream_t *stream, - const char *host, - int *events /* OUT*/, - bson_error_t *error); + bool (*handshake) (mongoc_stream_t *stream, const char *host, int *events /* OUT*/, bson_error_t *error); }; diff --git a/src/libmongoc/src/mongoc/mongoc-stream-tls-secure-channel.c b/src/libmongoc/src/mongoc/mongoc-stream-tls-secure-channel.c index ee93627582..5b4e8d3718 100644 --- a/src/libmongoc/src/mongoc/mongoc-stream-tls-secure-channel.c +++ b/src/libmongoc/src/mongoc/mongoc-stream-tls-secure-channel.c @@ -91,8 +91,7 @@ static void _mongoc_stream_tls_secure_channel_destroy (mongoc_stream_t *stream) { mongoc_stream_tls_t *tls = (mongoc_stream_tls_t *) stream; - mongoc_stream_tls_secure_channel_t *secure_channel = - (mongoc_stream_tls_secure_channel_t *) tls->ctx; + mongoc_stream_tls_secure_channel_t *secure_channel = (mongoc_stream_tls_secure_channel_t *) tls->ctx; ENTRY; BSON_ASSERT (secure_channel); @@ -112,47 +111,40 @@ _mongoc_stream_tls_secure_channel_destroy (mongoc_stream_t *stream) SecBufferDesc outbuf_desc; DWORD dwshut = SCHANNEL_SHUTDOWN; - _mongoc_secure_channel_init_sec_buffer ( - &Buffer, SECBUFFER_TOKEN, &dwshut, sizeof (dwshut)); + _mongoc_secure_channel_init_sec_buffer (&Buffer, SECBUFFER_TOKEN, &dwshut, sizeof (dwshut)); _mongoc_secure_channel_init_sec_buffer_desc (&BuffDesc, &Buffer, 1); - sspi_status = - ApplyControlToken (&secure_channel->ctxt->ctxt_handle, &BuffDesc); + sspi_status = ApplyControlToken (&secure_channel->ctxt->ctxt_handle, &BuffDesc); if (sspi_status != SEC_E_OK) { MONGOC_ERROR ("ApplyControlToken failure: %ld", sspi_status); } /* setup output buffer */ - _mongoc_secure_channel_init_sec_buffer ( - &outbuf, SECBUFFER_EMPTY, NULL, 0); + _mongoc_secure_channel_init_sec_buffer (&outbuf, SECBUFFER_EMPTY, NULL, 0); _mongoc_secure_channel_init_sec_buffer_desc (&outbuf_desc, &outbuf, 1); - sspi_status = - InitializeSecurityContext (&secure_channel->cred->cred_handle, - &secure_channel->ctxt->ctxt_handle, - /*tls->hostname*/ NULL, - secure_channel->req_flags, - 0, - 0, - NULL, - 0, - &secure_channel->ctxt->ctxt_handle, - &outbuf_desc, - &secure_channel->ret_flags, - &secure_channel->ctxt->time_stamp); + sspi_status = InitializeSecurityContext (&secure_channel->cred->cred_handle, + &secure_channel->ctxt->ctxt_handle, + /*tls->hostname*/ NULL, + secure_channel->req_flags, + 0, + 0, + NULL, + 0, + &secure_channel->ctxt->ctxt_handle, + &outbuf_desc, + &secure_channel->ret_flags, + &secure_channel->ctxt->time_stamp); if ((sspi_status == SEC_E_OK) || (sspi_status == SEC_I_CONTEXT_EXPIRED)) { /* send close message which is in output buffer */ - ssize_t written = - mongoc_secure_channel_write (tls, outbuf.pvBuffer, outbuf.cbBuffer); + ssize_t written = mongoc_secure_channel_write (tls, outbuf.pvBuffer, outbuf.cbBuffer); FreeContextBuffer (outbuf.pvBuffer); if (outbuf.cbBuffer != (size_t) written) { - TRACE ("failed to send close msg (wrote %zd out of %lu)", - written, - outbuf.cbBuffer); + TRACE ("failed to send close msg (wrote %zd out of %lu)", written, outbuf.cbBuffer); } } } @@ -210,8 +202,7 @@ _mongoc_stream_tls_secure_channel_close (mongoc_stream_t *stream) { int ret = 0; mongoc_stream_tls_t *tls = (mongoc_stream_tls_t *) stream; - mongoc_stream_tls_secure_channel_t *secure_channel = - (mongoc_stream_tls_secure_channel_t *) tls->ctx; + mongoc_stream_tls_secure_channel_t *secure_channel = (mongoc_stream_tls_secure_channel_t *) tls->ctx; ENTRY; BSON_ASSERT (secure_channel); @@ -224,8 +215,7 @@ static int _mongoc_stream_tls_secure_channel_flush (mongoc_stream_t *stream) { mongoc_stream_tls_t *tls = (mongoc_stream_tls_t *) stream; - mongoc_stream_tls_secure_channel_t *secure_channel = - (mongoc_stream_tls_secure_channel_t *) tls->ctx; + mongoc_stream_tls_secure_channel_t *secure_channel = (mongoc_stream_tls_secure_channel_t *) tls->ctx; ENTRY; BSON_ASSERT (secure_channel); @@ -233,13 +223,10 @@ _mongoc_stream_tls_secure_channel_flush (mongoc_stream_t *stream) } static ssize_t -_mongoc_stream_tls_secure_channel_write (mongoc_stream_t *stream, - char *buf, - size_t buf_len) +_mongoc_stream_tls_secure_channel_write (mongoc_stream_t *stream, char *buf, size_t buf_len) { mongoc_stream_tls_t *tls = (mongoc_stream_tls_t *) stream; - mongoc_stream_tls_secure_channel_t *secure_channel = - (mongoc_stream_tls_secure_channel_t *) tls->ctx; + mongoc_stream_tls_secure_channel_t *secure_channel = (mongoc_stream_tls_secure_channel_t *) tls->ctx; ssize_t written = -1; size_t data_len = 0; unsigned char *data = NULL; @@ -254,9 +241,8 @@ _mongoc_stream_tls_secure_channel_write (mongoc_stream_t *stream, /* check if the maximum stream sizes were queried */ if (secure_channel->stream_sizes.cbMaximumMessage == 0) { - sspi_status = QueryContextAttributes (&secure_channel->ctxt->ctxt_handle, - SECPKG_ATTR_STREAM_SIZES, - &secure_channel->stream_sizes); + sspi_status = QueryContextAttributes ( + &secure_channel->ctxt->ctxt_handle, SECPKG_ATTR_STREAM_SIZES, &secure_channel->stream_sizes); if (sspi_status != SEC_E_OK) { TRACE ("failing here: %d", __LINE__); @@ -266,43 +252,33 @@ _mongoc_stream_tls_secure_channel_write (mongoc_stream_t *stream, /* check if the buffer is longer than the maximum message length */ if (buf_len > secure_channel->stream_sizes.cbMaximumMessage) { - TRACE ("SHRINKING buf_len from %zu to %lu", - buf_len, - secure_channel->stream_sizes.cbMaximumMessage); + TRACE ("SHRINKING buf_len from %zu to %lu", buf_len, secure_channel->stream_sizes.cbMaximumMessage); buf_len = secure_channel->stream_sizes.cbMaximumMessage; } /* calculate the complete message length and allocate a buffer for it */ - data_len = secure_channel->stream_sizes.cbHeader + buf_len + - secure_channel->stream_sizes.cbTrailer; + data_len = secure_channel->stream_sizes.cbHeader + buf_len + secure_channel->stream_sizes.cbTrailer; data = (unsigned char *) bson_malloc (data_len); /* setup output buffers (header, data, trailer, empty) */ _mongoc_secure_channel_init_sec_buffer ( - &outbuf[0], - SECBUFFER_STREAM_HEADER, - data, - secure_channel->stream_sizes.cbHeader); - _mongoc_secure_channel_init_sec_buffer ( - &outbuf[1], - SECBUFFER_DATA, - data + secure_channel->stream_sizes.cbHeader, - (unsigned long) (buf_len & (size_t) 0xFFFFFFFFUL)); - _mongoc_secure_channel_init_sec_buffer ( - &outbuf[2], - SECBUFFER_STREAM_TRAILER, - data + secure_channel->stream_sizes.cbHeader + buf_len, - secure_channel->stream_sizes.cbTrailer); - _mongoc_secure_channel_init_sec_buffer ( - &outbuf[3], SECBUFFER_EMPTY, NULL, 0); + &outbuf[0], SECBUFFER_STREAM_HEADER, data, secure_channel->stream_sizes.cbHeader); + _mongoc_secure_channel_init_sec_buffer (&outbuf[1], + SECBUFFER_DATA, + data + secure_channel->stream_sizes.cbHeader, + (unsigned long) (buf_len & (size_t) 0xFFFFFFFFUL)); + _mongoc_secure_channel_init_sec_buffer (&outbuf[2], + SECBUFFER_STREAM_TRAILER, + data + secure_channel->stream_sizes.cbHeader + buf_len, + secure_channel->stream_sizes.cbTrailer); + _mongoc_secure_channel_init_sec_buffer (&outbuf[3], SECBUFFER_EMPTY, NULL, 0); _mongoc_secure_channel_init_sec_buffer_desc (&outbuf_desc, outbuf, 4); /* copy data into output buffer */ memcpy (outbuf[1].pvBuffer, buf, buf_len); /* https://msdn.microsoft.com/en-us/library/windows/desktop/aa375390.aspx */ - sspi_status = - EncryptMessage (&secure_channel->ctxt->ctxt_handle, 0, &outbuf_desc, 0); + sspi_status = EncryptMessage (&secure_channel->ctxt->ctxt_handle, 0, &outbuf_desc, 0); /* check if the message was encrypted */ if (sspi_status == SEC_E_OK) { @@ -335,8 +311,7 @@ _mongoc_stream_tls_secure_channel_writev (mongoc_stream_t *stream, int32_t timeout_msec) { mongoc_stream_tls_t *tls = (mongoc_stream_tls_t *) stream; - mongoc_stream_tls_secure_channel_t *secure_channel = - (mongoc_stream_tls_secure_channel_t *) tls->ctx; + mongoc_stream_tls_secure_channel_t *secure_channel = (mongoc_stream_tls_secure_channel_t *) tls->ctx; char buf[MONGOC_STREAM_TLS_BUFFER_SIZE]; ssize_t ret = 0; ssize_t child_ret; @@ -379,9 +354,7 @@ _mongoc_stream_tls_secure_channel_writev (mongoc_stream_t *stream, BSON_ASSERT (buf_end >= buf_tail); const size_t buf_remaining = (size_t) (buf_end - buf_tail); - if (buf_head != buf_tail || - ((i + 1u < iovcnt) && - (buf_remaining > (iov[i].iov_len - iov_pos)))) { + if (buf_head != buf_tail || ((i + 1u < iovcnt) && (buf_remaining > (iov[i].iov_len - iov_pos)))) { /* If we have either of: * - buffered bytes already * - another iovec to send after this one and we don't have more @@ -416,11 +389,8 @@ _mongoc_stream_tls_secure_channel_writev (mongoc_stream_t *stream, /* We get here if we buffered some bytes and filled the buffer, or * if we didn't buffer and have to send out of the iovec */ - child_ret = _mongoc_stream_tls_secure_channel_write ( - stream, to_write, to_write_len); - TRACE ("Child0wrote: %zd, was supposed to write: %zu", - child_ret, - to_write_len); + child_ret = _mongoc_stream_tls_secure_channel_write (stream, to_write, to_write_len); + TRACE ("Child0wrote: %zd, was supposed to write: %zu", child_ret, to_write_len); if (child_ret < 0) { RETURN (ret); @@ -438,11 +408,8 @@ _mongoc_stream_tls_secure_channel_writev (mongoc_stream_t *stream, if (buf_head != buf_tail) { /* If we have any bytes buffered, send */ - child_ret = _mongoc_stream_tls_secure_channel_write ( - stream, buf_head, buf_tail - buf_head); - TRACE ("Child1wrote: %zd, was supposed to write: %td", - child_ret, - buf_tail - buf_head); + child_ret = _mongoc_stream_tls_secure_channel_write (stream, buf_head, buf_tail - buf_head); + TRACE ("Child1wrote: %zd, was supposed to write: %td", child_ret, buf_tail - buf_head); if (child_ret < 0) { RETURN (child_ret); @@ -462,14 +429,11 @@ _mongoc_stream_tls_secure_channel_writev (mongoc_stream_t *stream, /* move up to "len" decrypted bytes to buf, return number of bytes */ static ssize_t -_mongoc_stream_tls_secure_channel_debuf ( - mongoc_stream_tls_secure_channel_t *secure_channel, char *buf, size_t size) +_mongoc_stream_tls_secure_channel_debuf (mongoc_stream_tls_secure_channel_t *secure_channel, char *buf, size_t size) { size_t s = BSON_MIN (size, secure_channel->decdata_offset); memcpy (buf, secure_channel->decdata_buffer, s); - memmove (secure_channel->decdata_buffer, - secure_channel->decdata_buffer + s, - secure_channel->decdata_offset - s); + memmove (secure_channel->decdata_buffer, secure_channel->decdata_buffer + s, secure_channel->decdata_offset - s); secure_channel->decdata_offset -= s; @@ -484,8 +448,7 @@ _mongoc_stream_tls_secure_channel_debuf ( /* decrypt as many received bytes as possible to secure_channel.decdata_buf */ static void -_mongoc_stream_tls_secure_channel_decrypt ( - mongoc_stream_tls_secure_channel_t *secure_channel) +_mongoc_stream_tls_secure_channel_decrypt (mongoc_stream_tls_secure_channel_t *secure_channel) { size_t size = 0; size_t remaining; @@ -500,53 +463,40 @@ _mongoc_stream_tls_secure_channel_decrypt ( /* decrypt loop */ while (secure_channel->encdata_offset > 0 && sspi_status == SEC_E_OK) { /* prepare data buffer for DecryptMessage call */ - _mongoc_secure_channel_init_sec_buffer ( - &inbuf[0], - SECBUFFER_DATA, - secure_channel->encdata_buffer, - (unsigned long) (secure_channel->encdata_offset & - (size_t) 0xFFFFFFFFUL)); + _mongoc_secure_channel_init_sec_buffer (&inbuf[0], + SECBUFFER_DATA, + secure_channel->encdata_buffer, + (unsigned long) (secure_channel->encdata_offset & (size_t) 0xFFFFFFFFUL)); /* we need 3 more empty input buffers for possible output */ - _mongoc_secure_channel_init_sec_buffer ( - &inbuf[1], SECBUFFER_EMPTY, NULL, 0); - _mongoc_secure_channel_init_sec_buffer ( - &inbuf[2], SECBUFFER_EMPTY, NULL, 0); - _mongoc_secure_channel_init_sec_buffer ( - &inbuf[3], SECBUFFER_EMPTY, NULL, 0); + _mongoc_secure_channel_init_sec_buffer (&inbuf[1], SECBUFFER_EMPTY, NULL, 0); + _mongoc_secure_channel_init_sec_buffer (&inbuf[2], SECBUFFER_EMPTY, NULL, 0); + _mongoc_secure_channel_init_sec_buffer (&inbuf[3], SECBUFFER_EMPTY, NULL, 0); _mongoc_secure_channel_init_sec_buffer_desc (&inbuf_desc, inbuf, 4); /* https://msdn.microsoft.com/en-us/library/windows/desktop/aa375348.aspx */ - sspi_status = DecryptMessage ( - &secure_channel->ctxt->ctxt_handle, &inbuf_desc, 0, NULL); + sspi_status = DecryptMessage (&secure_channel->ctxt->ctxt_handle, &inbuf_desc, 0, NULL); /* check if everything went fine (server may want to renegotiate * or shutdown the connection context) */ - if (sspi_status == SEC_E_OK || sspi_status == SEC_I_RENEGOTIATE || - sspi_status == SEC_I_CONTEXT_EXPIRED) { + if (sspi_status == SEC_E_OK || sspi_status == SEC_I_RENEGOTIATE || sspi_status == SEC_I_CONTEXT_EXPIRED) { /* check for successfully decrypted data, even before actual * renegotiation or shutdown of the connection context */ if (inbuf[1].BufferType == SECBUFFER_DATA) { TRACE ("decrypted data length: %lu", inbuf[1].cbBuffer); size = inbuf[1].cbBuffer; - remaining = - secure_channel->decdata_length - secure_channel->decdata_offset; + remaining = secure_channel->decdata_length - secure_channel->decdata_offset; if (remaining < size) { mongoc_secure_channel_realloc_buf ( - &secure_channel->decdata_length, - &secure_channel->decdata_buffer, - size); + &secure_channel->decdata_length, &secure_channel->decdata_buffer, size); } /* copy decrypted data to internal buffer */ if (size) { - memcpy (secure_channel->decdata_buffer + - secure_channel->decdata_offset, - inbuf[1].pvBuffer, - size); + memcpy (secure_channel->decdata_buffer + secure_channel->decdata_offset, inbuf[1].pvBuffer, size); secure_channel->decdata_offset += size; } @@ -567,9 +517,7 @@ _mongoc_stream_tls_secure_channel_decrypt ( /* move remaining encrypted data forward to the beginning of * buffer */ memmove (secure_channel->encdata_buffer, - (secure_channel->encdata_buffer + - secure_channel->encdata_offset) - - inbuf[3].cbBuffer, + (secure_channel->encdata_buffer + secure_channel->encdata_offset) - inbuf[3].cbBuffer, inbuf[3].cbBuffer); secure_channel->encdata_offset = inbuf[3].cbBuffer; } @@ -617,13 +565,10 @@ _mongoc_stream_tls_secure_channel_decrypt ( static ssize_t -_mongoc_stream_tls_secure_channel_read (mongoc_stream_t *stream, - char *buf, - size_t len) +_mongoc_stream_tls_secure_channel_read (mongoc_stream_t *stream, char *buf, size_t len) { mongoc_stream_tls_t *tls = (mongoc_stream_tls_t *) stream; - mongoc_stream_tls_secure_channel_t *secure_channel = - (mongoc_stream_tls_secure_channel_t *) tls->ctx; + mongoc_stream_tls_secure_channel_t *secure_channel = (mongoc_stream_tls_secure_channel_t *) tls->ctx; ssize_t size = 0; ssize_t nread; @@ -645,8 +590,7 @@ _mongoc_stream_tls_secure_channel_read (mongoc_stream_t *stream, if (secure_channel->encdata_offset) { _mongoc_stream_tls_secure_channel_decrypt (secure_channel); if (secure_channel->decdata_offset) { - return _mongoc_stream_tls_secure_channel_debuf ( - secure_channel, buf, len); + return _mongoc_stream_tls_secure_channel_debuf (secure_channel, buf, len); } } @@ -669,11 +613,8 @@ _mongoc_stream_tls_secure_channel_read (mongoc_stream_t *stream, size = secure_channel->encdata_length - secure_channel->encdata_offset; /* read encrypted data from socket. returns 0 on shutdown or error */ - nread = - mongoc_secure_channel_read (tls, - (char *) (secure_channel->encdata_buffer + - secure_channel->encdata_offset), - (size_t) size); + nread = mongoc_secure_channel_read ( + tls, (char *) (secure_channel->encdata_buffer + secure_channel->encdata_offset), (size_t) size); if (!nread) { if (MONGOC_ERRNO_IS_AGAIN (errno)) { @@ -696,15 +637,11 @@ _mongoc_stream_tls_secure_channel_read (mongoc_stream_t *stream, /* This function is copypasta of _mongoc_stream_tls_openssl_readv */ static ssize_t -_mongoc_stream_tls_secure_channel_readv (mongoc_stream_t *stream, - mongoc_iovec_t *iov, - size_t iovcnt, - size_t min_bytes, - int32_t timeout_msec) +_mongoc_stream_tls_secure_channel_readv ( + mongoc_stream_t *stream, mongoc_iovec_t *iov, size_t iovcnt, size_t min_bytes, int32_t timeout_msec) { mongoc_stream_tls_t *tls = (mongoc_stream_tls_t *) stream; - mongoc_stream_tls_secure_channel_t *secure_channel = - (mongoc_stream_tls_secure_channel_t *) tls->ctx; + mongoc_stream_tls_secure_channel_t *secure_channel = (mongoc_stream_tls_secure_channel_t *) tls->ctx; ssize_t ret = 0; size_t i; size_t iov_pos = 0; @@ -727,9 +664,7 @@ _mongoc_stream_tls_secure_channel_readv (mongoc_stream_t *stream, while (iov_pos < iov[i].iov_len) { ssize_t read_ret = _mongoc_stream_tls_secure_channel_read ( - stream, - (char *) iov[i].iov_base + iov_pos, - (int) (iov[i].iov_len - iov_pos)); + stream, (char *) iov[i].iov_base + iov_pos, (int) (iov[i].iov_len - iov_pos)); if (read_ret < 0) { RETURN (-1); @@ -770,28 +705,22 @@ _mongoc_stream_tls_secure_channel_readv (mongoc_stream_t *stream, } static int -_mongoc_stream_tls_secure_channel_setsockopt (mongoc_stream_t *stream, - int level, - int optname, - void *optval, - mongoc_socklen_t optlen) +_mongoc_stream_tls_secure_channel_setsockopt ( + mongoc_stream_t *stream, int level, int optname, void *optval, mongoc_socklen_t optlen) { mongoc_stream_tls_t *tls = (mongoc_stream_tls_t *) stream; - mongoc_stream_tls_secure_channel_t *secure_channel = - (mongoc_stream_tls_secure_channel_t *) tls->ctx; + mongoc_stream_tls_secure_channel_t *secure_channel = (mongoc_stream_tls_secure_channel_t *) tls->ctx; ENTRY; BSON_ASSERT (secure_channel); - RETURN (mongoc_stream_setsockopt ( - tls->base_stream, level, optname, optval, optlen)); + RETURN (mongoc_stream_setsockopt (tls->base_stream, level, optname, optval, optlen)); } static mongoc_stream_t * _mongoc_stream_tls_secure_channel_get_base_stream (mongoc_stream_t *stream) { mongoc_stream_tls_t *tls = (mongoc_stream_tls_t *) stream; - mongoc_stream_tls_secure_channel_t *secure_channel = - (mongoc_stream_tls_secure_channel_t *) tls->ctx; + mongoc_stream_tls_secure_channel_t *secure_channel = (mongoc_stream_tls_secure_channel_t *) tls->ctx; ENTRY; BSON_ASSERT (secure_channel); @@ -800,12 +729,10 @@ _mongoc_stream_tls_secure_channel_get_base_stream (mongoc_stream_t *stream) static bool -_mongoc_stream_tls_secure_channel_check_closed ( - mongoc_stream_t *stream) /* IN */ +_mongoc_stream_tls_secure_channel_check_closed (mongoc_stream_t *stream) /* IN */ { mongoc_stream_tls_t *tls = (mongoc_stream_tls_t *) stream; - mongoc_stream_tls_secure_channel_t *secure_channel = - (mongoc_stream_tls_secure_channel_t *) tls->ctx; + mongoc_stream_tls_secure_channel_t *secure_channel = (mongoc_stream_tls_secure_channel_t *) tls->ctx; ENTRY; BSON_ASSERT (secure_channel); @@ -813,14 +740,10 @@ _mongoc_stream_tls_secure_channel_check_closed ( } bool -mongoc_stream_tls_secure_channel_handshake (mongoc_stream_t *stream, - const char *host, - int *events, - bson_error_t *error) +mongoc_stream_tls_secure_channel_handshake (mongoc_stream_t *stream, const char *host, int *events, bson_error_t *error) { mongoc_stream_tls_t *tls = (mongoc_stream_tls_t *) stream; - mongoc_stream_tls_secure_channel_t *secure_channel = - (mongoc_stream_tls_secure_channel_t *) tls->ctx; + mongoc_stream_tls_secure_channel_t *secure_channel = (mongoc_stream_tls_secure_channel_t *) tls->ctx; ENTRY; BSON_ASSERT (secure_channel); @@ -829,9 +752,7 @@ mongoc_stream_tls_secure_channel_handshake (mongoc_stream_t *stream, error->code = 0; } - TRACE ("Getting ready for state: %d, timeout is %" PRId64, - secure_channel->connecting_state + 1, - tls->timeout_msec); + TRACE ("Getting ready for state: %d, timeout is %" PRId64, secure_channel->connecting_state + 1, tls->timeout_msec); switch (secure_channel->connecting_state) { case ssl_connect_1: @@ -888,10 +809,7 @@ mongoc_stream_tls_secure_channel_handshake (mongoc_stream_t *stream, *events = 0; if (error && !error->code) { - bson_set_error (error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_SOCKET, - "TLS handshake failed"); + bson_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "TLS handshake failed"); } RETURN (false); @@ -918,10 +836,7 @@ _mongoc_stream_tls_secure_channel_should_retry (mongoc_stream_t *stream) } mongoc_stream_t * -mongoc_stream_tls_secure_channel_new (mongoc_stream_t *base_stream, - const char *host, - mongoc_ssl_opt_t *opt, - int client) +mongoc_stream_tls_secure_channel_new (mongoc_stream_t *base_stream, const char *host, mongoc_ssl_opt_t *opt, int client) { SECURITY_STATUS sspi_status = SEC_E_OK; SCHANNEL_CRED schannel_cred; @@ -934,14 +849,11 @@ mongoc_stream_tls_secure_channel_new (mongoc_stream_t *base_stream, BSON_ASSERT (opt); - secure_channel = (mongoc_stream_tls_secure_channel_t *) bson_malloc0 ( - sizeof *secure_channel); + secure_channel = (mongoc_stream_tls_secure_channel_t *) bson_malloc0 (sizeof *secure_channel); - secure_channel->decdata_buffer = - bson_malloc (MONGOC_SCHANNEL_BUFFER_INIT_SIZE); + secure_channel->decdata_buffer = bson_malloc (MONGOC_SCHANNEL_BUFFER_INIT_SIZE); secure_channel->decdata_length = MONGOC_SCHANNEL_BUFFER_INIT_SIZE; - secure_channel->encdata_buffer = - bson_malloc (MONGOC_SCHANNEL_BUFFER_INIT_SIZE); + secure_channel->encdata_buffer = bson_malloc (MONGOC_SCHANNEL_BUFFER_INIT_SIZE); secure_channel->encdata_length = MONGOC_SCHANNEL_BUFFER_INIT_SIZE; tls = (mongoc_stream_tls_t *) bson_malloc0 (sizeof *tls); @@ -953,8 +865,7 @@ mongoc_stream_tls_secure_channel_new (mongoc_stream_t *base_stream, tls->parent.writev = _mongoc_stream_tls_secure_channel_writev; tls->parent.readv = _mongoc_stream_tls_secure_channel_readv; tls->parent.setsockopt = _mongoc_stream_tls_secure_channel_setsockopt; - tls->parent.get_base_stream = - _mongoc_stream_tls_secure_channel_get_base_stream; + tls->parent.get_base_stream = _mongoc_stream_tls_secure_channel_get_base_stream; tls->parent.check_closed = _mongoc_stream_tls_secure_channel_check_closed; tls->parent.timed_out = _mongoc_stream_tls_secure_channel_timed_out; tls->parent.should_retry = _mongoc_stream_tls_secure_channel_should_retry; @@ -1016,44 +927,38 @@ mongoc_stream_tls_secure_channel_new (mongoc_stream_t *base_stream, } - schannel_cred.grbitEnabledProtocols = - SP_PROT_TLS1_1_CLIENT | SP_PROT_TLS1_2_CLIENT; + schannel_cred.grbitEnabledProtocols = SP_PROT_TLS1_1_CLIENT | SP_PROT_TLS1_2_CLIENT; - secure_channel->cred = (mongoc_secure_channel_cred *) bson_malloc0 ( - sizeof (mongoc_secure_channel_cred)); + secure_channel->cred = (mongoc_secure_channel_cred *) bson_malloc0 (sizeof (mongoc_secure_channel_cred)); /* Example: * https://msdn.microsoft.com/en-us/library/windows/desktop/aa375454%28v=vs.85%29.aspx * AcquireCredentialsHandle: * https://msdn.microsoft.com/en-us/library/windows/desktop/aa374716.aspx */ - sspi_status = AcquireCredentialsHandle ( - NULL, /* principal */ - UNISP_NAME, /* security package */ - SECPKG_CRED_OUTBOUND, /* we are preparing outbound connection */ - NULL, /* Optional logon */ - &schannel_cred, /* TLS "configuration", "auth data" */ - NULL, /* unused */ - NULL, /* unused */ - &secure_channel->cred->cred_handle, /* credential OUT param */ - &secure_channel->cred->time_stamp); /* certificate expiration time */ + sspi_status = AcquireCredentialsHandle (NULL, /* principal */ + UNISP_NAME, /* security package */ + SECPKG_CRED_OUTBOUND, /* we are preparing outbound connection */ + NULL, /* Optional logon */ + &schannel_cred, /* TLS "configuration", "auth data" */ + NULL, /* unused */ + NULL, /* unused */ + &secure_channel->cred->cred_handle, /* credential OUT param */ + &secure_channel->cred->time_stamp); /* certificate expiration time */ if (sspi_status != SEC_E_OK) { LPTSTR msg = NULL; - FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_ARGUMENT_ARRAY, + FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY, NULL, GetLastError (), LANG_NEUTRAL, (LPTSTR) &msg, 0, NULL); - MONGOC_ERROR ( - "Failed to initialize security context, error code: 0x%04X%04X: '%s'", - (unsigned int) (sspi_status >> 16) & 0xffff, - (unsigned int) sspi_status & 0xffff, - msg); + MONGOC_ERROR ("Failed to initialize security context, error code: 0x%04X%04X: '%s'", + (unsigned int) (sspi_status >> 16) & 0xffff, + (unsigned int) sspi_status & 0xffff, + msg); LocalFree (msg); RETURN (NULL); } diff --git a/src/libmongoc/src/mongoc/mongoc-stream-tls-secure-channel.h b/src/libmongoc/src/mongoc/mongoc-stream-tls-secure-channel.h index 2feac06520..9cc5f0e9b7 100644 --- a/src/libmongoc/src/mongoc/mongoc-stream-tls-secure-channel.h +++ b/src/libmongoc/src/mongoc/mongoc-stream-tls-secure-channel.h @@ -27,10 +27,8 @@ BSON_BEGIN_DECLS MONGOC_EXPORT (mongoc_stream_t *) -mongoc_stream_tls_secure_channel_new (mongoc_stream_t *base_stream, - const char *host, - mongoc_ssl_opt_t *opt, - int client) BSON_GNUC_WARN_UNUSED_RESULT; +mongoc_stream_tls_secure_channel_new (mongoc_stream_t *base_stream, const char *host, mongoc_ssl_opt_t *opt, int client) + BSON_GNUC_WARN_UNUSED_RESULT; BSON_END_DECLS diff --git a/src/libmongoc/src/mongoc/mongoc-stream-tls-secure-transport.c b/src/libmongoc/src/mongoc/mongoc-stream-tls-secure-transport.c index f20ec6b082..74c6bb8d9d 100644 --- a/src/libmongoc/src/mongoc/mongoc-stream-tls-secure-transport.c +++ b/src/libmongoc/src/mongoc/mongoc-stream-tls-secure-transport.c @@ -44,8 +44,7 @@ static void _mongoc_stream_tls_secure_transport_destroy (mongoc_stream_t *stream) { mongoc_stream_tls_t *tls = (mongoc_stream_tls_t *) stream; - mongoc_stream_tls_secure_transport_t *secure_transport = - (mongoc_stream_tls_secure_transport_t *) tls->ctx; + mongoc_stream_tls_secure_transport_t *secure_transport = (mongoc_stream_tls_secure_transport_t *) tls->ctx; ENTRY; BSON_ASSERT (secure_transport); @@ -84,8 +83,7 @@ _mongoc_stream_tls_secure_transport_close (mongoc_stream_t *stream) { int ret = 0; mongoc_stream_tls_t *tls = (mongoc_stream_tls_t *) stream; - mongoc_stream_tls_secure_transport_t *secure_transport = - (mongoc_stream_tls_secure_transport_t *) tls->ctx; + mongoc_stream_tls_secure_transport_t *secure_transport = (mongoc_stream_tls_secure_transport_t *) tls->ctx; ENTRY; BSON_ASSERT (secure_transport); @@ -98,8 +96,7 @@ static int _mongoc_stream_tls_secure_transport_flush (mongoc_stream_t *stream) { mongoc_stream_tls_t *tls = (mongoc_stream_tls_t *) stream; - mongoc_stream_tls_secure_transport_t *secure_transport = - (mongoc_stream_tls_secure_transport_t *) tls->ctx; + mongoc_stream_tls_secure_transport_t *secure_transport = (mongoc_stream_tls_secure_transport_t *) tls->ctx; ENTRY; BSON_ASSERT (secure_transport); @@ -107,14 +104,11 @@ _mongoc_stream_tls_secure_transport_flush (mongoc_stream_t *stream) } static ssize_t -_mongoc_stream_tls_secure_transport_write (mongoc_stream_t *stream, - char *buf, - size_t buf_len) +_mongoc_stream_tls_secure_transport_write (mongoc_stream_t *stream, char *buf, size_t buf_len) { OSStatus status; mongoc_stream_tls_t *tls = (mongoc_stream_tls_t *) stream; - mongoc_stream_tls_secure_transport_t *secure_transport = - (mongoc_stream_tls_secure_transport_t *) tls->ctx; + mongoc_stream_tls_secure_transport_t *secure_transport = (mongoc_stream_tls_secure_transport_t *) tls->ctx; ssize_t write_ret; int64_t now; int64_t expire = 0; @@ -126,8 +120,7 @@ _mongoc_stream_tls_secure_transport_write (mongoc_stream_t *stream, expire = bson_get_monotonic_time () + (tls->timeout_msec * 1000UL); } - status = SSLWrite ( - secure_transport->ssl_ctx_ref, buf, buf_len, (size_t *) &write_ret); + status = SSLWrite (secure_transport->ssl_ctx_ref, buf, buf_len, (size_t *) &write_ret); switch (status) { case errSSLWouldBlock: @@ -167,8 +160,7 @@ _mongoc_stream_tls_secure_transport_writev (mongoc_stream_t *stream, int32_t timeout_msec) { mongoc_stream_tls_t *tls = (mongoc_stream_tls_t *) stream; - mongoc_stream_tls_secure_transport_t *secure_transport = - (mongoc_stream_tls_secure_transport_t *) tls->ctx; + mongoc_stream_tls_secure_transport_t *secure_transport = (mongoc_stream_tls_secure_transport_t *) tls->ctx; char buf[MONGOC_STREAM_TLS_BUFFER_SIZE]; ssize_t ret = 0; ssize_t child_ret; @@ -204,9 +196,7 @@ _mongoc_stream_tls_secure_transport_writev (mongoc_stream_t *stream, iov_pos = 0; while (iov_pos < iov[i].iov_len) { - if (buf_head != buf_tail || - ((i + 1 < iovcnt) && - ((buf_end - buf_tail) > (iov[i].iov_len - iov_pos)))) { + if (buf_head != buf_tail || ((i + 1 < iovcnt) && ((buf_end - buf_tail) > (iov[i].iov_len - iov_pos)))) { /* If we have either of: * - buffered bytes already * - another iovec to send after this one and we don't have more @@ -241,8 +231,7 @@ _mongoc_stream_tls_secure_transport_writev (mongoc_stream_t *stream, /* We get here if we buffered some bytes and filled the buffer, or * if we didn't buffer and have to send out of the iovec */ - child_ret = _mongoc_stream_tls_secure_transport_write ( - stream, to_write, to_write_len); + child_ret = _mongoc_stream_tls_secure_transport_write (stream, to_write, to_write_len); if (child_ret < 0) { RETURN (ret); @@ -264,8 +253,7 @@ _mongoc_stream_tls_secure_transport_writev (mongoc_stream_t *stream, if (buf_head != buf_tail) { /* If we have any bytes buffered, send */ - child_ret = _mongoc_stream_tls_secure_transport_write ( - stream, buf_head, buf_tail - buf_head); + child_ret = _mongoc_stream_tls_secure_transport_write (stream, buf_head, buf_tail - buf_head); if (child_ret < 0) { RETURN (child_ret); @@ -284,15 +272,11 @@ _mongoc_stream_tls_secure_transport_writev (mongoc_stream_t *stream, /* This function is copypasta of _mongoc_stream_tls_openssl_readv */ static ssize_t -_mongoc_stream_tls_secure_transport_readv (mongoc_stream_t *stream, - mongoc_iovec_t *iov, - size_t iovcnt, - size_t min_bytes, - int32_t timeout_msec) +_mongoc_stream_tls_secure_transport_readv ( + mongoc_stream_t *stream, mongoc_iovec_t *iov, size_t iovcnt, size_t min_bytes, int32_t timeout_msec) { mongoc_stream_tls_t *tls = (mongoc_stream_tls_t *) stream; - mongoc_stream_tls_secure_transport_t *secure_transport = - (mongoc_stream_tls_secure_transport_t *) tls->ctx; + mongoc_stream_tls_secure_transport_t *secure_transport = (mongoc_stream_tls_secure_transport_t *) tls->ctx; ssize_t ret = 0; size_t i; size_t read_ret; @@ -331,10 +315,8 @@ _mongoc_stream_tls_secure_transport_readv (mongoc_stream_t *stream, to_read = remaining_buf_size; } - OSStatus status = SSLRead (secure_transport->ssl_ctx_ref, - (char *) iov[i].iov_base + iov_pos, - to_read, - &read_ret); + OSStatus status = + SSLRead (secure_transport->ssl_ctx_ref, (char *) iov[i].iov_base + iov_pos, to_read, &read_ret); if (status != noErr) { RETURN (-1); @@ -375,28 +357,22 @@ _mongoc_stream_tls_secure_transport_readv (mongoc_stream_t *stream, } static int -_mongoc_stream_tls_secure_transport_setsockopt (mongoc_stream_t *stream, - int level, - int optname, - void *optval, - mongoc_socklen_t optlen) +_mongoc_stream_tls_secure_transport_setsockopt ( + mongoc_stream_t *stream, int level, int optname, void *optval, mongoc_socklen_t optlen) { mongoc_stream_tls_t *tls = (mongoc_stream_tls_t *) stream; - mongoc_stream_tls_secure_transport_t *secure_transport = - (mongoc_stream_tls_secure_transport_t *) tls->ctx; + mongoc_stream_tls_secure_transport_t *secure_transport = (mongoc_stream_tls_secure_transport_t *) tls->ctx; ENTRY; BSON_ASSERT (secure_transport); - RETURN (mongoc_stream_setsockopt ( - tls->base_stream, level, optname, optval, optlen)); + RETURN (mongoc_stream_setsockopt (tls->base_stream, level, optname, optval, optlen)); } static mongoc_stream_t * _mongoc_stream_tls_secure_transport_get_base_stream (mongoc_stream_t *stream) { mongoc_stream_tls_t *tls = (mongoc_stream_tls_t *) stream; - mongoc_stream_tls_secure_transport_t *secure_transport = - (mongoc_stream_tls_secure_transport_t *) tls->ctx; + mongoc_stream_tls_secure_transport_t *secure_transport = (mongoc_stream_tls_secure_transport_t *) tls->ctx; ENTRY; BSON_ASSERT (secure_transport); @@ -405,12 +381,10 @@ _mongoc_stream_tls_secure_transport_get_base_stream (mongoc_stream_t *stream) static bool -_mongoc_stream_tls_secure_transport_check_closed ( - mongoc_stream_t *stream) /* IN */ +_mongoc_stream_tls_secure_transport_check_closed (mongoc_stream_t *stream) /* IN */ { mongoc_stream_tls_t *tls = (mongoc_stream_tls_t *) stream; - mongoc_stream_tls_secure_transport_t *secure_transport = - (mongoc_stream_tls_secure_transport_t *) tls->ctx; + mongoc_stream_tls_secure_transport_t *secure_transport = (mongoc_stream_tls_secure_transport_t *) tls->ctx; ENTRY; BSON_ASSERT (secure_transport); @@ -418,22 +392,14 @@ _mongoc_stream_tls_secure_transport_check_closed ( } static void -_set_error_from_osstatus (OSStatus status, - const char *prefix, - bson_error_t *error) +_set_error_from_osstatus (OSStatus status, const char *prefix, bson_error_t *error) { CFStringRef err; char *err_str; err = SecCopyErrorMessageString (status, NULL); err_str = _mongoc_cfstringref_to_cstring (err); - bson_set_error (error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_SOCKET, - "%s: %s (%d)", - prefix, - err_str, - status); + bson_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "%s: %s (%d)", prefix, err_str, status); bson_free (err_str); CFRelease (err); @@ -462,8 +428,7 @@ explain_trust_result (SecTrustRef trust, SecTrustResultType trust_result) bson_string_append (reason, "Certificate trust evaluation failure"); break; default: - bson_string_append_printf ( - reason, "Certificate trust failure #%d", (int) trust_result); + bson_string_append_printf (reason, "Certificate trust failure #%d", (int) trust_result); break; } bson_string_append (reason, ": "); @@ -528,22 +493,19 @@ _verify_peer (mongoc_stream_t *stream, bson_error_t *error) SecPolicyRef rev_policy = NULL; SecTrustResultType trust_result; mongoc_stream_tls_t *tls = (mongoc_stream_tls_t *) stream; - mongoc_stream_tls_secure_transport_t *secure_transport = - (mongoc_stream_tls_secure_transport_t *) tls->ctx; + mongoc_stream_tls_secure_transport_t *secure_transport = (mongoc_stream_tls_secure_transport_t *) tls->ctx; bool ret = false; status = SSLCopyPeerTrust (secure_transport->ssl_ctx_ref, &trust); if (status != noErr) { - _set_error_from_osstatus ( - status, "Certificate validation errored", error); + _set_error_from_osstatus (status, "Certificate validation errored", error); goto fail; } status = SecTrustCopyPolicies (trust, &policies); if (status != noErr) { - _set_error_from_osstatus ( - status, "Certificate validation errored", error); + _set_error_from_osstatus (status, "Certificate validation errored", error); goto fail; } @@ -559,8 +521,7 @@ _verify_peer (mongoc_stream_t *stream, bson_error_t *error) status = SecTrustSetPolicies (trust, policies_mutable); if (status != noErr) { - _set_error_from_osstatus ( - status, "Certificate validation errored", error); + _set_error_from_osstatus (status, "Certificate validation errored", error); goto fail; } @@ -569,19 +530,13 @@ _verify_peer (mongoc_stream_t *stream, bson_error_t *error) * addressed. */ status = SecTrustEvaluate (trust, &trust_result); if (status != noErr) { - _set_error_from_osstatus ( - status, "Certificate validation errored", error); + _set_error_from_osstatus (status, "Certificate validation errored", error); goto fail; } - if (trust_result != kSecTrustResultProceed && - trust_result != kSecTrustResultUnspecified) { + if (trust_result != kSecTrustResultProceed && trust_result != kSecTrustResultUnspecified) { char *reason = explain_trust_result (trust, trust_result); - bson_set_error (error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_SOCKET, - "TLS handshake failed (%s)", - reason); + bson_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "TLS handshake failed (%s)", reason); bson_free (reason); goto fail; } @@ -603,8 +558,7 @@ mongoc_stream_tls_secure_transport_handshake (mongoc_stream_t *stream, { OSStatus ret = 0; mongoc_stream_tls_t *tls = (mongoc_stream_tls_t *) stream; - mongoc_stream_tls_secure_transport_t *secure_transport = - (mongoc_stream_tls_secure_transport_t *) tls->ctx; + mongoc_stream_tls_secure_transport_t *secure_transport = (mongoc_stream_tls_secure_transport_t *) tls->ctx; ENTRY; BSON_ASSERT (secure_transport); @@ -612,8 +566,7 @@ mongoc_stream_tls_secure_transport_handshake (mongoc_stream_t *stream, ret = SSLHandshake (secure_transport->ssl_ctx_ref); if (ret == errSSLServerAuthCompleted) { - if (!tls->ssl_opts.weak_cert_validation && - !_verify_peer (stream, error)) { + if (!tls->ssl_opts.weak_cert_validation && !_verify_peer (stream, error)) { *events = 0; RETURN (false); } @@ -673,14 +626,12 @@ mongoc_stream_tls_secure_transport_new (mongoc_stream_t *base_stream, RETURN (NULL); } if (opt->crl_file) { - MONGOC_ERROR ( - "Setting mongoc_ssl_opt_t.crl_file has no effect when built " - "against Secure Transport"); + MONGOC_ERROR ("Setting mongoc_ssl_opt_t.crl_file has no effect when built " + "against Secure Transport"); RETURN (NULL); } - secure_transport = (mongoc_stream_tls_secure_transport_t *) bson_malloc0 ( - sizeof *secure_transport); + secure_transport = (mongoc_stream_tls_secure_transport_t *) bson_malloc0 (sizeof *secure_transport); tls = (mongoc_stream_tls_t *) bson_malloc0 (sizeof *tls); tls->parent.type = MONGOC_STREAM_TLS; @@ -691,8 +642,7 @@ mongoc_stream_tls_secure_transport_new (mongoc_stream_t *base_stream, tls->parent.writev = _mongoc_stream_tls_secure_transport_writev; tls->parent.readv = _mongoc_stream_tls_secure_transport_readv; tls->parent.setsockopt = _mongoc_stream_tls_secure_transport_setsockopt; - tls->parent.get_base_stream = - _mongoc_stream_tls_secure_transport_get_base_stream; + tls->parent.get_base_stream = _mongoc_stream_tls_secure_transport_get_base_stream; tls->parent.check_closed = _mongoc_stream_tls_secure_transport_check_closed; tls->parent.timed_out = _mongoc_stream_tls_secure_channel_timed_out; tls->parent.should_retry = _mongoc_stream_tls_secure_channel_should_retry; @@ -702,23 +652,17 @@ mongoc_stream_tls_secure_transport_new (mongoc_stream_t *base_stream, tls->timeout_msec = -1; secure_transport->ssl_ctx_ref = - SSLCreateContext (kCFAllocatorDefault, - client ? kSSLClientSide : kSSLServerSide, - kSSLStreamType); + SSLCreateContext (kCFAllocatorDefault, client ? kSSLClientSide : kSSLServerSide, kSSLStreamType); - SSLSetIOFuncs (secure_transport->ssl_ctx_ref, - mongoc_secure_transport_read, - mongoc_secure_transport_write); + SSLSetIOFuncs (secure_transport->ssl_ctx_ref, mongoc_secure_transport_read, mongoc_secure_transport_write); SSLSetProtocolVersionMin (secure_transport->ssl_ctx_ref, kTLSProtocol1); - if (opt->pem_file && - !mongoc_secure_transport_setup_certificate (secure_transport, opt)) { + if (opt->pem_file && !mongoc_secure_transport_setup_certificate (secure_transport, opt)) { mongoc_stream_destroy ((mongoc_stream_t *) tls); RETURN (NULL); } - if (opt->ca_file && - !mongoc_secure_transport_setup_ca (secure_transport, opt)) { + if (opt->ca_file && !mongoc_secure_transport_setup_ca (secure_transport, opt)) { mongoc_stream_destroy ((mongoc_stream_t *) tls); RETURN (NULL); } @@ -729,13 +673,10 @@ mongoc_stream_tls_secure_transport_new (mongoc_stream_t *base_stream, if (client) { /* This option has SSL_Handshake stop before it verifies peer cert. Set * this since we verify peer cert manually later. */ - SSLSetSessionOption (secure_transport->ssl_ctx_ref, - kSSLSessionOptionBreakOnServerAuth, - true); + SSLSetSessionOption (secure_transport->ssl_ctx_ref, kSSLSessionOptionBreakOnServerAuth, true); } else if (!opt->allow_invalid_hostname) { /* used only in mock_server_t tests */ - SSLSetClientSideAuthenticate (secure_transport->ssl_ctx_ref, - kAlwaysAuthenticate); + SSLSetClientSideAuthenticate (secure_transport->ssl_ctx_ref, kAlwaysAuthenticate); } if (!opt->allow_invalid_hostname) { diff --git a/src/libmongoc/src/mongoc/mongoc-stream-tls-secure-transport.h b/src/libmongoc/src/mongoc/mongoc-stream-tls-secure-transport.h index 5e93e44037..8cdf302471 100644 --- a/src/libmongoc/src/mongoc/mongoc-stream-tls-secure-transport.h +++ b/src/libmongoc/src/mongoc/mongoc-stream-tls-secure-transport.h @@ -30,8 +30,7 @@ MONGOC_EXPORT (mongoc_stream_t *) mongoc_stream_tls_secure_transport_new (mongoc_stream_t *base_stream, const char *host, mongoc_ssl_opt_t *opt, - int client) - BSON_GNUC_WARN_UNUSED_RESULT; + int client) BSON_GNUC_WARN_UNUSED_RESULT; BSON_END_DECLS diff --git a/src/libmongoc/src/mongoc/mongoc-stream-tls.c b/src/libmongoc/src/mongoc/mongoc-stream-tls.c index dcf9b4bd4c..db1a238b0d 100644 --- a/src/libmongoc/src/mongoc/mongoc-stream-tls.c +++ b/src/libmongoc/src/mongoc/mongoc-stream-tls.c @@ -53,14 +53,10 @@ * Performs TLS handshake dance */ bool -mongoc_stream_tls_handshake (mongoc_stream_t *stream, - const char *host, - int32_t timeout_msec, - int *events, - bson_error_t *error) +mongoc_stream_tls_handshake ( + mongoc_stream_t *stream, const char *host, int32_t timeout_msec, int *events, bson_error_t *error) { - mongoc_stream_tls_t *stream_tls = - (mongoc_stream_tls_t *) mongoc_stream_get_tls_stream (stream); + mongoc_stream_tls_t *stream_tls = (mongoc_stream_tls_t *) mongoc_stream_get_tls_stream (stream); BSON_ASSERT (stream_tls); BSON_ASSERT (stream_tls->handshake); @@ -71,10 +67,7 @@ mongoc_stream_tls_handshake (mongoc_stream_t *stream, } bool -mongoc_stream_tls_handshake_block (mongoc_stream_t *stream, - const char *host, - int32_t timeout_msec, - bson_error_t *error) +mongoc_stream_tls_handshake_block (mongoc_stream_t *stream, const char *host, int32_t timeout_msec, bson_error_t *error) { int events; ssize_t ret = 0; @@ -98,8 +91,7 @@ mongoc_stream_tls_handshake_block (mongoc_stream_t *stream, do { events = 0; - if (mongoc_stream_tls_handshake ( - stream, host, timeout_msec, &events, error)) { + if (mongoc_stream_tls_handshake (stream, host, timeout_msec, &events, error)) { return true; } @@ -112,10 +104,7 @@ mongoc_stream_tls_handshake_block (mongoc_stream_t *stream, const int64_t now = bson_get_monotonic_time (); const int64_t remaining = expire - now; if (remaining < 0) { - bson_set_error (error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_SOCKET, - "TLS handshake timed out."); + bson_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "TLS handshake timed out."); return false; } else { const int64_t msec = remaining / 1000; @@ -128,10 +117,7 @@ mongoc_stream_tls_handshake_block (mongoc_stream_t *stream, } while (events && ret > 0); if (error && !error->code) { - bson_set_error (error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_SOCKET, - "TLS handshake failed."); + bson_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "TLS handshake failed."); } return false; } @@ -142,8 +128,7 @@ mongoc_stream_tls_handshake_block (mongoc_stream_t *stream, bool mongoc_stream_tls_do_handshake (mongoc_stream_t *stream, int32_t timeout_msec) { - mongoc_stream_tls_t *stream_tls = - (mongoc_stream_tls_t *) mongoc_stream_get_tls_stream (stream); + mongoc_stream_tls_t *stream_tls = (mongoc_stream_tls_t *) mongoc_stream_get_tls_stream (stream); BSON_UNUSED (timeout_msec); @@ -162,8 +147,7 @@ mongoc_stream_tls_do_handshake (mongoc_stream_t *stream, int32_t timeout_msec) bool mongoc_stream_tls_check_cert (mongoc_stream_t *stream, const char *host) { - mongoc_stream_tls_t *stream_tls = - (mongoc_stream_tls_t *) mongoc_stream_get_tls_stream (stream); + mongoc_stream_tls_t *stream_tls = (mongoc_stream_tls_t *) mongoc_stream_get_tls_stream (stream); BSON_UNUSED (host); @@ -202,10 +186,7 @@ mongoc_stream_tls_check_cert (mongoc_stream_t *stream, const char *host) */ mongoc_stream_t * -mongoc_stream_tls_new_with_hostname (mongoc_stream_t *base_stream, - const char *host, - mongoc_ssl_opt_t *opt, - int client) +mongoc_stream_tls_new_with_hostname (mongoc_stream_t *base_stream, const char *host, mongoc_ssl_opt_t *opt, int client) { BSON_ASSERT (base_stream); @@ -227,8 +208,7 @@ mongoc_stream_tls_new_with_hostname (mongoc_stream_t *base_stream, #elif defined(MONGOC_ENABLE_SSL_LIBRESSL) return mongoc_stream_tls_libressl_new (base_stream, host, opt, client); #elif defined(MONGOC_ENABLE_SSL_SECURE_TRANSPORT) - return mongoc_stream_tls_secure_transport_new ( - base_stream, host, opt, client); + return mongoc_stream_tls_secure_transport_new (base_stream, host, opt, client); #elif defined(MONGOC_ENABLE_SSL_SECURE_CHANNEL) return mongoc_stream_tls_secure_channel_new (base_stream, host, opt, client); #else @@ -237,9 +217,7 @@ mongoc_stream_tls_new_with_hostname (mongoc_stream_t *base_stream, } mongoc_stream_t * -mongoc_stream_tls_new (mongoc_stream_t *base_stream, - mongoc_ssl_opt_t *opt, - int client) +mongoc_stream_tls_new (mongoc_stream_t *base_stream, mongoc_ssl_opt_t *opt, int client) { return mongoc_stream_tls_new_with_hostname (base_stream, NULL, opt, client); } diff --git a/src/libmongoc/src/mongoc/mongoc-stream-tls.h b/src/libmongoc/src/mongoc/mongoc-stream-tls.h index 3d41f3e654..df51733db4 100644 --- a/src/libmongoc/src/mongoc/mongoc-stream-tls.h +++ b/src/libmongoc/src/mongoc/mongoc-stream-tls.h @@ -31,11 +31,8 @@ BSON_BEGIN_DECLS typedef struct _mongoc_stream_tls_t mongoc_stream_tls_t; MONGOC_EXPORT (bool) -mongoc_stream_tls_handshake (mongoc_stream_t *stream, - const char *host, - int32_t timeout_msec, - int *events, - bson_error_t *error); +mongoc_stream_tls_handshake ( + mongoc_stream_t *stream, const char *host, int32_t timeout_msec, int *events, bson_error_t *error); MONGOC_EXPORT (bool) mongoc_stream_tls_handshake_block (mongoc_stream_t *stream, const char *host, @@ -48,14 +45,10 @@ MONGOC_EXPORT (bool) mongoc_stream_tls_check_cert (mongoc_stream_t *stream, const char *host) BSON_GNUC_DEPRECATED_FOR (mongoc_stream_tls_handshake); MONGOC_EXPORT (mongoc_stream_t *) -mongoc_stream_tls_new_with_hostname (mongoc_stream_t *base_stream, - const char *host, - mongoc_ssl_opt_t *opt, - int client) BSON_GNUC_WARN_UNUSED_RESULT; +mongoc_stream_tls_new_with_hostname (mongoc_stream_t *base_stream, const char *host, mongoc_ssl_opt_t *opt, int client) + BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (mongoc_stream_t *) -mongoc_stream_tls_new (mongoc_stream_t *base_stream, - mongoc_ssl_opt_t *opt, - int client) BSON_GNUC_WARN_UNUSED_RESULT +mongoc_stream_tls_new (mongoc_stream_t *base_stream, mongoc_ssl_opt_t *opt, int client) BSON_GNUC_WARN_UNUSED_RESULT BSON_GNUC_DEPRECATED_FOR (mongoc_stream_tls_new_with_hostname); diff --git a/src/libmongoc/src/mongoc/mongoc-stream.c b/src/libmongoc/src/mongoc/mongoc-stream.c index 99a619fb73..b0cff7ee76 100644 --- a/src/libmongoc/src/mongoc/mongoc-stream.c +++ b/src/libmongoc/src/mongoc/mongoc-stream.c @@ -142,10 +142,7 @@ mongoc_stream_flush (mongoc_stream_t *stream) * Returns: the number of bytes written, or -1 upon failure. */ ssize_t -mongoc_stream_writev (mongoc_stream_t *stream, - mongoc_iovec_t *iov, - size_t iovcnt, - int32_t timeout_msec) +mongoc_stream_writev (mongoc_stream_t *stream, mongoc_iovec_t *iov, size_t iovcnt, int32_t timeout_msec) { ssize_t ret; @@ -180,10 +177,7 @@ mongoc_stream_writev (mongoc_stream_t *stream, * Returns: -1 on failure, otherwise the number of bytes written. */ ssize_t -mongoc_stream_write (mongoc_stream_t *stream, - void *buf, - size_t count, - int32_t timeout_msec) +mongoc_stream_write (mongoc_stream_t *stream, void *buf, size_t count, int32_t timeout_msec) { mongoc_iovec_t iov; ssize_t ret; @@ -219,11 +213,8 @@ mongoc_stream_write (mongoc_stream_t *stream, * Returns: the number of bytes read or -1 on failure. */ ssize_t -mongoc_stream_readv (mongoc_stream_t *stream, - mongoc_iovec_t *iov, - size_t iovcnt, - size_t min_bytes, - int32_t timeout_msec) +mongoc_stream_readv ( + mongoc_stream_t *stream, mongoc_iovec_t *iov, size_t iovcnt, size_t min_bytes, int32_t timeout_msec) { ssize_t ret; @@ -260,11 +251,7 @@ mongoc_stream_readv (mongoc_stream_t *stream, * Returns: -1 on failure, otherwise the number of bytes read. */ ssize_t -mongoc_stream_read (mongoc_stream_t *stream, - void *buf, - size_t count, - size_t min_bytes, - int32_t timeout_msec) +mongoc_stream_read (mongoc_stream_t *stream, void *buf, size_t count, size_t min_bytes, int32_t timeout_msec) { mongoc_iovec_t iov; ssize_t ret; @@ -286,11 +273,7 @@ mongoc_stream_read (mongoc_stream_t *stream, int -mongoc_stream_setsockopt (mongoc_stream_t *stream, - int level, - int optname, - void *optval, - mongoc_socklen_t optlen) +mongoc_stream_setsockopt (mongoc_stream_t *stream, int level, int optname, void *optval, mongoc_socklen_t optlen) { BSON_ASSERT_PARAM (stream); @@ -332,20 +315,16 @@ mongoc_stream_get_tls_stream (mongoc_stream_t *stream) /* IN */ { BSON_ASSERT_PARAM (stream); - for (; stream && stream->type != MONGOC_STREAM_TLS; - stream = stream->get_base_stream (stream)) + for (; stream && stream->type != MONGOC_STREAM_TLS; stream = stream->get_base_stream (stream)) ; return stream; } ssize_t -mongoc_stream_poll (mongoc_stream_poll_t *streams, - size_t nstreams, - int32_t timeout) +mongoc_stream_poll (mongoc_stream_poll_t *streams, size_t nstreams, int32_t timeout) { - mongoc_stream_poll_t *poller = - (mongoc_stream_poll_t *) bson_malloc (sizeof (*poller) * nstreams); + mongoc_stream_poll_t *poller = (mongoc_stream_poll_t *) bson_malloc (sizeof (*poller) * nstreams); int last_type = 0; ssize_t rval = -1; @@ -423,11 +402,8 @@ mongoc_stream_should_retry (mongoc_stream_t *stream) } bool -_mongoc_stream_writev_full (mongoc_stream_t *stream, - mongoc_iovec_t *iov, - size_t iovcnt, - int64_t timeout_msec, - bson_error_t *error) +_mongoc_stream_writev_full ( + mongoc_stream_t *stream, mongoc_iovec_t *iov, size_t iovcnt, int64_t timeout_msec, bson_error_t *error) { size_t total_bytes = 0; ssize_t r; @@ -442,8 +418,7 @@ _mongoc_stream_writev_full (mongoc_stream_t *stream, bson_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, - "timeout_msec value %" PRId64 - " exceeds supported 32-bit range", + "timeout_msec value %" PRId64 " exceeds supported 32-bit range", timeout_msec); RETURN (false); } @@ -473,8 +448,8 @@ _mongoc_stream_writev_full (mongoc_stream_t *stream, bson_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, - "Failure to send all requested bytes (only sent: %" PRIu64 - "/%zu in %" PRId64 "ms) during socket delivery", + "Failure to send all requested bytes (only sent: %" PRIu64 "/%zu in %" PRId64 + "ms) during socket delivery", (uint64_t) r, total_bytes, timeout_msec); diff --git a/src/libmongoc/src/mongoc/mongoc-stream.h b/src/libmongoc/src/mongoc/mongoc-stream.h index 402fc50927..009b69a137 100644 --- a/src/libmongoc/src/mongoc/mongoc-stream.h +++ b/src/libmongoc/src/mongoc/mongoc-stream.h @@ -40,25 +40,13 @@ struct _mongoc_stream_t { void (*destroy) (mongoc_stream_t *stream); int (*close) (mongoc_stream_t *stream); int (*flush) (mongoc_stream_t *stream); - ssize_t (*writev) (mongoc_stream_t *stream, - mongoc_iovec_t *iov, - size_t iovcnt, - int32_t timeout_msec); - ssize_t (*readv) (mongoc_stream_t *stream, - mongoc_iovec_t *iov, - size_t iovcnt, - size_t min_bytes, - int32_t timeout_msec); - int (*setsockopt) (mongoc_stream_t *stream, - int level, - int optname, - void *optval, - mongoc_socklen_t optlen); + ssize_t (*writev) (mongoc_stream_t *stream, mongoc_iovec_t *iov, size_t iovcnt, int32_t timeout_msec); + ssize_t (*readv) ( + mongoc_stream_t *stream, mongoc_iovec_t *iov, size_t iovcnt, size_t min_bytes, int32_t timeout_msec); + int (*setsockopt) (mongoc_stream_t *stream, int level, int optname, void *optval, mongoc_socklen_t optlen); mongoc_stream_t *(*get_base_stream) (mongoc_stream_t *stream); bool (*check_closed) (mongoc_stream_t *stream); - ssize_t (*poll) (mongoc_stream_poll_t *streams, - size_t nstreams, - int32_t timeout); + ssize_t (*poll) (mongoc_stream_poll_t *streams, size_t nstreams, int32_t timeout); void (*failed) (mongoc_stream_t *stream); bool (*timed_out) (mongoc_stream_t *stream); bool (*should_retry) (mongoc_stream_t *stream); @@ -79,33 +67,16 @@ mongoc_stream_failed (mongoc_stream_t *stream); MONGOC_EXPORT (int) mongoc_stream_flush (mongoc_stream_t *stream); MONGOC_EXPORT (ssize_t) -mongoc_stream_writev (mongoc_stream_t *stream, - mongoc_iovec_t *iov, - size_t iovcnt, - int32_t timeout_msec); +mongoc_stream_writev (mongoc_stream_t *stream, mongoc_iovec_t *iov, size_t iovcnt, int32_t timeout_msec); MONGOC_EXPORT (ssize_t) -mongoc_stream_write (mongoc_stream_t *stream, - void *buf, - size_t count, - int32_t timeout_msec); +mongoc_stream_write (mongoc_stream_t *stream, void *buf, size_t count, int32_t timeout_msec); MONGOC_EXPORT (ssize_t) -mongoc_stream_readv (mongoc_stream_t *stream, - mongoc_iovec_t *iov, - size_t iovcnt, - size_t min_bytes, - int32_t timeout_msec); +mongoc_stream_readv ( + mongoc_stream_t *stream, mongoc_iovec_t *iov, size_t iovcnt, size_t min_bytes, int32_t timeout_msec); MONGOC_EXPORT (ssize_t) -mongoc_stream_read (mongoc_stream_t *stream, - void *buf, - size_t count, - size_t min_bytes, - int32_t timeout_msec); +mongoc_stream_read (mongoc_stream_t *stream, void *buf, size_t count, size_t min_bytes, int32_t timeout_msec); MONGOC_EXPORT (int) -mongoc_stream_setsockopt (mongoc_stream_t *stream, - int level, - int optname, - void *optval, - mongoc_socklen_t optlen); +mongoc_stream_setsockopt (mongoc_stream_t *stream, int level, int optname, void *optval, mongoc_socklen_t optlen); MONGOC_EXPORT (bool) mongoc_stream_check_closed (mongoc_stream_t *stream); MONGOC_EXPORT (bool) @@ -113,9 +84,7 @@ mongoc_stream_timed_out (mongoc_stream_t *stream); MONGOC_EXPORT (bool) mongoc_stream_should_retry (mongoc_stream_t *stream); MONGOC_EXPORT (ssize_t) -mongoc_stream_poll (mongoc_stream_poll_t *streams, - size_t nstreams, - int32_t timeout); +mongoc_stream_poll (mongoc_stream_poll_t *streams, size_t nstreams, int32_t timeout); BSON_END_DECLS diff --git a/src/libmongoc/src/mongoc/mongoc-thread-private.h b/src/libmongoc/src/mongoc/mongoc-thread-private.h index 6117fbcd3e..ba8e826301 100644 --- a/src/libmongoc/src/mongoc/mongoc-thread-private.h +++ b/src/libmongoc/src/mongoc/mongoc-thread-private.h @@ -31,17 +31,14 @@ #define mongoc_cond_init(_n) pthread_cond_init ((_n), NULL) #if defined(MONGOC_ENABLE_DEBUG_ASSERTIONS) -#define mongoc_cond_wait(cond, mutex) \ - pthread_cond_wait (cond, &(mutex)->wrapped_mutex); +#define mongoc_cond_wait(cond, mutex) pthread_cond_wait (cond, &(mutex)->wrapped_mutex); #else #define mongoc_cond_wait pthread_cond_wait #endif #define mongoc_cond_signal pthread_cond_signal static BSON_INLINE int -mongoc_cond_timedwait (pthread_cond_t *cond, - bson_mutex_t *mutex, - int64_t timeout_msec) +mongoc_cond_timedwait (pthread_cond_t *cond, bson_mutex_t *mutex, int64_t timeout_msec) { struct timespec to; struct timeval tv; @@ -71,9 +68,7 @@ mongo_cond_ret_is_timedout (int ret) #define mongoc_cond_init InitializeConditionVariable #define mongoc_cond_wait(_c, _m) mongoc_cond_timedwait ((_c), (_m), INFINITE) static BSON_INLINE int -mongoc_cond_timedwait (mongoc_cond_t *cond, - bson_mutex_t *mutex, - int64_t timeout_msec) +mongoc_cond_timedwait (mongoc_cond_t *cond, bson_mutex_t *mutex, int64_t timeout_msec) { int r; diff --git a/src/libmongoc/src/mongoc/mongoc-topology-background-monitoring-private.h b/src/libmongoc/src/mongoc/mongoc-topology-background-monitoring-private.h index bf441549c3..aa18849207 100644 --- a/src/libmongoc/src/mongoc/mongoc-topology-background-monitoring-private.h +++ b/src/libmongoc/src/mongoc/mongoc-topology-background-monitoring-private.h @@ -29,18 +29,15 @@ void _mongoc_topology_background_monitoring_start (mongoc_topology_t *topology); void -_mongoc_topology_background_monitoring_reconcile ( - mongoc_topology_t *topology, mongoc_topology_description_t *td); +_mongoc_topology_background_monitoring_reconcile (mongoc_topology_t *topology, mongoc_topology_description_t *td); void -_mongoc_topology_background_monitoring_request_scan ( - mongoc_topology_t *topology); +_mongoc_topology_background_monitoring_request_scan (mongoc_topology_t *topology); void _mongoc_topology_background_monitoring_stop (mongoc_topology_t *topology); void -_mongoc_topology_background_monitoring_cancel_check ( - mongoc_topology_t *topology, uint32_t server_id); +_mongoc_topology_background_monitoring_cancel_check (mongoc_topology_t *topology, uint32_t server_id); #endif /* MONGOC_TOPOLOGY_BACKGROUND_MONITORING_PRIVATE_H */ diff --git a/src/libmongoc/src/mongoc/mongoc-topology-background-monitoring.c b/src/libmongoc/src/mongoc/mongoc-topology-background-monitoring.c index bcab5196bf..154b4126ff 100644 --- a/src/libmongoc/src/mongoc/mongoc-topology-background-monitoring.c +++ b/src/libmongoc/src/mongoc/mongoc-topology-background-monitoring.c @@ -36,8 +36,7 @@ static BSON_THREAD_FUN (srv_polling_run, topology_void) mongoc_topology_t *topology; topology = topology_void; - while (bson_atomic_int_fetch (&topology->scanner_state, - bson_memory_order_relaxed) == + while (bson_atomic_int_fetch (&topology->scanner_state, bson_memory_order_relaxed) == MONGOC_TOPOLOGY_SCANNER_BG_RUNNING) { int64_t now_ms; int64_t scan_due_ms; @@ -54,30 +53,25 @@ static BSON_THREAD_FUN (srv_polling_run, topology_void) /* Unlock and sleep until next scan is due, or until shutdown signalled. */ now_ms = bson_get_monotonic_time () / 1000; - scan_due_ms = topology->srv_polling_last_scan_ms + - topology->srv_polling_rescan_interval_ms; + scan_due_ms = topology->srv_polling_last_scan_ms + topology->srv_polling_rescan_interval_ms; sleep_duration_ms = scan_due_ms - now_ms; if (sleep_duration_ms > 0) { - TRACE ("srv polling thread sleeping for %" PRId64 "ms", - sleep_duration_ms); + TRACE ("srv polling thread sleeping for %" PRId64 "ms", sleep_duration_ms); } /* Check for shutdown again here. mongoc_topology_rescan_srv unlocks the * topology srv_polling_mtx for the scan. The topology may have shut * down in that time. */ bson_mutex_lock (&topology->srv_polling_mtx); - if (bson_atomic_int_fetch (&topology->scanner_state, - bson_memory_order_relaxed) != + if (bson_atomic_int_fetch (&topology->scanner_state, bson_memory_order_relaxed) != MONGOC_TOPOLOGY_SCANNER_BG_RUNNING) { bson_mutex_unlock (&topology->srv_polling_mtx); break; } /* If shutting down, stop. */ - mongoc_cond_timedwait (&topology->srv_polling_cond, - &topology->srv_polling_mtx, - sleep_duration_ms); + mongoc_cond_timedwait (&topology->srv_polling_cond, &topology->srv_polling_mtx, sleep_duration_ms); bson_mutex_unlock (&topology->srv_polling_mtx); } BSON_THREAD_RETURN; @@ -94,8 +88,7 @@ _background_monitor_reconcile_server_monitor (mongoc_topology_t *topology, mongoc_server_description_t *sd) { mongoc_set_t *server_monitors = topology->server_monitors; - mongoc_server_monitor_t *server_monitor = - mongoc_set_get (server_monitors, sd->id); + mongoc_server_monitor_t *server_monitor = mongoc_set_get (server_monitors, sd->id); if (!server_monitor) { /* Add a new server monitor. */ @@ -136,11 +129,10 @@ _mongoc_topology_background_monitoring_start (mongoc_topology_t *topology) return; } - prev_state = bson_atomic_int_compare_exchange_strong ( - &topology->scanner_state, - MONGOC_TOPOLOGY_SCANNER_OFF, - MONGOC_TOPOLOGY_SCANNER_BG_RUNNING, - bson_memory_order_relaxed); + prev_state = bson_atomic_int_compare_exchange_strong (&topology->scanner_state, + MONGOC_TOPOLOGY_SCANNER_OFF, + MONGOC_TOPOLOGY_SCANNER_BG_RUNNING, + bson_memory_order_relaxed); if (prev_state != MONGOC_TOPOLOGY_SCANNER_OFF) { /* The topology scanner is already running, or another thread is starting @@ -162,8 +154,7 @@ _mongoc_topology_background_monitoring_start (mongoc_topology_t *topology) _mongoc_topology_background_monitoring_reconcile (topology, tdmod.new_td); /* Start SRV polling thread. */ if (mongoc_topology_should_rescan_srv (topology)) { - int ret = mcommon_thread_create ( - &topology->srv_polling_thread, srv_polling_run, topology); + int ret = mcommon_thread_create (&topology->srv_polling_thread, srv_polling_run, topology); if (ret == 0) { topology->is_srv_polling = true; } else { @@ -185,16 +176,14 @@ _mongoc_topology_background_monitoring_start (mongoc_topology_t *topology) * topology description. */ static void -_remove_orphaned_server_monitors (mongoc_set_t *server_monitors, - mongoc_set_t *server_descriptions) +_remove_orphaned_server_monitors (mongoc_set_t *server_monitors, mongoc_set_t *server_descriptions) { uint32_t *server_monitor_ids_to_remove; uint32_t n_server_monitor_ids_to_remove = 0; /* Signal shutdown to server monitors no longer in the topology description. */ - server_monitor_ids_to_remove = - bson_malloc0 (sizeof (uint32_t) * server_monitors->items_len); + server_monitor_ids_to_remove = bson_malloc0 (sizeof (uint32_t) * server_monitors->items_len); for (size_t i = 0u; i < server_monitors->items_len; i++) { mongoc_server_monitor_t *server_monitor; uint32_t id; @@ -226,15 +215,13 @@ _remove_orphaned_server_monitors (mongoc_set_t *server_monitors, * completed shutdown. */ void -_mongoc_topology_background_monitoring_reconcile ( - mongoc_topology_t *topology, mongoc_topology_description_t *td) +_mongoc_topology_background_monitoring_reconcile (mongoc_topology_t *topology, mongoc_topology_description_t *td) { mongoc_set_t *server_descriptions = mc_tpld_servers (td); BSON_ASSERT (!topology->single_threaded); - if (bson_atomic_int_fetch (&topology->scanner_state, - bson_memory_order_relaxed) != + if (bson_atomic_int_fetch (&topology->scanner_state, bson_memory_order_relaxed) != MONGOC_TOPOLOGY_SCANNER_BG_RUNNING) { return; } @@ -247,10 +234,8 @@ _mongoc_topology_background_monitoring_reconcile ( _background_monitor_reconcile_server_monitor (topology, td, sd); } - _remove_orphaned_server_monitors (topology->server_monitors, - server_descriptions); - _remove_orphaned_server_monitors (topology->rtt_monitors, - server_descriptions); + _remove_orphaned_server_monitors (topology->server_monitors, server_descriptions); + _remove_orphaned_server_monitors (topology->rtt_monitors, server_descriptions); } /* Request all server monitors to scan. @@ -259,15 +244,13 @@ _mongoc_topology_background_monitoring_reconcile ( * errors). Locks server monitor mutexes to deliver scan_requested. */ void -_mongoc_topology_background_monitoring_request_scan ( - mongoc_topology_t *topology) +_mongoc_topology_background_monitoring_request_scan (mongoc_topology_t *topology) { mongoc_set_t *server_monitors; BSON_ASSERT (!topology->single_threaded); - if (bson_atomic_int_fetch (&topology->scanner_state, - bson_memory_order_relaxed) == + if (bson_atomic_int_fetch (&topology->scanner_state, bson_memory_order_relaxed) == MONGOC_TOPOLOGY_SCANNER_SHUTTING_DOWN) { return; } @@ -297,8 +280,7 @@ _mongoc_topology_background_monitoring_stop (mongoc_topology_t *topology) BSON_ASSERT (!topology->single_threaded); - if (bson_atomic_int_fetch (&topology->scanner_state, - bson_memory_order_relaxed) != + if (bson_atomic_int_fetch (&topology->scanner_state, bson_memory_order_relaxed) != MONGOC_TOPOLOGY_SCANNER_BG_RUNNING) { return; } @@ -307,9 +289,8 @@ _mongoc_topology_background_monitoring_stop (mongoc_topology_t *topology) /* Tell the srv polling thread to stop */ bson_mutex_lock (&topology->srv_polling_mtx); - bson_atomic_int_exchange (&topology->scanner_state, - MONGOC_TOPOLOGY_SCANNER_SHUTTING_DOWN, - bson_memory_order_relaxed); + bson_atomic_int_exchange ( + &topology->scanner_state, MONGOC_TOPOLOGY_SCANNER_SHUTTING_DOWN, bson_memory_order_relaxed); if (topology->is_srv_polling) { /* Signal the srv poller to break out of waiting */ @@ -362,9 +343,7 @@ _mongoc_topology_background_monitoring_stop (mongoc_topology_t *topology) mongoc_set_destroy (topology->rtt_monitors); topology->server_monitors = mongoc_set_new (1, NULL, NULL); topology->rtt_monitors = mongoc_set_new (1, NULL, NULL); - bson_atomic_int_exchange (&topology->scanner_state, - MONGOC_TOPOLOGY_SCANNER_OFF, - bson_memory_order_relaxed); + bson_atomic_int_exchange (&topology->scanner_state, MONGOC_TOPOLOGY_SCANNER_OFF, bson_memory_order_relaxed); mongoc_cond_broadcast (&topology->cond_client); bson_mutex_unlock (&topology->tpld_modification_mtx); } @@ -375,8 +354,7 @@ _mongoc_topology_background_monitoring_stop (mongoc_topology_t *topology) * Called from application threads on network errors. */ void -_mongoc_topology_background_monitoring_cancel_check ( - mongoc_topology_t *topology, uint32_t server_id) +_mongoc_topology_background_monitoring_cancel_check (mongoc_topology_t *topology, uint32_t server_id) { mongoc_server_monitor_t *server_monitor; diff --git a/src/libmongoc/src/mongoc/mongoc-topology-description-apm-private.h b/src/libmongoc/src/mongoc/mongoc-topology-description-apm-private.h index 9c914248fb..ec62acf7e6 100644 --- a/src/libmongoc/src/mongoc/mongoc-topology-description-apm-private.h +++ b/src/libmongoc/src/mongoc/mongoc-topology-description-apm-private.h @@ -30,32 +30,27 @@ */ void -_mongoc_topology_description_monitor_server_opening ( - const mongoc_topology_description_t *td, mongoc_server_description_t *sd); +_mongoc_topology_description_monitor_server_opening (const mongoc_topology_description_t *td, + mongoc_server_description_t *sd); void -_mongoc_topology_description_monitor_server_changed ( - const mongoc_topology_description_t *td, - const mongoc_server_description_t *prev_sd, - const mongoc_server_description_t *new_sd); +_mongoc_topology_description_monitor_server_changed (const mongoc_topology_description_t *td, + const mongoc_server_description_t *prev_sd, + const mongoc_server_description_t *new_sd); void -_mongoc_topology_description_monitor_server_closed ( - const mongoc_topology_description_t *td, - const mongoc_server_description_t *sd); +_mongoc_topology_description_monitor_server_closed (const mongoc_topology_description_t *td, + const mongoc_server_description_t *sd); /* td is not const: we set its "opened" field here */ void -_mongoc_topology_description_monitor_opening ( - mongoc_topology_description_t *td); +_mongoc_topology_description_monitor_opening (mongoc_topology_description_t *td); void -_mongoc_topology_description_monitor_changed ( - const mongoc_topology_description_t *prev_td, - const mongoc_topology_description_t *new_td); +_mongoc_topology_description_monitor_changed (const mongoc_topology_description_t *prev_td, + const mongoc_topology_description_t *new_td); void -_mongoc_topology_description_monitor_closed ( - const mongoc_topology_description_t *td); +_mongoc_topology_description_monitor_closed (const mongoc_topology_description_t *td); #endif /* MONGOC_TOPOLOGY_DESCRIPTION_APM_PRIVATE_H */ diff --git a/src/libmongoc/src/mongoc/mongoc-topology-description-apm.c b/src/libmongoc/src/mongoc/mongoc-topology-description-apm.c index 318dac4136..f4a2f1a15f 100644 --- a/src/libmongoc/src/mongoc/mongoc-topology-description-apm.c +++ b/src/libmongoc/src/mongoc/mongoc-topology-description-apm.c @@ -26,8 +26,8 @@ /* ServerOpeningEvent */ void -_mongoc_topology_description_monitor_server_opening ( - const mongoc_topology_description_t *td, mongoc_server_description_t *sd) +_mongoc_topology_description_monitor_server_opening (const mongoc_topology_description_t *td, + mongoc_server_description_t *sd) { if (td->apm_callbacks.server_opening && !sd->opened) { mongoc_apm_server_opening_t event; @@ -42,10 +42,9 @@ _mongoc_topology_description_monitor_server_opening ( /* ServerDescriptionChangedEvent */ void -_mongoc_topology_description_monitor_server_changed ( - const mongoc_topology_description_t *td, - const mongoc_server_description_t *prev_sd, - const mongoc_server_description_t *new_sd) +_mongoc_topology_description_monitor_server_changed (const mongoc_topology_description_t *td, + const mongoc_server_description_t *prev_sd, + const mongoc_server_description_t *new_sd) { if (td->apm_callbacks.server_changed) { mongoc_apm_server_changed_t event; @@ -62,9 +61,8 @@ _mongoc_topology_description_monitor_server_changed ( /* ServerClosedEvent */ void -_mongoc_topology_description_monitor_server_closed ( - const mongoc_topology_description_t *td, - const mongoc_server_description_t *sd) +_mongoc_topology_description_monitor_server_closed (const mongoc_topology_description_t *td, + const mongoc_server_description_t *sd) { if (td->apm_callbacks.server_closed) { mongoc_apm_server_closed_t event; @@ -149,9 +147,8 @@ _mongoc_topology_description_monitor_opening (mongoc_topology_description_t *td) /* TopologyDescriptionChangedEvent */ void -_mongoc_topology_description_monitor_changed ( - const mongoc_topology_description_t *prev_td, - const mongoc_topology_description_t *new_td) +_mongoc_topology_description_monitor_changed (const mongoc_topology_description_t *prev_td, + const mongoc_topology_description_t *new_td) { if (new_td->apm_callbacks.topology_changed) { mongoc_apm_topology_changed_t event; @@ -168,8 +165,7 @@ _mongoc_topology_description_monitor_changed ( /* TopologyClosedEvent */ void -_mongoc_topology_description_monitor_closed ( - const mongoc_topology_description_t *td) +_mongoc_topology_description_monitor_closed (const mongoc_topology_description_t *td) { if (td->apm_callbacks.topology_closed) { mongoc_apm_topology_closed_t event; diff --git a/src/libmongoc/src/mongoc/mongoc-topology-description-private.h b/src/libmongoc/src/mongoc/mongoc-topology-description-private.h index edafc7695e..141c9c86ef 100644 --- a/src/libmongoc/src/mongoc/mongoc-topology-description-private.h +++ b/src/libmongoc/src/mongoc/mongoc-topology-description-private.h @@ -64,15 +64,10 @@ struct _mongoc_topology_description_t { void *apm_context; }; -typedef enum { - MONGOC_SS_READ, - MONGOC_SS_WRITE, - MONGOC_SS_AGGREGATE_WITH_WRITE -} mongoc_ss_optype_t; +typedef enum { MONGOC_SS_READ, MONGOC_SS_WRITE, MONGOC_SS_AGGREGATE_WITH_WRITE } mongoc_ss_optype_t; void -mongoc_topology_description_init (mongoc_topology_description_t *description, - int64_t heartbeat_msec); +mongoc_topology_description_init (mongoc_topology_description_t *description, int64_t heartbeat_msec); /** @@ -94,75 +89,61 @@ mc_tpld_servers_const (const mongoc_topology_description_t *tpld) } void -_mongoc_topology_description_copy_to (const mongoc_topology_description_t *src, - mongoc_topology_description_t *dst); +_mongoc_topology_description_copy_to (const mongoc_topology_description_t *src, mongoc_topology_description_t *dst); void -mongoc_topology_description_cleanup ( - mongoc_topology_description_t *description); +mongoc_topology_description_cleanup (mongoc_topology_description_t *description); void -mongoc_topology_description_handle_hello ( - mongoc_topology_description_t *topology, - uint32_t server_id, - const bson_t *hello_response, - int64_t rtt_msec, - const bson_error_t *error /* IN */); +mongoc_topology_description_handle_hello (mongoc_topology_description_t *topology, + uint32_t server_id, + const bson_t *hello_response, + int64_t rtt_msec, + const bson_error_t *error /* IN */); mongoc_server_description_t const * -mongoc_topology_description_select ( - const mongoc_topology_description_t *description, - mongoc_ss_optype_t optype, - const mongoc_read_prefs_t *read_pref, - bool *must_use_primary, - const mongoc_deprioritized_servers_t *ds, - int64_t local_threshold_ms); +mongoc_topology_description_select (const mongoc_topology_description_t *description, + mongoc_ss_optype_t optype, + const mongoc_read_prefs_t *read_pref, + bool *must_use_primary, + const mongoc_deprioritized_servers_t *ds, + int64_t local_threshold_ms); mongoc_server_description_t * -mongoc_topology_description_server_by_id ( - mongoc_topology_description_t *description, - uint32_t id, - bson_error_t *error); +mongoc_topology_description_server_by_id (mongoc_topology_description_t *description, uint32_t id, bson_error_t *error); const mongoc_server_description_t * -mongoc_topology_description_server_by_id_const ( - const mongoc_topology_description_t *description, - uint32_t id, - bson_error_t *error); +mongoc_topology_description_server_by_id_const (const mongoc_topology_description_t *description, + uint32_t id, + bson_error_t *error); int32_t -mongoc_topology_description_lowest_max_wire_version ( - const mongoc_topology_description_t *td); +mongoc_topology_description_lowest_max_wire_version (const mongoc_topology_description_t *td); bool -mongoc_topology_description_all_sds_have_write_date ( - const mongoc_topology_description_t *td); +mongoc_topology_description_all_sds_have_write_date (const mongoc_topology_description_t *td); bool -_mongoc_topology_description_validate_max_staleness ( - const mongoc_topology_description_t *td, - int64_t max_staleness_seconds, - bson_error_t *error); +_mongoc_topology_description_validate_max_staleness (const mongoc_topology_description_t *td, + int64_t max_staleness_seconds, + bson_error_t *error); void -mongoc_topology_description_suitable_servers ( - mongoc_array_t *set, /* OUT */ - mongoc_ss_optype_t optype, - const mongoc_topology_description_t *topology, - const mongoc_read_prefs_t *read_pref, - bool *must_use_primary, - const mongoc_deprioritized_servers_t *ds, - int64_t local_threshold_ms); +mongoc_topology_description_suitable_servers (mongoc_array_t *set, /* OUT */ + mongoc_ss_optype_t optype, + const mongoc_topology_description_t *topology, + const mongoc_read_prefs_t *read_pref, + bool *must_use_primary, + const mongoc_deprioritized_servers_t *ds, + int64_t local_threshold_ms); bool -mongoc_topology_description_has_data_node ( - const mongoc_topology_description_t *td); +mongoc_topology_description_has_data_node (const mongoc_topology_description_t *td); void -mongoc_topology_description_invalidate_server ( - mongoc_topology_description_t *topology, - uint32_t id, - const bson_error_t *error /* IN */); +mongoc_topology_description_invalidate_server (mongoc_topology_description_t *topology, + uint32_t id, + const bson_error_t *error /* IN */); bool mongoc_topology_description_add_server (mongoc_topology_description_t *topology, @@ -170,12 +151,10 @@ mongoc_topology_description_add_server (mongoc_topology_description_t *topology, uint32_t *id /* OUT */); void -mongoc_topology_description_update_cluster_time ( - mongoc_topology_description_t *td, const bson_t *reply); +mongoc_topology_description_update_cluster_time (mongoc_topology_description_t *td, const bson_t *reply); void -mongoc_topology_description_reconcile (mongoc_topology_description_t *td, - mongoc_host_list_t *host_list); +mongoc_topology_description_reconcile (mongoc_topology_description_t *td, mongoc_host_list_t *host_list); /** * @brief Invalidate open connnections to a server. @@ -192,15 +171,13 @@ mongoc_topology_description_reconcile (mongoc_topology_description_t *td, * single connection per server and therefore have no connection pool. */ void -_mongoc_topology_description_clear_connection_pool ( - mongoc_topology_description_t *td, - uint32_t server_id, - const bson_oid_t *service_id); +_mongoc_topology_description_clear_connection_pool (mongoc_topology_description_t *td, + uint32_t server_id, + const bson_oid_t *service_id); void -mongoc_deprioritized_servers_add_if_sharded ( - mongoc_deprioritized_servers_t *ds, - mongoc_topology_description_type_t topology_type, - const mongoc_server_description_t *sd); +mongoc_deprioritized_servers_add_if_sharded (mongoc_deprioritized_servers_t *ds, + mongoc_topology_description_type_t topology_type, + const mongoc_server_description_t *sd); #endif /* MONGOC_TOPOLOGY_DESCRIPTION_PRIVATE_H */ diff --git a/src/libmongoc/src/mongoc/mongoc-topology-description.c b/src/libmongoc/src/mongoc/mongoc-topology-description.c index fb885d6940..54b82b3121 100644 --- a/src/libmongoc/src/mongoc/mongoc-topology-description.c +++ b/src/libmongoc/src/mongoc/mongoc-topology-description.c @@ -74,8 +74,7 @@ _mongoc_topology_server_dtor (void *server_, void *ctx_) *-------------------------------------------------------------------------- */ void -mongoc_topology_description_init (mongoc_topology_description_t *description, - int64_t heartbeat_msec) +mongoc_topology_description_init (mongoc_topology_description_t *description, int64_t heartbeat_msec) { ENTRY; @@ -87,8 +86,7 @@ mongoc_topology_description_init (mongoc_topology_description_t *description, description->opened = false; description->type = MONGOC_TOPOLOGY_UNKNOWN; description->heartbeat_msec = heartbeat_msec; - description->_servers_ = - mongoc_set_new (8, _mongoc_topology_server_dtor, NULL); + description->_servers_ = mongoc_set_new (8, _mongoc_topology_server_dtor, NULL); description->set_name = NULL; description->max_set_version = MONGOC_NO_SET_VERSION; description->stale = true; @@ -117,8 +115,7 @@ mongoc_topology_description_init (mongoc_topology_description_t *description, *-------------------------------------------------------------------------- */ void -_mongoc_topology_description_copy_to (const mongoc_topology_description_t *src, - mongoc_topology_description_t *dst) +_mongoc_topology_description_copy_to (const mongoc_topology_description_t *src, mongoc_topology_description_t *dst) { size_t nitems; const mongoc_server_description_t *sd; @@ -139,23 +136,17 @@ _mongoc_topology_description_copy_to (const mongoc_topology_description_t *src, nitems = bson_next_power_of_two (mc_tpld_servers_const (src)->items_len); dst->_servers_ = mongoc_set_new (nitems, _mongoc_topology_server_dtor, NULL); for (size_t i = 0u; i < mc_tpld_servers_const (src)->items_len; i++) { - sd = - mongoc_set_get_item_and_id_const (mc_tpld_servers_const (src), i, &id); - mongoc_set_add ( - mc_tpld_servers (dst), id, mongoc_server_description_new_copy (sd)); + sd = mongoc_set_get_item_and_id_const (mc_tpld_servers_const (src), i, &id); + mongoc_set_add (mc_tpld_servers (dst), id, mongoc_server_description_new_copy (sd)); } dst->set_name = bson_strdup (src->set_name); dst->max_set_version = src->max_set_version; - memcpy (&dst->compatibility_error, - &src->compatibility_error, - sizeof (bson_error_t)); + memcpy (&dst->compatibility_error, &src->compatibility_error, sizeof (bson_error_t)); dst->max_server_id = src->max_server_id; dst->max_hosts = src->max_hosts; dst->stale = src->stale; - memcpy (&dst->apm_callbacks, - &src->apm_callbacks, - sizeof (mongoc_apm_callbacks_t)); + memcpy (&dst->apm_callbacks, &src->apm_callbacks, sizeof (mongoc_apm_callbacks_t)); dst->apm_context = src->apm_context; @@ -184,8 +175,7 @@ _mongoc_topology_description_copy_to (const mongoc_topology_description_t *src, *------------------------------------------------------------------------- */ mongoc_topology_description_t * -mongoc_topology_description_new_copy ( - const mongoc_topology_description_t *description) +mongoc_topology_description_new_copy (const mongoc_topology_description_t *description) { mongoc_topology_description_t *copy; @@ -268,15 +258,13 @@ mongoc_topology_description_destroy (mongoc_topology_description_t *description) /* find the primary, then stop iterating */ static bool -_mongoc_topology_description_has_primary_cb (const void *item, - void *ctx /* OUT */) +_mongoc_topology_description_has_primary_cb (const void *item, void *ctx /* OUT */) { const mongoc_server_description_t *server = item; const mongoc_server_description_t **primary = ctx; /* TODO should this include MONGOS? */ - if (server->type == MONGOC_SERVER_RS_PRIMARY || - server->type == MONGOC_SERVER_STANDALONE) { + if (server->type == MONGOC_SERVER_RS_PRIMARY || server->type == MONGOC_SERVER_STANDALONE) { *primary = (mongoc_server_description_t *) item; return false; } @@ -299,14 +287,12 @@ _mongoc_topology_description_has_primary_cb (const void *item, *-------------------------------------------------------------------------- */ static const mongoc_server_description_t * -_mongoc_topology_description_has_primary ( - const mongoc_topology_description_t *description) +_mongoc_topology_description_has_primary (const mongoc_topology_description_t *description) { mongoc_server_description_t *primary = NULL; - mongoc_set_for_each_const (mc_tpld_servers_const (description), - _mongoc_topology_description_has_primary_cb, - &primary); + mongoc_set_for_each_const ( + mc_tpld_servers_const (description), _mongoc_topology_description_has_primary_cb, &primary); return primary; } @@ -329,13 +315,12 @@ _mongoc_topology_description_has_primary ( *-------------------------------------------------------------------------- */ static bool -_mongoc_server_description_primary_is_not_stale ( - mongoc_topology_description_t *td, const mongoc_server_description_t *sd) +_mongoc_server_description_primary_is_not_stale (mongoc_topology_description_t *td, + const mongoc_server_description_t *sd) { /* initially max_set_version is -1 and max_election_id is zeroed */ return (bson_oid_compare (&sd->election_id, &td->max_election_id) > 0) || - ((bson_oid_compare (&sd->election_id, &td->max_election_id) == 0) && - sd->set_version >= td->max_set_version); + ((bson_oid_compare (&sd->election_id, &td->max_election_id) == 0) && sd->set_version >= td->max_set_version); } /* @@ -356,13 +341,11 @@ _mongoc_server_description_primary_is_not_stale ( *-------------------------------------------------------------------------- */ static bool -_mongoc_topology_description_later_election ( - mongoc_topology_description_t *td, const mongoc_server_description_t *sd) +_mongoc_topology_description_later_election (mongoc_topology_description_t *td, const mongoc_server_description_t *sd) { /* initially max_set_version is -1 and max_election_id is zeroed */ return td->max_set_version > sd->set_version || - (td->max_set_version == sd->set_version && - bson_oid_compare (&td->max_election_id, &sd->election_id) > 0); + (td->max_set_version == sd->set_version && bson_oid_compare (&td->max_election_id, &sd->election_id) > 0); } /* @@ -376,8 +359,8 @@ _mongoc_topology_description_later_election ( *-------------------------------------------------------------------------- */ static void -_mongoc_topology_description_set_max_set_version ( - mongoc_topology_description_t *td, const mongoc_server_description_t *sd) +_mongoc_topology_description_set_max_set_version (mongoc_topology_description_t *td, + const mongoc_server_description_t *sd) { td->max_set_version = sd->set_version; } @@ -393,17 +376,16 @@ _mongoc_topology_description_set_max_set_version ( *-------------------------------------------------------------------------- */ static void -_mongoc_topology_description_set_max_election_id ( - mongoc_topology_description_t *td, const mongoc_server_description_t *sd) +_mongoc_topology_description_set_max_election_id (mongoc_topology_description_t *td, + const mongoc_server_description_t *sd) { bson_oid_copy (&sd->election_id, &td->max_election_id); } static bool -_mongoc_topology_description_server_is_candidate ( - mongoc_server_description_type_t desc_type, - mongoc_read_mode_t read_mode, - mongoc_topology_description_type_t topology_type) +_mongoc_topology_description_server_is_candidate (mongoc_server_description_type_t desc_type, + mongoc_read_mode_t read_mode, + mongoc_topology_description_type_t topology_type) { switch ((int) topology_type) { case MONGOC_TOPOLOGY_SINGLE: @@ -481,11 +463,9 @@ _mongoc_replica_set_read_suitable_cb (const void *item, void *ctx) data->primary = server; } - if (_mongoc_topology_description_server_is_candidate ( - server->type, data->read_mode, data->topology_type)) { + if (_mongoc_topology_description_server_is_candidate (server->type, data->read_mode, data->topology_type)) { if (server->type == MONGOC_SERVER_RS_PRIMARY) { - if (data->read_mode == MONGOC_READ_PRIMARY || - data->read_mode == MONGOC_READ_PRIMARY_PREFERRED) { + if (data->read_mode == MONGOC_READ_PRIMARY || data->read_mode == MONGOC_READ_PRIMARY_PREFERRED) { /* we want a primary and we have one, done! */ return false; } @@ -522,13 +502,8 @@ _mongoc_try_mode_secondary (mongoc_array_t *set, /* OUT */ secondary = mongoc_read_prefs_copy (read_pref); mongoc_read_prefs_set_mode (secondary, MONGOC_READ_SECONDARY); - mongoc_topology_description_suitable_servers (set, - MONGOC_SS_READ, - topology, - secondary, - must_use_primary, - ds, - local_threshold_ms); + mongoc_topology_description_suitable_servers ( + set, MONGOC_SS_READ, topology, secondary, must_use_primary, ds, local_threshold_ms); mongoc_read_prefs_destroy (secondary); } @@ -553,8 +528,7 @@ _mongoc_td_servers_to_candidates_array (const void *item, void *ctx) // there are no other suitable servers. The server selection algorithm MUST // ignore the deprioritized servers if the topology is not a sharded cluster. static void -_mongoc_filter_deprioritized_servers (mongoc_suitable_data_t *data, - const mongoc_deprioritized_servers_t *ds) +_mongoc_filter_deprioritized_servers (mongoc_suitable_data_t *data, const mongoc_deprioritized_servers_t *ds) { BSON_ASSERT_PARAM (data); BSON_ASSERT_PARAM (ds); @@ -562,27 +536,21 @@ _mongoc_filter_deprioritized_servers (mongoc_suitable_data_t *data, TRACE ("%s", "deprioritization: filtering list of candidates"); mongoc_array_t filtered_servers; - _mongoc_array_init (&filtered_servers, - sizeof (const mongoc_server_description_t *)); + _mongoc_array_init (&filtered_servers, sizeof (const mongoc_server_description_t *)); for (size_t idx = 0u; idx < data->candidates_len; ++idx) { mongoc_server_description_t const *const sd = data->candidates[idx]; if (!mongoc_deprioritized_servers_contains (ds, sd)) { - TRACE ("deprioritization: - kept: %s (id: %" PRIu32 ")", - sd->host.host_and_port, - sd->id); + TRACE ("deprioritization: - kept: %s (id: %" PRIu32 ")", sd->host.host_and_port, sd->id); _mongoc_array_append_val (&filtered_servers, sd); } else { - TRACE ("deprioritization: - removed: %s (id: %" PRIu32 ")", - sd->host.host_and_port, - sd->id); + TRACE ("deprioritization: - removed: %s (id: %" PRIu32 ")", sd->host.host_and_port, sd->id); } } if (filtered_servers.len == 0u) { - TRACE ("%s", - "deprioritization: reverted due to no other suitable servers"); + TRACE ("%s", "deprioritization: reverted due to no other suitable servers"); _mongoc_array_destroy (&filtered_servers); } else if (filtered_servers.len == data->candidates_len) { TRACE ("%s", "deprioritization: none found in list of candidates"); @@ -592,9 +560,7 @@ _mongoc_filter_deprioritized_servers (mongoc_suitable_data_t *data, data->candidates_len = filtered_servers.len; // `(void*)`: avoid MSVC error C4090: // 'function': different 'const' qualifiers - memmove ((void *) data->candidates, - filtered_servers.data, - filtered_servers.len * filtered_servers.element_size); + memmove ((void *) data->candidates, filtered_servers.data, filtered_servers.len * filtered_servers.element_size); _mongoc_array_destroy (&filtered_servers); } } @@ -608,9 +574,7 @@ _mongoc_filter_suitable_mongos (mongoc_suitable_data_t *data) while (idx < data->candidates_len) { if (_mongoc_topology_description_server_is_candidate ( - data->candidates[idx]->type, - data->read_mode, - data->topology_type)) { + data->candidates[idx]->type, data->read_mode, data->topology_type)) { // All candidates in the latency window are suitable. ++idx; } else { @@ -640,17 +604,14 @@ _mongoc_filter_suitable_mongos (mongoc_suitable_data_t *data) *------------------------------------------------------------------------- */ int32_t -mongoc_topology_description_lowest_max_wire_version ( - const mongoc_topology_description_t *td) +mongoc_topology_description_lowest_max_wire_version (const mongoc_topology_description_t *td) { int32_t ret = INT32_MAX; const mongoc_set_t *servers = mc_tpld_servers_const (td); for (size_t i = 0u; (size_t) i < servers->items_len; i++) { - const mongoc_server_description_t *sd = - mongoc_set_get_item_const (servers, i); - if (sd->type != MONGOC_SERVER_UNKNOWN && - sd->type != MONGOC_SERVER_POSSIBLE_PRIMARY && + const mongoc_server_description_t *sd = mongoc_set_get_item_const (servers, i); + if (sd->type != MONGOC_SERVER_UNKNOWN && sd->type != MONGOC_SERVER_POSSIBLE_PRIMARY && sd->max_wire_version < ret) { ret = sd->max_wire_version; } @@ -674,17 +635,13 @@ mongoc_topology_description_lowest_max_wire_version ( *------------------------------------------------------------------------- */ bool -mongoc_topology_description_all_sds_have_write_date ( - const mongoc_topology_description_t *td) +mongoc_topology_description_all_sds_have_write_date (const mongoc_topology_description_t *td) { - for (size_t i = 0u; (size_t) i < mc_tpld_servers_const (td)->items_len; - i++) { - const mongoc_server_description_t *sd = - mongoc_set_get_item_const (mc_tpld_servers_const (td), i); + for (size_t i = 0u; (size_t) i < mc_tpld_servers_const (td)->items_len; i++) { + const mongoc_server_description_t *sd = mongoc_set_get_item_const (mc_tpld_servers_const (td), i); if (sd->last_write_date_ms <= 0 && - (sd->type == MONGOC_SERVER_RS_PRIMARY || - sd->type == MONGOC_SERVER_RS_SECONDARY)) { + (sd->type == MONGOC_SERVER_RS_PRIMARY || sd->type == MONGOC_SERVER_RS_SECONDARY)) { return false; } } @@ -707,10 +664,9 @@ mongoc_topology_description_all_sds_have_write_date ( *------------------------------------------------------------------------- */ bool -_mongoc_topology_description_validate_max_staleness ( - const mongoc_topology_description_t *td, - int64_t max_staleness_seconds, - bson_error_t *error) +_mongoc_topology_description_validate_max_staleness (const mongoc_topology_description_t *td, + int64_t max_staleness_seconds, + bson_error_t *error) { mongoc_topology_description_type_t td_type; @@ -724,18 +680,15 @@ _mongoc_topology_description_validate_max_staleness ( td_type = td->type; - if (td_type != MONGOC_TOPOLOGY_RS_WITH_PRIMARY && - td_type != MONGOC_TOPOLOGY_RS_NO_PRIMARY) { + if (td_type != MONGOC_TOPOLOGY_RS_WITH_PRIMARY && td_type != MONGOC_TOPOLOGY_RS_NO_PRIMARY) { return true; } - if (max_staleness_seconds * 1000 < - td->heartbeat_msec + MONGOC_IDLE_WRITE_PERIOD_MS) { + if (max_staleness_seconds * 1000 < td->heartbeat_msec + MONGOC_IDLE_WRITE_PERIOD_MS) { bson_set_error (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, - "maxStalenessSeconds is set to %" PRId64 - ", it must be at least heartbeatFrequencyMS (%" PRId64 + "maxStalenessSeconds is set to %" PRId64 ", it must be at least heartbeatFrequencyMS (%" PRId64 ") + server's idle write period (%d seconds)", max_staleness_seconds, td->heartbeat_msec, @@ -747,8 +700,7 @@ _mongoc_topology_description_validate_max_staleness ( bson_set_error (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, - "maxStalenessSeconds is set to %" PRId64 - ", it must be at least %d seconds", + "maxStalenessSeconds is set to %" PRId64 ", it must be at least %d seconds", max_staleness_seconds, MONGOC_SMALLEST_MAX_STALENESS_SECONDS); return false; @@ -758,8 +710,7 @@ _mongoc_topology_description_validate_max_staleness ( } static bool -_check_any_server_less_than_wire_version_13 (const void *sd_, - void *any_too_old_) +_check_any_server_less_than_wire_version_13 (const void *sd_, void *any_too_old_) { const mongoc_server_description_t *sd = sd_; bool *any_too_old = any_too_old_; @@ -803,9 +754,7 @@ _must_use_primary (const mongoc_topology_description_t *td, /* Check if any of the servers are too old to support the * aggregate-with-write on a secondary server */ bool any_too_old = false; - mongoc_set_for_each_const (mc_tpld_servers_const (td), - _check_any_server_less_than_wire_version_13, - &any_too_old); + mongoc_set_for_each_const (mc_tpld_servers_const (td), _check_any_server_less_than_wire_version_13, &any_too_old); if (any_too_old) { /* Force the read preference back to reading from a primary server, as * one or more servers in the system may not support the operation */ @@ -835,28 +784,24 @@ _must_use_primary (const mongoc_topology_description_t *td, */ void -mongoc_topology_description_suitable_servers ( - mongoc_array_t *set, /* OUT */ - mongoc_ss_optype_t optype, - const mongoc_topology_description_t *topology, - const mongoc_read_prefs_t *read_pref, - bool *must_use_primary, - const mongoc_deprioritized_servers_t *ds, - int64_t local_threshold_ms) +mongoc_topology_description_suitable_servers (mongoc_array_t *set, /* OUT */ + mongoc_ss_optype_t optype, + const mongoc_topology_description_t *topology, + const mongoc_read_prefs_t *read_pref, + bool *must_use_primary, + const mongoc_deprioritized_servers_t *ds, + int64_t local_threshold_ms) { const mongoc_set_t *td_servers = mc_tpld_servers_const (topology); - const mongoc_read_mode_t given_read_mode = - mongoc_read_prefs_get_mode (read_pref); - const bool override_use_primary = - _must_use_primary (topology, optype, given_read_mode); + const mongoc_read_mode_t given_read_mode = mongoc_read_prefs_get_mode (read_pref); + const bool override_use_primary = _must_use_primary (topology, optype, given_read_mode); mongoc_suitable_data_t data = { .primary = NULL, .topology_type = topology->type, .has_secondary = false, .candidates_len = 0, - .candidates = bson_malloc0 (sizeof (mongoc_server_description_t *) * - td_servers->items_len), + .candidates = bson_malloc0 (sizeof (mongoc_server_description_t *) * td_servers->items_len), }; /* The "effective" read mode is the read mode that we should behave for, and @@ -870,8 +815,7 @@ mongoc_topology_description_suitable_servers ( * If the operation is an aggregate that contains writing stages, we need to * be more careful about selecting an appropriate server. */ - data.read_mode = - override_use_primary ? MONGOC_READ_PRIMARY : given_read_mode; + data.read_mode = override_use_primary ? MONGOC_READ_PRIMARY : given_read_mode; if (must_use_primary) { /* The caller wants to know if we have overriden their read preference */ *must_use_primary = override_use_primary; @@ -880,30 +824,25 @@ mongoc_topology_description_suitable_servers ( /* Single server -- * Either it is suitable or it isn't */ if (topology->type == MONGOC_TOPOLOGY_SINGLE) { - const mongoc_server_description_t *server = - mongoc_set_get_item_const (td_servers, 0); - if (_mongoc_topology_description_server_is_candidate ( - server->type, data.read_mode, topology->type)) { + const mongoc_server_description_t *server = mongoc_set_get_item_const (td_servers, 0); + if (_mongoc_topology_description_server_is_candidate (server->type, data.read_mode, topology->type)) { _mongoc_array_append_val (set, server); } else { - TRACE ( - "Rejected [%s] [%s] for read mode [%s] with topology type Single", - mongoc_server_description_type (server), - server->host.host_and_port, - _mongoc_read_mode_as_str (data.read_mode)); + TRACE ("Rejected [%s] [%s] for read mode [%s] with topology type Single", + mongoc_server_description_type (server), + server->host.host_and_port, + _mongoc_read_mode_as_str (data.read_mode)); } 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 (topology->type == MONGOC_TOPOLOGY_RS_NO_PRIMARY || topology->type == MONGOC_TOPOLOGY_RS_WITH_PRIMARY) { switch (optype) { case MONGOC_SS_AGGREGATE_WITH_WRITE: case MONGOC_SS_READ: { - mongoc_set_for_each_const ( - td_servers, _mongoc_replica_set_read_suitable_cb, &data); + mongoc_set_for_each_const (td_servers, _mongoc_replica_set_read_suitable_cb, &data); if (data.read_mode == MONGOC_READ_PRIMARY) { if (data.primary) { @@ -920,12 +859,7 @@ mongoc_topology_description_suitable_servers ( if (data.read_mode == MONGOC_READ_SECONDARY_PREFERRED) { /* try read_mode SECONDARY */ - _mongoc_try_mode_secondary (set, - topology, - read_pref, - must_use_primary, - NULL, - local_threshold_ms); + _mongoc_try_mode_secondary (set, topology, read_pref, must_use_primary, NULL, local_threshold_ms); /* otherwise fall back to primary */ if (!set->len && data.primary) { @@ -937,8 +871,7 @@ mongoc_topology_description_suitable_servers ( if (data.read_mode == MONGOC_READ_SECONDARY) { for (size_t i = 0u; i < data.candidates_len; i++) { - if (data.candidates[i] && - data.candidates[i]->type != MONGOC_SERVER_RS_SECONDARY) { + if (data.candidates[i] && data.candidates[i]->type != MONGOC_SERVER_RS_SECONDARY) { TRACE ("Rejected [%s] [%s] for mode [%s] with RS topology", mongoc_server_description_type (data.candidates[i]), data.candidates[i]->host.host_and_port, @@ -949,21 +882,14 @@ mongoc_topology_description_suitable_servers ( } /* mode is SECONDARY or NEAREST, filter by staleness and tags */ - mongoc_server_description_filter_stale (data.candidates, - data.candidates_len, - data.primary, - topology->heartbeat_msec, - read_pref); - - mongoc_server_description_filter_tags ( - data.candidates, data.candidates_len, read_pref); + mongoc_server_description_filter_stale ( + data.candidates, data.candidates_len, data.primary, topology->heartbeat_msec, read_pref); + + mongoc_server_description_filter_tags (data.candidates, data.candidates_len, read_pref); } break; case MONGOC_SS_WRITE: { if (topology->type == MONGOC_TOPOLOGY_RS_WITH_PRIMARY) { - mongoc_set_for_each_const ( - td_servers, - _mongoc_topology_description_has_primary_cb, - (void *) &data.primary); + mongoc_set_for_each_const (td_servers, _mongoc_topology_description_has_primary_cb, (void *) &data.primary); if (data.primary) { _mongoc_array_append_val (set, data.primary); goto DONE; @@ -977,8 +903,7 @@ mongoc_topology_description_suitable_servers ( // Sharded clusters -- if (topology->type == MONGOC_TOPOLOGY_SHARDED) { - mongoc_set_for_each_const ( - td_servers, _mongoc_td_servers_to_candidates_array, &data); + mongoc_set_for_each_const (td_servers, _mongoc_td_servers_to_candidates_array, &data); if (ds) { _mongoc_filter_deprioritized_servers (&data, ds); @@ -1020,8 +945,7 @@ mongoc_topology_description_suitable_servers ( const int64_t rtt_limit = nearest + local_threshold_ms; for (size_t i = 0u; i < data.candidates_len; i++) { - if (data.candidates[i] && - (data.candidates[i]->round_trip_time_msec <= rtt_limit)) { + if (data.candidates[i] && (data.candidates[i]->round_trip_time_msec <= rtt_limit)) { _mongoc_array_append_val (set, data.candidates[i]); } } @@ -1043,14 +967,12 @@ mongoc_topology_description_suitable_servers ( *-------------------------------------------------------------------------- */ bool -mongoc_topology_description_has_data_node ( - const mongoc_topology_description_t *td) +mongoc_topology_description_has_data_node (const mongoc_topology_description_t *td) { const mongoc_set_t *servers = mc_tpld_servers_const (td); for (size_t i = 0u; i < servers->items_len; i++) { - const mongoc_server_description_t *sd = - mongoc_set_get_item_const (servers, i); + const mongoc_server_description_t *sd = mongoc_set_get_item_const (servers, i); if (_is_data_node (sd)) { return true; } @@ -1079,24 +1001,21 @@ mongoc_topology_description_has_data_node ( *------------------------------------------------------------------------- */ mongoc_server_description_t const * -mongoc_topology_description_select ( - const mongoc_topology_description_t *topology, - mongoc_ss_optype_t optype, - const mongoc_read_prefs_t *read_pref, - bool *must_use_primary, - const mongoc_deprioritized_servers_t *ds, - int64_t local_threshold_ms) +mongoc_topology_description_select (const mongoc_topology_description_t *topology, + mongoc_ss_optype_t optype, + const mongoc_read_prefs_t *read_pref, + bool *must_use_primary, + const mongoc_deprioritized_servers_t *ds, + int64_t local_threshold_ms) { mongoc_array_t suitable_servers; ENTRY; if (topology->type == MONGOC_TOPOLOGY_SINGLE) { - mongoc_server_description_t const *const sd = - mongoc_set_get_item_const (mc_tpld_servers_const (topology), 0); + mongoc_server_description_t const *const sd = mongoc_set_get_item_const (mc_tpld_servers_const (topology), 0); - if (optype == MONGOC_SS_AGGREGATE_WITH_WRITE && - sd->max_wire_version < WIRE_VERSION_5_0) { + if (optype == MONGOC_SS_AGGREGATE_WITH_WRITE && sd->max_wire_version < WIRE_VERSION_5_0) { /* The single server may be part of an unseen replica set that may not * support aggr-with-write operations on secondaries. Force the read * preference to use a primary. */ @@ -1113,25 +1032,17 @@ mongoc_topology_description_select ( } } - _mongoc_array_init (&suitable_servers, - sizeof (mongoc_server_description_t *)); + _mongoc_array_init (&suitable_servers, sizeof (mongoc_server_description_t *)); - mongoc_topology_description_suitable_servers (&suitable_servers, - optype, - topology, - read_pref, - must_use_primary, - ds, - local_threshold_ms); + mongoc_topology_description_suitable_servers ( + &suitable_servers, optype, topology, read_pref, must_use_primary, ds, local_threshold_ms); mongoc_server_description_t const *sd = NULL; if (suitable_servers.len != 0) { - const int rand_n = - _mongoc_rand_simple ((unsigned *) &topology->rand_seed); - sd = _mongoc_array_index (&suitable_servers, - mongoc_server_description_t *, - (size_t) rand_n % suitable_servers.len); + const int rand_n = _mongoc_rand_simple ((unsigned *) &topology->rand_seed); + sd = + _mongoc_array_index (&suitable_servers, mongoc_server_description_t *, (size_t) rand_n % suitable_servers.len); } _mongoc_array_destroy (&suitable_servers); @@ -1168,16 +1079,15 @@ mongoc_topology_description_select ( */ mongoc_server_description_t * -mongoc_topology_description_server_by_id ( - mongoc_topology_description_t *description, uint32_t id, bson_error_t *error) +mongoc_topology_description_server_by_id (mongoc_topology_description_t *description, uint32_t id, bson_error_t *error) { - return (mongoc_server_description_t *) - mongoc_topology_description_server_by_id_const (description, id, error); + return (mongoc_server_description_t *) mongoc_topology_description_server_by_id_const (description, id, error); } const mongoc_server_description_t * -mongoc_topology_description_server_by_id_const ( - const mongoc_topology_description_t *td, uint32_t id, bson_error_t *error) +mongoc_topology_description_server_by_id_const (const mongoc_topology_description_t *td, + uint32_t id, + bson_error_t *error) { const mongoc_server_description_t *sd; @@ -1185,11 +1095,8 @@ mongoc_topology_description_server_by_id_const ( sd = mongoc_set_get_const (mc_tpld_servers_const (td), id); if (!sd) { - bson_set_error (error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_NOT_ESTABLISHED, - "Could not find description for node %u", - id); + bson_set_error ( + error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_NOT_ESTABLISHED, "Could not find description for node %u", id); } return sd; @@ -1211,9 +1118,8 @@ mongoc_topology_description_server_by_id_const ( *-------------------------------------------------------------------------- */ static void -_mongoc_topology_description_remove_server ( - mongoc_topology_description_t *description, - const mongoc_server_description_t *server) +_mongoc_topology_description_remove_server (mongoc_topology_description_t *description, + const mongoc_server_description_t *server) { BSON_ASSERT (description); BSON_ASSERT (server); @@ -1235,8 +1141,7 @@ typedef struct _mongoc_address_and_id_t { /* find the given server and stop iterating */ static bool -_mongoc_topology_description_has_server_cb (const void *item, - void *ctx /* IN - OUT */) +_mongoc_topology_description_has_server_cb (const void *item, void *ctx /* IN - OUT */) { const mongoc_server_description_t *server = item; mongoc_address_and_id_t *data = (mongoc_address_and_id_t *) ctx; @@ -1287,10 +1192,9 @@ _mongoc_topology_description_has_set_version (mongoc_topology_description_t *td) *-------------------------------------------------------------------------- */ static bool -_mongoc_topology_description_has_server ( - mongoc_topology_description_t *description, - const char *address, - uint32_t *id /* OUT */) +_mongoc_topology_description_has_server (mongoc_topology_description_t *description, + const char *address, + uint32_t *id /* OUT */) { mongoc_address_and_id_t data; @@ -1299,9 +1203,7 @@ _mongoc_topology_description_has_server ( data.address = address; data.found = false; - mongoc_set_for_each_const (mc_tpld_servers_const (description), - _mongoc_topology_description_has_server_cb, - &data); + mongoc_set_for_each_const (mc_tpld_servers_const (description), _mongoc_topology_description_has_server_cb, &data); if (data.found && id) { *id = data.id; @@ -1321,8 +1223,7 @@ _mongoc_label_unknown_member_cb (void *item, void *ctx) mongoc_server_description_t *server = (mongoc_server_description_t *) item; mongoc_address_and_type_t *data = (mongoc_address_and_type_t *) ctx; - if (strcasecmp (server->connection_address, data->address) == 0 && - server->type == MONGOC_SERVER_UNKNOWN) { + if (strcasecmp (server->connection_address, data->address) == 0 && server->type == MONGOC_SERVER_UNKNOWN) { mongoc_server_description_set_state (server, data->type); return false; } @@ -1346,10 +1247,9 @@ _mongoc_label_unknown_member_cb (void *item, void *ctx) *-------------------------------------------------------------------------- */ static void -_mongoc_topology_description_label_unknown_member ( - mongoc_topology_description_t *description, - const char *address, - mongoc_server_description_type_t type) +_mongoc_topology_description_label_unknown_member (mongoc_topology_description_t *description, + const char *address, + mongoc_server_description_type_t type) { mongoc_address_and_type_t data; @@ -1359,8 +1259,7 @@ _mongoc_topology_description_label_unknown_member ( data.type = type; data.address = address; - mongoc_set_for_each ( - mc_tpld_servers (description), _mongoc_label_unknown_member_cb, &data); + mongoc_set_for_each (mc_tpld_servers (description), _mongoc_label_unknown_member_cb, &data); } /* @@ -1380,9 +1279,8 @@ _mongoc_topology_description_label_unknown_member ( *-------------------------------------------------------------------------- */ static void -_mongoc_topology_description_set_state ( - mongoc_topology_description_t *description, - mongoc_topology_description_type_t type) +_mongoc_topology_description_set_state (mongoc_topology_description_t *description, + mongoc_topology_description_type_t type) { description->type = type; } @@ -1392,11 +1290,9 @@ static void _update_rs_type (mongoc_topology_description_t *topology) { if (_mongoc_topology_description_has_primary (topology)) { - _mongoc_topology_description_set_state (topology, - MONGOC_TOPOLOGY_RS_WITH_PRIMARY); + _mongoc_topology_description_set_state (topology, MONGOC_TOPOLOGY_RS_WITH_PRIMARY); } else { - _mongoc_topology_description_set_state (topology, - MONGOC_TOPOLOGY_RS_NO_PRIMARY); + _mongoc_topology_description_set_state (topology, MONGOC_TOPOLOGY_RS_NO_PRIMARY); } } @@ -1419,9 +1315,8 @@ _update_rs_type (mongoc_topology_description_t *topology) *-------------------------------------------------------------------------- */ static void -_mongoc_topology_description_check_if_has_primary ( - mongoc_topology_description_t *topology, - const mongoc_server_description_t *server) +_mongoc_topology_description_check_if_has_primary (mongoc_topology_description_t *topology, + const mongoc_server_description_t *server) { BSON_UNUSED (server); @@ -1445,10 +1340,9 @@ _mongoc_topology_description_check_if_has_primary ( * _mongoc_topology_handle_app_error. This should not be called directly */ void -mongoc_topology_description_invalidate_server ( - mongoc_topology_description_t *td, - uint32_t id, - const bson_error_t *error /* IN */) +mongoc_topology_description_invalidate_server (mongoc_topology_description_t *td, + uint32_t id, + const bson_error_t *error /* IN */) { BSON_ASSERT (error); @@ -1458,8 +1352,7 @@ mongoc_topology_description_invalidate_server ( } /* send NULL hello reply */ - mongoc_topology_description_handle_hello ( - td, id, NULL, MONGOC_RTT_UNSET, error); + mongoc_topology_description_handle_hello (td, id, NULL, MONGOC_RTT_UNSET, error); } /* @@ -1490,8 +1383,7 @@ mongoc_topology_description_add_server (mongoc_topology_description_t *topology, BSON_ASSERT (topology); BSON_ASSERT (server); - if (!_mongoc_topology_description_has_server ( - topology, server, &server_id)) { + if (!_mongoc_topology_description_has_server (topology, server, &server_id)) { /* TODO this might not be an accurate count in all cases */ server_id = ++topology->max_server_id; @@ -1502,8 +1394,7 @@ mongoc_topology_description_add_server (mongoc_topology_description_t *topology, /* if we're in topology_new then no callbacks are registered and this is * a no-op. later, if we discover a new RS member this sends an event. */ - _mongoc_topology_description_monitor_server_opening (topology, - description); + _mongoc_topology_description_monitor_server_opening (topology, description); } if (id) { @@ -1547,8 +1438,7 @@ mongoc_topology_description_add_server (mongoc_topology_description_t *topology, */ void -mongoc_topology_description_update_cluster_time ( - mongoc_topology_description_t *td, const bson_t *reply) +mongoc_topology_description_update_cluster_time (mongoc_topology_description_t *td, const bson_t *reply) { bson_iter_t iter; bson_iter_t child; @@ -1560,8 +1450,7 @@ mongoc_topology_description_update_cluster_time ( return; } - if (!BSON_ITER_HOLDS_DOCUMENT (&iter) || - !bson_iter_recurse (&iter, &child)) { + if (!BSON_ITER_HOLDS_DOCUMENT (&iter) || !bson_iter_recurse (&iter, &child)) { MONGOC_ERROR ("Can't parse $clusterTime"); return; } @@ -1569,8 +1458,7 @@ mongoc_topology_description_update_cluster_time ( bson_iter_document (&iter, &size, &data); BSON_ASSERT (bson_init_static (&cluster_time, data, (size_t) size)); - if (bson_empty (&td->cluster_time) || - _mongoc_cluster_time_greater (&cluster_time, &td->cluster_time)) { + if (bson_empty (&td->cluster_time) || _mongoc_cluster_time_greater (&cluster_time, &td->cluster_time)) { bson_destroy (&td->cluster_time); bson_copy_to (&cluster_time, &td->cluster_time); } @@ -1578,9 +1466,8 @@ mongoc_topology_description_update_cluster_time ( static void -_mongoc_topology_description_add_new_servers ( - mongoc_topology_description_t *topology, - const mongoc_server_description_t *server) +_mongoc_topology_description_add_new_servers (mongoc_topology_description_t *topology, + const mongoc_server_description_t *server) { bson_iter_t member_iter; const bson_t *rs_members[3]; @@ -1594,8 +1481,7 @@ _mongoc_topology_description_add_new_servers ( BSON_ASSERT (bson_iter_init (&member_iter, rs_members[i])); while (bson_iter_next (&member_iter)) { - mongoc_topology_description_add_server ( - topology, bson_iter_utf8 (&member_iter, NULL), NULL); + mongoc_topology_description_add_server (topology, bson_iter_utf8 (&member_iter, NULL), NULL); } } } @@ -1612,8 +1498,7 @@ _mongoc_topology_description_invalidate_primaries_cb (void *item, void *ctx) mongoc_server_description_t *server = (mongoc_server_description_t *) item; mongoc_primary_and_topology_t *data = (mongoc_primary_and_topology_t *) ctx; - if (server->id != data->primary->id && - server->type == MONGOC_SERVER_RS_PRIMARY) { + if (server->id != data->primary->id && server->type == MONGOC_SERVER_RS_PRIMARY) { mongoc_server_description_set_state (server, MONGOC_SERVER_UNKNOWN); mongoc_server_description_set_set_version (server, MONGOC_NO_SET_VERSION); mongoc_server_description_set_election_id (server, NULL); @@ -1625,9 +1510,8 @@ _mongoc_topology_description_invalidate_primaries_cb (void *item, void *ctx) /* Remove and destroy all replica set members not in primary's hosts lists */ static void -_mongoc_topology_description_remove_unreported_servers ( - mongoc_topology_description_t *topology, - const mongoc_server_description_t *primary) +_mongoc_topology_description_remove_unreported_servers (mongoc_topology_description_t *topology, + const mongoc_server_description_t *primary) { mongoc_array_t to_remove; @@ -1639,8 +1523,7 @@ _mongoc_topology_description_remove_unreported_servers ( * doesn't report its own connection_address in its hosts list. * See hosts_differ_from_seeds.json */ for (size_t i = 0u; i < mc_tpld_servers_const (topology)->items_len; i++) { - const mongoc_server_description_t *member = - mongoc_set_get_item_const (mc_tpld_servers_const (topology), i); + const mongoc_server_description_t *member = mongoc_set_get_item_const (mc_tpld_servers_const (topology), i); const char *address = member->connection_address; if (!mongoc_server_description_has_rs_member (primary, address)) { _mongoc_array_append_val (&to_remove, member); @@ -1650,8 +1533,7 @@ _mongoc_topology_description_remove_unreported_servers ( /* now it's safe to call _mongoc_topology_description_remove_server, * even on the primary */ for (size_t i = 0u; i < to_remove.len; i++) { - const mongoc_server_description_t *member = - _mongoc_array_index (&to_remove, mongoc_server_description_t *, i); + const mongoc_server_description_t *member = _mongoc_array_index (&to_remove, mongoc_server_description_t *, i); _mongoc_topology_description_remove_server (topology, member); } @@ -1679,8 +1561,7 @@ _mongoc_topology_description_remove_unreported_servers ( *-------------------------------------------------------------------------- */ static bool -_mongoc_topology_description_matches_me ( - const mongoc_server_description_t *server) +_mongoc_topology_description_matches_me (const mongoc_server_description_t *server) { BSON_ASSERT (server->connection_address); @@ -1722,9 +1603,8 @@ _mongoc_topology_description_matches_me ( *-------------------------------------------------------------------------- */ static void -_mongoc_topology_description_update_rs_from_primary ( - mongoc_topology_description_t *topology, - const mongoc_server_description_t *server) +_mongoc_topology_description_update_rs_from_primary (mongoc_topology_description_t *topology, + const mongoc_server_description_t *server) { mongoc_primary_and_topology_t data; bson_error_t error; @@ -1732,8 +1612,7 @@ _mongoc_topology_description_update_rs_from_primary ( BSON_ASSERT (topology); BSON_ASSERT (server); - if (!_mongoc_topology_description_has_server ( - topology, server->connection_address, NULL)) + if (!_mongoc_topology_description_has_server (topology, server->connection_address, NULL)) return; /* If server->set_name was null this function wouldn't be called from @@ -1757,19 +1636,15 @@ _mongoc_topology_description_update_rs_from_primary ( _mongoc_topology_description_set_max_set_version (topology, server); } else { - bson_set_error (&error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_CONNECT, - "member's setVersion or electionId is stale"); - mongoc_topology_description_invalidate_server ( - topology, server->id, &error); + bson_set_error ( + &error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_CONNECT, "member's setVersion or electionId is stale"); + mongoc_topology_description_invalidate_server (topology, server->id, &error); _update_rs_type (topology); return; } } else { // old comparison rules, namely setVersion is checked before electionId - if (mongoc_server_description_has_set_version (server) && - mongoc_server_description_has_election_id (server)) { + if (mongoc_server_description_has_set_version (server) && mongoc_server_description_has_election_id (server)) { /* Server Discovery And Monitoring Spec: "The client remembers the * greatest electionId reported by a primary, and distrusts primaries * with lesser electionIds. This prevents the client from oscillating @@ -1777,12 +1652,9 @@ _mongoc_topology_description_update_rs_from_primary ( */ if (_mongoc_topology_description_later_election (topology, server)) { // stale primary code return: - bson_set_error (&error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_CONNECT, - "member's setVersion or electionId is stale"); - mongoc_topology_description_invalidate_server ( - topology, server->id, &error); + bson_set_error ( + &error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_CONNECT, "member's setVersion or electionId is stale"); + mongoc_topology_description_invalidate_server (topology, server->id, &error); _update_rs_type (topology); return; } @@ -1800,9 +1672,7 @@ _mongoc_topology_description_update_rs_from_primary ( /* 'Server' is the primary! Invalidate other primaries if found */ data.primary = server; data.topology = topology; - mongoc_set_for_each (mc_tpld_servers (topology), - _mongoc_topology_description_invalidate_primaries_cb, - &data); + mongoc_set_for_each (mc_tpld_servers (topology), _mongoc_topology_description_invalidate_primaries_cb, &data); /* Add to topology description any new servers primary knows about */ _mongoc_topology_description_add_new_servers (topology, server); @@ -1830,15 +1700,13 @@ _mongoc_topology_description_update_rs_from_primary ( *-------------------------------------------------------------------------- */ static void -_mongoc_topology_description_update_rs_without_primary ( - mongoc_topology_description_t *topology, - const mongoc_server_description_t *server) +_mongoc_topology_description_update_rs_without_primary (mongoc_topology_description_t *topology, + const mongoc_server_description_t *server) { BSON_ASSERT (topology); BSON_ASSERT (server); - if (!_mongoc_topology_description_has_server ( - topology, server->connection_address, NULL)) { + if (!_mongoc_topology_description_has_server (topology, server->connection_address, NULL)) { return; } @@ -1884,15 +1752,13 @@ _mongoc_topology_description_update_rs_without_primary ( *-------------------------------------------------------------------------- */ static void -_mongoc_topology_description_update_rs_with_primary_from_member ( - mongoc_topology_description_t *topology, - const mongoc_server_description_t *server) +_mongoc_topology_description_update_rs_with_primary_from_member (mongoc_topology_description_t *topology, + const mongoc_server_description_t *server) { BSON_ASSERT (topology); BSON_ASSERT (server); - if (!_mongoc_topology_description_has_server ( - topology, server->connection_address, NULL)) { + if (!_mongoc_topology_description_has_server (topology, server->connection_address, NULL)) { return; } @@ -1910,10 +1776,8 @@ _mongoc_topology_description_update_rs_with_primary_from_member ( /* If there is no primary, label server's current_primary as the * POSSIBLE_PRIMARY */ - if (!_mongoc_topology_description_has_primary (topology) && - server->current_primary) { - _mongoc_topology_description_set_state (topology, - MONGOC_TOPOLOGY_RS_NO_PRIMARY); + if (!_mongoc_topology_description_has_primary (topology) && server->current_primary) { + _mongoc_topology_description_set_state (topology, MONGOC_TOPOLOGY_RS_NO_PRIMARY); _mongoc_topology_description_label_unknown_member ( topology, server->current_primary, MONGOC_SERVER_POSSIBLE_PRIMARY); } @@ -1935,9 +1799,8 @@ _mongoc_topology_description_update_rs_with_primary_from_member ( *-------------------------------------------------------------------------- */ static void -_mongoc_topology_description_set_topology_type_to_sharded ( - mongoc_topology_description_t *topology, - const mongoc_server_description_t *server) +_mongoc_topology_description_set_topology_type_to_sharded (mongoc_topology_description_t *topology, + const mongoc_server_description_t *server) { BSON_UNUSED (server); @@ -1962,12 +1825,10 @@ _mongoc_topology_description_set_topology_type_to_sharded ( *-------------------------------------------------------------------------- */ static void -_mongoc_topology_description_transition_unknown_to_rs_no_primary ( - mongoc_topology_description_t *topology, - const mongoc_server_description_t *server) +_mongoc_topology_description_transition_unknown_to_rs_no_primary (mongoc_topology_description_t *topology, + const mongoc_server_description_t *server) { - _mongoc_topology_description_set_state (topology, - MONGOC_TOPOLOGY_RS_NO_PRIMARY); + _mongoc_topology_description_set_state (topology, MONGOC_TOPOLOGY_RS_NO_PRIMARY); _mongoc_topology_description_update_rs_without_primary (topology, server); } @@ -1987,9 +1848,8 @@ _mongoc_topology_description_transition_unknown_to_rs_no_primary ( *-------------------------------------------------------------------------- */ static void -_mongoc_topology_description_remove_and_check_primary ( - mongoc_topology_description_t *topology, - const mongoc_server_description_t *server) +_mongoc_topology_description_remove_and_check_primary (mongoc_topology_description_t *topology, + const mongoc_server_description_t *server) { _mongoc_topology_description_remove_server (topology, server); _update_rs_type (topology); @@ -2014,15 +1874,13 @@ _mongoc_topology_description_remove_and_check_primary ( *-------------------------------------------------------------------------- */ static void -_mongoc_topology_description_update_unknown_with_standalone ( - mongoc_topology_description_t *topology, - const mongoc_server_description_t *server) +_mongoc_topology_description_update_unknown_with_standalone (mongoc_topology_description_t *topology, + const mongoc_server_description_t *server) { BSON_ASSERT (topology); BSON_ASSERT (server); - if (!_mongoc_topology_description_has_server ( - topology, server->connection_address, NULL)) + if (!_mongoc_topology_description_has_server (topology, server->connection_address, NULL)) return; if (mc_tpld_servers_const (topology)->items_len > 1) { @@ -2053,59 +1911,57 @@ _mongoc_topology_description_update_unknown_with_standalone ( *-------------------------------------------------------------------------- */ -typedef void (*transition_t) (mongoc_topology_description_t *topology, - const mongoc_server_description_t *server); +typedef void (*transition_t) (mongoc_topology_description_t *topology, const mongoc_server_description_t *server); -transition_t gSDAMTransitionTable - [MONGOC_SERVER_DESCRIPTION_TYPES][MONGOC_TOPOLOGY_DESCRIPTION_TYPES] = { - { - /* UNKNOWN */ - NULL, /* MONGOC_TOPOLOGY_UNKNOWN */ - NULL, /* MONGOC_TOPOLOGY_SHARDED */ - NULL, /* MONGOC_TOPOLOGY_RS_NO_PRIMARY */ - _mongoc_topology_description_check_if_has_primary /* MONGOC_TOPOLOGY_RS_WITH_PRIMARY - */ - }, - {/* STANDALONE */ - _mongoc_topology_description_update_unknown_with_standalone, - _mongoc_topology_description_remove_server, - _mongoc_topology_description_remove_server, - _mongoc_topology_description_remove_and_check_primary}, - {/* MONGOS */ - _mongoc_topology_description_set_topology_type_to_sharded, - NULL, - _mongoc_topology_description_remove_server, - _mongoc_topology_description_remove_and_check_primary}, - {/* POSSIBLE_PRIMARY */ - NULL, - NULL, - NULL, - NULL}, - {/* PRIMARY */ - _mongoc_topology_description_update_rs_from_primary, - _mongoc_topology_description_remove_server, - _mongoc_topology_description_update_rs_from_primary, - _mongoc_topology_description_update_rs_from_primary}, - {/* SECONDARY */ - _mongoc_topology_description_transition_unknown_to_rs_no_primary, - _mongoc_topology_description_remove_server, - _mongoc_topology_description_update_rs_without_primary, - _mongoc_topology_description_update_rs_with_primary_from_member}, - {/* ARBITER */ - _mongoc_topology_description_transition_unknown_to_rs_no_primary, - _mongoc_topology_description_remove_server, - _mongoc_topology_description_update_rs_without_primary, - _mongoc_topology_description_update_rs_with_primary_from_member}, - {/* RS_OTHER */ - _mongoc_topology_description_transition_unknown_to_rs_no_primary, - _mongoc_topology_description_remove_server, - _mongoc_topology_description_update_rs_without_primary, - _mongoc_topology_description_update_rs_with_primary_from_member}, - {/* RS_GHOST */ - NULL, - _mongoc_topology_description_remove_server, - NULL, - _mongoc_topology_description_check_if_has_primary}}; +transition_t gSDAMTransitionTable[MONGOC_SERVER_DESCRIPTION_TYPES][MONGOC_TOPOLOGY_DESCRIPTION_TYPES] = { + { + /* UNKNOWN */ + NULL, /* MONGOC_TOPOLOGY_UNKNOWN */ + NULL, /* MONGOC_TOPOLOGY_SHARDED */ + NULL, /* MONGOC_TOPOLOGY_RS_NO_PRIMARY */ + _mongoc_topology_description_check_if_has_primary /* MONGOC_TOPOLOGY_RS_WITH_PRIMARY + */ + }, + {/* STANDALONE */ + _mongoc_topology_description_update_unknown_with_standalone, + _mongoc_topology_description_remove_server, + _mongoc_topology_description_remove_server, + _mongoc_topology_description_remove_and_check_primary}, + {/* MONGOS */ + _mongoc_topology_description_set_topology_type_to_sharded, + NULL, + _mongoc_topology_description_remove_server, + _mongoc_topology_description_remove_and_check_primary}, + {/* POSSIBLE_PRIMARY */ + NULL, + NULL, + NULL, + NULL}, + {/* PRIMARY */ + _mongoc_topology_description_update_rs_from_primary, + _mongoc_topology_description_remove_server, + _mongoc_topology_description_update_rs_from_primary, + _mongoc_topology_description_update_rs_from_primary}, + {/* SECONDARY */ + _mongoc_topology_description_transition_unknown_to_rs_no_primary, + _mongoc_topology_description_remove_server, + _mongoc_topology_description_update_rs_without_primary, + _mongoc_topology_description_update_rs_with_primary_from_member}, + {/* ARBITER */ + _mongoc_topology_description_transition_unknown_to_rs_no_primary, + _mongoc_topology_description_remove_server, + _mongoc_topology_description_update_rs_without_primary, + _mongoc_topology_description_update_rs_with_primary_from_member}, + {/* RS_OTHER */ + _mongoc_topology_description_transition_unknown_to_rs_no_primary, + _mongoc_topology_description_remove_server, + _mongoc_topology_description_update_rs_without_primary, + _mongoc_topology_description_update_rs_with_primary_from_member}, + {/* RS_GHOST */ + NULL, + _mongoc_topology_description_remove_server, + NULL, + _mongoc_topology_description_check_if_has_primary}}; /* *-------------------------------------------------------------------------- @@ -2164,8 +2020,7 @@ _tpld_type_str (mongoc_topology_description_type_t type) */ static void -_mongoc_topology_description_update_session_timeout ( - mongoc_topology_description_t *td) +_mongoc_topology_description_update_session_timeout (mongoc_topology_description_t *td) { mongoc_set_t *set; mongoc_server_description_t *sd; @@ -2206,42 +2061,37 @@ _mongoc_topology_description_update_session_timeout ( */ static void -_mongoc_topology_description_check_compatible ( - mongoc_topology_description_t *td) +_mongoc_topology_description_check_compatible (mongoc_topology_description_t *td) { mongoc_set_t const *const servers = mc_tpld_servers_const (td); memset (&td->compatibility_error, 0, sizeof (bson_error_t)); for (size_t i = 0; i < servers->items_len; i++) { - mongoc_server_description_t const *const sd = - mongoc_set_get_item_const (servers, i); - if (sd->type == MONGOC_SERVER_UNKNOWN || - sd->type == MONGOC_SERVER_POSSIBLE_PRIMARY) { + mongoc_server_description_t const *const sd = mongoc_set_get_item_const (servers, i); + if (sd->type == MONGOC_SERVER_UNKNOWN || sd->type == MONGOC_SERVER_POSSIBLE_PRIMARY) { continue; } if (sd->min_wire_version > WIRE_VERSION_MAX) { - bson_set_error ( - &td->compatibility_error, - MONGOC_ERROR_PROTOCOL, - MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION, - "Server at %s requires wire version %d," - " but this version of libmongoc only supports up to %d", - sd->host.host_and_port, - sd->min_wire_version, - WIRE_VERSION_MAX); + bson_set_error (&td->compatibility_error, + MONGOC_ERROR_PROTOCOL, + MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION, + "Server at %s requires wire version %d," + " but this version of libmongoc only supports up to %d", + sd->host.host_and_port, + sd->min_wire_version, + WIRE_VERSION_MAX); } else if (sd->max_wire_version < WIRE_VERSION_MIN) { - bson_set_error ( - &td->compatibility_error, - MONGOC_ERROR_PROTOCOL, - MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION, - "Server at %s reports wire version %d, but this" - " version of libmongoc requires at least %d (MongoDB %s)", - sd->host.host_and_port, - sd->max_wire_version, - WIRE_VERSION_MIN, - _mongoc_wire_version_to_server_version (WIRE_VERSION_MIN)); + bson_set_error (&td->compatibility_error, + MONGOC_ERROR_PROTOCOL, + MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION, + "Server at %s reports wire version %d, but this" + " version of libmongoc requires at least %d (MongoDB %s)", + sd->host.host_and_port, + sd->max_wire_version, + WIRE_VERSION_MIN, + _mongoc_wire_version_to_server_version (WIRE_VERSION_MIN)); } } } @@ -2259,12 +2109,11 @@ _mongoc_topology_description_check_compatible ( */ void -mongoc_topology_description_handle_hello ( - mongoc_topology_description_t *topology, - uint32_t server_id, - const bson_t *hello_response, - int64_t rtt_msec, - const bson_error_t *error /* IN */) +mongoc_topology_description_handle_hello (mongoc_topology_description_t *topology, + uint32_t server_id, + const bson_t *hello_response, + int64_t rtt_msec, + const bson_error_t *error /* IN */) { mongoc_topology_description_t *prev_td = NULL; mongoc_server_description_t *prev_sd = NULL; @@ -2287,8 +2136,7 @@ mongoc_topology_description_handle_hello ( _mongoc_topology_description_copy_to (topology, prev_td); } - if (hello_response && - bson_iter_init_find (&iter, hello_response, "topologyVersion") && + if (hello_response && bson_iter_init_find (&iter, hello_response, "topologyVersion") && BSON_ITER_HOLDS_DOCUMENT (&iter)) { bson_t incoming_topology_version; const uint8_t *bytes; @@ -2297,8 +2145,7 @@ mongoc_topology_description_handle_hello ( bson_iter_document (&iter, &len, &bytes); BSON_ASSERT (bson_init_static (&incoming_topology_version, bytes, len)); - if (mongoc_server_description_topology_version_cmp ( - &sd->topology_version, &incoming_topology_version) == 1) { + if (mongoc_server_description_topology_version_cmp (&sd->topology_version, &incoming_topology_version) == 1) { TRACE ("%s", "topology version is strictly less. Skipping."); if (prev_td) { mongoc_topology_description_cleanup (prev_td); @@ -2308,8 +2155,7 @@ mongoc_topology_description_handle_hello ( } } - if (topology->apm_callbacks.topology_changed || - topology->apm_callbacks.server_changed) { + if (topology->apm_callbacks.topology_changed || topology->apm_callbacks.server_changed) { /* Only copy the previous server description if a monitoring callback is * registered. */ prev_sd = mongoc_server_description_new_copy (sd); @@ -2347,8 +2193,7 @@ mongoc_topology_description_handle_hello ( if (wrong_set_name) { /* Replace with unknown. */ TRACE ("%s", "wrong set name"); - mongoc_server_description_handle_hello ( - sd, NULL, MONGOC_RTT_UNSET, &set_name_err); + mongoc_server_description_handle_hello (sd, NULL, MONGOC_RTT_UNSET, &set_name_err); } } @@ -2358,8 +2203,7 @@ mongoc_topology_description_handle_hello ( sd_changed = !_mongoc_server_description_equal (prev_sd, sd); } if (sd_changed) { - _mongoc_topology_description_monitor_server_changed ( - topology, prev_sd, sd); + _mongoc_topology_description_monitor_server_changed (topology, prev_sd, sd); } if (gSDAMTransitionTable[sd->type][topology->type]) { @@ -2408,8 +2252,8 @@ mongoc_topology_description_handle_hello ( *-------------------------------------------------------------------------- */ bool -mongoc_topology_description_has_readable_server ( - const mongoc_topology_description_t *td, const mongoc_read_prefs_t *prefs) +mongoc_topology_description_has_readable_server (const mongoc_topology_description_t *td, + const mongoc_read_prefs_t *prefs) { bson_error_t error; @@ -2418,8 +2262,7 @@ mongoc_topology_description_has_readable_server ( } /* local threshold argument doesn't matter */ - return mongoc_topology_description_select ( - td, MONGOC_SS_READ, prefs, NULL, NULL, 0) != NULL; + return mongoc_topology_description_select (td, MONGOC_SS_READ, prefs, NULL, NULL, 0) != NULL; } /* @@ -2436,8 +2279,7 @@ mongoc_topology_description_has_readable_server ( *-------------------------------------------------------------------------- */ bool -mongoc_topology_description_has_writable_server ( - const mongoc_topology_description_t *td) +mongoc_topology_description_has_writable_server (const mongoc_topology_description_t *td) { bson_error_t error; @@ -2445,8 +2287,7 @@ mongoc_topology_description_has_writable_server ( return false; } - return mongoc_topology_description_select ( - td, MONGOC_SS_WRITE, NULL, NULL, NULL, 0) != NULL; + return mongoc_topology_description_select (td, MONGOC_SS_WRITE, NULL, NULL, NULL, 0) != NULL; } /* @@ -2504,22 +2345,18 @@ mongoc_topology_description_type (const mongoc_topology_description_t *td) *-------------------------------------------------------------------------- */ mongoc_server_description_t ** -mongoc_topology_description_get_servers ( - const mongoc_topology_description_t *td, size_t *n /* OUT */) +mongoc_topology_description_get_servers (const mongoc_topology_description_t *td, size_t *n /* OUT */) { - const mongoc_set_t *const set = - mc_tpld_servers_const (BSON_ASSERT_PTR_INLINE (td)); + const mongoc_set_t *const set = mc_tpld_servers_const (BSON_ASSERT_PTR_INLINE (td)); /* enough room for all descriptions, even if some are unknown */ - mongoc_server_description_t **sds = - bson_malloc0 (sizeof (mongoc_server_description_t *) * set->items_len); + mongoc_server_description_t **sds = bson_malloc0 (sizeof (mongoc_server_description_t *) * set->items_len); BSON_ASSERT_PARAM (n); *n = 0; for (size_t i = 0; i < set->items_len; ++i) { - const mongoc_server_description_t *sd = - mongoc_set_get_item_const (set, i); + const mongoc_server_description_t *sd = mongoc_set_get_item_const (set, i); if (sd->type != MONGOC_SERVER_UNKNOWN) { sds[*n] = mongoc_server_description_new_copy (sd); @@ -2579,8 +2416,7 @@ _remove_if_not_in_host_list_cb (void *sd_void, void *ctx_void) } void -mongoc_topology_description_reconcile (mongoc_topology_description_t *td, - mongoc_host_list_t *host_list) +mongoc_topology_description_reconcile (mongoc_topology_description_t *td, mongoc_host_list_t *host_list) { mongoc_set_t *servers; size_t host_list_length; @@ -2632,12 +2468,10 @@ mongoc_topology_description_reconcile (mongoc_topology_description_t *td, * Do not limit size of results yet (pass host_list_length) as we want to * update any existing hosts in the topology, but add new hosts. */ - const mongoc_host_list_t *const *hl_array = _mongoc_apply_srv_max_hosts ( - host_list, host_list_length, &hl_array_size); + const mongoc_host_list_t *const *hl_array = + _mongoc_apply_srv_max_hosts (host_list, host_list_length, &hl_array_size); - for (idx = 0u; - servers->items_len < max_with_missing && idx < hl_array_size; - ++idx) { + for (idx = 0u; servers->items_len < max_with_missing && idx < hl_array_size; ++idx) { const mongoc_host_list_t *const elem = hl_array[idx]; /* "add" is really an "upsert" */ @@ -2667,16 +2501,14 @@ mongoc_topology_description_reconcile (mongoc_topology_description_t *td, /* At this point, the number of hosts in the host list should not exceed * srvMaxHosts. */ - BSON_ASSERT (td->max_hosts == 0 || - servers->items_len <= (size_t) td->max_hosts); + BSON_ASSERT (td->max_hosts == 0 || servers->items_len <= (size_t) td->max_hosts); } void -_mongoc_topology_description_clear_connection_pool ( - mongoc_topology_description_t *td, - uint32_t server_id, - const bson_oid_t *service_id) +_mongoc_topology_description_clear_connection_pool (mongoc_topology_description_t *td, + uint32_t server_id, + const bson_oid_t *service_id) { mongoc_server_description_t *sd; bson_error_t error; @@ -2696,18 +2528,15 @@ _mongoc_topology_description_clear_connection_pool ( void -mongoc_deprioritized_servers_add_if_sharded ( - mongoc_deprioritized_servers_t *ds, - mongoc_topology_description_type_t topology_type, - const mongoc_server_description_t *sd) +mongoc_deprioritized_servers_add_if_sharded (mongoc_deprioritized_servers_t *ds, + mongoc_topology_description_type_t topology_type, + const mongoc_server_description_t *sd) { // In a sharded cluster, the server on which the operation failed MUST // be provided to the server selection mechanism as a deprioritized // server. if (topology_type == MONGOC_TOPOLOGY_SHARDED) { - TRACE ("deprioritization: add to list: %s (id: %" PRIu32 ")", - sd->host.host_and_port, - sd->id); + TRACE ("deprioritization: add to list: %s (id: %" PRIu32 ")", sd->host.host_and_port, sd->id); mongoc_deprioritized_servers_add (ds, sd); } } diff --git a/src/libmongoc/src/mongoc/mongoc-topology-description.h b/src/libmongoc/src/mongoc/mongoc-topology-description.h index 75b7fbca26..cd45957ebe 100644 --- a/src/libmongoc/src/mongoc/mongoc-topology-description.h +++ b/src/libmongoc/src/mongoc/mongoc-topology-description.h @@ -30,29 +30,24 @@ BSON_BEGIN_DECLS typedef struct _mongoc_topology_description_t mongoc_topology_description_t; MONGOC_EXPORT (void) -mongoc_topology_description_destroy ( - mongoc_topology_description_t *description); +mongoc_topology_description_destroy (mongoc_topology_description_t *description); MONGOC_EXPORT (mongoc_topology_description_t *) -mongoc_topology_description_new_copy ( - const mongoc_topology_description_t *description) - BSON_GNUC_WARN_UNUSED_RESULT; +mongoc_topology_description_new_copy (const mongoc_topology_description_t *description) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (bool) -mongoc_topology_description_has_readable_server ( - const mongoc_topology_description_t *td, const mongoc_read_prefs_t *prefs); +mongoc_topology_description_has_readable_server (const mongoc_topology_description_t *td, + const mongoc_read_prefs_t *prefs); MONGOC_EXPORT (bool) -mongoc_topology_description_has_writable_server ( - const mongoc_topology_description_t *td); +mongoc_topology_description_has_writable_server (const mongoc_topology_description_t *td); MONGOC_EXPORT (const char *) mongoc_topology_description_type (const mongoc_topology_description_t *td); MONGOC_EXPORT (mongoc_server_description_t **) -mongoc_topology_description_get_servers ( - const mongoc_topology_description_t *td, - size_t *n) BSON_GNUC_WARN_UNUSED_RESULT; +mongoc_topology_description_get_servers (const mongoc_topology_description_t *td, + size_t *n) BSON_GNUC_WARN_UNUSED_RESULT; BSON_END_DECLS diff --git a/src/libmongoc/src/mongoc/mongoc-topology-private.h b/src/libmongoc/src/mongoc/mongoc-topology-private.h index 2681001a95..19f816dc45 100644 --- a/src/libmongoc/src/mongoc/mongoc-topology-private.h +++ b/src/libmongoc/src/mongoc/mongoc-topology-private.h @@ -73,14 +73,13 @@ typedef struct _mongoc_rr_data_t { struct _mongoc_topology_t; -MONGOC_DECL_SPECIAL_TS_POOL ( - mongoc_server_session_t, - mongoc_server_session_pool, - struct _mongoc_topology_t, - /* ctor/dtor/prune are defined in the new_with_params call */ - NULL, - NULL, - NULL) +MONGOC_DECL_SPECIAL_TS_POOL (mongoc_server_session_t, + mongoc_server_session_pool, + struct _mongoc_topology_t, + /* ctor/dtor/prune are defined in the new_with_params call */ + NULL, + NULL, + NULL) typedef bool (*_mongoc_rr_resolver_fn) (const char *hostname, mongoc_rr_type_t rr_type, @@ -233,8 +232,7 @@ void mongoc_topology_destroy (mongoc_topology_t *topology); void -mongoc_topology_reconcile (const mongoc_topology_t *topology, - mongoc_topology_description_t *td); +mongoc_topology_reconcile (const mongoc_topology_t *topology, mongoc_topology_description_t *td); bool mongoc_topology_compatible (const mongoc_topology_description_t *td, @@ -313,9 +311,7 @@ mongoc_topology_select_server_id (mongoc_topology_t *topology, * `_mongoc_host_list_destroy_all()` */ mongoc_host_list_t * -_mongoc_topology_host_by_id (const mongoc_topology_description_t *topology, - uint32_t id, - bson_error_t *error); +_mongoc_topology_host_by_id (const mongoc_topology_description_t *topology, uint32_t id, bson_error_t *error); /** * @brief Update the topology from the response to a handshake on a new @@ -330,12 +326,10 @@ _mongoc_topology_host_by_id (const mongoc_topology_description_t *topology, * @return false If the server was already removed from the topology. */ bool -_mongoc_topology_update_from_handshake (mongoc_topology_t *topology, - const mongoc_server_description_t *sd); +_mongoc_topology_update_from_handshake (mongoc_topology_t *topology, const mongoc_server_description_t *sd); void -_mongoc_topology_update_last_used (mongoc_topology_t *topology, - uint32_t server_id); +_mongoc_topology_update_last_used (mongoc_topology_t *topology, uint32_t server_id); int64_t mongoc_topology_server_timestamp (mongoc_topology_t *topology, uint32_t id); @@ -350,23 +344,19 @@ bool _mongoc_topology_set_appname (mongoc_topology_t *topology, const char *appname); void -_mongoc_topology_update_cluster_time (mongoc_topology_t *topology, - const bson_t *reply); +_mongoc_topology_update_cluster_time (mongoc_topology_t *topology, const bson_t *reply); mongoc_server_session_t * -_mongoc_topology_pop_server_session (mongoc_topology_t *topology, - bson_error_t *error); +_mongoc_topology_pop_server_session (mongoc_topology_t *topology, bson_error_t *error); void -_mongoc_topology_push_server_session (mongoc_topology_t *topology, - mongoc_server_session_t *server_session); +_mongoc_topology_push_server_session (mongoc_topology_t *topology, mongoc_server_session_t *server_session); bool _mongoc_topology_end_sessions_cmd (mongoc_topology_t *topology, bson_t *cmd); void -_mongoc_topology_do_blocking_scan (mongoc_topology_t *topology, - bson_error_t *error); +_mongoc_topology_do_blocking_scan (mongoc_topology_t *topology, bson_error_t *error); /** * @brief Duplicate the handshake command of the topology scanner. @@ -383,8 +373,7 @@ _mongoc_topology_do_blocking_scan (mongoc_topology_t *topology, * node in _mongoc_stream_run_hello. */ void -_mongoc_topology_dup_handshake_cmd (const mongoc_topology_t *topology, - bson_t *copy_into); +_mongoc_topology_dup_handshake_cmd (const mongoc_topology_t *topology, bson_t *copy_into); void _mongoc_topology_request_scan (mongoc_topology_t *topology); @@ -443,16 +432,14 @@ mongoc_topology_should_rescan_srv (mongoc_topology_t *topology); * Callers should call this before monitoring starts. */ void -_mongoc_topology_set_rr_resolver (mongoc_topology_t *topology, - _mongoc_rr_resolver_fn rr_resolver); +_mongoc_topology_set_rr_resolver (mongoc_topology_t *topology, _mongoc_rr_resolver_fn rr_resolver); /* _mongoc_topology_set_srv_polling_rescan_interval_ms is called by tests to * shorten the rescan interval. * Callers should call this before monitoring starts. */ void -_mongoc_topology_set_srv_polling_rescan_interval_ms ( - mongoc_topology_t *topology, int64_t val); +_mongoc_topology_set_srv_polling_rescan_interval_ms (mongoc_topology_t *topology, int64_t val); /** * @brief Return the latest connection generation for the server_id and/or @@ -468,10 +455,9 @@ _mongoc_topology_set_srv_polling_rescan_interval_ms ( * server does not exist in the topology. */ uint32_t -_mongoc_topology_get_connection_pool_generation ( - const mongoc_topology_description_t *td, - uint32_t server_id, - const bson_oid_t *service_id); +_mongoc_topology_get_connection_pool_generation (const mongoc_topology_description_t *td, + uint32_t server_id, + const bson_oid_t *service_id); /** * @brief Obtain a reference to the current topology description for the given @@ -484,8 +470,7 @@ _mongoc_topology_get_connection_pool_generation ( static BSON_INLINE mc_shared_tpld mc_tpld_take_ref (const mongoc_topology_t *tpl) { - return (mc_shared_tpld){ - ._sptr_ = mongoc_atomic_shared_ptr_load (&tpl->_shared_descr_._sptr_)}; + return (mc_shared_tpld){._sptr_ = mongoc_atomic_shared_ptr_load (&tpl->_shared_descr_._sptr_)}; } /** @@ -611,10 +596,8 @@ _mongoc_topology_invalidate_server (mongoc_topology_t *td, uint32_t server_id) { bson_error_t error; mc_tpld_modification tdmod = mc_tpld_modify_begin (td); - bson_set_error ( - &error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_CONNECT, "invalidated"); - mongoc_topology_description_invalidate_server ( - tdmod.new_td, server_id, &error); + bson_set_error (&error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_CONNECT, "invalidated"); + mongoc_topology_description_invalidate_server (tdmod.new_td, server_id, &error); mc_tpld_modify_commit (tdmod); } @@ -626,9 +609,7 @@ _mongoc_topology_invalidate_server (mongoc_topology_t *td, uint32_t server_id) * array must not be freed, as they are still owned by `hl`. */ const mongoc_host_list_t ** -_mongoc_apply_srv_max_hosts (const mongoc_host_list_t *hl, - size_t max_hosts, - size_t *hl_array_size); +_mongoc_apply_srv_max_hosts (const mongoc_host_list_t *hl, size_t max_hosts, size_t *hl_array_size); /* Returns true if a versioned server API has been selected, otherwise returns diff --git a/src/libmongoc/src/mongoc/mongoc-topology-scanner-private.h b/src/libmongoc/src/mongoc/mongoc-topology-scanner-private.h index 01e826fef8..9303309ddc 100644 --- a/src/libmongoc/src/mongoc/mongoc-topology-scanner-private.h +++ b/src/libmongoc/src/mongoc/mongoc-topology-scanner-private.h @@ -35,15 +35,10 @@ BSON_BEGIN_DECLS -typedef void (*mongoc_topology_scanner_setup_err_cb_t) ( - uint32_t id, void *data, const bson_error_t *error /* IN */); +typedef void (*mongoc_topology_scanner_setup_err_cb_t) (uint32_t id, void *data, const bson_error_t *error /* IN */); typedef void (*mongoc_topology_scanner_cb_t) ( - uint32_t id, - const bson_t *bson, - int64_t rtt, - void *data, - const bson_error_t *error /* IN */); + uint32_t id, const bson_t *bson, int64_t rtt, void *data, const bson_error_t *error /* IN */); struct mongoc_topology_scanner; struct mongoc_topology_scanner_node; @@ -145,12 +140,11 @@ typedef struct mongoc_topology_scanner { } mongoc_topology_scanner_t; mongoc_topology_scanner_t * -mongoc_topology_scanner_new ( - const mongoc_uri_t *uri, - mongoc_topology_scanner_setup_err_cb_t setup_err_cb, - mongoc_topology_scanner_cb_t cb, - void *data, - int64_t connect_timeout_msec); +mongoc_topology_scanner_new (const mongoc_uri_t *uri, + mongoc_topology_scanner_setup_err_cb_t setup_err_cb, + mongoc_topology_scanner_cb_t cb, + void *data, + int64_t connect_timeout_msec); void mongoc_topology_scanner_destroy (mongoc_topology_scanner_t *ts); @@ -159,10 +153,7 @@ bool mongoc_topology_scanner_valid (mongoc_topology_scanner_t *ts); void -mongoc_topology_scanner_add (mongoc_topology_scanner_t *ts, - const mongoc_host_list_t *host, - uint32_t id, - bool hello_ok); +mongoc_topology_scanner_add (mongoc_topology_scanner_t *ts, const mongoc_host_list_t *host, uint32_t id, bool hello_ok); void mongoc_topology_scanner_scan (mongoc_topology_scanner_t *ts, uint32_t id); @@ -174,20 +165,16 @@ void mongoc_topology_scanner_node_retire (mongoc_topology_scanner_node_t *node); void -mongoc_topology_scanner_node_disconnect (mongoc_topology_scanner_node_t *node, - bool failed); +mongoc_topology_scanner_node_disconnect (mongoc_topology_scanner_node_t *node, bool failed); void -mongoc_topology_scanner_node_destroy (mongoc_topology_scanner_node_t *node, - bool failed); +mongoc_topology_scanner_node_destroy (mongoc_topology_scanner_node_t *node, bool failed); bool -mongoc_topology_scanner_in_cooldown (mongoc_topology_scanner_t *ts, - int64_t when); +mongoc_topology_scanner_in_cooldown (mongoc_topology_scanner_t *ts, int64_t when); void -mongoc_topology_scanner_start (mongoc_topology_scanner_t *ts, - bool obey_cooldown); +mongoc_topology_scanner_start (mongoc_topology_scanner_t *ts, bool obey_cooldown); void mongoc_topology_scanner_work (mongoc_topology_scanner_t *ts); @@ -196,37 +183,31 @@ void _mongoc_topology_scanner_finish (mongoc_topology_scanner_t *ts); void -mongoc_topology_scanner_get_error (mongoc_topology_scanner_t *ts, - bson_error_t *error); +mongoc_topology_scanner_get_error (mongoc_topology_scanner_t *ts, bson_error_t *error); void mongoc_topology_scanner_reset (mongoc_topology_scanner_t *ts); void -mongoc_topology_scanner_node_setup (mongoc_topology_scanner_node_t *node, - bson_error_t *error); +mongoc_topology_scanner_node_setup (mongoc_topology_scanner_node_t *node, bson_error_t *error); mongoc_topology_scanner_node_t * mongoc_topology_scanner_get_node (mongoc_topology_scanner_t *ts, uint32_t id); void -_mongoc_topology_scanner_add_speculative_authentication ( - bson_t *cmd, - const mongoc_uri_t *uri, - const mongoc_ssl_opt_t *ssl_opts, - mongoc_scram_t *scram /* OUT */); +_mongoc_topology_scanner_add_speculative_authentication (bson_t *cmd, + const mongoc_uri_t *uri, + const mongoc_ssl_opt_t *ssl_opts, + mongoc_scram_t *scram /* OUT */); void -_mongoc_topology_scanner_parse_speculative_authentication ( - const bson_t *hello, bson_t *speculative_authenticate); +_mongoc_topology_scanner_parse_speculative_authentication (const bson_t *hello, bson_t *speculative_authenticate); const char * -_mongoc_topology_scanner_get_speculative_auth_mechanism ( - const mongoc_uri_t *uri); +_mongoc_topology_scanner_get_speculative_auth_mechanism (const mongoc_uri_t *uri); const bson_t * -_mongoc_topology_scanner_get_monitoring_cmd (mongoc_topology_scanner_t *ts, - bool hello_ok); +_mongoc_topology_scanner_get_monitoring_cmd (mongoc_topology_scanner_t *ts, bool hello_ok); /** * @brief Get the scanner's associated handshake command BSON document. @@ -236,45 +217,34 @@ _mongoc_topology_scanner_get_monitoring_cmd (mongoc_topology_scanner_t *ts, * will be copied into the pointee. */ void -_mongoc_topology_scanner_dup_handshake_cmd (mongoc_topology_scanner_t *ts, - bson_t *copy_into); +_mongoc_topology_scanner_dup_handshake_cmd (mongoc_topology_scanner_t *ts, bson_t *copy_into); bool -mongoc_topology_scanner_has_node_for_host (mongoc_topology_scanner_t *ts, - mongoc_host_list_t *host); +mongoc_topology_scanner_has_node_for_host (mongoc_topology_scanner_t *ts, mongoc_host_list_t *host); void -mongoc_topology_scanner_set_stream_initiator (mongoc_topology_scanner_t *ts, - mongoc_stream_initiator_t si, - void *ctx); +mongoc_topology_scanner_set_stream_initiator (mongoc_topology_scanner_t *ts, mongoc_stream_initiator_t si, void *ctx); bool -_mongoc_topology_scanner_set_appname (mongoc_topology_scanner_t *ts, - const char *name); +_mongoc_topology_scanner_set_appname (mongoc_topology_scanner_t *ts, const char *name); void -_mongoc_topology_scanner_set_cluster_time (mongoc_topology_scanner_t *ts, - const bson_t *cluster_time); +_mongoc_topology_scanner_set_cluster_time (mongoc_topology_scanner_t *ts, const bson_t *cluster_time); void -_mongoc_topology_scanner_set_dns_cache_timeout (mongoc_topology_scanner_t *ts, - int64_t timeout_ms); +_mongoc_topology_scanner_set_dns_cache_timeout (mongoc_topology_scanner_t *ts, int64_t timeout_ms); #ifdef MONGOC_ENABLE_SSL void -mongoc_topology_scanner_set_ssl_opts (mongoc_topology_scanner_t *ts, - mongoc_ssl_opt_t *opts); +mongoc_topology_scanner_set_ssl_opts (mongoc_topology_scanner_t *ts, mongoc_ssl_opt_t *opts); #endif bool -mongoc_topology_scanner_node_in_cooldown (mongoc_topology_scanner_node_t *node, - int64_t when); +mongoc_topology_scanner_node_in_cooldown (mongoc_topology_scanner_node_t *node, int64_t when); void -_mongoc_topology_scanner_set_server_api (mongoc_topology_scanner_t *ts, - const mongoc_server_api_t *api); +_mongoc_topology_scanner_set_server_api (mongoc_topology_scanner_t *ts, const mongoc_server_api_t *api); void -_mongoc_topology_scanner_set_loadbalanced (mongoc_topology_scanner_t *ts, - bool val); +_mongoc_topology_scanner_set_loadbalanced (mongoc_topology_scanner_t *ts, bool val); /* for testing. */ mongoc_stream_t * diff --git a/src/libmongoc/src/mongoc/mongoc-topology-scanner.c b/src/libmongoc/src/mongoc/mongoc-topology-scanner.c index f8065b57b2..0cea51831f 100644 --- a/src/libmongoc/src/mongoc/mongoc-topology-scanner.c +++ b/src/libmongoc/src/mongoc/mongoc-topology-scanner.c @@ -50,14 +50,10 @@ static void _async_connected (mongoc_async_cmd_t *acmd); static void -_async_success (mongoc_async_cmd_t *acmd, - const bson_t *hello_response, - int64_t duration_usec); +_async_success (mongoc_async_cmd_t *acmd, const bson_t *hello_response, int64_t duration_usec); static void -_async_error_or_timeout (mongoc_async_cmd_t *acmd, - int64_t duration_usec, - const char *default_err_msg); +_async_error_or_timeout (mongoc_async_cmd_t *acmd, int64_t duration_usec, const char *default_err_msg); static void _async_handler (mongoc_async_cmd_t *acmd, @@ -66,22 +62,20 @@ _async_handler (mongoc_async_cmd_t *acmd, int64_t duration_usec); static void -_mongoc_topology_scanner_monitor_heartbeat_started ( - const mongoc_topology_scanner_t *ts, const mongoc_host_list_t *host); +_mongoc_topology_scanner_monitor_heartbeat_started (const mongoc_topology_scanner_t *ts, + const mongoc_host_list_t *host); static void -_mongoc_topology_scanner_monitor_heartbeat_succeeded ( - const mongoc_topology_scanner_t *ts, - const mongoc_host_list_t *host, - const bson_t *reply, - int64_t duration_usec); +_mongoc_topology_scanner_monitor_heartbeat_succeeded (const mongoc_topology_scanner_t *ts, + const mongoc_host_list_t *host, + const bson_t *reply, + int64_t duration_usec); static void -_mongoc_topology_scanner_monitor_heartbeat_failed ( - const mongoc_topology_scanner_t *ts, - const mongoc_host_list_t *host, - const bson_error_t *error, - int64_t duration_usec); +_mongoc_topology_scanner_monitor_heartbeat_failed (const mongoc_topology_scanner_t *ts, + const mongoc_host_list_t *host, + const bson_error_t *error, + int64_t duration_usec); /* reset "retired" nodes that failed or were removed in the previous scan */ @@ -91,8 +85,7 @@ _delete_retired_nodes (mongoc_topology_scanner_t *ts); /* cancel any pending async commands for a specific node excluding acmd. * If acmd is NULL, cancel all async commands on the node. */ static void -_cancel_commands_excluding (mongoc_topology_scanner_node_t *node, - mongoc_async_cmd_t *acmd); +_cancel_commands_excluding (mongoc_topology_scanner_node_t *node, mongoc_async_cmd_t *acmd); /* return the number of pending async commands for a node. */ static int @@ -100,8 +93,7 @@ _count_acmds (mongoc_topology_scanner_node_t *node); /* if acmd fails, schedule the sibling commands sooner. */ static void -_jumpstart_other_acmds (mongoc_topology_scanner_node_t *node, - mongoc_async_cmd_t *acmd); +_jumpstart_other_acmds (mongoc_topology_scanner_node_t *node, mongoc_async_cmd_t *acmd); static void _add_hello (mongoc_topology_scanner_t *ts) @@ -148,8 +140,7 @@ _reset_hello (mongoc_topology_scanner_t *ts) } const char * -_mongoc_topology_scanner_get_speculative_auth_mechanism ( - const mongoc_uri_t *uri) +_mongoc_topology_scanner_get_speculative_auth_mechanism (const mongoc_uri_t *uri) { const char *mechanism = mongoc_uri_get_auth_mechanism (uri); bool requires_auth = mechanism || mongoc_uri_get_username (uri); @@ -166,17 +157,15 @@ _mongoc_topology_scanner_get_speculative_auth_mechanism ( } void -_mongoc_topology_scanner_add_speculative_authentication ( - bson_t *cmd, - const mongoc_uri_t *uri, - const mongoc_ssl_opt_t *ssl_opts, - mongoc_scram_t *scram /* OUT */) +_mongoc_topology_scanner_add_speculative_authentication (bson_t *cmd, + const mongoc_uri_t *uri, + const mongoc_ssl_opt_t *ssl_opts, + mongoc_scram_t *scram /* OUT */) { bson_t auth_cmd; bson_error_t error; bool has_auth = false; - const char *mechanism = - _mongoc_topology_scanner_get_speculative_auth_mechanism (uri); + const char *mechanism = _mongoc_topology_scanner_get_speculative_auth_mechanism (uri); if (!mechanism) { return; @@ -186,28 +175,23 @@ _mongoc_topology_scanner_add_speculative_authentication ( /* Ignore errors while building authentication document: we proceed with * the handshake as usual and let the subsequent authenticate command * fail. */ - if (_mongoc_cluster_get_auth_cmd_x509 ( - uri, ssl_opts, &auth_cmd, &error)) { + if (_mongoc_cluster_get_auth_cmd_x509 (uri, ssl_opts, &auth_cmd, &error)) { has_auth = true; BSON_APPEND_UTF8 (&auth_cmd, "db", "$external"); } } #ifdef MONGOC_ENABLE_CRYPTO - if (strcasecmp (mechanism, "SCRAM-SHA-1") == 0 || - strcasecmp (mechanism, "SCRAM-SHA-256") == 0) { + if (strcasecmp (mechanism, "SCRAM-SHA-1") == 0 || strcasecmp (mechanism, "SCRAM-SHA-256") == 0) { mongoc_crypto_hash_algorithm_t algo = - strcasecmp (mechanism, "SCRAM-SHA-1") == 0 - ? MONGOC_CRYPTO_ALGORITHM_SHA_1 - : MONGOC_CRYPTO_ALGORITHM_SHA_256; + strcasecmp (mechanism, "SCRAM-SHA-1") == 0 ? MONGOC_CRYPTO_ALGORITHM_SHA_1 : MONGOC_CRYPTO_ALGORITHM_SHA_256; _mongoc_uri_init_scram (uri, scram, algo); if (_mongoc_cluster_get_auth_cmd_scram (algo, scram, &auth_cmd, &error)) { const char *auth_source; - if (!(auth_source = mongoc_uri_get_auth_source (uri)) || - (*auth_source == '\0')) { + if (!(auth_source = mongoc_uri_get_auth_source (uri)) || (*auth_source == '\0')) { auth_source = "admin"; } @@ -224,8 +208,7 @@ _mongoc_topology_scanner_add_speculative_authentication ( } void -_mongoc_topology_scanner_parse_speculative_authentication ( - const bson_t *hello, bson_t *speculative_authenticate) +_mongoc_topology_scanner_parse_speculative_authentication (const bson_t *hello, bson_t *speculative_authenticate) { bson_iter_t iter; uint32_t data_len; @@ -247,10 +230,7 @@ _mongoc_topology_scanner_parse_speculative_authentication ( } static bson_t * -_build_handshake_cmd (const bson_t *basis_cmd, - const char *appname, - const mongoc_uri_t *uri, - bool is_loadbalanced) +_build_handshake_cmd (const bson_t *basis_cmd, const char *appname, const mongoc_uri_t *uri, bool is_loadbalanced) { bson_t *doc = bson_copy (basis_cmd); bson_iter_t iter; @@ -258,8 +238,7 @@ _build_handshake_cmd (const bson_t *basis_cmd, bson_array_builder_t *subarray; BSON_ASSERT (doc); - bson_t *handshake_doc = - _mongoc_handshake_build_doc_with_application (appname); + bson_t *handshake_doc = _mongoc_handshake_build_doc_with_application (appname); if (!handshake_doc) { bson_destroy (doc); @@ -274,8 +253,7 @@ _build_handshake_cmd (const bson_t *basis_cmd, if (bson_iter_init (&iter, compressors)) { while (bson_iter_next (&iter)) { - bson_array_builder_append_utf8 ( - subarray, bson_iter_key (&iter), -1); + bson_array_builder_append_utf8 (subarray, bson_iter_key (&iter), -1); } } } @@ -292,21 +270,17 @@ _build_handshake_cmd (const bson_t *basis_cmd, static bool _should_use_op_msg (const mongoc_topology_scanner_t *ts) { - return mongoc_topology_scanner_uses_server_api (ts) || - mongoc_topology_scanner_uses_loadbalanced (ts); + return mongoc_topology_scanner_uses_server_api (ts) || mongoc_topology_scanner_uses_loadbalanced (ts); } const bson_t * -_mongoc_topology_scanner_get_monitoring_cmd (mongoc_topology_scanner_t *ts, - bool hello_ok) +_mongoc_topology_scanner_get_monitoring_cmd (mongoc_topology_scanner_t *ts, bool hello_ok) { - return hello_ok || _should_use_op_msg (ts) ? &ts->hello_cmd - : &ts->legacy_hello_cmd; + return hello_ok || _should_use_op_msg (ts) ? &ts->hello_cmd : &ts->legacy_hello_cmd; } void -_mongoc_topology_scanner_dup_handshake_cmd (mongoc_topology_scanner_t *ts, - bson_t *copy_into) +_mongoc_topology_scanner_dup_handshake_cmd (mongoc_topology_scanner_t *ts, bson_t *copy_into) { bson_t *new_cmd; const char *appname; @@ -315,8 +289,7 @@ _mongoc_topology_scanner_dup_handshake_cmd (mongoc_topology_scanner_t *ts, /* appname will only be changed from NULL, so a non-null pointer will never * be invalidated after this fetch. */ - appname = - bson_atomic_ptr_fetch ((void *) &ts->appname, bson_memory_order_relaxed); + appname = bson_atomic_ptr_fetch ((void *) &ts->appname, bson_memory_order_relaxed); bson_mutex_lock (&ts->handshake_cmd_mtx); /* If this is the first time using the node or if it's the first time @@ -333,10 +306,7 @@ _mongoc_topology_scanner_dup_handshake_cmd (mongoc_topology_scanner_t *ts, BSON_ASSERT (ts->handshake_cmd == NULL); bson_mutex_unlock (&ts->handshake_cmd_mtx); new_cmd = _build_handshake_cmd ( - _should_use_op_msg (ts) ? &ts->hello_cmd : &ts->legacy_hello_cmd, - appname, - ts->uri, - ts->loadbalanced); + _should_use_op_msg (ts) ? &ts->hello_cmd : &ts->legacy_hello_cmd, appname, ts->uri, ts->loadbalanced); bson_mutex_lock (&ts->handshake_cmd_mtx); if (ts->handshake_state != HANDSHAKE_CMD_UNINITIALIZED) { /* Someone else updated the handshake_cmd while we were building ours. @@ -349,8 +319,7 @@ _mongoc_topology_scanner_dup_handshake_cmd (mongoc_topology_scanner_t *ts, ts->handshake_cmd = new_cmd; /* The "_build" may have failed. */ /* Even if new_cmd is NULL, this is still what we want */ - ts->handshake_state = - new_cmd == NULL ? HANDSHAKE_CMD_TOO_BIG : HANDSHAKE_CMD_OKAY; + ts->handshake_state = new_cmd == NULL ? HANDSHAKE_CMD_TOO_BIG : HANDSHAKE_CMD_OKAY; if (ts->handshake_state == HANDSHAKE_CMD_TOO_BIG) { MONGOC_WARNING ("Handshake doc too big, not including in hello"); } @@ -358,8 +327,7 @@ _mongoc_topology_scanner_dup_handshake_cmd (mongoc_topology_scanner_t *ts, after_init: /* If the doc turned out to be too big */ if (ts->handshake_state == HANDSHAKE_CMD_TOO_BIG) { - bson_t *ret = - _should_use_op_msg (ts) ? &ts->hello_cmd : &ts->legacy_hello_cmd; + bson_t *ret = _should_use_op_msg (ts) ? &ts->hello_cmd : &ts->legacy_hello_cmd; bson_copy_to (ret, copy_into); } else { BSON_ASSERT (ts->handshake_cmd != NULL); @@ -381,33 +349,28 @@ _begin_hello_cmd (mongoc_topology_scanner_node_t *node, /* If we're asked to use a specific API version, we should send our hello handshake via op_msg rather than the legacy op_query: */ - const int32_t cmd_opcode = - _should_use_op_msg (ts) ? MONGOC_OP_CODE_MSG : MONGOC_OP_CODE_QUERY; + const int32_t cmd_opcode = _should_use_op_msg (ts) ? MONGOC_OP_CODE_MSG : MONGOC_OP_CODE_QUERY; if (node->last_used != -1 && node->last_failed == -1 && !use_handshake) { /* The node's been used before and not failed recently */ - bson_copy_to ( - _mongoc_topology_scanner_get_monitoring_cmd (ts, node->hello_ok), - &cmd); + bson_copy_to (_mongoc_topology_scanner_get_monitoring_cmd (ts, node->hello_ok), &cmd); } else { _mongoc_topology_scanner_dup_handshake_cmd (ts, &cmd); } - if (node->ts->negotiate_sasl_supported_mechs && - !node->negotiated_sasl_supported_mechs) { + if (node->ts->negotiate_sasl_supported_mechs && !node->negotiated_sasl_supported_mechs) { _mongoc_handshake_append_sasl_supported_mechs (ts->uri, &cmd); } - if (node->ts->speculative_authentication && !node->has_auth && - bson_empty (&node->speculative_auth_response) && node->scram.step == 0) { + if (node->ts->speculative_authentication && !node->has_auth && bson_empty (&node->speculative_auth_response) && + node->scram.step == 0) { mongoc_ssl_opt_t *ssl_opts = NULL; #ifdef MONGOC_ENABLE_SSL ssl_opts = ts->ssl_opts; #endif - _mongoc_topology_scanner_add_speculative_authentication ( - &cmd, ts->uri, ssl_opts, &node->scram); + _mongoc_topology_scanner_add_speculative_authentication (&cmd, ts->uri, ssl_opts, &node->scram); } if (!bson_empty (&ts->cluster_time)) { @@ -437,15 +400,13 @@ _begin_hello_cmd (mongoc_topology_scanner_node_t *node, mongoc_topology_scanner_t * -mongoc_topology_scanner_new ( - const mongoc_uri_t *uri, - mongoc_topology_scanner_setup_err_cb_t setup_err_cb, - mongoc_topology_scanner_cb_t cb, - void *data, - int64_t connect_timeout_msec) +mongoc_topology_scanner_new (const mongoc_uri_t *uri, + mongoc_topology_scanner_setup_err_cb_t setup_err_cb, + mongoc_topology_scanner_cb_t cb, + void *data, + int64_t connect_timeout_msec) { - mongoc_topology_scanner_t *ts = - BSON_ALIGNED_ALLOC0 (mongoc_topology_scanner_t); + mongoc_topology_scanner_t *ts = BSON_ALIGNED_ALLOC0 (mongoc_topology_scanner_t); ts->async = mongoc_async_new (); @@ -468,8 +429,7 @@ mongoc_topology_scanner_new ( #ifdef MONGOC_ENABLE_SSL void -mongoc_topology_scanner_set_ssl_opts (mongoc_topology_scanner_t *ts, - mongoc_ssl_opt_t *opts) +mongoc_topology_scanner_set_ssl_opts (mongoc_topology_scanner_t *ts, mongoc_ssl_opt_t *opts) { ts->ssl_opts = opts; ts->setup = mongoc_async_cmd_tls_setup; @@ -477,9 +437,7 @@ mongoc_topology_scanner_set_ssl_opts (mongoc_topology_scanner_t *ts, #endif void -mongoc_topology_scanner_set_stream_initiator (mongoc_topology_scanner_t *ts, - mongoc_stream_initiator_t si, - void *ctx) +mongoc_topology_scanner_set_stream_initiator (mongoc_topology_scanner_t *ts, mongoc_stream_initiator_t si, void *ctx) { ts->initiator = si; ts->initiator_context = ctx; @@ -519,10 +477,7 @@ mongoc_topology_scanner_valid (mongoc_topology_scanner_t *ts) } void -mongoc_topology_scanner_add (mongoc_topology_scanner_t *ts, - const mongoc_host_list_t *host, - uint32_t id, - bool hello_ok) +mongoc_topology_scanner_add (mongoc_topology_scanner_t *ts, const mongoc_host_list_t *host, uint32_t id, bool hello_ok) { mongoc_topology_scanner_node_t *node; @@ -579,8 +534,7 @@ mongoc_topology_scanner_node_retire (mongoc_topology_scanner_node_t *node) } void -mongoc_topology_scanner_node_disconnect (mongoc_topology_scanner_node_t *node, - bool failed) +mongoc_topology_scanner_node_disconnect (mongoc_topology_scanner_node_t *node, bool failed) { /* the node may or may not have succeeded in finding a working stream. */ if (node->stream) { @@ -597,8 +551,7 @@ mongoc_topology_scanner_node_disconnect (mongoc_topology_scanner_node_t *node, } void -mongoc_topology_scanner_node_destroy (mongoc_topology_scanner_node_t *node, - bool failed) +mongoc_topology_scanner_node_destroy (mongoc_topology_scanner_node_t *node, bool failed) { DL_DELETE (node->ts->nodes, node); mongoc_topology_scanner_node_disconnect (node, failed); @@ -653,8 +606,7 @@ mongoc_topology_scanner_get_node (mongoc_topology_scanner_t *ts, uint32_t id) *-------------------------------------------------------------------------- */ bool -mongoc_topology_scanner_has_node_for_host (mongoc_topology_scanner_t *ts, - mongoc_host_list_t *host) +mongoc_topology_scanner_has_node_for_host (mongoc_topology_scanner_t *ts, mongoc_host_list_t *host) { mongoc_topology_scanner_node_t *ele, *tmp; @@ -671,21 +623,17 @@ mongoc_topology_scanner_has_node_for_host (mongoc_topology_scanner_t *ts, static void _async_connected (mongoc_async_cmd_t *acmd) { - mongoc_topology_scanner_node_t *node = - (mongoc_topology_scanner_node_t *) acmd->data; + mongoc_topology_scanner_node_t *node = (mongoc_topology_scanner_node_t *) acmd->data; /* this cmd connected successfully, cancel other cmds on this node. */ _cancel_commands_excluding (node, acmd); node->successful_dns_result = acmd->dns_result; } static void -_async_success (mongoc_async_cmd_t *acmd, - const bson_t *hello_response, - int64_t duration_usec) +_async_success (mongoc_async_cmd_t *acmd, const bson_t *hello_response, int64_t duration_usec) { void *data = acmd->data; - mongoc_topology_scanner_node_t *node = - (mongoc_topology_scanner_node_t *) data; + mongoc_topology_scanner_node_t *node = (mongoc_topology_scanner_node_t *) data; mongoc_stream_t *stream = acmd->stream; mongoc_topology_scanner_t *ts = node->ts; @@ -699,8 +647,7 @@ _async_success (mongoc_async_cmd_t *acmd, node->last_used = bson_get_monotonic_time (); node->last_failed = -1; - _mongoc_topology_scanner_monitor_heartbeat_succeeded ( - ts, &node->host, hello_response, duration_usec); + _mongoc_topology_scanner_monitor_heartbeat_succeeded (ts, &node->host, hello_response, duration_usec); /* set our successful stream. */ BSON_ASSERT (!node->stream); @@ -711,39 +658,28 @@ _async_success (mongoc_async_cmd_t *acmd, /* Store a server description associated with the handshake. */ mongoc_server_description_init (&sd, node->host.host_and_port, node->id); - mongoc_server_description_handle_hello ( - &sd, hello_response, duration_usec / 1000, &acmd->error); + mongoc_server_description_handle_hello (&sd, hello_response, duration_usec / 1000, &acmd->error); node->handshake_sd = mongoc_server_description_new_copy (&sd); mongoc_server_description_cleanup (&sd); } - if (ts->negotiate_sasl_supported_mechs && - !node->negotiated_sasl_supported_mechs) { - _mongoc_handshake_parse_sasl_supported_mechs ( - hello_response, &node->sasl_supported_mechs); + if (ts->negotiate_sasl_supported_mechs && !node->negotiated_sasl_supported_mechs) { + _mongoc_handshake_parse_sasl_supported_mechs (hello_response, &node->sasl_supported_mechs); } if (ts->speculative_authentication) { - _mongoc_topology_scanner_parse_speculative_authentication ( - hello_response, &node->speculative_auth_response); + _mongoc_topology_scanner_parse_speculative_authentication (hello_response, &node->speculative_auth_response); } /* mongoc_topology_scanner_cb_t takes rtt_msec, not usec */ - ts->cb (node->id, - hello_response, - duration_usec / 1000, - ts->cb_data, - &acmd->error); + ts->cb (node->id, hello_response, duration_usec / 1000, ts->cb_data, &acmd->error); } static void -_async_error_or_timeout (mongoc_async_cmd_t *acmd, - int64_t duration_usec, - const char *default_err_msg) +_async_error_or_timeout (mongoc_async_cmd_t *acmd, int64_t duration_usec, const char *default_err_msg) { void *data = acmd->data; - mongoc_topology_scanner_node_t *node = - (mongoc_topology_scanner_node_t *) data; + mongoc_topology_scanner_node_t *node = (mongoc_topology_scanner_node_t *) data; mongoc_stream_t *stream = acmd->stream; mongoc_topology_scanner_t *ts = node->ts; bson_error_t *error = &acmd->error; @@ -784,8 +720,7 @@ _async_error_or_timeout (mongoc_async_cmd_t *acmd, message, node->host.host_and_port); - _mongoc_topology_scanner_monitor_heartbeat_failed ( - ts, &node->host, &node->last_error, duration_usec); + _mongoc_topology_scanner_monitor_heartbeat_failed (ts, &node->host, &node->last_error, duration_usec); /* call the topology scanner callback. cannot connect to this node. * callback takes rtt_msec, not usec. */ @@ -839,8 +774,7 @@ _async_handler (mongoc_async_cmd_t *acmd, } mongoc_stream_t * -_mongoc_topology_scanner_node_setup_stream_for_tls ( - mongoc_topology_scanner_node_t *node, mongoc_stream_t *stream) +_mongoc_topology_scanner_node_setup_stream_for_tls (mongoc_topology_scanner_node_t *node, mongoc_stream_t *stream) { #ifdef MONGOC_ENABLE_SSL mongoc_stream_t *tls_stream; @@ -850,8 +784,7 @@ _mongoc_topology_scanner_node_setup_stream_for_tls ( } #ifdef MONGOC_ENABLE_SSL if (node->ts->ssl_opts) { - tls_stream = mongoc_stream_tls_new_with_hostname ( - stream, node->host.host, node->ts->ssl_opts, 1); + tls_stream = mongoc_stream_tls_new_with_hostname (stream, node->host.host, node->ts->ssl_opts, 1); if (!tls_stream) { mongoc_stream_destroy (stream); return NULL; @@ -867,23 +800,19 @@ _mongoc_topology_scanner_node_setup_stream_for_tls ( mongoc_stream_t * _mongoc_topology_scanner_tcp_initiate (mongoc_async_cmd_t *acmd) { - mongoc_topology_scanner_node_t *node = - (mongoc_topology_scanner_node_t *) acmd->data; + mongoc_topology_scanner_node_t *node = (mongoc_topology_scanner_node_t *) acmd->data; struct addrinfo *res = acmd->dns_result; mongoc_socket_t *sock = NULL; BSON_ASSERT (acmd->dns_result); /* create a new non-blocking socket. */ - if (!(sock = mongoc_socket_new ( - res->ai_family, res->ai_socktype, res->ai_protocol))) { + if (!(sock = mongoc_socket_new (res->ai_family, res->ai_socktype, res->ai_protocol))) { return NULL; } - (void) mongoc_socket_connect ( - sock, res->ai_addr, (mongoc_socklen_t) res->ai_addrlen, 0); + (void) mongoc_socket_connect (sock, res->ai_addr, (mongoc_socklen_t) res->ai_addrlen, 0); - return _mongoc_topology_scanner_node_setup_stream_for_tls ( - node, mongoc_stream_socket_new (sock)); + return _mongoc_topology_scanner_node_setup_stream_for_tls (node, mongoc_stream_socket_new (sock)); } /* *-------------------------------------------------------------------------- @@ -899,8 +828,7 @@ _mongoc_topology_scanner_tcp_initiate (mongoc_async_cmd_t *acmd) */ bool -mongoc_topology_scanner_node_setup_tcp (mongoc_topology_scanner_node_t *node, - bson_error_t *error) +mongoc_topology_scanner_node_setup_tcp (mongoc_topology_scanner_node_t *node, bson_error_t *error) { struct addrinfo hints; struct addrinfo *iter; @@ -915,8 +843,7 @@ mongoc_topology_scanner_node_setup_tcp (mongoc_topology_scanner_node_t *node, host = &node->host; /* if cached dns results are expired, flush. */ - if (node->dns_results && - (now - node->last_dns_cache) > node->ts->dns_cache_timeout_ms * 1000) { + if (node->dns_results && (now - node->last_dns_cache) > node->ts->dns_cache_timeout_ms * 1000) { freeaddrinfo (node->dns_results); node->dns_results = NULL; node->successful_dns_result = NULL; @@ -935,11 +862,8 @@ mongoc_topology_scanner_node_setup_tcp (mongoc_topology_scanner_node_t *node, if (s != 0) { mongoc_counter_dns_failure_inc (); - bson_set_error (error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_NAME_RESOLUTION, - "Failed to resolve '%s'", - host->host); + bson_set_error ( + error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_NAME_RESOLUTION, "Failed to resolve '%s'", host->host); RETURN (false); } @@ -957,12 +881,7 @@ mongoc_topology_scanner_node_setup_tcp (mongoc_topology_scanner_node_t *node, } else { LL_FOREACH2 (node->dns_results, iter, ai_next) { - _begin_hello_cmd (node, - NULL /* stream */, - false /* is_setup_done */, - iter, - delay, - true /* use_handshake */); + _begin_hello_cmd (node, NULL /* stream */, false /* is_setup_done */, iter, delay, true /* use_handshake */); /* each subsequent DNS result will have an additional 250ms delay. */ delay += HAPPY_EYEBALLS_DELAY_MS; } @@ -972,15 +891,12 @@ mongoc_topology_scanner_node_setup_tcp (mongoc_topology_scanner_node_t *node, } bool -mongoc_topology_scanner_node_connect_unix (mongoc_topology_scanner_node_t *node, - bson_error_t *error) +mongoc_topology_scanner_node_connect_unix (mongoc_topology_scanner_node_t *node, bson_error_t *error) { #ifdef _WIN32 ENTRY; - bson_set_error (error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_CONNECT, - "UNIX domain sockets not supported on win32."); + bson_set_error ( + error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_CONNECT, "UNIX domain sockets not supported on win32."); RETURN (false); #else struct sockaddr_un saddr; @@ -999,15 +915,11 @@ mongoc_topology_scanner_node_connect_unix (mongoc_topology_scanner_node_t *node, sock = mongoc_socket_new (AF_UNIX, SOCK_STREAM, 0); if (sock == NULL) { - bson_set_error (error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_SOCKET, - "Failed to create socket."); + bson_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "Failed to create socket."); RETURN (false); } - if (-1 == mongoc_socket_connect ( - sock, (struct sockaddr *) &saddr, sizeof saddr, -1)) { + if (-1 == mongoc_socket_connect (sock, (struct sockaddr *) &saddr, sizeof saddr, -1)) { char buf[128]; char *errstr; @@ -1022,21 +934,13 @@ mongoc_topology_scanner_node_connect_unix (mongoc_topology_scanner_node_t *node, RETURN (false); } - stream = _mongoc_topology_scanner_node_setup_stream_for_tls ( - node, mongoc_stream_socket_new (sock)); + stream = _mongoc_topology_scanner_node_setup_stream_for_tls (node, mongoc_stream_socket_new (sock)); if (stream) { - _begin_hello_cmd (node, - stream, - false /* is_setup_done */, - NULL /* dns result */, - 0 /* delay */, - true /* use_handshake */); + _begin_hello_cmd ( + node, stream, false /* is_setup_done */, NULL /* dns result */, 0 /* delay */, true /* use_handshake */); RETURN (true); } - bson_set_error (error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_CONNECT, - "Failed to create TLS stream"); + bson_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_CONNECT, "Failed to create TLS stream"); RETURN (false); #endif } @@ -1056,8 +960,7 @@ mongoc_topology_scanner_node_connect_unix (mongoc_topology_scanner_node_t *node, */ void -mongoc_topology_scanner_node_setup (mongoc_topology_scanner_node_t *node, - bson_error_t *error) +mongoc_topology_scanner_node_setup (mongoc_topology_scanner_node_t *node, bson_error_t *error) { bool success = false; mongoc_stream_t *stream; @@ -1089,14 +992,12 @@ mongoc_topology_scanner_node_setup (mongoc_topology_scanner_node_t *node, // Destroy and zero `node->scram`. _mongoc_scram_destroy (&node->scram); #endif - memset ( - &node->sasl_supported_mechs, 0, sizeof (node->sasl_supported_mechs)); + memset (&node->sasl_supported_mechs, 0, sizeof (node->sasl_supported_mechs)); node->negotiated_sasl_supported_mechs = false; } if (node->ts->initiator) { - stream = node->ts->initiator ( - node->ts->uri, &node->host, node->ts->initiator_context, error); + stream = node->ts->initiator (node->ts->uri, &node->host, node->ts->initiator_context, error); if (stream) { success = true; _begin_hello_cmd (node, @@ -1116,10 +1017,7 @@ mongoc_topology_scanner_node_setup (mongoc_topology_scanner_node_t *node, if (!success) { _mongoc_topology_scanner_monitor_heartbeat_failed ( - node->ts, - &node->host, - error, - (bson_get_monotonic_time () - start) / 1000); + node->ts, &node->host, error, (bson_get_monotonic_time () - start) / 1000); node->ts->setup_err_cb (node->id, node->ts->cb_data, error); return; @@ -1144,8 +1042,7 @@ mongoc_topology_scanner_node_setup (mongoc_topology_scanner_node_t *node, *-------------------------------------------------------------------------- */ bool -mongoc_topology_scanner_node_in_cooldown (mongoc_topology_scanner_node_t *node, - int64_t when) +mongoc_topology_scanner_node_in_cooldown (mongoc_topology_scanner_node_t *node, int64_t when) { if (node->last_failed == -1 || node->ts->bypass_cooldown) { return false; /* node is new, or connected */ @@ -1166,8 +1063,7 @@ mongoc_topology_scanner_node_in_cooldown (mongoc_topology_scanner_node_t *node, */ bool -mongoc_topology_scanner_in_cooldown (mongoc_topology_scanner_t *ts, - int64_t when) +mongoc_topology_scanner_in_cooldown (mongoc_topology_scanner_t *ts, int64_t when) { mongoc_topology_scanner_node_t *node; @@ -1210,8 +1106,7 @@ mongoc_topology_scanner_in_cooldown (mongoc_topology_scanner_t *ts, */ void -mongoc_topology_scanner_start (mongoc_topology_scanner_t *ts, - bool obey_cooldown) +mongoc_topology_scanner_start (mongoc_topology_scanner_t *ts, bool obey_cooldown) { mongoc_topology_scanner_node_t *node, *tmp; bool skip; @@ -1225,8 +1120,7 @@ mongoc_topology_scanner_start (mongoc_topology_scanner_t *ts, DL_FOREACH_SAFE (ts->nodes, node, tmp) { - skip = - obey_cooldown && mongoc_topology_scanner_node_in_cooldown (node, now); + skip = obey_cooldown && mongoc_topology_scanner_node_in_cooldown (node, now); if (!skip) { mongoc_topology_scanner_node_setup (node, &node->last_error); @@ -1307,8 +1201,7 @@ mongoc_topology_scanner_work (mongoc_topology_scanner_t *ts) */ void -mongoc_topology_scanner_get_error (mongoc_topology_scanner_t *ts, - bson_error_t *error) +mongoc_topology_scanner_get_error (mongoc_topology_scanner_t *ts, bson_error_t *error) { BSON_ASSERT (ts); BSON_ASSERT (error); @@ -1320,8 +1213,7 @@ mongoc_topology_scanner_get_error (mongoc_topology_scanner_t *ts, * Set a field in the topology scanner. */ bool -_mongoc_topology_scanner_set_appname (mongoc_topology_scanner_t *ts, - const char *appname) +_mongoc_topology_scanner_set_appname (mongoc_topology_scanner_t *ts, const char *appname) { char *s; const char *prev; @@ -1331,8 +1223,7 @@ _mongoc_topology_scanner_set_appname (mongoc_topology_scanner_t *ts, } s = bson_strdup (appname); - prev = bson_atomic_ptr_compare_exchange_strong ( - (void *) &ts->appname, NULL, s, bson_memory_order_relaxed); + prev = bson_atomic_ptr_compare_exchange_strong ((void *) &ts->appname, NULL, s, bson_memory_order_relaxed); if (prev == NULL) { return true; } @@ -1347,8 +1238,7 @@ _mongoc_topology_scanner_set_appname (mongoc_topology_scanner_t *ts, * @cluster_time is like {clusterTime: } */ void -_mongoc_topology_scanner_set_cluster_time (mongoc_topology_scanner_t *ts, - const bson_t *cluster_time) +_mongoc_topology_scanner_set_cluster_time (mongoc_topology_scanner_t *ts, const bson_t *cluster_time) { bson_destroy (&ts->cluster_time); bson_copy_to (cluster_time, &ts->cluster_time); @@ -1356,8 +1246,7 @@ _mongoc_topology_scanner_set_cluster_time (mongoc_topology_scanner_t *ts, /* SDAM Monitoring Spec: send HeartbeatStartedEvent */ static void -_mongoc_topology_scanner_monitor_heartbeat_started ( - const mongoc_topology_scanner_t *ts, const mongoc_host_list_t *host) +_mongoc_topology_scanner_monitor_heartbeat_started (const mongoc_topology_scanner_t *ts, const mongoc_host_list_t *host) { if (ts->apm_callbacks.server_heartbeat_started) { mongoc_apm_server_heartbeat_started_t event; @@ -1370,19 +1259,17 @@ _mongoc_topology_scanner_monitor_heartbeat_started ( /* SDAM Monitoring Spec: send HeartbeatSucceededEvent */ static void -_mongoc_topology_scanner_monitor_heartbeat_succeeded ( - const mongoc_topology_scanner_t *ts, - const mongoc_host_list_t *host, - const bson_t *reply, - int64_t duration_usec) +_mongoc_topology_scanner_monitor_heartbeat_succeeded (const mongoc_topology_scanner_t *ts, + const mongoc_host_list_t *host, + const bson_t *reply, + int64_t duration_usec) { if (ts->apm_callbacks.server_heartbeat_succeeded) { mongoc_apm_server_heartbeat_succeeded_t event; bson_t hello_redacted; bson_init (&hello_redacted); - bson_copy_to_excluding_noinit ( - reply, &hello_redacted, "speculativeAuthenticate", NULL); + bson_copy_to_excluding_noinit (reply, &hello_redacted, "speculativeAuthenticate", NULL); event.host = host; event.context = ts->apm_context; @@ -1397,11 +1284,10 @@ _mongoc_topology_scanner_monitor_heartbeat_succeeded ( /* SDAM Monitoring Spec: send HeartbeatFailedEvent */ static void -_mongoc_topology_scanner_monitor_heartbeat_failed ( - const mongoc_topology_scanner_t *ts, - const mongoc_host_list_t *host, - const bson_error_t *error, - int64_t duration_usec) +_mongoc_topology_scanner_monitor_heartbeat_failed (const mongoc_topology_scanner_t *ts, + const mongoc_host_list_t *host, + const bson_error_t *error, + int64_t duration_usec) { if (ts->apm_callbacks.server_heartbeat_failed) { mongoc_apm_server_heartbeat_failed_t event; @@ -1416,8 +1302,7 @@ _mongoc_topology_scanner_monitor_heartbeat_failed ( /* this is for testing the dns cache timeout. */ void -_mongoc_topology_scanner_set_dns_cache_timeout (mongoc_topology_scanner_t *ts, - int64_t timeout_ms) +_mongoc_topology_scanner_set_dns_cache_timeout (mongoc_topology_scanner_t *ts, int64_t timeout_ms) { ts->dns_cache_timeout_ms = timeout_ms; } @@ -1437,14 +1322,12 @@ _delete_retired_nodes (mongoc_topology_scanner_t *ts) } static void -_cancel_commands_excluding (mongoc_topology_scanner_node_t *node, - mongoc_async_cmd_t *acmd) +_cancel_commands_excluding (mongoc_topology_scanner_node_t *node, mongoc_async_cmd_t *acmd) { mongoc_async_cmd_t *iter; DL_FOREACH (node->ts->async->cmds, iter) { - if ((mongoc_topology_scanner_node_t *) iter->data == node && - iter != acmd) { + if ((mongoc_topology_scanner_node_t *) iter->data == node && iter != acmd) { iter->state = MONGOC_ASYNC_CMD_CANCELED_STATE; } } @@ -1465,23 +1348,20 @@ _count_acmds (mongoc_topology_scanner_node_t *node) } static void -_jumpstart_other_acmds (mongoc_topology_scanner_node_t *node, - mongoc_async_cmd_t *acmd) +_jumpstart_other_acmds (mongoc_topology_scanner_node_t *node, mongoc_async_cmd_t *acmd) { mongoc_async_cmd_t *iter; DL_FOREACH (node->ts->async->cmds, iter) { - if ((mongoc_topology_scanner_node_t *) iter->data == node && - iter != acmd && acmd->initiate_delay_ms < iter->initiate_delay_ms) { - iter->initiate_delay_ms = - BSON_MAX (iter->initiate_delay_ms - HAPPY_EYEBALLS_DELAY_MS, 0); + if ((mongoc_topology_scanner_node_t *) iter->data == node && iter != acmd && + acmd->initiate_delay_ms < iter->initiate_delay_ms) { + iter->initiate_delay_ms = BSON_MAX (iter->initiate_delay_ms - HAPPY_EYEBALLS_DELAY_MS, 0); } } } void -_mongoc_topology_scanner_set_server_api (mongoc_topology_scanner_t *ts, - const mongoc_server_api_t *api) +_mongoc_topology_scanner_set_server_api (mongoc_topology_scanner_t *ts, const mongoc_server_api_t *api) { BSON_ASSERT (ts); BSON_ASSERT (api); @@ -1492,8 +1372,7 @@ _mongoc_topology_scanner_set_server_api (mongoc_topology_scanner_t *ts, /* This must be called before the handshake command is constructed. */ void -_mongoc_topology_scanner_set_loadbalanced (mongoc_topology_scanner_t *ts, - bool val) +_mongoc_topology_scanner_set_loadbalanced (mongoc_topology_scanner_t *ts, bool val) { BSON_UNUSED (val); diff --git a/src/libmongoc/src/mongoc/mongoc-topology.c b/src/libmongoc/src/mongoc/mongoc-topology.c index 4d9ae1a45f..b1a5a4ee45 100644 --- a/src/libmongoc/src/mongoc/mongoc-topology.c +++ b/src/libmongoc/src/mongoc/mongoc-topology.c @@ -38,12 +38,10 @@ #include static void -_topology_collect_errors (const mongoc_topology_description_t *topology, - bson_error_t *error_out); +_topology_collect_errors (const mongoc_topology_description_t *topology, bson_error_t *error_out); static bool -_mongoc_topology_reconcile_add_nodes (mongoc_server_description_t *sd, - mongoc_topology_scanner_t *scanner) +_mongoc_topology_reconcile_add_nodes (mongoc_server_description_t *sd, mongoc_topology_scanner_t *scanner) { mongoc_topology_scanner_node_t *node; @@ -66,8 +64,7 @@ _mongoc_topology_reconcile_add_nodes (mongoc_server_description_t *sd, * Not called for multi threaded monitoring. */ void -mongoc_topology_reconcile (const mongoc_topology_t *topology, - mongoc_topology_description_t *td) +mongoc_topology_reconcile (const mongoc_topology_t *topology, mongoc_topology_description_t *td) { mongoc_set_t *servers; mongoc_server_description_t *sd; @@ -99,8 +96,7 @@ _mongoc_topology_update_no_lock (uint32_t id, mongoc_topology_description_t *td, const bson_error_t *error /* IN */) { - mongoc_topology_description_handle_hello ( - td, id, hello_response, rtt_msec, error); + mongoc_topology_description_handle_hello (td, id, hello_response, rtt_msec, error); /* return false if server removed from topology */ return mongoc_topology_description_server_by_id (td, id, NULL) != NULL; @@ -119,9 +115,7 @@ _mongoc_topology_update_no_lock (uint32_t id, */ void -_mongoc_topology_scanner_setup_err_cb (uint32_t id, - void *data, - const bson_error_t *error /* IN */) +_mongoc_topology_scanner_setup_err_cb (uint32_t id, void *data, const bson_error_t *error /* IN */) { mongoc_topology_t *topology = BSON_ASSERT_PTR_INLINE (data); @@ -133,8 +127,7 @@ _mongoc_topology_scanner_setup_err_cb (uint32_t id, // Use `mc_tpld_unsafe_get_mutable` to get a mutable topology description // without locking. This function only applies to single-threaded clients. mongoc_topology_description_t *td = mc_tpld_unsafe_get_mutable (topology); - mongoc_topology_description_handle_hello ( - td, id, NULL /* hello reply */, -1 /* rtt_msec */, error); + mongoc_topology_description_handle_hello (td, id, NULL /* hello reply */, -1 /* rtt_msec */, error); } } @@ -153,11 +146,8 @@ _mongoc_topology_scanner_setup_err_cb (uint32_t id, */ void -_mongoc_topology_scanner_cb (uint32_t id, - const bson_t *hello_response, - int64_t rtt_msec, - void *data, - const bson_error_t *error /* IN */) +_mongoc_topology_scanner_cb ( + uint32_t id, const bson_t *hello_response, int64_t rtt_msec, void *data, const bson_error_t *error /* IN */) { mongoc_topology_t *const topology = BSON_ASSERT_PTR_INLINE (data); mongoc_server_description_t *sd; @@ -180,8 +170,7 @@ _mongoc_topology_scanner_cb (uint32_t id, /* Server monitoring: When a server check fails due to a network error * (including a network timeout), the client MUST clear its connection * pool for the server */ - _mongoc_topology_description_clear_connection_pool ( - td, id, &kZeroServiceId); + _mongoc_topology_description_clear_connection_pool (td, id, &kZeroServiceId); } /* Server Discovery and Monitoring Spec: "Once a server is connected, the @@ -205,9 +194,7 @@ _mongoc_topology_scanner_cb (uint32_t id, } static void -_server_session_init (mongoc_server_session_t *session, - mongoc_topology_t *unused, - bson_error_t *error) +_server_session_init (mongoc_server_session_t *session, mongoc_topology_t *unused, bson_error_t *error) { BSON_UNUSED (unused); @@ -215,8 +202,7 @@ _server_session_init (mongoc_server_session_t *session, } static void -_server_session_destroy (mongoc_server_session_t *session, - mongoc_topology_t *unused) +_server_session_destroy (mongoc_server_session_t *session, mongoc_topology_t *unused) { BSON_UNUSED (unused); @@ -224,8 +210,7 @@ _server_session_destroy (mongoc_server_session_t *session, } static int -_server_session_should_prune (mongoc_server_session_t *session, - mongoc_topology_t *topo) +_server_session_should_prune (mongoc_server_session_t *session, mongoc_topology_t *topo) { BSON_ASSERT_PARAM (session); BSON_ASSERT_PARAM (topo); @@ -263,9 +248,7 @@ _tpld_destroy_and_free (void *tpl_descr) } const mongoc_host_list_t ** -_mongoc_apply_srv_max_hosts (const mongoc_host_list_t *hl, - size_t max_hosts, - size_t *hl_array_size) +_mongoc_apply_srv_max_hosts (const mongoc_host_list_t *hl, size_t max_hosts, size_t *hl_array_size) { const mongoc_host_list_t **hl_array; @@ -299,8 +282,7 @@ _mongoc_apply_srv_max_hosts (const mongoc_host_list_t *hl, * Drivers SHOULD use the `Fisher-Yates shuffle` for randomization. */ for (size_t idx = hl_size - 1u; idx > 0u; --idx) { /* 0 <= swap_pos <= idx */ - const size_t swap_pos = - _mongoc_rand_size_t (0u, idx, _mongoc_simple_rand_size_t); + const size_t swap_pos = _mongoc_rand_size_t (0u, idx, _mongoc_simple_rand_size_t); const mongoc_host_list_t *tmp = hl_array[swap_pos]; hl_array[swap_pos] = hl_array[idx]; @@ -323,20 +305,18 @@ _detect_nongenuine_host (const char *host) mongoc_lowercase (host, host_lowercase); if (mongoc_ends_with (host_lowercase, ".cosmos.azure.com")) { - MONGOC_INFO ( - "You appear to be connected to a CosmosDB cluster. For more " - "information regarding feature compatibility and support please " - "visit https://www.mongodb.com/supportability/cosmosdb"); + MONGOC_INFO ("You appear to be connected to a CosmosDB cluster. For more " + "information regarding feature compatibility and support please " + "visit https://www.mongodb.com/supportability/cosmosdb"); bson_free (host_lowercase); return true; } if (mongoc_ends_with (host_lowercase, ".docdb.amazonaws.com") || mongoc_ends_with (host_lowercase, ".docdb-elastic.amazonaws.com")) { - MONGOC_INFO ( - "You appear to be connected to a DocumentDB cluster. For more " - "information regarding feature compatibility and support please " - "visit https://www.mongodb.com/supportability/documentdb"); + MONGOC_INFO ("You appear to be connected to a DocumentDB cluster. For more " + "information regarding feature compatibility and support please " + "visit https://www.mongodb.com/supportability/documentdb"); bson_free (host_lowercase); return true; } @@ -396,34 +376,26 @@ mongoc_topology_new (const mongoc_uri_t *uri, bool single_threaded) _detect_nongenuine_hosts (uri); #ifndef MONGOC_ENABLE_CRYPTO - if (mongoc_uri_get_option_as_bool ( - uri, MONGOC_URI_RETRYWRITES, MONGOC_DEFAULT_RETRYWRITES)) { + if (mongoc_uri_get_option_as_bool (uri, MONGOC_URI_RETRYWRITES, MONGOC_DEFAULT_RETRYWRITES)) { /* retryWrites requires sessions, which require crypto - just warn */ - MONGOC_WARNING ( - "retryWrites not supported without an SSL crypto library"); + MONGOC_WARNING ("retryWrites not supported without an SSL crypto library"); } #endif topology = (mongoc_topology_t *) bson_malloc0 (sizeof *topology); topology->usleep_fn = mongoc_usleep_default_impl; - topology->session_pool = - mongoc_server_session_pool_new_with_params (_server_session_init, - _server_session_destroy, - _server_session_should_prune, - topology); + topology->session_pool = mongoc_server_session_pool_new_with_params ( + _server_session_init, _server_session_destroy, _server_session_should_prune, topology); topology->valid = false; - const int32_t heartbeat_default = - single_threaded ? MONGOC_TOPOLOGY_HEARTBEAT_FREQUENCY_MS_SINGLE_THREADED - : MONGOC_TOPOLOGY_HEARTBEAT_FREQUENCY_MS_MULTI_THREADED; + const int32_t heartbeat_default = single_threaded ? MONGOC_TOPOLOGY_HEARTBEAT_FREQUENCY_MS_SINGLE_THREADED + : MONGOC_TOPOLOGY_HEARTBEAT_FREQUENCY_MS_MULTI_THREADED; - const int32_t heartbeat = mongoc_uri_get_option_as_int32 ( - uri, MONGOC_URI_HEARTBEATFREQUENCYMS, heartbeat_default); + const int32_t heartbeat = mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_HEARTBEATFREQUENCYMS, heartbeat_default); - topology->_shared_descr_._sptr_ = mongoc_shared_ptr_create ( - BSON_ALIGNED_ALLOC0 (mongoc_topology_description_t), - _tpld_destroy_and_free); + topology->_shared_descr_._sptr_ = + mongoc_shared_ptr_create (BSON_ALIGNED_ALLOC0 (mongoc_topology_description_t), _tpld_destroy_and_free); td = mc_tpld_unsafe_get_mutable (topology); mongoc_topology_description_init (td, heartbeat); @@ -442,23 +414,19 @@ mongoc_topology_new (const mongoc_uri_t *uri, bool single_threaded) * * "The serverSelectionTryOnce option MUST be true by default." */ - topology->server_selection_try_once = mongoc_uri_get_option_as_bool ( - uri, MONGOC_URI_SERVERSELECTIONTRYONCE, true); + topology->server_selection_try_once = + mongoc_uri_get_option_as_bool (uri, MONGOC_URI_SERVERSELECTIONTRYONCE, true); } else { topology->server_selection_try_once = false; } topology->server_selection_timeout_msec = mongoc_uri_get_option_as_int32 ( - topology->uri, - MONGOC_URI_SERVERSELECTIONTIMEOUTMS, - MONGOC_TOPOLOGY_SERVER_SELECTION_TIMEOUT_MS); + topology->uri, MONGOC_URI_SERVERSELECTIONTIMEOUTMS, MONGOC_TOPOLOGY_SERVER_SELECTION_TIMEOUT_MS); /* tests can override this */ - topology->min_heartbeat_frequency_msec = - MONGOC_TOPOLOGY_MIN_HEARTBEAT_FREQUENCY_MS; + topology->min_heartbeat_frequency_msec = MONGOC_TOPOLOGY_MIN_HEARTBEAT_FREQUENCY_MS; - topology->local_threshold_msec = - mongoc_uri_get_local_threshold_option (topology->uri); + topology->local_threshold_msec = mongoc_uri_get_local_threshold_option (topology->uri); /* Total time allowed to check a server is connectTimeoutMS. * Server Discovery And Monitoring Spec: @@ -468,17 +436,14 @@ mongoc_topology_new (const mongoc_uri_t *uri, bool single_threaded) * socketTimeoutMS to the connectTimeoutMS." */ topology->connect_timeout_msec = - mongoc_uri_get_option_as_int32 (topology->uri, - MONGOC_URI_CONNECTTIMEOUTMS, - MONGOC_DEFAULT_CONNECTTIMEOUTMS); + mongoc_uri_get_option_as_int32 (topology->uri, MONGOC_URI_CONNECTTIMEOUTMS, MONGOC_DEFAULT_CONNECTTIMEOUTMS); topology->scanner_state = MONGOC_TOPOLOGY_SCANNER_OFF; - topology->scanner = - mongoc_topology_scanner_new (topology->uri, - _mongoc_topology_scanner_setup_err_cb, - _mongoc_topology_scanner_cb, - topology, - topology->connect_timeout_msec); + topology->scanner = mongoc_topology_scanner_new (topology->uri, + _mongoc_topology_scanner_setup_err_cb, + _mongoc_topology_scanner_cb, + topology, + topology->connect_timeout_msec); bson_mutex_init (&topology->tpld_modification_mtx); mongoc_cond_init (&topology->cond_client); @@ -507,49 +472,38 @@ mongoc_topology_new (const mongoc_uri_t *uri, bool single_threaded) * lookup fails, SRV polling will still start when background monitoring * starts. */ topology->srv_polling_last_scan_ms = bson_get_monotonic_time () / 1000; - topology->srv_polling_rescan_interval_ms = - MONGOC_TOPOLOGY_MIN_RESCAN_SRV_INTERVAL_MS; + topology->srv_polling_rescan_interval_ms = MONGOC_TOPOLOGY_MIN_RESCAN_SRV_INTERVAL_MS; /* a mongodb+srv URI. try SRV lookup, if no error then also try TXT */ - prefixed_hostname = bson_strdup_printf ( - "_%s._tcp.%s", mongoc_uri_get_srv_service_name (uri), srv_hostname); - if (!topology->rr_resolver (prefixed_hostname, - MONGOC_RR_SRV, - &rr_data, - MONGOC_RR_DEFAULT_BUFFER_SIZE, - &topology->scanner->error)) { + prefixed_hostname = bson_strdup_printf ("_%s._tcp.%s", mongoc_uri_get_srv_service_name (uri), srv_hostname); + if (!topology->rr_resolver ( + prefixed_hostname, MONGOC_RR_SRV, &rr_data, MONGOC_RR_DEFAULT_BUFFER_SIZE, &topology->scanner->error)) { GOTO (srv_fail); } /* Failure to find TXT records will not return an error (since it is only * for options). But _mongoc_client_get_rr may return an error if * there is more than one TXT record returned. */ - if (!topology->rr_resolver (srv_hostname, - MONGOC_RR_TXT, - &rr_data, - MONGOC_RR_DEFAULT_BUFFER_SIZE, - &topology->scanner->error)) { + if (!topology->rr_resolver ( + srv_hostname, MONGOC_RR_TXT, &rr_data, MONGOC_RR_DEFAULT_BUFFER_SIZE, &topology->scanner->error)) { GOTO (srv_fail); } /* Use rr_data to update the topology's URI. */ if (rr_data.txt_record_opts && - !mongoc_uri_parse_options (topology->uri, - rr_data.txt_record_opts, - true /* from_dns */, - &topology->scanner->error)) { + !mongoc_uri_parse_options ( + topology->uri, rr_data.txt_record_opts, true /* from_dns */, &topology->scanner->error)) { GOTO (srv_fail); } - if (!mongoc_uri_init_with_srv_host_list ( - topology->uri, rr_data.hosts, &topology->scanner->error)) { + if (!mongoc_uri_init_with_srv_host_list (topology->uri, rr_data.hosts, &topology->scanner->error)) { GOTO (srv_fail); } topology->srv_polling_last_scan_ms = bson_get_monotonic_time () / 1000; /* TODO (CDRIVER-4047) use BSON_MIN */ - topology->srv_polling_rescan_interval_ms = BSON_MAX ( - rr_data.min_ttl * 1000, MONGOC_TOPOLOGY_MIN_RESCAN_SRV_INTERVAL_MS); + topology->srv_polling_rescan_interval_ms = + BSON_MAX (rr_data.min_ttl * 1000, MONGOC_TOPOLOGY_MIN_RESCAN_SRV_INTERVAL_MS); topology->valid = true; srv_fail: @@ -564,8 +518,7 @@ mongoc_topology_new (const mongoc_uri_t *uri, bool single_threaded) topology->valid = false; } - td->max_hosts = - mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_SRVMAXHOSTS, 0); + td->max_hosts = mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_SRVMAXHOSTS, 0); if (td->max_hosts < 0) { topology->valid = false; @@ -584,17 +537,13 @@ mongoc_topology_new (const mongoc_uri_t *uri, bool single_threaded) * - otherwise, if the seed list has a single host, initialize to SINGLE * - everything else gets initialized to UNKNOWN */ - has_directconnection = - mongoc_uri_has_option (uri, MONGOC_URI_DIRECTCONNECTION); - directconnection = - has_directconnection && - mongoc_uri_get_option_as_bool (uri, MONGOC_URI_DIRECTCONNECTION, false); + has_directconnection = mongoc_uri_has_option (uri, MONGOC_URI_DIRECTCONNECTION); + directconnection = has_directconnection && mongoc_uri_get_option_as_bool (uri, MONGOC_URI_DIRECTCONNECTION, false); hl = mongoc_uri_get_hosts (topology->uri); /* If loadBalanced is enabled, directConnection is disabled. This was * validated in mongoc_uri_finalize_loadbalanced, which is called by * mongoc_uri_finalize. */ - if (mongoc_uri_get_option_as_bool ( - topology->uri, MONGOC_URI_LOADBALANCED, false)) { + if (mongoc_uri_get_option_as_bool (topology->uri, MONGOC_URI_LOADBALANCED, false)) { init_type = MONGOC_TOPOLOGY_LOAD_BALANCED; if (topology->single_threaded) { /* Cooldown only applies to server monitoring for single-threaded @@ -647,8 +596,7 @@ mongoc_topology_new (const mongoc_uri_t *uri, bool single_threaded) size_t hl_array_size = 0u; BSON_ASSERT (bson_in_range_signed (size_t, td->max_hosts)); - const mongoc_host_list_t *const *hl_array = - _mongoc_apply_srv_max_hosts (hl, (size_t) td->max_hosts, &hl_array_size); + const mongoc_host_list_t *const *hl_array = _mongoc_apply_srv_max_hosts (hl, (size_t) td->max_hosts, &hl_array_size); for (size_t idx = 0u; idx < hl_array_size; ++idx) { const mongoc_host_list_t *const elem = hl_array[idx]; @@ -681,13 +629,10 @@ mongoc_topology_set_apm_callbacks (mongoc_topology_t *topology, { if (callbacks) { memcpy (&td->apm_callbacks, callbacks, sizeof (mongoc_apm_callbacks_t)); - memcpy (&topology->scanner->apm_callbacks, - callbacks, - sizeof (mongoc_apm_callbacks_t)); + memcpy (&topology->scanner->apm_callbacks, callbacks, sizeof (mongoc_apm_callbacks_t)); } else { memset (&td->apm_callbacks, 0, sizeof (mongoc_apm_callbacks_t)); - memset ( - &topology->scanner->apm_callbacks, 0, sizeof (mongoc_apm_callbacks_t)); + memset (&topology->scanner->apm_callbacks, 0, sizeof (mongoc_apm_callbacks_t)); } td->apm_context = context; @@ -739,16 +684,14 @@ mongoc_topology_destroy (mongoc_topology_t *topology) if (topology->valid) { /* Do not emit a topology_closed event. A topology opening event was not * emitted. */ - _mongoc_topology_description_monitor_closed ( - mc_tpld_unsafe_get_const (topology)); + _mongoc_topology_description_monitor_closed (mc_tpld_unsafe_get_const (topology)); } mongoc_uri_destroy (topology->uri); mongoc_shared_ptr_reset_null (&topology->_shared_descr_._sptr_); mongoc_topology_scanner_destroy (topology->scanner); mongoc_server_session_pool_free (topology->session_pool); - bson_free (topology->clientSideEncryption.autoOptions.extraOptions - .cryptSharedLibPath); + bson_free (topology->clientSideEncryption.autoOptions.extraOptions.cryptSharedLibPath); mongoc_cond_destroy (&topology->cond_client); bson_mutex_destroy (&topology->tpld_modification_mtx); @@ -857,8 +800,7 @@ mongoc_topology_rescan_srv (mongoc_topology_t *topology) BSON_ASSERT (mongoc_topology_should_rescan_srv (topology)); srv_hostname = mongoc_uri_get_srv_hostname (topology->uri); - scan_time_ms = topology->srv_polling_last_scan_ms + - topology->srv_polling_rescan_interval_ms; + scan_time_ms = topology->srv_polling_last_scan_ms + topology->srv_polling_rescan_interval_ms; if (bson_get_monotonic_time () / 1000 < scan_time_ms) { /* Query SRV no more frequently than srv_polling_rescan_interval_ms. */ return; @@ -868,15 +810,10 @@ mongoc_topology_rescan_srv (mongoc_topology_t *topology) /* Go forth and query... */ prefixed_hostname = - bson_strdup_printf ("_%s._tcp.%s", - mongoc_uri_get_srv_service_name (topology->uri), - srv_hostname); + bson_strdup_printf ("_%s._tcp.%s", mongoc_uri_get_srv_service_name (topology->uri), srv_hostname); - ret = topology->rr_resolver (prefixed_hostname, - MONGOC_RR_SRV, - &rr_data, - MONGOC_RR_DEFAULT_BUFFER_SIZE, - &topology->scanner->error); + ret = topology->rr_resolver ( + prefixed_hostname, MONGOC_RR_SRV, &rr_data, MONGOC_RR_DEFAULT_BUFFER_SIZE, &topology->scanner->error); td = mc_tpld_take_ref (topology); topology->srv_polling_last_scan_ms = bson_get_monotonic_time () / 1000; @@ -888,14 +825,12 @@ mongoc_topology_rescan_srv (mongoc_topology_t *topology) } /* TODO (CDRIVER-4047) use BSON_MIN */ - topology->srv_polling_rescan_interval_ms = BSON_MAX ( - rr_data.min_ttl * 1000, MONGOC_TOPOLOGY_MIN_RESCAN_SRV_INTERVAL_MS); + topology->srv_polling_rescan_interval_ms = + BSON_MAX (rr_data.min_ttl * 1000, MONGOC_TOPOLOGY_MIN_RESCAN_SRV_INTERVAL_MS); tdmod = mc_tpld_modify_begin (topology); - if (!mongoc_topology_apply_scanned_srv_hosts (topology->uri, - tdmod.new_td, - rr_data.hosts, - &topology->scanner->error)) { + if (!mongoc_topology_apply_scanned_srv_hosts ( + topology->uri, tdmod.new_td, rr_data.hosts, &topology->scanner->error)) { MONGOC_ERROR ("%s", topology->scanner->error.message); /* Special case when DNS returns zero records successfully or no valid * hosts exist. @@ -972,8 +907,7 @@ mongoc_topology_scan_once (mongoc_topology_t *topology, bool obey_cooldown) *-------------------------------------------------------------------------- */ void -_mongoc_topology_do_blocking_scan (mongoc_topology_t *topology, - bson_error_t *error) +_mongoc_topology_do_blocking_scan (mongoc_topology_t *topology, bson_error_t *error) { BSON_ASSERT (topology->single_threaded); _mongoc_handshake_freeze (); @@ -1000,21 +934,17 @@ mongoc_topology_compatible (const mongoc_topology_description_t *td, return true; } - const int64_t max_staleness_seconds = - mongoc_read_prefs_get_max_staleness_seconds (read_prefs); + const int64_t max_staleness_seconds = mongoc_read_prefs_get_max_staleness_seconds (read_prefs); if (max_staleness_seconds != MONGOC_NO_MAX_STALENESS) { /* shouldn't happen if we've properly enforced wire version */ if (!mongoc_topology_description_all_sds_have_write_date (td)) { - bson_set_error (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION, - "Not all servers have lastWriteDate"); + bson_set_error ( + error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION, "Not all servers have lastWriteDate"); return false; } - if (!_mongoc_topology_description_validate_max_staleness ( - td, max_staleness_seconds, error)) { + if (!_mongoc_topology_description_validate_max_staleness (td, max_staleness_seconds, error)) { return false; } } @@ -1024,9 +954,7 @@ mongoc_topology_compatible (const mongoc_topology_description_t *td, static void -_mongoc_server_selection_error (const char *msg, - const bson_error_t *scanner_error, - bson_error_t *error) +_mongoc_server_selection_error (const char *msg, const bson_error_t *scanner_error, bson_error_t *error) { if (scanner_error && scanner_error->code) { bson_set_error (error, @@ -1036,11 +964,7 @@ _mongoc_server_selection_error (const char *msg, msg, scanner_error->message); } else { - bson_set_error (error, - MONGOC_ERROR_SERVER_SELECTION, - MONGOC_ERROR_SERVER_SELECTION_FAILURE, - "%s", - msg); + bson_set_error (error, MONGOC_ERROR_SERVER_SELECTION, MONGOC_ERROR_SERVER_SELECTION_FAILURE, "%s", msg); } } @@ -1052,16 +976,13 @@ mongoc_topology_select (mongoc_topology_t *topology, bool *must_use_primary, bson_error_t *error) { - uint32_t server_id = mongoc_topology_select_server_id ( - topology, optype, read_prefs, must_use_primary, NULL, error); + uint32_t server_id = mongoc_topology_select_server_id (topology, optype, read_prefs, must_use_primary, NULL, error); if (server_id) { /* new copy of the server description */ mongoc_server_description_t *ret; mc_shared_tpld td = mc_tpld_take_ref (topology); - mongoc_server_description_t const *sd = - mongoc_topology_description_server_by_id_const ( - td.ptr, server_id, error); + mongoc_server_description_t const *sd = mongoc_topology_description_server_by_id_const (td.ptr, server_id, error); ret = mongoc_server_description_new_copy (sd); mc_tpld_drop_ref (&td); return ret; @@ -1075,8 +996,7 @@ mongoc_topology_select (mongoc_topology_t *topology, * Successful post-condition: On a single threaded client, a connection will * have been established. */ static uint32_t -_mongoc_topology_select_server_id_loadbalanced (mongoc_topology_t *topology, - bson_error_t *error) +_mongoc_topology_select_server_id_loadbalanced (mongoc_topology_t *topology, bson_error_t *error) { mongoc_server_description_t const *selected_server; int32_t selected_server_id; @@ -1093,17 +1013,15 @@ _mongoc_topology_select_server_id_loadbalanced (mongoc_topology_t *topology, mc_tpld_modify_commit (tdmod); mc_tpld_renew_ref (&td, topology); } - selected_server = - mongoc_topology_description_select (td.ptr, - MONGOC_SS_WRITE, - NULL /* read prefs */, - NULL /* chosen read mode */, - NULL /* deprioritized servers */, - 0 /* local threshold */); + selected_server = mongoc_topology_description_select (td.ptr, + MONGOC_SS_WRITE, + NULL /* read prefs */, + NULL /* chosen read mode */, + NULL /* deprioritized servers */, + 0 /* local threshold */); if (!selected_server) { - _mongoc_server_selection_error ( - "No suitable server found in load balanced deployment", NULL, error); + _mongoc_server_selection_error ("No suitable server found in load balanced deployment", NULL, error); selected_server_id = 0; goto done; } @@ -1117,13 +1035,9 @@ _mongoc_topology_select_server_id_loadbalanced (mongoc_topology_t *topology, /* If this is a single threaded topology, we must ensure that a connection is * available to this server. Wrapping drivers make the assumption that * successful server selection implies a connection is available. */ - node = - mongoc_topology_scanner_get_node (topology->scanner, selected_server_id); + node = mongoc_topology_scanner_get_node (topology->scanner, selected_server_id); if (!node) { - _mongoc_server_selection_error ( - "Topology scanner in invalid state; cannot find load balancer", - NULL, - error); + _mongoc_server_selection_error ("Topology scanner in invalid state; cannot find load balancer", NULL, error); selected_server_id = 0; goto done; } @@ -1170,8 +1084,7 @@ mongoc_topology_select_server_id (mongoc_topology_t *topology, const mongoc_deprioritized_servers_t *ds, bson_error_t *error) { - static const char *timeout_msg = - "No suitable servers found: `serverSelectionTimeoutMS` expired"; + static const char *timeout_msg = "No suitable servers found: `serverSelectionTimeoutMS` expired"; mongoc_topology_scanner_t *ts; int r; @@ -1206,8 +1119,7 @@ mongoc_topology_select_server_id (mongoc_topology_t *topology, } if (td.ptr->type == MONGOC_TOPOLOGY_LOAD_BALANCED) { - server_id = - _mongoc_topology_select_server_id_loadbalanced (topology, error); + server_id = _mongoc_topology_select_server_id_loadbalanced (topology, error); goto done; } @@ -1215,16 +1127,14 @@ mongoc_topology_select_server_id (mongoc_topology_t *topology, local_threshold_ms = topology->local_threshold_msec; try_once = topology->server_selection_try_once; loop_start = loop_end = bson_get_monotonic_time (); - expire_at = - loop_start + ((int64_t) topology->server_selection_timeout_msec * 1000); + expire_at = loop_start + ((int64_t) topology->server_selection_timeout_msec * 1000); if (topology->single_threaded) { if (!td.ptr->opened) { // Use `mc_tpld_unsafe_get_mutable` to get a mutable topology // description without locking. This block only applies to // single-threaded clients. - _mongoc_topology_description_monitor_opening ( - mc_tpld_unsafe_get_mutable (topology)); + _mongoc_topology_description_monitor_opening (mc_tpld_unsafe_get_mutable (topology)); mc_tpld_renew_ref (&td, topology); } @@ -1239,16 +1149,14 @@ mongoc_topology_select_server_id (mongoc_topology_t *topology, for (;;) { if (topology->stale) { /* how soon are we allowed to scan? */ - scan_ready = topology->last_scan + - topology->min_heartbeat_frequency_msec * 1000; + scan_ready = topology->last_scan + topology->min_heartbeat_frequency_msec * 1000; if (scan_ready > expire_at && !try_once) { /* selection timeout will expire before min heartbeat passes */ - _mongoc_server_selection_error ( - "No suitable servers found: " - "`serverselectiontimeoutms` timed out", - &scanner_error, - error); + _mongoc_server_selection_error ("No suitable servers found: " + "`serverselectiontimeoutms` timed out", + &scanner_error, + error); server_id = 0; goto done; @@ -1256,12 +1164,8 @@ mongoc_topology_select_server_id (mongoc_topology_t *topology, sleep_usec = scan_ready - loop_end; if (sleep_usec > 0) { - if (try_once && - mongoc_topology_scanner_in_cooldown (ts, scan_ready)) { - _mongoc_server_selection_error ( - "No servers yet eligible for rescan", - &scanner_error, - error); + if (try_once && mongoc_topology_scanner_in_cooldown (ts, scan_ready)) { + _mongoc_server_selection_error ("No servers yet eligible for rescan", &scanner_error, error); server_id = 0; goto done; @@ -1284,12 +1188,7 @@ mongoc_topology_select_server_id (mongoc_topology_t *topology, } selected_server = - mongoc_topology_description_select (td.ptr, - optype, - read_prefs, - must_use_primary, - ds, - local_threshold_ms); + mongoc_topology_description_select (td.ptr, optype, read_prefs, must_use_primary, ds, local_threshold_ms); if (selected_server) { server_id = selected_server->id; @@ -1301,9 +1200,7 @@ mongoc_topology_select_server_id (mongoc_topology_t *topology, if (try_once) { if (tried_once) { _mongoc_server_selection_error ( - "No suitable servers found (`serverSelectionTryOnce` set)", - &scanner_error, - error); + "No suitable servers found (`serverSelectionTryOnce` set)", &scanner_error, error); server_id = 0; goto done; @@ -1313,8 +1210,7 @@ mongoc_topology_select_server_id (mongoc_topology_t *topology, if (loop_end > expire_at) { /* no time left in server_selection_timeout_msec */ - _mongoc_server_selection_error ( - timeout_msg, &scanner_error, error); + _mongoc_server_selection_error (timeout_msg, &scanner_error, error); server_id = 0; goto done; @@ -1334,8 +1230,8 @@ mongoc_topology_select_server_id (mongoc_topology_t *topology, goto done; } - selected_server = mongoc_topology_description_select ( - td.ptr, optype, read_prefs, must_use_primary, ds, local_threshold_ms); + selected_server = + mongoc_topology_description_select (td.ptr, optype, read_prefs, must_use_primary, ds, local_threshold_ms); if (selected_server) { server_id = selected_server->id; @@ -1350,8 +1246,8 @@ mongoc_topology_select_server_id (mongoc_topology_t *topology, /* Now that we have the lock, check again, since a scan may have * occurred while we were waiting on the lock. */ mc_tpld_renew_ref (&td, topology); - selected_server = mongoc_topology_description_select ( - td.ptr, optype, read_prefs, must_use_primary, ds, local_threshold_ms); + selected_server = + mongoc_topology_description_select (td.ptr, optype, read_prefs, must_use_primary, ds, local_threshold_ms); if (selected_server) { server_id = selected_server->id; bson_mutex_unlock (&topology->tpld_modification_mtx); @@ -1359,16 +1255,13 @@ mongoc_topology_select_server_id (mongoc_topology_t *topology, } /* Still nothing. Request that the scanner do a scan now. */ - TRACE ( - "server selection requesting an immediate scan, want %s", - _mongoc_read_mode_as_str (mongoc_read_prefs_get_mode (read_prefs))); + TRACE ("server selection requesting an immediate scan, want %s", + _mongoc_read_mode_as_str (mongoc_read_prefs_get_mode (read_prefs))); _mongoc_topology_request_scan (topology); - TRACE ("server selection about to wait for %" PRId64 "ms", - (expire_at - loop_start) / 1000); - r = mongoc_cond_timedwait (&topology->cond_client, - &topology->tpld_modification_mtx, - (expire_at - loop_start) / 1000); + TRACE ("server selection about to wait for %" PRId64 "ms", (expire_at - loop_start) / 1000); + r = mongoc_cond_timedwait ( + &topology->cond_client, &topology->tpld_modification_mtx, (expire_at - loop_start) / 1000); TRACE ("%s", "server selection awake"); /* Refresh our topology handle */ mc_tpld_renew_ref (&td, topology); @@ -1414,9 +1307,7 @@ mongoc_topology_select_server_id (mongoc_topology_t *topology, mongoc_host_list_t * -_mongoc_topology_host_by_id (const mongoc_topology_description_t *td, - uint32_t id, - bson_error_t *error) +_mongoc_topology_host_by_id (const mongoc_topology_description_t *td, uint32_t id, bson_error_t *error) { mongoc_server_description_t const *sd; mongoc_host_list_t *host = NULL; @@ -1440,8 +1331,7 @@ _mongoc_topology_request_scan (mongoc_topology_t *topology) } bool -_mongoc_topology_update_from_handshake (mongoc_topology_t *topology, - const mongoc_server_description_t *sd) +_mongoc_topology_update_from_handshake (mongoc_topology_t *topology, const mongoc_server_description_t *sd) { bool has_server; mc_tpld_modification tdmod; @@ -1459,11 +1349,8 @@ _mongoc_topology_update_from_handshake (mongoc_topology_t *topology, tdmod = mc_tpld_modify_begin (topology); /* return false if server was removed from topology */ - has_server = _mongoc_topology_update_no_lock (sd->id, - &sd->last_hello_response, - sd->round_trip_time_msec, - tdmod.new_td, - NULL); + has_server = + _mongoc_topology_update_no_lock (sd->id, &sd->last_hello_response, sd->round_trip_time_msec, tdmod.new_td, NULL); /* if pooled, wake threads waiting in mongoc_topology_server_by_id */ mongoc_cond_broadcast (&topology->cond_client); @@ -1487,8 +1374,7 @@ _mongoc_topology_update_from_handshake (mongoc_topology_t *topology, */ void -_mongoc_topology_update_last_used (mongoc_topology_t *topology, - uint32_t server_id) +_mongoc_topology_update_last_used (mongoc_topology_t *topology, uint32_t server_id) { mongoc_topology_scanner_node_t *node; @@ -1538,8 +1424,7 @@ _mongoc_topology_set_appname (mongoc_topology_t *topology, const char *appname) */ void -_mongoc_topology_update_cluster_time (mongoc_topology_t *topology, - const bson_t *reply) +_mongoc_topology_update_cluster_time (mongoc_topology_t *topology, const bson_t *reply) { bson_iter_t iter; bson_iter_t child; @@ -1552,8 +1437,7 @@ _mongoc_topology_update_cluster_time (mongoc_topology_t *topology, return; } - if (!BSON_ITER_HOLDS_DOCUMENT (&iter) || - !bson_iter_recurse (&iter, &child)) { + if (!BSON_ITER_HOLDS_DOCUMENT (&iter) || !bson_iter_recurse (&iter, &child)) { MONGOC_ERROR ("Can't parse $clusterTime"); return; } @@ -1570,18 +1454,15 @@ _mongoc_topology_update_cluster_time (mongoc_topology_t *topology, * * Check that the cluster time has actually changed from what we have on * record before opening a topology modification to update it. */ - if (bson_empty (&td.ptr->cluster_time) || - _mongoc_cluster_time_greater (&cluster_time, &td.ptr->cluster_time)) { + if (bson_empty (&td.ptr->cluster_time) || _mongoc_cluster_time_greater (&cluster_time, &td.ptr->cluster_time)) { mc_tpld_modification tdmod = mc_tpld_modify_begin (topology); /* Check again if we need to update the cluster time, since it may have * been updated behind our back. */ if (bson_empty (&tdmod.new_td->cluster_time) || - _mongoc_cluster_time_greater (&cluster_time, - &tdmod.new_td->cluster_time)) { + _mongoc_cluster_time_greater (&cluster_time, &tdmod.new_td->cluster_time)) { bson_destroy (&tdmod.new_td->cluster_time); bson_copy_to (&cluster_time, &tdmod.new_td->cluster_time); - _mongoc_topology_scanner_set_cluster_time ( - topology->scanner, &tdmod.new_td->cluster_time); + _mongoc_topology_scanner_set_cluster_time (topology->scanner, &tdmod.new_td->cluster_time); mc_tpld_modify_commit (tdmod); } else { mc_tpld_modify_drop (tdmod); @@ -1603,8 +1484,7 @@ _mongoc_topology_update_cluster_time (mongoc_topology_t *topology, */ mongoc_server_session_t * -_mongoc_topology_pop_server_session (mongoc_topology_t *topology, - bson_error_t *error) +_mongoc_topology_pop_server_session (mongoc_topology_t *topology, bson_error_t *error) { int64_t timeout; mongoc_server_session_t *ss = NULL; @@ -1620,13 +1500,12 @@ _mongoc_topology_pop_server_session (mongoc_topology_t *topology, if (!loadbalanced && timeout == MONGOC_NO_SESSIONS) { /* if needed, connect and check for session timeout again */ if (!mongoc_topology_description_has_data_node (td.ptr)) { - if (!mongoc_topology_select_server_id ( - topology, - MONGOC_SS_READ, - NULL /* read prefs */, - NULL /* chosen read mode */, - NULL /* deprioritized servers */, - error)) { + if (!mongoc_topology_select_server_id (topology, + MONGOC_SS_READ, + NULL /* read prefs */, + NULL /* chosen read mode */, + NULL /* deprioritized servers */, + error)) { ss = NULL; goto done; } @@ -1638,10 +1517,8 @@ _mongoc_topology_pop_server_session (mongoc_topology_t *topology, } if (timeout == MONGOC_NO_SESSIONS) { - bson_set_error (error, - MONGOC_ERROR_CLIENT, - MONGOC_ERROR_CLIENT_SESSION_FAILURE, - "Server does not support sessions"); + bson_set_error ( + error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_SESSION_FAILURE, "Server does not support sessions"); ss = NULL; goto done; } @@ -1665,8 +1542,7 @@ _mongoc_topology_pop_server_session (mongoc_topology_t *topology, */ void -_mongoc_topology_push_server_session (mongoc_topology_t *topology, - mongoc_server_session_t *server_session) +_mongoc_topology_push_server_session (mongoc_topology_t *topology, mongoc_server_session_t *server_session) { ENTRY; @@ -1716,15 +1592,13 @@ _mongoc_topology_end_sessions_cmd (mongoc_topology_t *topology, bson_t *cmd) /* Only end up to 10'000 sessions */ const int ENDED_SESSION_PRUNING_LIMIT = 10000; int i = 0; - mongoc_server_session_t *ss = - mongoc_server_session_pool_get_existing (topology->session_pool); + mongoc_server_session_t *ss = mongoc_server_session_pool_get_existing (topology->session_pool); bson_init (cmd); BSON_APPEND_ARRAY_BUILDER_BEGIN (cmd, "endSessions", &ar); for (; i < ENDED_SESSION_PRUNING_LIMIT && ss != NULL; - ++i, - ss = mongoc_server_session_pool_get_existing (topology->session_pool)) { + ++i, ss = mongoc_server_session_pool_get_existing (topology->session_pool)) { bson_array_builder_append_document (ar, &ss->lsid); mongoc_server_session_pool_drop (topology->session_pool, ss); } @@ -1741,8 +1615,7 @@ _mongoc_topology_end_sessions_cmd (mongoc_topology_t *topology, bson_t *cmd) } void -_mongoc_topology_dup_handshake_cmd (const mongoc_topology_t *topology, - bson_t *copy_into) +_mongoc_topology_dup_handshake_cmd (const mongoc_topology_t *topology, bson_t *copy_into) { _mongoc_topology_scanner_dup_handshake_cmd (topology->scanner, copy_into); } @@ -1761,8 +1634,7 @@ _find_topology_version (const bson_t *reply, bson_t *topology_version) const uint8_t *bytes; uint32_t len; - if (!bson_iter_init_find (&iter, reply, "topologyVersion") || - !BSON_ITER_HOLDS_DOCUMENT (&iter)) { + if (!bson_iter_init_find (&iter, reply, "topologyVersion") || !BSON_ITER_HOLDS_DOCUMENT (&iter)) { bson_init (topology_version); return; } @@ -1790,8 +1662,7 @@ _handle_sdam_app_error_command (mongoc_topology_t *topology, BSON_UNUSED (td); - if (_mongoc_cmd_check_ok_no_wce ( - reply, MONGOC_ERROR_API_VERSION_2, &cmd_error)) { + if (_mongoc_cmd_check_ok_no_wce (reply, MONGOC_ERROR_API_VERSION_2, &cmd_error)) { /* No error. */ return false; } @@ -1806,21 +1677,18 @@ _handle_sdam_app_error_command (mongoc_topology_t *topology, * version of the server than we have stored in the topology description. */ _find_topology_version (reply, &incoming_topology_version); - if (mongoc_server_description_topology_version_cmp ( - &sd->topology_version, &incoming_topology_version) >= 0) { + if (mongoc_server_description_topology_version_cmp (&sd->topology_version, &incoming_topology_version) >= 0) { /* The server description is greater or equal, ignore the error. */ bson_destroy (&incoming_topology_version); return false; } - should_clear_pool = (max_wire_version <= WIRE_VERSION_4_0 || - _mongoc_error_is_shutdown (&cmd_error)); + should_clear_pool = (max_wire_version <= WIRE_VERSION_4_0 || _mongoc_error_is_shutdown (&cmd_error)); tdmod = mc_tpld_modify_begin (topology); /* Get the server handle again, which might have been removed. */ - mut_sd = - mongoc_topology_description_server_by_id (tdmod.new_td, server_id, NULL); + mut_sd = mongoc_topology_description_server_by_id (tdmod.new_td, server_id, NULL); if (!mut_sd) { /* Server was already removed/invalidated */ @@ -1831,8 +1699,7 @@ _handle_sdam_app_error_command (mongoc_topology_t *topology, /* Check the topology version a second time, now that we have an exclusive * lock on the latest topology description. */ - if (mongoc_server_description_topology_version_cmp ( - &mut_sd->topology_version, &incoming_topology_version) >= 0) { + if (mongoc_server_description_topology_version_cmp (&mut_sd->topology_version, &incoming_topology_version) >= 0) { /* The server description is greater or equal, ignore the error. */ mc_tpld_modify_drop (tdmod); bson_destroy (&incoming_topology_version); @@ -1847,8 +1714,7 @@ _handle_sdam_app_error_command (mongoc_topology_t *topology, } /* Overwrite the topology version. */ - mongoc_server_description_set_topology_version (mut_sd, - &incoming_topology_version); + mongoc_server_description_set_topology_version (mut_sd, &incoming_topology_version); /* SDAM: When handling a "not primary" or "node is recovering" error, the * client MUST clear the server's connection pool if and only if the error @@ -1856,8 +1722,7 @@ _handle_sdam_app_error_command (mongoc_topology_t *topology, * < 4.2. */ if (should_clear_pool) { - _mongoc_topology_description_clear_connection_pool ( - tdmod.new_td, server_id, service_id); + _mongoc_topology_description_clear_connection_pool (tdmod.new_td, server_id, service_id); pool_cleared = true; } @@ -1867,8 +1732,7 @@ _handle_sdam_app_error_command (mongoc_topology_t *topology, * current ServerDescription's topologyVersion it MUST replace the * server's description with a ServerDescription of type Unknown. */ - mongoc_topology_description_invalidate_server ( - tdmod.new_td, server_id, &cmd_error); + mongoc_topology_description_invalidate_server (tdmod.new_td, server_id, &cmd_error); if (topology->single_threaded) { /* SDAM: For single-threaded clients, in the case of a "not primary" or @@ -1911,8 +1775,7 @@ _mongoc_topology_handle_app_error (mongoc_topology_t *topology, mc_shared_tpld td = mc_tpld_take_ref (topology); /* Start by checking every condition in which we should ignore the error */ - sd = mongoc_topology_description_server_by_id_const ( - td.ptr, server_id, &server_selection_error); + sd = mongoc_topology_description_server_by_id_const (td.ptr, server_id, &server_selection_error); if (!sd) { /* The server was already removed from the topology. Ignore error. */ @@ -1938,34 +1801,24 @@ _mongoc_topology_handle_app_error (mongoc_topology_t *topology, /* Do something with the error */ if (type == MONGOC_SDAM_APP_ERROR_COMMAND) { - cleared_pool = _handle_sdam_app_error_command (topology, - td.ptr, - server_id, - generation, - service_id, - sd, - max_wire_version, - reply); + cleared_pool = _handle_sdam_app_error_command ( + topology, td.ptr, server_id, generation, service_id, sd, max_wire_version, reply); } else { /* Invalidate the server that saw the error. */ mc_tpld_modification tdmod = mc_tpld_modify_begin (topology); - sd = mongoc_topology_description_server_by_id_const ( - tdmod.new_td, server_id, NULL); + sd = mongoc_topology_description_server_by_id_const (tdmod.new_td, server_id, NULL); /* Check if the server has already been invalidated */ if (!sd || generation < mc_tpl_sd_get_generation (sd, service_id)) { mc_tpld_modify_drop (tdmod); goto ignore_error; } /* Mark server as unknown. */ - mongoc_topology_description_invalidate_server ( - tdmod.new_td, server_id, why); + mongoc_topology_description_invalidate_server (tdmod.new_td, server_id, why); /* Clear the connection pool */ - _mongoc_topology_description_clear_connection_pool ( - tdmod.new_td, server_id, service_id); + _mongoc_topology_description_clear_connection_pool (tdmod.new_td, server_id, service_id); cleared_pool = true; if (!topology->single_threaded) { - _mongoc_topology_background_monitoring_cancel_check (topology, - server_id); + _mongoc_topology_background_monitoring_cancel_check (topology, server_id); } mc_tpld_modify_commit (tdmod); } @@ -1982,8 +1835,7 @@ _mongoc_topology_handle_app_error (mongoc_topology_t *topology, * servers that were removed from the topology. */ static void -_topology_collect_errors (const mongoc_topology_description_t *td, - bson_error_t *error_out) +_topology_collect_errors (const mongoc_topology_description_t *td, bson_error_t *error_out) { const mongoc_server_description_t *server_description; bson_string_t *error_message; @@ -2000,39 +1852,33 @@ _topology_collect_errors (const mongoc_topology_description_t *td, if (error_message->len > 0) { bson_string_append_c (error_message, ' '); } - bson_string_append_printf ( - error_message, "[%s]", server_description->error.message); + bson_string_append_printf (error_message, "[%s]", server_description->error.message); /* The last error's code and domain wins. */ error_out->code = error->code; error_out->domain = error->domain; } } - bson_strncpy ((char *) &error_out->message, - error_message->str, - sizeof (error_out->message)); + bson_strncpy ((char *) &error_out->message, error_message->str, sizeof (error_out->message)); bson_string_free (error_message, true); } void -_mongoc_topology_set_rr_resolver (mongoc_topology_t *topology, - _mongoc_rr_resolver_fn rr_resolver) +_mongoc_topology_set_rr_resolver (mongoc_topology_t *topology, _mongoc_rr_resolver_fn rr_resolver) { topology->rr_resolver = rr_resolver; } void -_mongoc_topology_set_srv_polling_rescan_interval_ms ( - mongoc_topology_t *topology, int64_t val) +_mongoc_topology_set_srv_polling_rescan_interval_ms (mongoc_topology_t *topology, int64_t val) { topology->srv_polling_rescan_interval_ms = val; } uint32_t -_mongoc_topology_get_connection_pool_generation ( - const mongoc_topology_description_t *td, - uint32_t server_id, - const bson_oid_t *service_id) +_mongoc_topology_get_connection_pool_generation (const mongoc_topology_description_t *td, + uint32_t server_id, + const bson_oid_t *service_id) { const mongoc_server_description_t *sd; bson_error_t error; @@ -2066,12 +1912,9 @@ mc_tpld_modify_begin (mongoc_topology_t *tpl) void mc_tpld_modify_commit (mc_tpld_modification mod) { - mongoc_shared_ptr old_sptr = - mongoc_shared_ptr_copy (mod.topology->_shared_descr_._sptr_); - mongoc_shared_ptr new_sptr = - mongoc_shared_ptr_create (mod.new_td, _tpld_destroy_and_free); - mongoc_atomic_shared_ptr_store (&mod.topology->_shared_descr_._sptr_, - new_sptr); + mongoc_shared_ptr old_sptr = mongoc_shared_ptr_copy (mod.topology->_shared_descr_._sptr_); + mongoc_shared_ptr new_sptr = mongoc_shared_ptr_create (mod.new_td, _tpld_destroy_and_free); + mongoc_atomic_shared_ptr_store (&mod.topology->_shared_descr_._sptr_, new_sptr); bson_mutex_unlock (&mod.topology->tpld_modification_mtx); mongoc_shared_ptr_reset_null (&new_sptr); mongoc_shared_ptr_reset_null (&old_sptr); diff --git a/src/libmongoc/src/mongoc/mongoc-trace-private.h b/src/libmongoc/src/mongoc/mongoc-trace-private.h index 604b27621e..b003c48368 100644 --- a/src/libmongoc/src/mongoc/mongoc-trace-private.h +++ b/src/libmongoc/src/mongoc/mongoc-trace-private.h @@ -31,60 +31,39 @@ BSON_BEGIN_DECLS -#define TRACE(msg, ...) \ - do { \ - if (MONGOC_TRACE_ENABLED) { \ - mongoc_log (MONGOC_LOG_LEVEL_TRACE, \ - MONGOC_LOG_DOMAIN, \ - "TRACE: %s():%d " msg, \ - BSON_FUNC, \ - __LINE__, \ - __VA_ARGS__); \ - } \ +#define TRACE(msg, ...) \ + do { \ + if (MONGOC_TRACE_ENABLED) { \ + mongoc_log ( \ + MONGOC_LOG_LEVEL_TRACE, MONGOC_LOG_DOMAIN, "TRACE: %s():%d " msg, BSON_FUNC, __LINE__, __VA_ARGS__); \ + } \ } while (0) -#define ENTRY \ - do { \ - if (MONGOC_TRACE_ENABLED) { \ - mongoc_log (MONGOC_LOG_LEVEL_TRACE, \ - MONGOC_LOG_DOMAIN, \ - "ENTRY: %s():%d", \ - BSON_FUNC, \ - __LINE__); \ - } \ +#define ENTRY \ + do { \ + if (MONGOC_TRACE_ENABLED) { \ + mongoc_log (MONGOC_LOG_LEVEL_TRACE, MONGOC_LOG_DOMAIN, "ENTRY: %s():%d", BSON_FUNC, __LINE__); \ + } \ } while (0) -#define EXIT \ - do { \ - if (MONGOC_TRACE_ENABLED) { \ - mongoc_log (MONGOC_LOG_LEVEL_TRACE, \ - MONGOC_LOG_DOMAIN, \ - " EXIT: %s():%d", \ - BSON_FUNC, \ - __LINE__); \ - } \ - return; \ +#define EXIT \ + do { \ + if (MONGOC_TRACE_ENABLED) { \ + mongoc_log (MONGOC_LOG_LEVEL_TRACE, MONGOC_LOG_DOMAIN, " EXIT: %s():%d", BSON_FUNC, __LINE__); \ + } \ + return; \ } while (0) -#define RETURN(ret) \ - do { \ - if (MONGOC_TRACE_ENABLED) { \ - mongoc_log (MONGOC_LOG_LEVEL_TRACE, \ - MONGOC_LOG_DOMAIN, \ - " EXIT: %s():%d", \ - BSON_FUNC, \ - __LINE__); \ - } \ - return ret; \ +#define RETURN(ret) \ + do { \ + if (MONGOC_TRACE_ENABLED) { \ + mongoc_log (MONGOC_LOG_LEVEL_TRACE, MONGOC_LOG_DOMAIN, " EXIT: %s():%d", BSON_FUNC, __LINE__); \ + } \ + return ret; \ } while (0) -#define GOTO(label) \ - do { \ - if (MONGOC_TRACE_ENABLED) { \ - mongoc_log (MONGOC_LOG_LEVEL_TRACE, \ - MONGOC_LOG_DOMAIN, \ - " GOTO: %s():%d %s", \ - BSON_FUNC, \ - __LINE__, \ - #label); \ - } \ - goto label; \ +#define GOTO(label) \ + do { \ + if (MONGOC_TRACE_ENABLED) { \ + mongoc_log (MONGOC_LOG_LEVEL_TRACE, MONGOC_LOG_DOMAIN, " GOTO: %s():%d %s", BSON_FUNC, __LINE__, #label); \ + } \ + goto label; \ } while (0) #define DUMP_BYTES(_n, _b, _l) \ do { \ diff --git a/src/libmongoc/src/mongoc/mongoc-ts-pool-private.h b/src/libmongoc/src/mongoc/mongoc-ts-pool-private.h index 9a4c515162..95a0b940f5 100644 --- a/src/libmongoc/src/mongoc/mongoc-ts-pool-private.h +++ b/src/libmongoc/src/mongoc/mongoc-ts-pool-private.h @@ -10,9 +10,7 @@ struct _bson_error_t; /** Type of an object constructor function */ -typedef void (*_erased_constructor_fn) (void *self, - void *userdata, - struct _bson_error_t *error_out); +typedef void (*_erased_constructor_fn) (void *self, void *userdata, struct _bson_error_t *error_out); /** Type of an object destructor function */ typedef void (*_erased_destructor_fn) (void *self, void *userdata); /** Type of an object pruning predicate */ @@ -231,9 +229,7 @@ mongoc_ts_pool_drop (mongoc_ts_pool *pool, void *item); void mongoc_ts_pool_visit_each (mongoc_ts_pool *pool, void *visit_userdata, - int (*visitor) (void *item, - void *pool_userdata, - void *visit_userdata)); + int (*visitor) (void *item, void *pool_userdata, void *visit_userdata)); /** * @brief Declare a thread-safe pool type that contains elements of a specific @@ -250,95 +246,80 @@ mongoc_ts_pool_visit_each (mongoc_ts_pool *pool, * @param PrunePredicate A function that checks whether elements should be * dropped from the pool, or `NULL` */ -#define MONGOC_DECL_SPECIAL_TS_POOL(ElementType, \ - PoolName, \ - UserDataType, \ - Constructor, \ - Destructor, \ - PrunePredicate) \ - typedef struct PoolName { \ - mongoc_ts_pool *pool; \ - } PoolName; \ - \ - BSON_MAYBE_UNUSED static BSON_INLINE PoolName PoolName##_new_with_params ( \ - void (*constructor) ( \ - ElementType *, UserDataType *, struct _bson_error_t *), \ - void (*destructor) (ElementType *, UserDataType *), \ - int (*prune_predicate) (ElementType *, UserDataType *), \ - UserDataType *userdata) \ - { \ - PoolName ret; \ - mongoc_ts_pool_params params = {0}; \ - params.userdata = userdata; \ - params.constructor = (_erased_constructor_fn) constructor; \ - params.destructor = (_erased_destructor_fn) destructor; \ - params.prune_predicate = (_erased_prune_predicate) prune_predicate; \ - params.element_alignment = BSON_ALIGNOF (ElementType); \ - params.element_size = sizeof (ElementType); \ - ret.pool = mongoc_ts_pool_new (params); \ - return ret; \ - } \ - \ - BSON_MAYBE_UNUSED static BSON_INLINE PoolName PoolName##_new ( \ - UserDataType *userdata) \ - { \ - return PoolName##_new_with_params ( \ - Constructor, Destructor, PrunePredicate, userdata); \ - } \ - \ - BSON_MAYBE_UNUSED static BSON_INLINE void PoolName##_free (PoolName p) \ - { \ - mongoc_ts_pool_free (p.pool); \ - } \ - \ - BSON_MAYBE_UNUSED static BSON_INLINE void PoolName##_clear (PoolName p) \ - { \ - mongoc_ts_pool_clear (p.pool); \ - } \ - \ - BSON_MAYBE_UNUSED static BSON_INLINE ElementType *PoolName##_get_existing ( \ - PoolName p) \ - { \ - return (ElementType *) mongoc_ts_pool_get_existing (p.pool); \ - } \ - \ - BSON_MAYBE_UNUSED static BSON_INLINE ElementType *PoolName##_get ( \ - PoolName p, struct _bson_error_t *error) \ - { \ - return (ElementType *) mongoc_ts_pool_get (p.pool, error); \ - } \ - \ - BSON_MAYBE_UNUSED static BSON_INLINE void PoolName##_return ( \ - PoolName p, ElementType *elem) \ - { \ - mongoc_ts_pool_return (p.pool, elem); \ - } \ - \ - BSON_MAYBE_UNUSED static BSON_INLINE void PoolName##_drop ( \ - PoolName p, ElementType *elem) \ - { \ - mongoc_ts_pool_drop (p.pool, elem); \ - } \ - \ - BSON_MAYBE_UNUSED static BSON_INLINE size_t PoolName##_size (PoolName p) \ - { \ - return mongoc_ts_pool_size (p.pool); \ - } \ - \ - BSON_MAYBE_UNUSED static BSON_INLINE int PoolName##_is_empty (PoolName p) \ - { \ - return mongoc_ts_pool_is_empty (p.pool); \ - } \ - \ - BSON_MAYBE_UNUSED static BSON_INLINE void PoolName##_visit_each ( \ - PoolName p, \ - void *visit_userdata, \ - int (*visitor) (ElementType * elem, \ - UserDataType * pool_userdata, \ - void *visit_userdata)) \ - { \ - mongoc_ts_pool_visit_each ( \ - p.pool, visit_userdata, (int (*) (void *, void *, void *)) visitor); \ +#define MONGOC_DECL_SPECIAL_TS_POOL(ElementType, PoolName, UserDataType, Constructor, Destructor, PrunePredicate) \ + typedef struct PoolName { \ + mongoc_ts_pool *pool; \ + } PoolName; \ + \ + BSON_MAYBE_UNUSED static BSON_INLINE PoolName PoolName##_new_with_params ( \ + void (*constructor) (ElementType *, UserDataType *, struct _bson_error_t *), \ + void (*destructor) (ElementType *, UserDataType *), \ + int (*prune_predicate) (ElementType *, UserDataType *), \ + UserDataType *userdata) \ + { \ + PoolName ret; \ + mongoc_ts_pool_params params = {0}; \ + params.userdata = userdata; \ + params.constructor = (_erased_constructor_fn) constructor; \ + params.destructor = (_erased_destructor_fn) destructor; \ + params.prune_predicate = (_erased_prune_predicate) prune_predicate; \ + params.element_alignment = BSON_ALIGNOF (ElementType); \ + params.element_size = sizeof (ElementType); \ + ret.pool = mongoc_ts_pool_new (params); \ + return ret; \ + } \ + \ + BSON_MAYBE_UNUSED static BSON_INLINE PoolName PoolName##_new (UserDataType *userdata) \ + { \ + return PoolName##_new_with_params (Constructor, Destructor, PrunePredicate, userdata); \ + } \ + \ + BSON_MAYBE_UNUSED static BSON_INLINE void PoolName##_free (PoolName p) \ + { \ + mongoc_ts_pool_free (p.pool); \ + } \ + \ + BSON_MAYBE_UNUSED static BSON_INLINE void PoolName##_clear (PoolName p) \ + { \ + mongoc_ts_pool_clear (p.pool); \ + } \ + \ + BSON_MAYBE_UNUSED static BSON_INLINE ElementType *PoolName##_get_existing (PoolName p) \ + { \ + return (ElementType *) mongoc_ts_pool_get_existing (p.pool); \ + } \ + \ + BSON_MAYBE_UNUSED static BSON_INLINE ElementType *PoolName##_get (PoolName p, struct _bson_error_t *error) \ + { \ + return (ElementType *) mongoc_ts_pool_get (p.pool, error); \ + } \ + \ + BSON_MAYBE_UNUSED static BSON_INLINE void PoolName##_return (PoolName p, ElementType *elem) \ + { \ + mongoc_ts_pool_return (p.pool, elem); \ + } \ + \ + BSON_MAYBE_UNUSED static BSON_INLINE void PoolName##_drop (PoolName p, ElementType *elem) \ + { \ + mongoc_ts_pool_drop (p.pool, elem); \ + } \ + \ + BSON_MAYBE_UNUSED static BSON_INLINE size_t PoolName##_size (PoolName p) \ + { \ + return mongoc_ts_pool_size (p.pool); \ + } \ + \ + BSON_MAYBE_UNUSED static BSON_INLINE int PoolName##_is_empty (PoolName p) \ + { \ + return mongoc_ts_pool_is_empty (p.pool); \ + } \ + \ + BSON_MAYBE_UNUSED static BSON_INLINE void PoolName##_visit_each ( \ + PoolName p, \ + void *visit_userdata, \ + int (*visitor) (ElementType * elem, UserDataType * pool_userdata, void *visit_userdata)) \ + { \ + mongoc_ts_pool_visit_each (p.pool, visit_userdata, (int (*) (void *, void *, void *)) visitor); \ } #endif /* MONGOC_TS_POOL_PRIVATE_H */ diff --git a/src/libmongoc/src/mongoc/mongoc-ts-pool.c b/src/libmongoc/src/mongoc/mongoc-ts-pool.c index 42a7cc661b..f00e4e8d0e 100644 --- a/src/libmongoc/src/mongoc/mongoc-ts-pool.c +++ b/src/libmongoc/src/mongoc/mongoc-ts-pool.c @@ -31,8 +31,7 @@ typedef struct pool_node { } pool_node; // Flexible member array member should not contribute to sizeof result. -BSON_STATIC_ASSERT2 (pool_node_size, - sizeof (pool_node) == sizeof (void *) * 2u); +BSON_STATIC_ASSERT2 (pool_node_size, sizeof (pool_node) == sizeof (void *) * 2u); struct mongoc_ts_pool { mongoc_ts_pool_params params; @@ -75,16 +74,14 @@ _pool_node_new (const mongoc_ts_pool *pool) const size_t alignment = pool->params.element_alignment; const size_t size = pool->params.element_size; - const size_t minimum_size = - sizeof (pool_node) + _pool_node_data_offset (pool) + size; + const size_t minimum_size = sizeof (pool_node) + _pool_node_data_offset (pool) + size; if (alignment == 0) { return bson_malloc0 (minimum_size); } // aligned_alloc requires allocation size to be a multiple of the alignment. - const size_t required_size = - minimum_size + (alignment - (minimum_size % alignment)); + const size_t required_size = minimum_size + (alignment - (minimum_size % alignment)); return bson_aligned_alloc0 (alignment, required_size); } @@ -115,8 +112,7 @@ _pool_node_get_data (pool_node *node) static pool_node * _pool_node_from_item (void *item, const mongoc_ts_pool *pool) { - return (void *) (((unsigned char *) item) - _pool_node_data_offset (pool) - - offsetof (pool_node, data)); + return (void *) (((unsigned char *) item) - _pool_node_data_offset (pool) - offsetof (pool_node, data)); } /** @@ -127,8 +123,7 @@ _should_prune (const pool_node *node) { mongoc_ts_pool *pool = node->owner_pool; return pool->params.prune_predicate && - pool->params.prune_predicate (_pool_node_get_data_const (node), - pool->params.userdata); + pool->params.prune_predicate (_pool_node_get_data_const (node), pool->params.userdata); } /** @@ -156,8 +151,7 @@ _new_item (mongoc_ts_pool *pool, bson_error_t *error) error->domain = 0; error->message[0] = 0; /* Construct the object */ - pool->params.constructor ( - _pool_node_get_data (node), pool->params.userdata, error); + pool->params.constructor (_pool_node_get_data (node), pool->params.userdata, error); if (error->code != 0) { /* Constructor reported an error. Deallocate and drop the node. */ bson_free (node); @@ -165,8 +159,7 @@ _new_item (mongoc_ts_pool *pool, bson_error_t *error) } } if (node && audit_pool_enabled) { - bson_atomic_int32_fetch_add ( - &pool->outstanding_items, 1, bson_memory_order_relaxed); + bson_atomic_int32_fetch_add (&pool->outstanding_items, 1, bson_memory_order_relaxed); } return node; } @@ -179,8 +172,7 @@ _delete_item (pool_node *node) { mongoc_ts_pool *pool = node->owner_pool; if (pool->params.destructor) { - pool->params.destructor (_pool_node_get_data (node), - pool->params.userdata); + pool->params.destructor (_pool_node_get_data (node), pool->params.userdata); } bson_free (node); } @@ -201,8 +193,7 @@ _try_get (mongoc_ts_pool *pool) if (node) { bson_atomic_int32_fetch_sub (&pool->size, 1, bson_memory_order_relaxed); if (audit_pool_enabled) { - bson_atomic_int32_fetch_add ( - &pool->outstanding_items, 1, bson_memory_order_relaxed); + bson_atomic_int32_fetch_add (&pool->outstanding_items, 1, bson_memory_order_relaxed); } } return node; @@ -236,9 +227,7 @@ void mongoc_ts_pool_free (mongoc_ts_pool *pool) { if (audit_pool_enabled) { - BSON_ASSERT ( - pool->outstanding_items == 0 && - "Pool was destroyed while there are still items checked out"); + BSON_ASSERT (pool->outstanding_items == 0 && "Pool was destroyed while there are still items checked out"); } mongoc_ts_pool_clear (pool); bson_mutex_destroy (&pool->mtx); @@ -313,11 +302,9 @@ mongoc_ts_pool_return (mongoc_ts_pool *pool, void *item) node->next = pool->head; pool->head = node; bson_mutex_unlock (&pool->mtx); - bson_atomic_int32_fetch_add ( - &node->owner_pool->size, 1, bson_memory_order_relaxed); + bson_atomic_int32_fetch_add (&node->owner_pool->size, 1, bson_memory_order_relaxed); if (audit_pool_enabled) { - bson_atomic_int32_fetch_sub ( - &node->owner_pool->outstanding_items, 1, bson_memory_order_relaxed); + bson_atomic_int32_fetch_sub (&node->owner_pool->outstanding_items, 1, bson_memory_order_relaxed); } } } @@ -330,8 +317,7 @@ mongoc_ts_pool_drop (mongoc_ts_pool *pool, void *item) BSON_ASSERT (pool == node->owner_pool); if (audit_pool_enabled) { - bson_atomic_int32_fetch_sub ( - &node->owner_pool->outstanding_items, 1, bson_memory_order_relaxed); + bson_atomic_int32_fetch_sub (&node->owner_pool->outstanding_items, 1, bson_memory_order_relaxed); } _delete_item (node); } @@ -351,9 +337,7 @@ mongoc_ts_pool_size (const mongoc_ts_pool *pool) void mongoc_ts_pool_visit_each (mongoc_ts_pool *pool, void *visit_userdata, - int (*visit) (void *item, - void *pool_userdata, - void *visit_userdata)) + int (*visit) (void *item, void *pool_userdata, void *visit_userdata)) { /* Pointer to the pointer that must be updated in case of an item pruning */ pool_node **node_ptrptr; @@ -363,8 +347,7 @@ mongoc_ts_pool_visit_each (mongoc_ts_pool *pool, node_ptrptr = &pool->head; node = pool->head; while (node) { - const bool should_remove = visit ( - _pool_node_get_data (node), pool->params.userdata, visit_userdata); + const bool should_remove = visit (_pool_node_get_data (node), pool->params.userdata, visit_userdata); pool_node *const next_node = node->next; if (!should_remove) { node_ptrptr = &node->next; diff --git a/src/libmongoc/src/mongoc/mongoc-uri-private.h b/src/libmongoc/src/mongoc/mongoc-uri-private.h index 37182bf0d0..f2d8870d84 100644 --- a/src/libmongoc/src/mongoc/mongoc-uri-private.h +++ b/src/libmongoc/src/mongoc/mongoc-uri-private.h @@ -28,24 +28,16 @@ BSON_BEGIN_DECLS bool -mongoc_uri_upsert_host_and_port (mongoc_uri_t *uri, - const char *host_and_port, - bson_error_t *error); +mongoc_uri_upsert_host_and_port (mongoc_uri_t *uri, const char *host_and_port, bson_error_t *error); bool -mongoc_uri_upsert_host (mongoc_uri_t *uri, - const char *host, - uint16_t port, - bson_error_t *error); +mongoc_uri_upsert_host (mongoc_uri_t *uri, const char *host, uint16_t port, bson_error_t *error); void mongoc_uri_remove_host (mongoc_uri_t *uri, const char *host, uint16_t port); bool mongoc_uri_parse_host (mongoc_uri_t *uri, const char *str); bool -mongoc_uri_parse_options (mongoc_uri_t *uri, - const char *str, - bool from_dns, - bson_error_t *error); +mongoc_uri_parse_options (mongoc_uri_t *uri, const char *str, bool from_dns, bson_error_t *error); int32_t mongoc_uri_get_local_threshold_option (const mongoc_uri_t *uri); @@ -56,24 +48,17 @@ const char * mongoc_uri_canonicalize_option (const char *key); mongoc_uri_t * -_mongoc_uri_copy_and_replace_host_list (const mongoc_uri_t *original, - const char *host); +_mongoc_uri_copy_and_replace_host_list (const mongoc_uri_t *original, const char *host); bool -mongoc_uri_init_with_srv_host_list (mongoc_uri_t *uri, - mongoc_host_list_t *hosts, - bson_error_t *error); +mongoc_uri_init_with_srv_host_list (mongoc_uri_t *uri, mongoc_host_list_t *hosts, bson_error_t *error); bool -mongoc_uri_validate_srv_result (const mongoc_uri_t *uri, - const char *host, - bson_error_t *error); +mongoc_uri_validate_srv_result (const mongoc_uri_t *uri, const char *host, bson_error_t *error); #ifdef MONGOC_ENABLE_CRYPTO void -_mongoc_uri_init_scram (const mongoc_uri_t *uri, - mongoc_scram_t *scram, - mongoc_crypto_hash_algorithm_t algo); +_mongoc_uri_init_scram (const mongoc_uri_t *uri, mongoc_scram_t *scram, mongoc_crypto_hash_algorithm_t algo); #endif bool diff --git a/src/libmongoc/src/mongoc/mongoc-uri.c b/src/libmongoc/src/mongoc/mongoc-uri.c index 815f7aa8ef..5ea73e6780 100644 --- a/src/libmongoc/src/mongoc/mongoc-uri.c +++ b/src/libmongoc/src/mongoc/mongoc-uri.c @@ -56,33 +56,21 @@ struct _mongoc_uri_t { mongoc_write_concern_t *write_concern; }; -#define MONGOC_URI_ERROR(error, format, ...) \ - bson_set_error (error, \ - MONGOC_ERROR_COMMAND, \ - MONGOC_ERROR_COMMAND_INVALID_ARG, \ - format, \ - __VA_ARGS__) +#define MONGOC_URI_ERROR(error, format, ...) \ + bson_set_error (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, format, __VA_ARGS__) static const char *escape_instructions = "Percent-encode username and password" " according to RFC 3986"; static bool -_mongoc_uri_set_option_as_int32 (mongoc_uri_t *uri, - const char *option, - int32_t value); +_mongoc_uri_set_option_as_int32 (mongoc_uri_t *uri, const char *option, int32_t value); static bool -_mongoc_uri_set_option_as_int32_with_error (mongoc_uri_t *uri, - const char *option, - int32_t value, - bson_error_t *error); +_mongoc_uri_set_option_as_int32_with_error (mongoc_uri_t *uri, const char *option, int32_t value, bson_error_t *error); static bool -_mongoc_uri_set_option_as_int64_with_error (mongoc_uri_t *uri, - const char *option, - int64_t value, - bson_error_t *error); +_mongoc_uri_set_option_as_int64_with_error (mongoc_uri_t *uri, const char *option, int64_t value, bson_error_t *error); static void mongoc_uri_do_unescape (char **str) @@ -141,9 +129,7 @@ valid_hostname (const char *s) bool -mongoc_uri_validate_srv_result (const mongoc_uri_t *uri, - const char *host, - bson_error_t *error) +mongoc_uri_validate_srv_result (const mongoc_uri_t *uri, const char *host, bson_error_t *error) { const char *srv_hostname; const char *srv_host; @@ -174,12 +160,9 @@ mongoc_uri_validate_srv_result (const mongoc_uri_t *uri, /* copy and upsert @host into @uri's host list. */ static bool -_upsert_into_host_list (mongoc_uri_t *uri, - mongoc_host_list_t *host, - bson_error_t *error) +_upsert_into_host_list (mongoc_uri_t *uri, mongoc_host_list_t *host, bson_error_t *error) { - if (uri->is_srv && - !mongoc_uri_validate_srv_result (uri, host->host, error)) { + if (uri->is_srv && !mongoc_uri_validate_srv_result (uri, host->host, error)) { return false; } @@ -189,9 +172,7 @@ _upsert_into_host_list (mongoc_uri_t *uri, } bool -mongoc_uri_upsert_host_and_port (mongoc_uri_t *uri, - const char *host_and_port, - bson_error_t *error) +mongoc_uri_upsert_host_and_port (mongoc_uri_t *uri, const char *host_and_port, bson_error_t *error) { mongoc_host_list_t temp; @@ -204,10 +185,7 @@ mongoc_uri_upsert_host_and_port (mongoc_uri_t *uri, } bool -mongoc_uri_upsert_host (mongoc_uri_t *uri, - const char *host, - uint16_t port, - bson_error_t *error) +mongoc_uri_upsert_host (mongoc_uri_t *uri, const char *host, uint16_t port, bson_error_t *error) { mongoc_host_list_t temp; @@ -248,16 +226,12 @@ mongoc_uri_remove_host (mongoc_uri_t *uri, const char *host, uint16_t port) */ static char * -scan_to_unichar (const char *str, - bson_unichar_t match, - const char *terminators, - const char **end) +scan_to_unichar (const char *str, bson_unichar_t match, const char *terminators, const char **end) { bson_unichar_t c; const char *iter; - for (iter = str; iter && *iter && (c = bson_utf8_get_char (iter)); - iter = bson_utf8_next_char (iter)) { + for (iter = str; iter && *iter && (c = bson_utf8_get_char (iter)); iter = bson_utf8_next_char (iter)) { if (c == match) { *end = iter; return bson_strndup (str, iter - str); @@ -320,9 +294,7 @@ mongoc_uri_has_unescaped_chars (const char *str, const char *chars) /* "str" is non-NULL, the part of URI between "mongodb://" and first "@" */ static bool -mongoc_uri_parse_userpass (mongoc_uri_t *uri, - const char *str, - bson_error_t *error) +mongoc_uri_parse_userpass (mongoc_uri_t *uri, const char *str, bson_error_t *error) { const char *prohibited = "@:/"; const char *end_user; @@ -338,27 +310,21 @@ mongoc_uri_parse_userpass (mongoc_uri_t *uri, } if (mongoc_uri_has_unescaped_chars (uri->username, prohibited)) { - MONGOC_URI_ERROR (error, - "Username \"%s\" must not have unescaped chars. %s", - uri->username, - escape_instructions); + MONGOC_URI_ERROR (error, "Username \"%s\" must not have unescaped chars. %s", uri->username, escape_instructions); return false; } mongoc_uri_do_unescape (&uri->username); if (!uri->username) { - MONGOC_URI_ERROR ( - error, "Incorrect URI escapes in username. %s", escape_instructions); + MONGOC_URI_ERROR (error, "Incorrect URI escapes in username. %s", escape_instructions); return false; } /* Providing password at all is optional */ if (uri->password) { if (mongoc_uri_has_unescaped_chars (uri->password, prohibited)) { - MONGOC_URI_ERROR (error, - "Password \"%s\" must not have unescaped chars. %s", - uri->password, - escape_instructions); + MONGOC_URI_ERROR ( + error, "Password \"%s\" must not have unescaped chars. %s", uri->password, escape_instructions); return false; } @@ -431,14 +397,12 @@ mongoc_uri_parse_srv (mongoc_uri_t *uri, const char *str, bson_error_t *error) } if (strchr (uri->srv, ',')) { - MONGOC_URI_ERROR ( - error, "%s", "Multiple service names are prohibited in an SRV URI"); + MONGOC_URI_ERROR (error, "%s", "Multiple service names are prohibited in an SRV URI"); return false; } if (strchr (uri->srv, ':')) { - MONGOC_URI_ERROR ( - error, "%s", "Port numbers are prohibited in an SRV URI"); + MONGOC_URI_ERROR (error, "%s", "Port numbers are prohibited in an SRV URI"); return false; } @@ -466,8 +430,7 @@ mongoc_uri_parse_hosts (mongoc_uri_t *uri, const char *hosts) */ s = scan_to_unichar (hosts, '?', "", &end_hostport); if (s) { - MONGOC_WARNING ( - "%s", "A '/' is required between the host list and any options."); + MONGOC_WARNING ("%s", "A '/' is required between the host list and any options."); goto error; } next = hosts; @@ -536,8 +499,7 @@ mongoc_uri_parse_database (mongoc_uri_t *uri, const char *str, const char **end) /* invalid characters in database name */ for (c = "/\\. \"$"; *c; c++) { - invalid_c = - scan_to_unichar (uri->database, (bson_unichar_t) *c, "", &tmp); + invalid_c = scan_to_unichar (uri->database, (bson_unichar_t) *c, "", &tmp); if (invalid_c) { bson_free (invalid_c); return false; @@ -680,9 +642,7 @@ mongoc_uri_parse_tags (mongoc_uri_t *uri, /* IN */ return true; fail: - MONGOC_WARNING ("Unsupported value for \"" MONGOC_URI_READPREFERENCETAGS - "\": \"%s\"", - str); + MONGOC_WARNING ("Unsupported value for \"" MONGOC_URI_READPREFERENCETAGS "\": \"%s\"", str); bson_destroy (&b); return false; } @@ -709,9 +669,7 @@ mongoc_uri_parse_tags (mongoc_uri_t *uri, /* IN */ */ static void -mongoc_uri_bson_append_or_replace_key (bson_t *options, - const char *option, - const char *value) +mongoc_uri_bson_append_or_replace_key (bson_t *options, const char *option, const char *value) { bson_iter_t iter; bool found = false; @@ -754,20 +712,14 @@ mongoc_uri_has_option (const mongoc_uri_t *uri, const char *key) bool mongoc_uri_option_is_int32 (const char *key) { - return mongoc_uri_option_is_int64 (key) || - !strcasecmp (key, MONGOC_URI_CONNECTTIMEOUTMS) || + return mongoc_uri_option_is_int64 (key) || !strcasecmp (key, MONGOC_URI_CONNECTTIMEOUTMS) || !strcasecmp (key, MONGOC_URI_HEARTBEATFREQUENCYMS) || !strcasecmp (key, MONGOC_URI_SERVERSELECTIONTIMEOUTMS) || - !strcasecmp (key, MONGOC_URI_SOCKETCHECKINTERVALMS) || - !strcasecmp (key, MONGOC_URI_SOCKETTIMEOUTMS) || - !strcasecmp (key, MONGOC_URI_LOCALTHRESHOLDMS) || - !strcasecmp (key, MONGOC_URI_MAXPOOLSIZE) || - !strcasecmp (key, MONGOC_URI_MAXSTALENESSSECONDS) || - !strcasecmp (key, MONGOC_URI_MINPOOLSIZE) || - !strcasecmp (key, MONGOC_URI_MAXIDLETIMEMS) || - !strcasecmp (key, MONGOC_URI_WAITQUEUEMULTIPLE) || - !strcasecmp (key, MONGOC_URI_WAITQUEUETIMEOUTMS) || - !strcasecmp (key, MONGOC_URI_ZLIBCOMPRESSIONLEVEL) || + !strcasecmp (key, MONGOC_URI_SOCKETCHECKINTERVALMS) || !strcasecmp (key, MONGOC_URI_SOCKETTIMEOUTMS) || + !strcasecmp (key, MONGOC_URI_LOCALTHRESHOLDMS) || !strcasecmp (key, MONGOC_URI_MAXPOOLSIZE) || + !strcasecmp (key, MONGOC_URI_MAXSTALENESSSECONDS) || !strcasecmp (key, MONGOC_URI_MINPOOLSIZE) || + !strcasecmp (key, MONGOC_URI_MAXIDLETIMEMS) || !strcasecmp (key, MONGOC_URI_WAITQUEUEMULTIPLE) || + !strcasecmp (key, MONGOC_URI_WAITQUEUETIMEOUTMS) || !strcasecmp (key, MONGOC_URI_ZLIBCOMPRESSIONLEVEL) || !strcasecmp (key, MONGOC_URI_SRVMAXHOSTS); } @@ -780,36 +732,26 @@ mongoc_uri_option_is_int64 (const char *key) bool mongoc_uri_option_is_bool (const char *key) { - return !strcasecmp (key, MONGOC_URI_CANONICALIZEHOSTNAME) || - !strcasecmp (key, MONGOC_URI_DIRECTCONNECTION) || - !strcasecmp (key, MONGOC_URI_JOURNAL) || - !strcasecmp (key, MONGOC_URI_RETRYREADS) || - !strcasecmp (key, MONGOC_URI_RETRYWRITES) || - !strcasecmp (key, MONGOC_URI_SAFE) || - !strcasecmp (key, MONGOC_URI_SERVERSELECTIONTRYONCE) || - !strcasecmp (key, MONGOC_URI_TLS) || - !strcasecmp (key, MONGOC_URI_TLSINSECURE) || - !strcasecmp (key, MONGOC_URI_TLSALLOWINVALIDCERTIFICATES) || + return !strcasecmp (key, MONGOC_URI_CANONICALIZEHOSTNAME) || !strcasecmp (key, MONGOC_URI_DIRECTCONNECTION) || + !strcasecmp (key, MONGOC_URI_JOURNAL) || !strcasecmp (key, MONGOC_URI_RETRYREADS) || + !strcasecmp (key, MONGOC_URI_RETRYWRITES) || !strcasecmp (key, MONGOC_URI_SAFE) || + !strcasecmp (key, MONGOC_URI_SERVERSELECTIONTRYONCE) || !strcasecmp (key, MONGOC_URI_TLS) || + !strcasecmp (key, MONGOC_URI_TLSINSECURE) || !strcasecmp (key, MONGOC_URI_TLSALLOWINVALIDCERTIFICATES) || !strcasecmp (key, MONGOC_URI_TLSALLOWINVALIDHOSTNAMES) || !strcasecmp (key, MONGOC_URI_TLSDISABLECERTIFICATEREVOCATIONCHECK) || - !strcasecmp (key, MONGOC_URI_TLSDISABLEOCSPENDPOINTCHECK) || - !strcasecmp (key, MONGOC_URI_LOADBALANCED) || + !strcasecmp (key, MONGOC_URI_TLSDISABLEOCSPENDPOINTCHECK) || !strcasecmp (key, MONGOC_URI_LOADBALANCED) || /* deprecated options */ - !strcasecmp (key, MONGOC_URI_SSL) || - !strcasecmp (key, MONGOC_URI_SSLALLOWINVALIDCERTIFICATES) || + !strcasecmp (key, MONGOC_URI_SSL) || !strcasecmp (key, MONGOC_URI_SSLALLOWINVALIDCERTIFICATES) || !strcasecmp (key, MONGOC_URI_SSLALLOWINVALIDHOSTNAMES); } bool mongoc_uri_option_is_utf8 (const char *key) { - return !strcasecmp (key, MONGOC_URI_APPNAME) || - !strcasecmp (key, MONGOC_URI_REPLICASET) || - !strcasecmp (key, MONGOC_URI_READPREFERENCE) || - !strcasecmp (key, MONGOC_URI_SRVSERVICENAME) || + return !strcasecmp (key, MONGOC_URI_APPNAME) || !strcasecmp (key, MONGOC_URI_REPLICASET) || + !strcasecmp (key, MONGOC_URI_READPREFERENCE) || !strcasecmp (key, MONGOC_URI_SRVSERVICENAME) || !strcasecmp (key, MONGOC_URI_TLSCERTIFICATEKEYFILE) || - !strcasecmp (key, MONGOC_URI_TLSCERTIFICATEKEYFILEPASSWORD) || - !strcasecmp (key, MONGOC_URI_TLSCAFILE) || + !strcasecmp (key, MONGOC_URI_TLSCERTIFICATEKEYFILEPASSWORD) || !strcasecmp (key, MONGOC_URI_TLSCAFILE) || /* deprecated options */ !strcasecmp (key, MONGOC_URI_SSLCLIENTCERTIFICATEKEYFILE) || !strcasecmp (key, MONGOC_URI_SSLCLIENTCERTIFICATEKEYPASSWORD) || @@ -883,8 +825,7 @@ dns_option_allowed (const char *lkey) * authSource, replicaSet, and loadBalanced options through a TXT record, and * MUST raise an error if any other option is encountered." */ - return !strcmp (lkey, MONGOC_URI_AUTHSOURCE) || - !strcmp (lkey, MONGOC_URI_REPLICASET) || + return !strcmp (lkey, MONGOC_URI_AUTHSOURCE) || !strcmp (lkey, MONGOC_URI_REPLICASET) || !strcmp (lkey, MONGOC_URI_LOADBALANCED); } @@ -893,11 +834,7 @@ dns_option_allowed (const char *lkey) * Includes case-folding for key portion. */ static bool -mongoc_uri_split_option (mongoc_uri_t *uri, - bson_t *options, - const char *str, - bool from_dns, - bson_error_t *error) +mongoc_uri_split_option (mongoc_uri_t *uri, bson_t *options, const char *str, bool from_dns, bson_error_t *error) { bson_iter_t iter; const char *end_key; @@ -918,8 +855,7 @@ mongoc_uri_split_option (mongoc_uri_t *uri, mongoc_uri_do_unescape (&value); if (!value) { /* do_unescape detected invalid UTF-8 and freed value */ - MONGOC_URI_ERROR ( - error, "Value for URI option \"%s\" contains invalid UTF-8", key); + MONGOC_URI_ERROR (error, "Value for URI option \"%s\" contains invalid UTF-8", key); goto CLEANUP; } @@ -930,8 +866,7 @@ mongoc_uri_split_option (mongoc_uri_t *uri, * authSource, replicaSet, and loadBalanced options through a TXT record, and * MUST raise an error if any other option is encountered."*/ if (from_dns && !dns_option_allowed (lkey)) { - MONGOC_URI_ERROR ( - error, "URI option \"%s\" prohibited in TXT record", key); + MONGOC_URI_ERROR (error, "URI option \"%s\" prohibited in TXT record", key); goto CLEANUP; } @@ -942,17 +877,14 @@ mongoc_uri_split_option (mongoc_uri_t *uri, */ if (!strcmp (lkey, MONGOC_URI_READPREFERENCETAGS)) { if (!mongoc_uri_parse_tags (uri, value)) { - MONGOC_URI_ERROR ( - error, "Unsupported value for \"%s\": \"%s\"", key, value); + MONGOC_URI_ERROR (error, "Unsupported value for \"%s\": \"%s\"", key, value); goto CLEANUP; } - } else if (bson_iter_init_find (&iter, &uri->raw, lkey) || - bson_iter_init_find (&iter, options, lkey)) { + } else if (bson_iter_init_find (&iter, &uri->raw, lkey) || bson_iter_init_find (&iter, options, lkey)) { /* Special case, MONGOC_URI_W == "any non-int" is not overridden * by later values. */ - if (!strcmp (lkey, MONGOC_URI_W) && - (opt = bson_iter_utf8_unsafe (&iter, &opt_len))) { + if (!strcmp (lkey, MONGOC_URI_W) && (opt = bson_iter_utf8_unsafe (&iter, &opt_len))) { strtol (opt, &opt_end, 10); if (*opt_end != '\0') { ret = true; @@ -965,10 +897,7 @@ mongoc_uri_split_option (mongoc_uri_t *uri, * through TXT records." So, do NOT override existing options with TXT * options. */ if (from_dns) { - MONGOC_WARNING ( - "Cannot override URI option \"%s\" from TXT record \"%s\"", - key, - str); + MONGOC_WARNING ("Cannot override URI option \"%s\" from TXT record \"%s\"", key, str); ret = true; goto CLEANUP; } @@ -976,8 +905,7 @@ mongoc_uri_split_option (mongoc_uri_t *uri, } if (!(strcmp (lkey, MONGOC_URI_REPLICASET)) && *value == '\0') { - MONGOC_URI_ERROR ( - error, "Value for URI option \"%s\" cannot be empty string", lkey); + MONGOC_URI_ERROR (error, "Value for URI option \"%s\" cannot be empty string", lkey); goto CLEANUP; } @@ -998,9 +926,7 @@ mongoc_uri_split_option (mongoc_uri_t *uri, * If both names exist either way with differing values, error. */ static bool -mongoc_uri_options_validate_names (const bson_t *a, - const bson_t *b, - bson_error_t *error) +mongoc_uri_options_validate_names (const bson_t *a, const bson_t *b, bson_error_t *error) { bson_iter_t key_iter, canon_iter; const char *key = NULL; @@ -1056,21 +982,17 @@ mongoc_uri_options_validate_names (const bson_t *a, } -#define HANDLE_DUPE() \ - if (from_dns) { \ - MONGOC_WARNING ("Cannot override URI option \"%s\" from TXT record", \ - key); \ - continue; \ - } else if (1) { \ - MONGOC_WARNING ("Overwriting previously provided value for '%s'", key); \ - } else \ +#define HANDLE_DUPE() \ + if (from_dns) { \ + MONGOC_WARNING ("Cannot override URI option \"%s\" from TXT record", key); \ + continue; \ + } else if (1) { \ + MONGOC_WARNING ("Overwriting previously provided value for '%s'", key); \ + } else \ (void) 0 static bool -mongoc_uri_apply_options (mongoc_uri_t *uri, - const bson_t *options, - bool from_dns, - bson_error_t *error) +mongoc_uri_apply_options (mongoc_uri_t *uri, const bson_t *options, bool from_dns, bson_error_t *error) { bson_iter_t iter; int32_t v_int; @@ -1099,8 +1021,7 @@ mongoc_uri_apply_options (mongoc_uri_t *uri, goto UNSUPPORTED_VALUE; } - if (!_mongoc_uri_set_option_as_int64_with_error ( - uri, canon, v_int64, error)) { + if (!_mongoc_uri_set_option_as_int64_with_error (uri, canon, v_int64, error)) { return false; } } else { @@ -1112,8 +1033,7 @@ mongoc_uri_apply_options (mongoc_uri_t *uri, goto UNSUPPORTED_VALUE; } - if (!_mongoc_uri_set_option_as_int32_with_error ( - uri, canon, v_int, error)) { + if (!_mongoc_uri_set_option_as_int32_with_error (uri, canon, v_int, error)) { return false; } } else { @@ -1124,11 +1044,9 @@ mongoc_uri_apply_options (mongoc_uri_t *uri, v_int = (int) strtol (value, NULL, 10); _mongoc_uri_set_option_as_int32 (uri, MONGOC_URI_W, v_int); } else if (0 == strcasecmp (value, "majority")) { - mongoc_uri_bson_append_or_replace_key ( - &uri->options, MONGOC_URI_W, "majority"); + mongoc_uri_bson_append_or_replace_key (&uri->options, MONGOC_URI_W, "majority"); } else if (*value) { - mongoc_uri_bson_append_or_replace_key ( - &uri->options, MONGOC_URI_W, value); + mongoc_uri_bson_append_or_replace_key (&uri->options, MONGOC_URI_W, value); } } else if (mongoc_uri_option_is_bool (key)) { @@ -1137,21 +1055,16 @@ mongoc_uri_apply_options (mongoc_uri_t *uri, bval = true; } else if (0 == strcasecmp (value, "false")) { bval = false; - } else if ((0 == strcmp (value, "1")) || - (0 == strcasecmp (value, "yes")) || - (0 == strcasecmp (value, "y")) || - (0 == strcasecmp (value, "t"))) { + } else if ((0 == strcmp (value, "1")) || (0 == strcasecmp (value, "yes")) || + (0 == strcasecmp (value, "y")) || (0 == strcasecmp (value, "t"))) { MONGOC_WARNING ("Deprecated boolean value for \"%s\": \"%s\", " "please update to \"%s=true\"", key, value, key); bval = true; - } else if ((0 == strcasecmp (value, "0")) || - (0 == strcasecmp (value, "-1")) || - (0 == strcmp (value, "no")) || - (0 == strcmp (value, "n")) || - (0 == strcmp (value, "f"))) { + } else if ((0 == strcasecmp (value, "0")) || (0 == strcasecmp (value, "-1")) || + (0 == strcmp (value, "no")) || (0 == strcmp (value, "n")) || (0 == strcmp (value, "f"))) { MONGOC_WARNING ("Deprecated boolean value for \"%s\": \"%s\", " "please update to \"%s=false\"", key, @@ -1163,12 +1076,8 @@ mongoc_uri_apply_options (mongoc_uri_t *uri, } if (!mongoc_uri_set_option_as_bool (uri, canon, bval)) { - bson_set_error (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Failed to set %s to %d", - canon, - bval); + bson_set_error ( + error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Failed to set %s to %d", canon, bval); return false; } } else { @@ -1181,13 +1090,11 @@ mongoc_uri_apply_options (mongoc_uri_t *uri, * as a special case composing option. */ - } else if (!strcmp (key, MONGOC_URI_AUTHMECHANISM) || - !strcmp (key, MONGOC_URI_AUTHSOURCE)) { + } else if (!strcmp (key, MONGOC_URI_AUTHMECHANISM) || !strcmp (key, MONGOC_URI_AUTHSOURCE)) { if (bson_has_field (&uri->credentials, key)) { HANDLE_DUPE (); } - mongoc_uri_bson_append_or_replace_key ( - &uri->credentials, canon, value); + mongoc_uri_bson_append_or_replace_key (&uri->credentials, canon, value); } else if (!strcmp (key, MONGOC_URI_READCONCERNLEVEL)) { if (!mongoc_read_concern_is_default (uri->read_concern)) { @@ -1197,8 +1104,7 @@ mongoc_uri_apply_options (mongoc_uri_t *uri, } else if (!strcmp (key, MONGOC_URI_GSSAPISERVICENAME)) { char *tmp = bson_strdup_printf ("SERVICE_NAME:%s", value); - if (bson_has_field (&uri->credentials, - MONGOC_URI_AUTHMECHANISMPROPERTIES)) { + if (bson_has_field (&uri->credentials, MONGOC_URI_AUTHMECHANISMPROPERTIES)) { MONGOC_WARNING ("authMechanismProperties SERVICE_NAME already set, " "ignoring '%s'", key); @@ -1266,10 +1172,7 @@ mongoc_uri_apply_options (mongoc_uri_t *uri, * to their appropriate type and stored in uri->options. */ bool -mongoc_uri_parse_options (mongoc_uri_t *uri, - const char *str, - bool from_dns, - bson_error_t *error) +mongoc_uri_parse_options (mongoc_uri_t *uri, const char *str, bool from_dns, bson_error_t *error) { bson_t options; const char *end_option; @@ -1320,13 +1223,10 @@ mongoc_uri_finalize_tls (mongoc_uri_t *uri, bson_error_t *error) * tlsDisableOCSPEndpointCheck, and tlsDisableCertificateRevocationCheck, so * consider it an error to have both. The user might have the wrong idea. */ if (bson_has_field (&uri->options, MONGOC_URI_TLSINSECURE) && - (bson_has_field (&uri->options, - MONGOC_URI_TLSALLOWINVALIDCERTIFICATES) || + (bson_has_field (&uri->options, MONGOC_URI_TLSALLOWINVALIDCERTIFICATES) || bson_has_field (&uri->options, MONGOC_URI_TLSALLOWINVALIDHOSTNAMES) || - bson_has_field (&uri->options, - MONGOC_URI_TLSDISABLEOCSPENDPOINTCHECK) || - bson_has_field (&uri->options, - MONGOC_URI_TLSDISABLECERTIFICATEREVOCATIONCHECK))) { + bson_has_field (&uri->options, MONGOC_URI_TLSDISABLEOCSPENDPOINTCHECK) || + bson_has_field (&uri->options, MONGOC_URI_TLSDISABLECERTIFICATEREVOCATIONCHECK))) { MONGOC_URI_ERROR (error, "%s may not be specified with %s, %s, %s, or %s", MONGOC_URI_TLSINSECURE, @@ -1341,10 +1241,8 @@ mongoc_uri_finalize_tls (mongoc_uri_t *uri, bson_error_t *error) * tlsDisableCertificateRevocationCheck, so consider it an error to have * both. The user might have the wrong idea. */ if (bson_has_field (&uri->options, MONGOC_URI_TLSALLOWINVALIDCERTIFICATES) && - (bson_has_field (&uri->options, - MONGOC_URI_TLSDISABLECERTIFICATEREVOCATIONCHECK) || - bson_has_field (&uri->options, - MONGOC_URI_TLSDISABLEOCSPENDPOINTCHECK))) { + (bson_has_field (&uri->options, MONGOC_URI_TLSDISABLECERTIFICATEREVOCATIONCHECK) || + bson_has_field (&uri->options, MONGOC_URI_TLSDISABLEOCSPENDPOINTCHECK))) { MONGOC_URI_ERROR (error, "%s may not be specified with %s or %s", MONGOC_URI_TLSALLOWINVALIDCERTIFICATES, @@ -1356,8 +1254,7 @@ mongoc_uri_finalize_tls (mongoc_uri_t *uri, bson_error_t *error) /* tlsDisableCertificateRevocationCheck implies tlsDisableOCSPEndpointCheck, * so consider it an error to have both. The user might have the wrong idea. */ - if (bson_has_field (&uri->options, - MONGOC_URI_TLSDISABLECERTIFICATEREVOCATIONCHECK) && + if (bson_has_field (&uri->options, MONGOC_URI_TLSDISABLECERTIFICATEREVOCATIONCHECK) && bson_has_field (&uri->options, MONGOC_URI_TLSDISABLEOCSPENDPOINTCHECK)) { MONGOC_URI_ERROR (error, "%s may not be specified with %s", @@ -1377,8 +1274,7 @@ mongoc_uri_finalize_auth (mongoc_uri_t *uri, bson_error_t *error) const char *source = NULL; const bool require_auth = uri->username != NULL; - if (bson_iter_init_find_case ( - &iter, &uri->credentials, MONGOC_URI_AUTHSOURCE)) { + if (bson_iter_init_find_case (&iter, &uri->credentials, MONGOC_URI_AUTHSOURCE)) { source = bson_iter_utf8 (&iter, NULL); } @@ -1388,55 +1284,40 @@ mongoc_uri_finalize_auth (mongoc_uri_t *uri, bson_error_t *error) !strcasecmp (mongoc_uri_get_auth_mechanism (uri), "MONGODB-X509")) { if (source) { if (strcasecmp (source, "$external")) { - MONGOC_URI_ERROR ( - error, - "%s", - "GSSAPI and X509 require \"$external\" authSource"); + MONGOC_URI_ERROR (error, "%s", "GSSAPI and X509 require \"$external\" authSource"); return false; } } else { - bson_append_utf8 ( - &uri->credentials, MONGOC_URI_AUTHSOURCE, -1, "$external", -1); + bson_append_utf8 (&uri->credentials, MONGOC_URI_AUTHSOURCE, -1, "$external", -1); } } /* MONGODB-X509 and MONGODB-AWS are the only mechanisms that don't require * username */ - if (!(strcasecmp (mongoc_uri_get_auth_mechanism (uri), "MONGODB-X509") == - 0 || - strcasecmp (mongoc_uri_get_auth_mechanism (uri), "MONGODB-AWS") == - 0)) { - if (!mongoc_uri_get_username (uri) || - strcmp (mongoc_uri_get_username (uri), "") == 0) { - MONGOC_URI_ERROR (error, - "'%s' authentication mechanism requires username", - mongoc_uri_get_auth_mechanism (uri)); + if (!(strcasecmp (mongoc_uri_get_auth_mechanism (uri), "MONGODB-X509") == 0 || + strcasecmp (mongoc_uri_get_auth_mechanism (uri), "MONGODB-AWS") == 0)) { + if (!mongoc_uri_get_username (uri) || strcmp (mongoc_uri_get_username (uri), "") == 0) { + MONGOC_URI_ERROR ( + error, "'%s' authentication mechanism requires username", mongoc_uri_get_auth_mechanism (uri)); return false; } } /* MONGODB-X509 errors if a password is supplied. */ - if (strcasecmp (mongoc_uri_get_auth_mechanism (uri), "MONGODB-X509") == - 0) { + if (strcasecmp (mongoc_uri_get_auth_mechanism (uri), "MONGODB-X509") == 0) { if (mongoc_uri_get_password (uri)) { MONGOC_URI_ERROR ( - error, - "'%s' authentication mechanism does not accept a password", - mongoc_uri_get_auth_mechanism (uri)); + error, "'%s' authentication mechanism does not accept a password", mongoc_uri_get_auth_mechanism (uri)); return false; } } /* GSSAPI uses 'mongodb' as the default service name */ if (strcasecmp (mongoc_uri_get_auth_mechanism (uri), "GSSAPI") == 0 && - !(bson_iter_init_find ( - &iter, &uri->credentials, MONGOC_URI_AUTHMECHANISMPROPERTIES) && - BSON_ITER_HOLDS_DOCUMENT (&iter) && - bson_iter_recurse (&iter, &iter) && + !(bson_iter_init_find (&iter, &uri->credentials, MONGOC_URI_AUTHMECHANISMPROPERTIES) && + BSON_ITER_HOLDS_DOCUMENT (&iter) && bson_iter_recurse (&iter, &iter) && bson_iter_find_case (&iter, "SERVICE_NAME"))) { bson_t tmp; bson_t *props = NULL; - props = mongoc_uri_get_mechanism_properties (uri, &tmp) - ? bson_copy (&tmp) - : bson_new (); + props = mongoc_uri_get_mechanism_properties (uri, &tmp) ? bson_copy (&tmp) : bson_new (); BSON_APPEND_UTF8 (props, "SERVICE_NAME", "mongodb"); mongoc_uri_set_mechanism_properties (uri, props); @@ -1445,10 +1326,8 @@ mongoc_uri_finalize_auth (mongoc_uri_t *uri, bson_error_t *error) } } else if (require_auth) /* Default auth mechanism is used */ { - if (!mongoc_uri_get_username (uri) || - strcmp (mongoc_uri_get_username (uri), "") == 0) { - MONGOC_URI_ERROR ( - error, "%s", "Default authentication mechanism requires username"); + if (!mongoc_uri_get_username (uri) || strcmp (mongoc_uri_get_username (uri), "") == 0) { + MONGOC_URI_ERROR (error, "%s", "Default authentication mechanism requires username"); return false; } } @@ -1460,8 +1339,7 @@ mongoc_uri_finalize_directconnection (mongoc_uri_t *uri, bson_error_t *error) { bool directconnection = false; - directconnection = - mongoc_uri_get_option_as_bool (uri, MONGOC_URI_DIRECTCONNECTION, false); + directconnection = mongoc_uri_get_option_as_bool (uri, MONGOC_URI_DIRECTCONNECTION, false); if (!directconnection) { return true; } @@ -1471,18 +1349,14 @@ mongoc_uri_finalize_directconnection (mongoc_uri_t *uri, bson_error_t *error) * the URI may resolve to multiple hosts. The driver MUST allow specifying * directConnection=false URI option with an SRV URI." */ if (uri->is_srv) { - MONGOC_URI_ERROR ( - error, "%s", "SRV URI not allowed with directConnection option"); + MONGOC_URI_ERROR (error, "%s", "SRV URI not allowed with directConnection option"); return false; } /* URI options spec: "The driver MUST report an error if the * directConnection=true URI option is specified with multiple seeds." */ if (uri->hosts && uri->hosts->next) { - MONGOC_URI_ERROR ( - error, - "%s", - "Multiple seeds not allowed with directConnection option"); + MONGOC_URI_ERROR (error, "%s", "Multiple seeds not allowed with directConnection option"); return false; } @@ -1490,9 +1364,7 @@ mongoc_uri_finalize_directconnection (mongoc_uri_t *uri, bson_error_t *error) } static bool -mongoc_uri_parse_before_slash (mongoc_uri_t *uri, - const char *before_slash, - bson_error_t *error) +mongoc_uri_parse_before_slash (mongoc_uri_t *uri, const char *before_slash, bson_error_t *error) { char *userpass; const char *hosts; @@ -1506,8 +1378,7 @@ mongoc_uri_parse_before_slash (mongoc_uri_t *uri, hosts++; /* advance past "@" */ if (*hosts == '@') { /* special case: "mongodb://alice@@localhost" */ - MONGOC_URI_ERROR ( - error, "Invalid username or password. %s", escape_instructions); + MONGOC_URI_ERROR (error, "Invalid username or password. %s", escape_instructions); goto error; } } else { @@ -1548,10 +1419,7 @@ mongoc_uri_parse (mongoc_uri_t *uri, const char *str, bson_error_t *error) } if (!mongoc_uri_parse_scheme (uri, str, &str)) { - MONGOC_URI_ERROR ( - error, - "%s", - "Invalid URI Schema, expecting 'mongodb://' or 'mongodb+srv://'"); + MONGOC_URI_ERROR (error, "%s", "Invalid URI Schema, expecting 'mongodb://' or 'mongodb+srv://'"); goto error; } @@ -1582,8 +1450,7 @@ mongoc_uri_parse (mongoc_uri_t *uri, const char *str, bson_error_t *error) if (*str == '?') { str++; if (*str) { - if (!mongoc_uri_parse_options ( - uri, str, false /* from DNS */, error)) { + if (!mongoc_uri_parse_options (uri, str, false /* from DNS */, error)) { goto error; } } @@ -1622,8 +1489,7 @@ mongoc_uri_get_replica_set (const mongoc_uri_t *uri) BSON_ASSERT (uri); - if (bson_iter_init_find_case (&iter, &uri->options, MONGOC_URI_REPLICASET) && - BSON_ITER_HOLDS_UTF8 (&iter)) { + if (bson_iter_init_find_case (&iter, &uri->options, MONGOC_URI_REPLICASET) && BSON_ITER_HOLDS_UTF8 (&iter)) { return bson_iter_utf8 (&iter, NULL); } @@ -1646,9 +1512,7 @@ mongoc_uri_get_auth_mechanism (const mongoc_uri_t *uri) BSON_ASSERT (uri); - if (bson_iter_init_find_case ( - &iter, &uri->credentials, MONGOC_URI_AUTHMECHANISM) && - BSON_ITER_HOLDS_UTF8 (&iter)) { + if (bson_iter_init_find_case (&iter, &uri->credentials, MONGOC_URI_AUTHMECHANISM) && BSON_ITER_HOLDS_UTF8 (&iter)) { return bson_iter_utf8 (&iter, NULL); } @@ -1669,24 +1533,21 @@ mongoc_uri_set_auth_mechanism (mongoc_uri_t *uri, const char *value) return false; } - mongoc_uri_bson_append_or_replace_key ( - &uri->credentials, MONGOC_URI_AUTHMECHANISM, value); + mongoc_uri_bson_append_or_replace_key (&uri->credentials, MONGOC_URI_AUTHMECHANISM, value); return true; } bool -mongoc_uri_get_mechanism_properties (const mongoc_uri_t *uri, - bson_t *properties /* OUT */) +mongoc_uri_get_mechanism_properties (const mongoc_uri_t *uri, bson_t *properties /* OUT */) { bson_iter_t iter; BSON_ASSERT (uri); BSON_ASSERT (properties); - if (bson_iter_init_find_case ( - &iter, &uri->credentials, MONGOC_URI_AUTHMECHANISMPROPERTIES) && + if (bson_iter_init_find_case (&iter, &uri->credentials, MONGOC_URI_AUTHMECHANISMPROPERTIES) && BSON_ITER_HOLDS_DOCUMENT (&iter)) { uint32_t len = 0; const uint8_t *data = NULL; @@ -1702,20 +1563,18 @@ mongoc_uri_get_mechanism_properties (const mongoc_uri_t *uri, bool -mongoc_uri_set_mechanism_properties (mongoc_uri_t *uri, - const bson_t *properties) +mongoc_uri_set_mechanism_properties (mongoc_uri_t *uri, const bson_t *properties) { BSON_ASSERT (uri); BSON_ASSERT (properties); bson_t tmp = BSON_INITIALIZER; - bsonBuildAppend ( - tmp, - // Copy the existing credentials, dropping the existing properties if - // present - insert (uri->credentials, not(key (MONGOC_URI_AUTHMECHANISMPROPERTIES))), - // Append the new properties - kv (MONGOC_URI_AUTHMECHANISMPROPERTIES, bson (*properties))); + bsonBuildAppend (tmp, + // Copy the existing credentials, dropping the existing properties if + // present + insert (uri->credentials, not(key (MONGOC_URI_AUTHMECHANISMPROPERTIES))), + // Append the new properties + kv (MONGOC_URI_AUTHMECHANISMPROPERTIES, bson (*properties))); bson_reinit (&uri->credentials); bsonBuildAppend (uri->credentials, insert (tmp, true)); bson_destroy (&tmp); @@ -1730,29 +1589,25 @@ _mongoc_uri_assign_read_prefs_mode (mongoc_uri_t *uri, bson_error_t *error) mongoc_read_mode_t mode = 0; const char *pref = NULL; - bsonParse ( - uri->options, - find ( - // Find the 'readPreference' string - iKeyWithType (MONGOC_URI_READPREFERENCE, utf8), - case ( // Switch on the string content: - when (iStrEqual ("primary"), do (mode = MONGOC_READ_PRIMARY)), - when (iStrEqual ("primaryPreferred"), - do (mode = MONGOC_READ_PRIMARY_PREFERRED)), - when (iStrEqual ("secondary"), do (mode = MONGOC_READ_SECONDARY)), - when (iStrEqual ("secondaryPreferred"), - do (mode = MONGOC_READ_SECONDARY_PREFERRED)), - when (iStrEqual ("nearest"), do (mode = MONGOC_READ_NEAREST)), - else (do ({ - pref = bsonAs (cstr); - bsonParseError = "Unsupported readPreference value"; - }))))); + bsonParse (uri->options, + find ( + // Find the 'readPreference' string + iKeyWithType (MONGOC_URI_READPREFERENCE, utf8), + case ( // Switch on the string content: + when (iStrEqual ("primary"), do (mode = MONGOC_READ_PRIMARY)), + when (iStrEqual ("primaryPreferred"), do (mode = MONGOC_READ_PRIMARY_PREFERRED)), + when (iStrEqual ("secondary"), do (mode = MONGOC_READ_SECONDARY)), + when (iStrEqual ("secondaryPreferred"), do (mode = MONGOC_READ_SECONDARY_PREFERRED)), + when (iStrEqual ("nearest"), do (mode = MONGOC_READ_NEAREST)), + else (do ({ + pref = bsonAs (cstr); + bsonParseError = "Unsupported readPreference value"; + }))))); if (bsonParseError) { const char *prefix = "Error while assigning URI read preference"; if (pref) { - MONGOC_URI_ERROR ( - error, "%s: %s [readPreference=%s]", prefix, bsonParseError, pref); + MONGOC_URI_ERROR (error, "%s: %s [readPreference=%s]", prefix, bsonParseError, pref); } else { MONGOC_URI_ERROR (error, "%s: %s", prefix, bsonParseError); } @@ -1777,23 +1632,19 @@ _mongoc_uri_build_write_concern (mongoc_uri_t *uri, bson_error_t *error) write_concern = mongoc_write_concern_new (); uri->write_concern = write_concern; - bsonParse ( - uri->options, - find (iKeyWithType (MONGOC_URI_SAFE, bool), - do (mongoc_write_concern_set_w ( - write_concern, - bsonAs (bool) ? 1 : MONGOC_WRITE_CONCERN_W_UNACKNOWLEDGED)))); + bsonParse (uri->options, + find (iKeyWithType (MONGOC_URI_SAFE, bool), + do (mongoc_write_concern_set_w (write_concern, + bsonAs (bool) ? 1 : MONGOC_WRITE_CONCERN_W_UNACKNOWLEDGED)))); if (bsonParseError) { - MONGOC_URI_ERROR ( - error, "Error while parsing 'safe' URI option: %s", bsonParseError); + MONGOC_URI_ERROR (error, "Error while parsing 'safe' URI option: %s", bsonParseError); return false; } wtimeoutms = mongoc_uri_get_option_as_int64 (uri, MONGOC_URI_WTIMEOUTMS, 0); if (wtimeoutms < 0) { - MONGOC_URI_ERROR ( - error, "Unsupported wtimeoutMS value [w=%" PRId64 "]", wtimeoutms); + MONGOC_URI_ERROR (error, "Unsupported wtimeoutMS value [w=%" PRId64 "]", wtimeoutms); return false; } else if (wtimeoutms > 0) { mongoc_write_concern_set_wtimeout_int64 (write_concern, wtimeoutms); @@ -1801,54 +1652,43 @@ _mongoc_uri_build_write_concern (mongoc_uri_t *uri, bson_error_t *error) bsonParse (uri->options, find (iKeyWithType (MONGOC_URI_JOURNAL, bool), - do (mongoc_write_concern_set_journal (write_concern, - bsonAs (bool))))); + do (mongoc_write_concern_set_journal (write_concern, bsonAs (bool))))); if (bsonParseError) { - MONGOC_URI_ERROR ( - error, "Error while parsing 'journal' URI option: %s", bsonParseError); + MONGOC_URI_ERROR (error, "Error while parsing 'journal' URI option: %s", bsonParseError); return false; } int w_int = INT_MAX; const char *w_str = NULL; - bsonParse ( - uri->options, - find ( - iKey ("w"), // - storeInt32 (w_int), - storeStrRef (w_str), - case ( - // Special W options: - when ( - anyOf (eq (int32, MONGOC_WRITE_CONCERN_W_ERRORS_IGNORED), - eq (int32, MONGOC_WRITE_CONCERN_W_UNACKNOWLEDGED)), - // These conflict with journalling: - if (eval (mongoc_write_concern_get_journal (write_concern)), - then (error ("Journal conflicts with w value"))), - do (mongoc_write_concern_set_w (write_concern, bsonAs (int32)))), - // Other positive 'w' value: - when ( - allOf (type (int32), eval (bsonAs (int32) > 0)), - do (mongoc_write_concern_set_w (write_concern, bsonAs (int32)))), - // Special "majority" string: - when (iStrEqual ("majority"), - do (mongoc_write_concern_set_w ( - write_concern, MONGOC_WRITE_CONCERN_W_MAJORITY))), - // Other string: - when (type (utf8), - do (mongoc_write_concern_set_wtag (write_concern, - bsonAs (cstr)))), - // Invalid value: - else (error ("Unsupported w value"))))); + bsonParse (uri->options, + find (iKey ("w"), // + storeInt32 (w_int), + storeStrRef (w_str), + case ( + // Special W options: + when (anyOf (eq (int32, MONGOC_WRITE_CONCERN_W_ERRORS_IGNORED), + eq (int32, MONGOC_WRITE_CONCERN_W_UNACKNOWLEDGED)), + // These conflict with journalling: + if (eval (mongoc_write_concern_get_journal (write_concern)), + then (error ("Journal conflicts with w value"))), + do (mongoc_write_concern_set_w (write_concern, bsonAs (int32)))), + // Other positive 'w' value: + when (allOf (type (int32), eval (bsonAs (int32) > 0)), + do (mongoc_write_concern_set_w (write_concern, bsonAs (int32)))), + // Special "majority" string: + when (iStrEqual ("majority"), + do (mongoc_write_concern_set_w (write_concern, MONGOC_WRITE_CONCERN_W_MAJORITY))), + // Other string: + when (type (utf8), do (mongoc_write_concern_set_wtag (write_concern, bsonAs (cstr)))), + // Invalid value: + else (error ("Unsupported w value"))))); if (bsonParseError) { const char *const prefix = "Error while parsing the 'w' URI option"; if (w_str) { - MONGOC_URI_ERROR ( - error, "%s: %s [w=%s]", prefix, bsonParseError, w_str); + MONGOC_URI_ERROR (error, "%s: %s [w=%s]", prefix, bsonParseError, w_str); } else if (w_int != INT_MAX) { - MONGOC_URI_ERROR ( - error, "%s: %s [w=%d]", prefix, bsonParseError, w_int); + MONGOC_URI_ERROR (error, "%s: %s [w=%d]", prefix, bsonParseError, w_int); } else { MONGOC_URI_ERROR (error, "%s: %s", prefix, bsonParseError); } @@ -1866,21 +1706,13 @@ _mongoc_uri_get_max_staleness_option (const mongoc_uri_t *uri) int32_t retval = MONGOC_NO_MAX_STALENESS; if ((options = mongoc_uri_get_options (uri)) && - bson_iter_init_find_case ( - &iter, options, MONGOC_URI_MAXSTALENESSSECONDS) && - BSON_ITER_HOLDS_INT32 (&iter)) { + bson_iter_init_find_case (&iter, options, MONGOC_URI_MAXSTALENESSSECONDS) && BSON_ITER_HOLDS_INT32 (&iter)) { retval = bson_iter_int32 (&iter); if (retval == 0) { - MONGOC_WARNING ( - "Unsupported value for \"" MONGOC_URI_MAXSTALENESSSECONDS - "\": \"%d\"", - retval); + MONGOC_WARNING ("Unsupported value for \"" MONGOC_URI_MAXSTALENESSSECONDS "\": \"%d\"", retval); retval = -1; } else if (retval < 0 && retval != -1) { - MONGOC_WARNING ( - "Unsupported value for \"" MONGOC_URI_MAXSTALENESSSECONDS - "\": \"%d\"", - retval); + MONGOC_WARNING ("Unsupported value for \"" MONGOC_URI_MAXSTALENESSSECONDS "\": \"%d\"", retval); retval = MONGOC_NO_MAX_STALENESS; } } @@ -1922,8 +1754,7 @@ mongoc_uri_new_with_error (const char *uri_string, bson_error_t *error) return NULL; } max_staleness_seconds = _mongoc_uri_get_max_staleness_option (uri); - mongoc_read_prefs_set_max_staleness_seconds (uri->read_prefs, - max_staleness_seconds); + mongoc_read_prefs_set_max_staleness_seconds (uri->read_prefs, max_staleness_seconds); if (!mongoc_read_prefs_is_valid (uri->read_prefs)) { mongoc_uri_destroy (uri); @@ -2074,8 +1905,7 @@ mongoc_uri_get_auth_source (const mongoc_uri_t *uri) BSON_ASSERT (uri); - if (bson_iter_init_find_case ( - &iter, &uri->credentials, MONGOC_URI_AUTHSOURCE)) { + if (bson_iter_init_find_case (&iter, &uri->credentials, MONGOC_URI_AUTHSOURCE)) { return bson_iter_utf8 (&iter, NULL); } @@ -2088,8 +1918,7 @@ mongoc_uri_get_auth_source (const mongoc_uri_t *uri) */ mechanism = mongoc_uri_get_auth_mechanism (uri); if (mechanism) { - if (!strcasecmp (mechanism, "GSSAPI") || - !strcasecmp (mechanism, "MONGODB-X509")) { + if (!strcasecmp (mechanism, "GSSAPI") || !strcasecmp (mechanism, "MONGODB-X509")) { return "$external"; } if (!strcasecmp (mechanism, "PLAIN")) { @@ -2114,8 +1943,7 @@ mongoc_uri_set_auth_source (mongoc_uri_t *uri, const char *value) return false; } - mongoc_uri_bson_append_or_replace_key ( - &uri->credentials, MONGOC_URI_AUTHSOURCE, value); + mongoc_uri_bson_append_or_replace_key (&uri->credentials, MONGOC_URI_AUTHSOURCE, value); return true; } @@ -2143,8 +1971,7 @@ mongoc_uri_set_appname (mongoc_uri_t *uri, const char *value) return false; } - mongoc_uri_bson_append_or_replace_key ( - &uri->options, MONGOC_URI_APPNAME, value); + mongoc_uri_bson_append_or_replace_key (&uri->options, MONGOC_URI_APPNAME, value); return true; } @@ -2163,8 +1990,7 @@ mongoc_uri_set_compressors (mongoc_uri_t *uri, const char *value) } while ((entry = scan_to_unichar (value, ',', "", &end_compressor))) { if (mongoc_compressor_supported (entry)) { - mongoc_uri_bson_append_or_replace_key ( - &uri->compressors, entry, "yes"); + mongoc_uri_bson_append_or_replace_key (&uri->compressors, entry, "yes"); } else { MONGOC_WARNING ("Unsupported compressor: '%s'", entry); } @@ -2173,8 +1999,7 @@ mongoc_uri_set_compressors (mongoc_uri_t *uri, const char *value) } if (value) { if (mongoc_compressor_supported (value)) { - mongoc_uri_bson_append_or_replace_key ( - &uri->compressors, value, "yes"); + mongoc_uri_bson_append_or_replace_key (&uri->compressors, value, "yes"); } else { MONGOC_WARNING ("Unsupported compressor: '%s'", value); } @@ -2199,8 +2024,7 @@ mongoc_uri_get_local_threshold_option (const mongoc_uri_t *uri) bson_iter_t iter; int32_t retval = MONGOC_TOPOLOGY_LOCAL_THRESHOLD_MS; - if ((options = mongoc_uri_get_options (uri)) && - bson_iter_init_find_case (&iter, options, "localthresholdms") && + if ((options = mongoc_uri_get_options (uri)) && bson_iter_init_find_case (&iter, options, "localthresholdms") && BSON_ITER_HOLDS_INT32 (&iter)) { retval = bson_iter_int32 (&iter); @@ -2244,8 +2068,7 @@ mongoc_uri_get_srv_service_name (const mongoc_uri_t *uri) BSON_ASSERT_PARAM (uri); - if (bson_iter_init_find_case ( - &iter, &uri->options, MONGOC_URI_SRVSERVICENAME)) { + if (bson_iter_init_find_case (&iter, &uri->options, MONGOC_URI_SRVSERVICENAME)) { BSON_ASSERT (BSON_ITER_HOLDS_UTF8 (&iter)); return bson_iter_utf8 (&iter, NULL); } @@ -2396,8 +2219,7 @@ mongoc_uri_unescape (const char *escaped_string) /* Check that after unescaping, it is still valid UTF-8 */ if (unescape_occurred && !bson_utf8_validate (str->str, str->len, false)) { - MONGOC_WARNING ( - "Invalid %% escape sequence: unescaped string contains invalid UTF-8"); + MONGOC_WARNING ("Invalid %% escape sequence: unescaped string contains invalid UTF-8"); bson_string_free (str, true); return NULL; } @@ -2416,8 +2238,7 @@ mongoc_uri_get_read_prefs_t (const mongoc_uri_t *uri) /* IN */ void -mongoc_uri_set_read_prefs_t (mongoc_uri_t *uri, - const mongoc_read_prefs_t *prefs) +mongoc_uri_set_read_prefs_t (mongoc_uri_t *uri, const mongoc_read_prefs_t *prefs) { BSON_ASSERT (uri); BSON_ASSERT (prefs); @@ -2457,8 +2278,7 @@ mongoc_uri_get_write_concern (const mongoc_uri_t *uri) /* IN */ void -mongoc_uri_set_write_concern (mongoc_uri_t *uri, - const mongoc_write_concern_t *wc) +mongoc_uri_set_write_concern (mongoc_uri_t *uri, const mongoc_write_concern_t *wc) { BSON_ASSERT (uri); BSON_ASSERT (wc); @@ -2475,28 +2295,18 @@ mongoc_uri_get_tls (const mongoc_uri_t *uri) /* IN */ BSON_ASSERT (uri); - if (bson_iter_init_find_case (&iter, &uri->options, MONGOC_URI_TLS) && - BSON_ITER_HOLDS_BOOL (&iter)) { + if (bson_iter_init_find_case (&iter, &uri->options, MONGOC_URI_TLS) && BSON_ITER_HOLDS_BOOL (&iter)) { return bson_iter_bool (&iter); } - if (bson_iter_init_find_case ( - &iter, &uri->options, MONGOC_URI_TLSCERTIFICATEKEYFILE) || + if (bson_iter_init_find_case (&iter, &uri->options, MONGOC_URI_TLSCERTIFICATEKEYFILE) || bson_iter_init_find_case (&iter, &uri->options, MONGOC_URI_TLSCAFILE) || - bson_iter_init_find_case ( - &iter, &uri->options, MONGOC_URI_TLSALLOWINVALIDCERTIFICATES) || - bson_iter_init_find_case ( - &iter, &uri->options, MONGOC_URI_TLSALLOWINVALIDHOSTNAMES) || - bson_iter_init_find_case ( - &iter, &uri->options, MONGOC_URI_TLSINSECURE) || - bson_iter_init_find_case ( - &iter, &uri->options, MONGOC_URI_TLSCERTIFICATEKEYFILEPASSWORD) || - bson_iter_init_find_case ( - &iter, &uri->options, MONGOC_URI_TLSDISABLEOCSPENDPOINTCHECK) || - bson_iter_init_find_case ( - &iter, - &uri->options, - MONGOC_URI_TLSDISABLECERTIFICATEREVOCATIONCHECK)) { + bson_iter_init_find_case (&iter, &uri->options, MONGOC_URI_TLSALLOWINVALIDCERTIFICATES) || + bson_iter_init_find_case (&iter, &uri->options, MONGOC_URI_TLSALLOWINVALIDHOSTNAMES) || + bson_iter_init_find_case (&iter, &uri->options, MONGOC_URI_TLSINSECURE) || + bson_iter_init_find_case (&iter, &uri->options, MONGOC_URI_TLSCERTIFICATEKEYFILEPASSWORD) || + bson_iter_init_find_case (&iter, &uri->options, MONGOC_URI_TLSDISABLEOCSPENDPOINTCHECK) || + bson_iter_init_find_case (&iter, &uri->options, MONGOC_URI_TLSDISABLECERTIFICATEREVOCATIONCHECK)) { return true; } @@ -2532,9 +2342,7 @@ mongoc_uri_get_ssl (const mongoc_uri_t *uri) /* IN */ */ int32_t -mongoc_uri_get_option_as_int32 (const mongoc_uri_t *uri, - const char *option_orig, - int32_t fallback) +mongoc_uri_get_option_as_int32 (const mongoc_uri_t *uri, const char *option_orig, int32_t fallback) { const char *option; const bson_t *options; @@ -2548,14 +2356,11 @@ mongoc_uri_get_option_as_int32 (const mongoc_uri_t *uri, retval = mongoc_uri_get_option_as_int64 (uri, option_orig, 0); if (retval > INT32_MAX || retval < INT32_MIN) { - MONGOC_WARNING ("Cannot read 64-bit value for \"%s\": %" PRId64, - option_orig, - retval); + MONGOC_WARNING ("Cannot read 64-bit value for \"%s\": %" PRId64, option_orig, retval); retval = 0; } - } else if ((options = mongoc_uri_get_options (uri)) && - bson_iter_init_find_case (&iter, options, option) && + } else if ((options = mongoc_uri_get_options (uri)) && bson_iter_init_find_case (&iter, options, option) && BSON_ITER_HOLDS_INT32 (&iter)) { retval = bson_iter_int32 (&iter); } @@ -2593,9 +2398,7 @@ mongoc_uri_get_option_as_int32 (const mongoc_uri_t *uri, */ bool -mongoc_uri_set_option_as_int32 (mongoc_uri_t *uri, - const char *option_orig, - int32_t value) +mongoc_uri_set_option_as_int32 (mongoc_uri_t *uri, const char *option_orig, int32_t value) { const char *option; bson_error_t error; @@ -2608,11 +2411,7 @@ mongoc_uri_set_option_as_int32 (mongoc_uri_t *uri, option = mongoc_uri_canonicalize_option (option_orig); if (!mongoc_uri_option_is_int32 (option)) { - MONGOC_WARNING ( - "Unsupported value for \"%s\": %d, \"%s\" is not an int32 option", - option_orig, - value, - option); + MONGOC_WARNING ("Unsupported value for \"%s\": %d, \"%s\" is not an int32 option", option_orig, value, option); return false; } @@ -2665,17 +2464,12 @@ _mongoc_uri_set_option_as_int32_with_error (mongoc_uri_t *uri, } /* zlib levels are from -1 (default) through 9 (best compression) */ - if (!bson_strcasecmp (option, MONGOC_URI_ZLIBCOMPRESSIONLEVEL) && - (value < -1 || value > 9)) { - MONGOC_URI_ERROR (error, - "Invalid \"%s\" of %d: must be between -1 and 9", - option_orig, - value); + if (!bson_strcasecmp (option, MONGOC_URI_ZLIBCOMPRESSIONLEVEL) && (value < -1 || value > 9)) { + MONGOC_URI_ERROR (error, "Invalid \"%s\" of %d: must be between -1 and 9", option_orig, value); return false; } - if ((options = mongoc_uri_get_options (uri)) && - bson_iter_init_find_case (&iter, options, option)) { + if ((options = mongoc_uri_get_options (uri)) && bson_iter_init_find_case (&iter, options, option)) { if (BSON_ITER_HOLDS_INT32 (&iter)) { bson_iter_overwrite_int32 (&iter, value); return true; @@ -2691,8 +2485,7 @@ _mongoc_uri_set_option_as_int32_with_error (mongoc_uri_t *uri, option_lowercase = lowercase_str_new (option); if (!bson_append_int32 (&uri->options, option_lowercase, -1, value)) { bson_free (option_lowercase); - MONGOC_URI_ERROR ( - error, "Failed to set URI option \"%s\" to %d", option_orig, value); + MONGOC_URI_ERROR (error, "Failed to set URI option \"%s\" to %d", option_orig, value); return false; } @@ -2717,9 +2510,7 @@ _mongoc_uri_set_option_as_int32_with_error (mongoc_uri_t *uri, */ static bool -_mongoc_uri_set_option_as_int32 (mongoc_uri_t *uri, - const char *option_orig, - int32_t value) +_mongoc_uri_set_option_as_int32 (mongoc_uri_t *uri, const char *option_orig, int32_t value) { const char *option; const bson_t *options; @@ -2727,8 +2518,7 @@ _mongoc_uri_set_option_as_int32 (mongoc_uri_t *uri, char *option_lowercase = NULL; option = mongoc_uri_canonicalize_option (option_orig); - if ((options = mongoc_uri_get_options (uri)) && - bson_iter_init_find_case (&iter, options, option)) { + if ((options = mongoc_uri_get_options (uri)) && bson_iter_init_find_case (&iter, options, option)) { if (BSON_ITER_HOLDS_INT32 (&iter)) { bson_iter_overwrite_int32 (&iter, value); return true; @@ -2767,9 +2557,7 @@ _mongoc_uri_set_option_as_int32 (mongoc_uri_t *uri, */ int64_t -mongoc_uri_get_option_as_int64 (const mongoc_uri_t *uri, - const char *option_orig, - int64_t fallback) +mongoc_uri_get_option_as_int64 (const mongoc_uri_t *uri, const char *option_orig, int64_t fallback) { const char *option; const bson_t *options; @@ -2777,8 +2565,7 @@ mongoc_uri_get_option_as_int64 (const mongoc_uri_t *uri, int64_t retval = fallback; option = mongoc_uri_canonicalize_option (option_orig); - if ((options = mongoc_uri_get_options (uri)) && - bson_iter_init_find_case (&iter, options, option)) { + if ((options = mongoc_uri_get_options (uri)) && bson_iter_init_find_case (&iter, options, option)) { if (BSON_ITER_HOLDS_INT (&iter)) { if (!(retval = bson_iter_as_int64 (&iter))) { retval = fallback; @@ -2815,9 +2602,7 @@ mongoc_uri_get_option_as_int64 (const mongoc_uri_t *uri, */ bool -mongoc_uri_set_option_as_int64 (mongoc_uri_t *uri, - const char *option_orig, - int64_t value) +mongoc_uri_set_option_as_int64 (mongoc_uri_t *uri, const char *option_orig, int64_t value) { const char *option; bson_error_t error; @@ -2827,19 +2612,13 @@ mongoc_uri_set_option_as_int64 (mongoc_uri_t *uri, if (!mongoc_uri_option_is_int64 (option)) { if (mongoc_uri_option_is_int32 (option_orig)) { if (value >= INT32_MIN && value <= INT32_MAX) { - MONGOC_WARNING ( - "Setting value for 32-bit option \"%s\" through 64-bit method", - option_orig); + MONGOC_WARNING ("Setting value for 32-bit option \"%s\" through 64-bit method", option_orig); - return mongoc_uri_set_option_as_int32 ( - uri, option_orig, (int32_t) value); + return mongoc_uri_set_option_as_int32 (uri, option_orig, (int32_t) value); } - MONGOC_WARNING ("Unsupported value for \"%s\": %" PRId64 - ", \"%s\" is not an int64 option", - option_orig, - value, - option); + MONGOC_WARNING ( + "Unsupported value for \"%s\": %" PRId64 ", \"%s\" is not an int64 option", option_orig, value, option); return false; } } @@ -2881,15 +2660,13 @@ _mongoc_uri_set_option_as_int64_with_error (mongoc_uri_t *uri, option = mongoc_uri_canonicalize_option (option_orig); - if ((options = mongoc_uri_get_options (uri)) && - bson_iter_init_find_case (&iter, options, option)) { + if ((options = mongoc_uri_get_options (uri)) && bson_iter_init_find_case (&iter, options, option)) { if (BSON_ITER_HOLDS_INT64 (&iter)) { bson_iter_overwrite_int64 (&iter, value); return true; } else { MONGOC_URI_ERROR (error, - "Cannot set URI option \"%s\" to %" PRId64 - ", it already has " + "Cannot set URI option \"%s\" to %" PRId64 ", it already has " "a non-64-bit integer value", option, value); @@ -2900,10 +2677,7 @@ _mongoc_uri_set_option_as_int64_with_error (mongoc_uri_t *uri, option_lowercase = lowercase_str_new (option); if (!bson_append_int64 (&uri->options, option_lowercase, -1, value)) { bson_free (option_lowercase); - MONGOC_URI_ERROR (error, - "Failed to set URI option \"%s\" to %" PRId64, - option_orig, - value); + MONGOC_URI_ERROR (error, "Failed to set URI option \"%s\" to %" PRId64, option_orig, value); return false; } @@ -2929,17 +2703,14 @@ _mongoc_uri_set_option_as_int64_with_error (mongoc_uri_t *uri, */ bool -mongoc_uri_get_option_as_bool (const mongoc_uri_t *uri, - const char *option_orig, - bool fallback) +mongoc_uri_get_option_as_bool (const mongoc_uri_t *uri, const char *option_orig, bool fallback) { const char *option; const bson_t *options; bson_iter_t iter; option = mongoc_uri_canonicalize_option (option_orig); - if ((options = mongoc_uri_get_options (uri)) && - bson_iter_init_find_case (&iter, options, option) && + if ((options = mongoc_uri_get_options (uri)) && bson_iter_init_find_case (&iter, options, option) && BSON_ITER_HOLDS_BOOL (&iter)) { return bson_iter_bool (&iter); } @@ -2973,9 +2744,7 @@ mongoc_uri_get_option_as_bool (const mongoc_uri_t *uri, */ bool -mongoc_uri_set_option_as_bool (mongoc_uri_t *uri, - const char *option_orig, - bool value) +mongoc_uri_set_option_as_bool (mongoc_uri_t *uri, const char *option_orig, bool value) { const char *option; char *option_lowercase; @@ -2989,8 +2758,7 @@ mongoc_uri_set_option_as_bool (mongoc_uri_t *uri, return false; } - if ((options = mongoc_uri_get_options (uri)) && - bson_iter_init_find_case (&iter, options, option)) { + if ((options = mongoc_uri_get_options (uri)) && bson_iter_init_find_case (&iter, options, option)) { if (BSON_ITER_HOLDS_BOOL (&iter)) { bson_iter_overwrite_bool (&iter, value); return true; @@ -3022,17 +2790,14 @@ mongoc_uri_set_option_as_bool (mongoc_uri_t *uri, */ const char * -mongoc_uri_get_option_as_utf8 (const mongoc_uri_t *uri, - const char *option_orig, - const char *fallback) +mongoc_uri_get_option_as_utf8 (const mongoc_uri_t *uri, const char *option_orig, const char *fallback) { const char *option; const bson_t *options; bson_iter_t iter; option = mongoc_uri_canonicalize_option (option_orig); - if ((options = mongoc_uri_get_options (uri)) && - bson_iter_init_find_case (&iter, options, option) && + if ((options = mongoc_uri_get_options (uri)) && bson_iter_init_find_case (&iter, options, option) && BSON_ITER_HOLDS_UTF8 (&iter)) { return bson_iter_utf8 (&iter, NULL); } @@ -3070,9 +2835,7 @@ mongoc_uri_get_option_as_utf8 (const mongoc_uri_t *uri, */ bool -mongoc_uri_set_option_as_utf8 (mongoc_uri_t *uri, - const char *option_orig, - const char *value) +mongoc_uri_set_option_as_utf8 (mongoc_uri_t *uri, const char *option_orig, const char *value) { const char *option; size_t len; @@ -3094,8 +2857,7 @@ mongoc_uri_set_option_as_utf8 (mongoc_uri_t *uri, return mongoc_uri_set_appname (uri, value); } else { option_lowercase = lowercase_str_new (option); - mongoc_uri_bson_append_or_replace_key ( - &uri->options, option_lowercase, value); + mongoc_uri_bson_append_or_replace_key (&uri->options, option_lowercase, value); bson_free (option_lowercase); } @@ -3127,8 +2889,7 @@ _mongoc_uri_requires_auth_negotiation (const mongoc_uri_t *uri) /* A bit of a hack. Needed for multi mongos tests to create a URI with the same * auth, SSL, and compressors settings but with only one specific host. */ mongoc_uri_t * -_mongoc_uri_copy_and_replace_host_list (const mongoc_uri_t *original, - const char *host) +_mongoc_uri_copy_and_replace_host_list (const mongoc_uri_t *original, const char *host) { mongoc_uri_t *uri = mongoc_uri_copy (original); _mongoc_host_list_destroy_all (uri->hosts); @@ -3138,9 +2899,7 @@ _mongoc_uri_copy_and_replace_host_list (const mongoc_uri_t *original, } bool -mongoc_uri_init_with_srv_host_list (mongoc_uri_t *uri, - mongoc_host_list_t *host_list, - bson_error_t *error) +mongoc_uri_init_with_srv_host_list (mongoc_uri_t *uri, mongoc_host_list_t *host_list, bson_error_t *error) { mongoc_host_list_t *host; @@ -3159,9 +2918,7 @@ mongoc_uri_init_with_srv_host_list (mongoc_uri_t *uri, #ifdef MONGOC_ENABLE_CRYPTO void -_mongoc_uri_init_scram (const mongoc_uri_t *uri, - mongoc_scram_t *scram, - mongoc_crypto_hash_algorithm_t algo) +_mongoc_uri_init_scram (const mongoc_uri_t *uri, mongoc_scram_t *scram, mongoc_crypto_hash_algorithm_t algo) { BSON_ASSERT (uri); BSON_ASSERT (scram); @@ -3184,30 +2941,24 @@ mongoc_uri_finalize_loadbalanced (const mongoc_uri_t *uri, bson_error_t *error) * string, the driver MUST throw an exception if the connection string * contains more than one host/port. */ if (uri->hosts && uri->hosts->next) { - MONGOC_URI_ERROR ( - error, - "URI with \"%s\" enabled must not contain more than one host", - MONGOC_URI_LOADBALANCED); + MONGOC_URI_ERROR (error, "URI with \"%s\" enabled must not contain more than one host", MONGOC_URI_LOADBALANCED); return false; } if (mongoc_uri_has_option (uri, MONGOC_URI_REPLICASET)) { - MONGOC_URI_ERROR ( - error, - "URI with \"%s\" enabled must not contain option \"%s\"", - MONGOC_URI_LOADBALANCED, - MONGOC_URI_REPLICASET); + MONGOC_URI_ERROR (error, + "URI with \"%s\" enabled must not contain option \"%s\"", + MONGOC_URI_LOADBALANCED, + MONGOC_URI_REPLICASET); return false; } if (mongoc_uri_has_option (uri, MONGOC_URI_DIRECTCONNECTION) && - mongoc_uri_get_option_as_bool ( - uri, MONGOC_URI_DIRECTCONNECTION, false)) { - MONGOC_URI_ERROR ( - error, - "URI with \"%s\" enabled must not contain option \"%s\" enabled", - MONGOC_URI_LOADBALANCED, - MONGOC_URI_DIRECTCONNECTION); + mongoc_uri_get_option_as_bool (uri, MONGOC_URI_DIRECTCONNECTION, false)) { + MONGOC_URI_ERROR (error, + "URI with \"%s\" enabled must not contain option \"%s\" enabled", + MONGOC_URI_LOADBALANCED, + MONGOC_URI_DIRECTCONNECTION); return false; } @@ -3230,15 +2981,13 @@ mongoc_uri_finalize_srv (const mongoc_uri_t *uri, bson_error_t *error) } if (option) { - MONGOC_URI_ERROR ( - error, "%s must not be specified with a non-SRV URI", option); + MONGOC_URI_ERROR (error, "%s must not be specified with a non-SRV URI", option); return false; } } if (uri->is_srv) { - const int32_t max_hosts = - mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_SRVMAXHOSTS, 0); + const int32_t max_hosts = mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_SRVMAXHOSTS, 0); /* Initial DNS Seedless Discovery Spec: This option requires a * non-negative integer and defaults to zero (i.e. no limit). */ @@ -3256,10 +3005,7 @@ mongoc_uri_finalize_srv (const mongoc_uri_t *uri, bson_error_t *error) * integer, the driver MUST throw an error if the connection string * contains a `replicaSet` option. */ if (mongoc_uri_has_option (uri, MONGOC_URI_REPLICASET)) { - MONGOC_URI_ERROR (error, - "%s must not be specified with %s", - MONGOC_URI_SRVMAXHOSTS, - MONGOC_URI_REPLICASET); + MONGOC_URI_ERROR (error, "%s must not be specified with %s", MONGOC_URI_SRVMAXHOSTS, MONGOC_URI_REPLICASET); return false; } @@ -3267,12 +3013,9 @@ mongoc_uri_finalize_srv (const mongoc_uri_t *uri, bson_error_t *error) * integer, the driver MUST throw an error if the connection string * contains a `loadBalanced` option with a value of `true`. */ - if (mongoc_uri_get_option_as_bool ( - uri, MONGOC_URI_LOADBALANCED, false)) { - MONGOC_URI_ERROR (error, - "%s must not be specified with %s=true", - MONGOC_URI_SRVMAXHOSTS, - MONGOC_URI_LOADBALANCED); + if (mongoc_uri_get_option_as_bool (uri, MONGOC_URI_LOADBALANCED, false)) { + MONGOC_URI_ERROR ( + error, "%s must not be specified with %s=true", MONGOC_URI_SRVMAXHOSTS, MONGOC_URI_LOADBALANCED); return false; } } diff --git a/src/libmongoc/src/mongoc/mongoc-uri.h b/src/libmongoc/src/mongoc/mongoc-uri.h index 183c42d572..a8367d6e78 100644 --- a/src/libmongoc/src/mongoc/mongoc-uri.h +++ b/src/libmongoc/src/mongoc/mongoc-uri.h @@ -71,8 +71,7 @@ #define MONGOC_URI_TLSALLOWINVALIDCERTIFICATES "tlsallowinvalidcertificates" #define MONGOC_URI_TLSALLOWINVALIDHOSTNAMES "tlsallowinvalidhostnames" #define MONGOC_URI_TLSINSECURE "tlsinsecure" -#define MONGOC_URI_TLSDISABLECERTIFICATEREVOCATIONCHECK \ - "tlsdisablecertificaterevocationcheck" +#define MONGOC_URI_TLSDISABLECERTIFICATEREVOCATIONCHECK "tlsdisablecertificaterevocationcheck" #define MONGOC_URI_TLSDISABLEOCSPENDPOINTCHECK "tlsdisableocspendpointcheck" #define MONGOC_URI_W "w" #define MONGOC_URI_WAITQUEUEMULTIPLE "waitqueuemultiple" @@ -83,8 +82,7 @@ /* Deprecated in MongoDB 4.2, use "tls" variants instead. */ #define MONGOC_URI_SSL "ssl" #define MONGOC_URI_SSLCLIENTCERTIFICATEKEYFILE "sslclientcertificatekeyfile" -#define MONGOC_URI_SSLCLIENTCERTIFICATEKEYPASSWORD \ - "sslclientcertificatekeypassword" +#define MONGOC_URI_SSLCLIENTCERTIFICATEKEYPASSWORD "sslclientcertificatekeypassword" #define MONGOC_URI_SSLCERTIFICATEAUTHORITYFILE "sslcertificateauthorityfile" #define MONGOC_URI_SSLALLOWINVALIDCERTIFICATES "sslallowinvalidcertificates" #define MONGOC_URI_SSLALLOWINVALIDHOSTNAMES "sslallowinvalidhostnames" @@ -102,16 +100,13 @@ mongoc_uri_destroy (mongoc_uri_t *uri); MONGOC_EXPORT (mongoc_uri_t *) mongoc_uri_new (const char *uri_string) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (mongoc_uri_t *) -mongoc_uri_new_with_error (const char *uri_string, - bson_error_t *error) BSON_GNUC_WARN_UNUSED_RESULT; +mongoc_uri_new_with_error (const char *uri_string, bson_error_t *error) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (mongoc_uri_t *) -mongoc_uri_new_for_host_port (const char *hostname, - uint16_t port) BSON_GNUC_WARN_UNUSED_RESULT; +mongoc_uri_new_for_host_port (const char *hostname, uint16_t port) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (const mongoc_host_list_t *) mongoc_uri_get_hosts (const mongoc_uri_t *uri); MONGOC_EXPORT (const char *) -mongoc_uri_get_service (const mongoc_uri_t *uri) - BSON_GNUC_DEPRECATED_FOR (mongoc_uri_get_srv_hostname); +mongoc_uri_get_service (const mongoc_uri_t *uri) BSON_GNUC_DEPRECATED_FOR (mongoc_uri_get_srv_hostname); MONGOC_EXPORT (const char *) mongoc_uri_get_srv_hostname (const mongoc_uri_t *uri); MONGOC_EXPORT (const char *) @@ -139,40 +134,23 @@ mongoc_uri_option_is_bool (const char *key); MONGOC_EXPORT (bool) mongoc_uri_option_is_utf8 (const char *key); MONGOC_EXPORT (int32_t) -mongoc_uri_get_option_as_int32 (const mongoc_uri_t *uri, - const char *option, - int32_t fallback); +mongoc_uri_get_option_as_int32 (const mongoc_uri_t *uri, const char *option, int32_t fallback); MONGOC_EXPORT (int64_t) -mongoc_uri_get_option_as_int64 (const mongoc_uri_t *uri, - const char *option, - int64_t fallback); +mongoc_uri_get_option_as_int64 (const mongoc_uri_t *uri, const char *option, int64_t fallback); MONGOC_EXPORT (bool) -mongoc_uri_get_option_as_bool (const mongoc_uri_t *uri, - const char *option, - bool fallback); +mongoc_uri_get_option_as_bool (const mongoc_uri_t *uri, const char *option, bool fallback); MONGOC_EXPORT (const char *) -mongoc_uri_get_option_as_utf8 (const mongoc_uri_t *uri, - const char *option, - const char *fallback); +mongoc_uri_get_option_as_utf8 (const mongoc_uri_t *uri, const char *option, const char *fallback); MONGOC_EXPORT (bool) -mongoc_uri_set_option_as_int32 (mongoc_uri_t *uri, - const char *option, - int32_t value); +mongoc_uri_set_option_as_int32 (mongoc_uri_t *uri, const char *option, int32_t value); MONGOC_EXPORT (bool) -mongoc_uri_set_option_as_int64 (mongoc_uri_t *uri, - const char *option, - int64_t value); +mongoc_uri_set_option_as_int64 (mongoc_uri_t *uri, const char *option, int64_t value); MONGOC_EXPORT (bool) -mongoc_uri_set_option_as_bool (mongoc_uri_t *uri, - const char *option, - bool value); +mongoc_uri_set_option_as_bool (mongoc_uri_t *uri, const char *option, bool value); MONGOC_EXPORT (bool) -mongoc_uri_set_option_as_utf8 (mongoc_uri_t *uri, - const char *option, - const char *value); +mongoc_uri_set_option_as_utf8 (mongoc_uri_t *uri, const char *option, const char *value); MONGOC_EXPORT (const bson_t *) -mongoc_uri_get_read_prefs (const mongoc_uri_t *uri) - BSON_GNUC_DEPRECATED_FOR (mongoc_uri_get_read_prefs_t); +mongoc_uri_get_read_prefs (const mongoc_uri_t *uri) BSON_GNUC_DEPRECATED_FOR (mongoc_uri_get_read_prefs_t); MONGOC_EXPORT (const char *) mongoc_uri_get_replica_set (const mongoc_uri_t *uri); MONGOC_EXPORT (const char *) @@ -198,14 +176,11 @@ mongoc_uri_get_auth_mechanism (const mongoc_uri_t *uri); MONGOC_EXPORT (bool) mongoc_uri_set_auth_mechanism (mongoc_uri_t *uri, const char *value); MONGOC_EXPORT (bool) -mongoc_uri_get_mechanism_properties (const mongoc_uri_t *uri, - bson_t *properties); +mongoc_uri_get_mechanism_properties (const mongoc_uri_t *uri, bson_t *properties); MONGOC_EXPORT (bool) -mongoc_uri_set_mechanism_properties (mongoc_uri_t *uri, - const bson_t *properties); +mongoc_uri_set_mechanism_properties (mongoc_uri_t *uri, const bson_t *properties); MONGOC_EXPORT (bool) -mongoc_uri_get_ssl (const mongoc_uri_t *uri) - BSON_GNUC_DEPRECATED_FOR (mongoc_uri_get_tls); +mongoc_uri_get_ssl (const mongoc_uri_t *uri) BSON_GNUC_DEPRECATED_FOR (mongoc_uri_get_tls); MONGOC_EXPORT (bool) mongoc_uri_get_tls (const mongoc_uri_t *uri); MONGOC_EXPORT (char *) @@ -213,18 +188,15 @@ mongoc_uri_unescape (const char *escaped_string) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (const mongoc_read_prefs_t *) mongoc_uri_get_read_prefs_t (const mongoc_uri_t *uri); MONGOC_EXPORT (void) -mongoc_uri_set_read_prefs_t (mongoc_uri_t *uri, - const mongoc_read_prefs_t *prefs); +mongoc_uri_set_read_prefs_t (mongoc_uri_t *uri, const mongoc_read_prefs_t *prefs); MONGOC_EXPORT (const mongoc_write_concern_t *) mongoc_uri_get_write_concern (const mongoc_uri_t *uri); MONGOC_EXPORT (void) -mongoc_uri_set_write_concern (mongoc_uri_t *uri, - const mongoc_write_concern_t *wc); +mongoc_uri_set_write_concern (mongoc_uri_t *uri, const mongoc_write_concern_t *wc); MONGOC_EXPORT (const mongoc_read_concern_t *) mongoc_uri_get_read_concern (const mongoc_uri_t *uri); MONGOC_EXPORT (void) -mongoc_uri_set_read_concern (mongoc_uri_t *uri, - const mongoc_read_concern_t *rc); +mongoc_uri_set_read_concern (mongoc_uri_t *uri, const mongoc_read_concern_t *rc); BSON_END_DECLS diff --git a/src/libmongoc/src/mongoc/mongoc-util-private.h b/src/libmongoc/src/mongoc/mongoc-util-private.h index 19517104f3..70a646af45 100644 --- a/src/libmongoc/src/mongoc/mongoc-util-private.h +++ b/src/libmongoc/src/mongoc/mongoc-util-private.h @@ -35,14 +35,12 @@ #endif #if BSON_GNUC_CHECK_VERSION(4, 6) -#define BEGIN_IGNORE_DEPRECATIONS \ - _Pragma ("GCC diagnostic push") \ - _Pragma ("GCC diagnostic ignored \"-Wdeprecated-declarations\"") +#define BEGIN_IGNORE_DEPRECATIONS \ + _Pragma ("GCC diagnostic push") _Pragma ("GCC diagnostic ignored \"-Wdeprecated-declarations\"") #define END_IGNORE_DEPRECATIONS _Pragma ("GCC diagnostic pop") #elif defined(__clang__) -#define BEGIN_IGNORE_DEPRECATIONS \ - _Pragma ("clang diagnostic push") \ - _Pragma ("clang diagnostic ignored \"-Wdeprecated-declarations\"") +#define BEGIN_IGNORE_DEPRECATIONS \ + _Pragma ("clang diagnostic push") _Pragma ("clang diagnostic ignored \"-Wdeprecated-declarations\"") #define END_IGNORE_DEPRECATIONS _Pragma ("clang diagnostic pop") #else #define BEGIN_IGNORE_DEPRECATIONS @@ -111,19 +109,13 @@ _mongoc_get_server_id_from_opts (const bson_t *opts, bson_error_t *error); bool -_mongoc_validate_new_document (const bson_t *insert, - bson_validate_flags_t vflags, - bson_error_t *error); +_mongoc_validate_new_document (const bson_t *insert, bson_validate_flags_t vflags, bson_error_t *error); bool -_mongoc_validate_replace (const bson_t *insert, - bson_validate_flags_t vflags, - bson_error_t *error); +_mongoc_validate_replace (const bson_t *insert, bson_validate_flags_t vflags, bson_error_t *error); bool -_mongoc_validate_update (const bson_t *update, - bson_validate_flags_t vflags, - bson_error_t *error); +_mongoc_validate_update (const bson_t *update, bson_validate_flags_t vflags, bson_error_t *error); bool mongoc_ends_with (const char *str, const char *suffix); @@ -141,8 +133,7 @@ void _mongoc_bson_array_copy_labels_to (const bson_t *reply, bson_t *dst); void -_mongoc_add_transient_txn_error (const mongoc_client_session_t *cs, - bson_t *reply); +_mongoc_add_transient_txn_error (const mongoc_client_session_t *cs, bson_t *reply); bool _mongoc_document_is_pipeline (const bson_t *document); @@ -181,16 +172,11 @@ bool _mongoc_setenv (const char *name, const char *value); void -bson_copy_to_including_noinit (const bson_t *src, - bson_t *dst, - const char *first_include, - ...) BSON_GNUC_NULL_TERMINATED; +bson_copy_to_including_noinit (const bson_t *src, bson_t *dst, const char *first_include, ...) + BSON_GNUC_NULL_TERMINATED; void -bson_copy_to_including_noinit_va (const bson_t *src, - bson_t *dst, - const char *first_include, - va_list args); +bson_copy_to_including_noinit_va (const bson_t *src, bson_t *dst, const char *first_include, va_list args); /* Returns a uniformly-distributed uint32_t generated using * `_mongoc_rand_bytes()` if a source of cryptographic randomness is available @@ -267,9 +253,7 @@ _mongoc_rand_size_t (size_t min, size_t max, size_t (*rand) (void)); /* _mongoc_iter_document_as_bson attempts to read the document from @iter into * @bson. */ bool -_mongoc_iter_document_as_bson (const bson_iter_t *iter, - bson_t *bson, - bson_error_t *error); +_mongoc_iter_document_as_bson (const bson_iter_t *iter, bson_t *bson, bson_error_t *error); uint8_t * hex_to_bin (const char *hex, uint32_t *len); diff --git a/src/libmongoc/src/mongoc/mongoc-util.c b/src/libmongoc/src/mongoc/mongoc-util.c index 73fe534af7..2752e07594 100644 --- a/src/libmongoc/src/mongoc/mongoc-util.c +++ b/src/libmongoc/src/mongoc/mongoc-util.c @@ -33,16 +33,13 @@ #include "mongoc-sleep.h" const bson_validate_flags_t _mongoc_default_insert_vflags = - BSON_VALIDATE_UTF8 | BSON_VALIDATE_UTF8_ALLOW_NULL | - BSON_VALIDATE_EMPTY_KEYS; + BSON_VALIDATE_UTF8 | BSON_VALIDATE_UTF8_ALLOW_NULL | BSON_VALIDATE_EMPTY_KEYS; const bson_validate_flags_t _mongoc_default_replace_vflags = - BSON_VALIDATE_UTF8 | BSON_VALIDATE_UTF8_ALLOW_NULL | - BSON_VALIDATE_EMPTY_KEYS; + BSON_VALIDATE_UTF8 | BSON_VALIDATE_UTF8_ALLOW_NULL | BSON_VALIDATE_EMPTY_KEYS; const bson_validate_flags_t _mongoc_default_update_vflags = - BSON_VALIDATE_UTF8 | BSON_VALIDATE_UTF8_ALLOW_NULL | - BSON_VALIDATE_EMPTY_KEYS; + BSON_VALIDATE_UTF8 | BSON_VALIDATE_UTF8_ALLOW_NULL | BSON_VALIDATE_EMPTY_KEYS; int _mongoc_rand_simple (unsigned int *seed) @@ -73,8 +70,7 @@ _mongoc_hex_md5 (const char *input) int i; mcommon_md5_init (&md5); - mcommon_md5_append ( - &md5, (const uint8_t *) input, (uint32_t) strlen (input)); + mcommon_md5_append (&md5, (const uint8_t *) input, (uint32_t) strlen (input)); mcommon_md5_finish (&md5, digest); for (i = 0; i < sizeof digest; i++) { @@ -86,9 +82,7 @@ _mongoc_hex_md5 (const char *input) } void -mongoc_client_set_usleep_impl (mongoc_client_t *client, - mongoc_usleep_func_t usleep_func, - void *user_data) +mongoc_client_set_usleep_impl (mongoc_client_t *client, mongoc_usleep_func_t usleep_func, void *user_data) { client->topology->usleep_fn = usleep_func; client->topology->usleep_data = user_data; @@ -161,9 +155,8 @@ _mongoc_get_command_name (const bson_t *command) wrapper_name = "query"; } - if (wrapper_name && bson_iter_init_find (&iter, command, wrapper_name) && - BSON_ITER_HOLDS_DOCUMENT (&iter) && bson_iter_recurse (&iter, &child) && - bson_iter_next (&child)) { + if (wrapper_name && bson_iter_init_find (&iter, command, wrapper_name) && BSON_ITER_HOLDS_DOCUMENT (&iter) && + bson_iter_recurse (&iter, &child) && bson_iter_next (&child)) { name = bson_iter_key (&child); } @@ -341,11 +334,8 @@ _mongoc_wire_version_to_server_version (int32_t version) * if absent. On error, fills out *error with domain and code and return false. */ bool -_mongoc_get_server_id_from_opts (const bson_t *opts, - mongoc_error_domain_t domain, - mongoc_error_code_t code, - uint32_t *server_id, - bson_error_t *error) +_mongoc_get_server_id_from_opts ( + const bson_t *opts, mongoc_error_domain_t domain, mongoc_error_code_t code, uint32_t *server_id, bson_error_t *error) { bson_iter_t iter; @@ -360,8 +350,7 @@ _mongoc_get_server_id_from_opts (const bson_t *opts, } if (!BSON_ITER_HOLDS_INT (&iter)) { - bson_set_error ( - error, domain, code, "The serverId option must be an integer"); + bson_set_error (error, domain, code, "The serverId option must be an integer"); RETURN (false); } @@ -377,9 +366,7 @@ _mongoc_get_server_id_from_opts (const bson_t *opts, bool -_mongoc_validate_new_document (const bson_t *doc, - bson_validate_flags_t vflags, - bson_error_t *error) +_mongoc_validate_new_document (const bson_t *doc, bson_validate_flags_t vflags, bson_error_t *error) { bson_error_t validate_err; @@ -401,9 +388,7 @@ _mongoc_validate_new_document (const bson_t *doc, bool -_mongoc_validate_replace (const bson_t *doc, - bson_validate_flags_t vflags, - bson_error_t *error) +_mongoc_validate_replace (const bson_t *doc, bson_validate_flags_t vflags, bson_error_t *error) { bson_error_t validate_err; bson_iter_t iter; @@ -423,10 +408,7 @@ _mongoc_validate_replace (const bson_t *doc, } if (!bson_iter_init (&iter, doc)) { - bson_set_error (error, - MONGOC_ERROR_BSON, - MONGOC_ERROR_BSON_INVALID, - "replace document is corrupt"); + bson_set_error (error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "replace document is corrupt"); return false; } @@ -448,9 +430,7 @@ _mongoc_validate_replace (const bson_t *doc, bool -_mongoc_validate_update (const bson_t *update, - bson_validate_flags_t vflags, - bson_error_t *error) +_mongoc_validate_update (const bson_t *update, bson_validate_flags_t vflags, bson_error_t *error) { bson_error_t validate_err; bson_iter_t iter; @@ -474,10 +454,7 @@ _mongoc_validate_update (const bson_t *update, } if (!bson_iter_init (&iter, update)) { - bson_set_error (error, - MONGOC_ERROR_BSON, - MONGOC_ERROR_BSON_INVALID, - "update document is corrupt"); + bson_set_error (error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "update document is corrupt"); return false; } @@ -522,10 +499,7 @@ should_include (const char *first_include, va_list args, const char *name) void -bson_copy_to_including_noinit_va (const bson_t *src, - bson_t *dst, - const char *first_include, - va_list args) +bson_copy_to_including_noinit_va (const bson_t *src, bson_t *dst, const char *first_include, va_list args) { BSON_ASSERT_PARAM (src); BSON_ASSERT_PARAM (dst); @@ -549,10 +523,7 @@ bson_copy_to_including_noinit_va (const bson_t *src, } void -bson_copy_to_including_noinit (const bson_t *src, - bson_t *dst, - const char *first_include, - ...) +bson_copy_to_including_noinit (const bson_t *src, bson_t *dst, const char *first_include, ...) { BSON_ASSERT_PARAM (src); BSON_ASSERT_PARAM (dst); @@ -706,8 +677,7 @@ _mongoc_bson_array_copy_labels_to (const bson_t *reply, bson_t *dst) */ void -_mongoc_add_transient_txn_error (const mongoc_client_session_t *cs, - bson_t *reply) +_mongoc_add_transient_txn_error (const mongoc_client_session_t *cs, bson_t *reply) { if (!reply) { return; @@ -916,8 +886,7 @@ _mongoc_simple_rand_uint32_t (void) /* Ensure *all* bits are random, as RAND_MAX is only required to be at least * 32767 (2^15). */ - return (((uint32_t) rand () & 0x7FFFu) << 0u) | - (((uint32_t) rand () & 0x7FFFu) << 15u) | + return (((uint32_t) rand () & 0x7FFFu) << 0u) | (((uint32_t) rand () & 0x7FFFu) << 15u) | (((uint32_t) rand () & 0x0003u) << 30u); } @@ -928,10 +897,8 @@ _mongoc_simple_rand_uint64_t (void) /* Ensure *all* bits are random, as RAND_MAX is only required to be at least * 32767 (2^15). */ - return (((uint64_t) rand () & 0x7FFFu) << 0u) | - (((uint64_t) rand () & 0x7FFFu) << 15u) | - (((uint64_t) rand () & 0x7FFFu) << 30u) | - (((uint64_t) rand () & 0x7FFFu) << 45u) | + return (((uint64_t) rand () & 0x7FFFu) << 0u) | (((uint64_t) rand () & 0x7FFFu) << 15u) | + (((uint64_t) rand () & 0x7FFFu) << 30u) | (((uint64_t) rand () & 0x7FFFu) << 45u) | (((uint64_t) rand () & 0x0003u) << 60u); } @@ -955,8 +922,7 @@ _mongoc_rand_uint64_t (uint64_t min, uint64_t max, uint64_t (*rand) (void)) #if SIZE_MAX == UINT64_MAX -BSON_STATIC_ASSERT2 (_mongoc_simple_rand_size_t, - sizeof (size_t) == sizeof (uint64_t)); +BSON_STATIC_ASSERT2 (_mongoc_simple_rand_size_t, sizeof (size_t) == sizeof (uint64_t)); size_t _mongoc_simple_rand_size_t (void) @@ -970,14 +936,12 @@ _mongoc_rand_size_t (size_t min, size_t max, size_t (*rand) (void)) BSON_ASSERT (min <= max); BSON_ASSERT (min != 0u || max != UINT64_MAX); - return _mongoc_rand_java64 (max - min + 1u, (uint64_t (*) (void)) rand) + - min; + return _mongoc_rand_java64 (max - min + 1u, (uint64_t (*) (void)) rand) + min; } #elif SIZE_MAX == UINT32_MAX -BSON_STATIC_ASSERT2 (_mongoc_simple_rand_size_t, - sizeof (size_t) == sizeof (uint32_t)); +BSON_STATIC_ASSERT2 (_mongoc_simple_rand_size_t, sizeof (size_t) == sizeof (uint32_t)); size_t _mongoc_simple_rand_size_t (void) @@ -991,21 +955,17 @@ _mongoc_rand_size_t (size_t min, size_t max, size_t (*rand) (void)) BSON_ASSERT (min <= max); BSON_ASSERT (min != 0u || max != UINT32_MAX); - return _mongoc_rand_nduid32 (max - min + 1u, (uint32_t (*) (void)) rand) + - min; + return _mongoc_rand_nduid32 (max - min + 1u, (uint32_t (*) (void)) rand) + min; } #else -#error \ - "Implementation of _mongoc_simple_rand_size_t() requires size_t be exactly 32-bit or 64-bit" +#error "Implementation of _mongoc_simple_rand_size_t() requires size_t be exactly 32-bit or 64-bit" #endif bool -_mongoc_iter_document_as_bson (const bson_iter_t *iter, - bson_t *bson, - bson_error_t *error) +_mongoc_iter_document_as_bson (const bson_iter_t *iter, bson_t *bson, bson_error_t *error) { uint32_t len; const uint8_t *data; diff --git a/src/libmongoc/src/mongoc/mongoc-version-functions.c b/src/libmongoc/src/mongoc/mongoc-version-functions.c index 538330a51a..6ff81c641b 100644 --- a/src/libmongoc/src/mongoc/mongoc-version-functions.c +++ b/src/libmongoc/src/mongoc/mongoc-version-functions.c @@ -70,9 +70,7 @@ mongoc_get_version (void) * version. */ bool -mongoc_check_version (int required_major, - int required_minor, - int required_micro) +mongoc_check_version (int required_major, int required_minor, int required_micro) { return MONGOC_CHECK_VERSION (required_major, required_minor, required_micro); } diff --git a/src/libmongoc/src/mongoc/mongoc-version-functions.h b/src/libmongoc/src/mongoc/mongoc-version-functions.h index e8311dd10a..3c633d114d 100644 --- a/src/libmongoc/src/mongoc/mongoc-version-functions.h +++ b/src/libmongoc/src/mongoc/mongoc-version-functions.h @@ -35,9 +35,7 @@ mongoc_get_micro_version (void); MONGOC_EXPORT (const char *) mongoc_get_version (void); MONGOC_EXPORT (bool) -mongoc_check_version (int required_major, - int required_minor, - int required_micro); +mongoc_check_version (int required_major, int required_minor, int required_micro); BSON_END_DECLS diff --git a/src/libmongoc/src/mongoc/mongoc-write-command-private.h b/src/libmongoc/src/mongoc/mongoc-write-command-private.h index bc1a2e3fb9..9b9cc2edf4 100644 --- a/src/libmongoc/src/mongoc/mongoc-write-command-private.h +++ b/src/libmongoc/src/mongoc/mongoc-write-command-private.h @@ -105,9 +105,7 @@ typedef enum { void _mongoc_write_command_destroy (mongoc_write_command_t *command); void -_mongoc_write_command_init (bson_t *doc, - mongoc_write_command_t *command, - const char *collection); +_mongoc_write_command_init (bson_t *doc, mongoc_write_command_t *command, const char *collection); void _mongoc_write_command_init_insert (mongoc_write_command_t *command, const bson_t *document, @@ -148,8 +146,7 @@ _mongoc_write_command_init_update_idl (mongoc_write_command_t *command, const bson_t *opts, int64_t operation_id); void -_mongoc_write_command_insert_append (mongoc_write_command_t *command, - const bson_t *document); +_mongoc_write_command_insert_append (mongoc_write_command_t *command, const bson_t *document); void _mongoc_write_command_update_append (mongoc_write_command_t *command, const bson_t *selector, @@ -157,9 +154,7 @@ _mongoc_write_command_update_append (mongoc_write_command_t *command, const bson_t *opts); void -_mongoc_write_command_delete_append (mongoc_write_command_t *command, - const bson_t *selector, - const bson_t *opts); +_mongoc_write_command_delete_append (mongoc_write_command_t *command, const bson_t *selector, const bson_t *opts); void _mongoc_write_command_execute (mongoc_write_command_t *command, @@ -182,8 +177,7 @@ _mongoc_write_command_execute_idl (mongoc_write_command_t *command, mongoc_write_result_t *result); void _mongoc_write_result_init (mongoc_write_result_t *result); -#define MONGOC_WRITE_RESULT_COMPLETE(_result, ...) \ - _mongoc_write_result_complete (_result, __VA_ARGS__, NULL) +#define MONGOC_WRITE_RESULT_COMPLETE(_result, ...) _mongoc_write_result_complete (_result, __VA_ARGS__, NULL) bool _mongoc_write_result_complete (mongoc_write_result_t *result, int32_t error_api_version, @@ -199,9 +193,7 @@ mongoc_write_err_type_t _mongoc_write_error_get_type (bson_t *reply); bool -_mongoc_write_error_update_if_unsupported_storage_engine (bool cmd_ret, - bson_error_t *cmd_err, - bson_t *reply); +_mongoc_write_error_update_if_unsupported_storage_engine (bool cmd_ret, bson_error_t *cmd_err, bson_t *reply); BSON_END_DECLS diff --git a/src/libmongoc/src/mongoc/mongoc-write-command.c b/src/libmongoc/src/mongoc/mongoc-write-command.c index 83c71179cf..d4c481c666 100644 --- a/src/libmongoc/src/mongoc/mongoc-write-command.c +++ b/src/libmongoc/src/mongoc/mongoc-write-command.c @@ -35,8 +35,7 @@ static const uint32_t gCommandFieldLens[] = {7, 9, 7}; void -_mongoc_write_command_insert_append (mongoc_write_command_t *command, - const bson_t *document) +_mongoc_write_command_insert_append (mongoc_write_command_t *command, const bson_t *document) { bson_iter_t iter; bson_oid_t oid; @@ -61,8 +60,7 @@ _mongoc_write_command_insert_append (mongoc_write_command_t *command, _mongoc_buffer_append (&command->payload, bson_get_data (&tmp), tmp.len); bson_destroy (&tmp); } else { - _mongoc_buffer_append ( - &command->payload, bson_get_data (document), document->len); + _mongoc_buffer_append (&command->payload, bson_get_data (document), document->len); } command->n_documents++; @@ -95,8 +93,7 @@ _mongoc_write_command_update_append (mongoc_write_command_t *command, bson_concat (&document, opts); } - _mongoc_buffer_append ( - &command->payload, bson_get_data (&document), document.len); + _mongoc_buffer_append (&command->payload, bson_get_data (&document), document.len); command->n_documents++; bson_destroy (&document); @@ -105,9 +102,7 @@ _mongoc_write_command_update_append (mongoc_write_command_t *command, } void -_mongoc_write_command_delete_append (mongoc_write_command_t *command, - const bson_t *selector, - const bson_t *opts) +_mongoc_write_command_delete_append (mongoc_write_command_t *command, const bson_t *selector, const bson_t *opts) { bson_t document; @@ -125,8 +120,7 @@ _mongoc_write_command_delete_append (mongoc_write_command_t *command, bson_concat (&document, opts); } - _mongoc_buffer_append ( - &command->payload, bson_get_data (&document), document.len); + _mongoc_buffer_append (&command->payload, bson_get_data (&document), document.len); command->n_documents++; bson_destroy (&document); @@ -135,11 +129,8 @@ _mongoc_write_command_delete_append (mongoc_write_command_t *command, } static void -_mongoc_write_command_init_bulk (mongoc_write_command_t *command, - int type, - mongoc_bulk_write_flags_t flags, - int64_t operation_id, - const bson_t *opts) +_mongoc_write_command_init_bulk ( + mongoc_write_command_t *command, int type, mongoc_bulk_write_flags_t flags, int64_t operation_id, const bson_t *opts) { ENTRY; @@ -172,8 +163,7 @@ _mongoc_write_command_init_insert (mongoc_write_command_t *command, /* IN */ BSON_ASSERT (command); - _mongoc_write_command_init_bulk ( - command, MONGOC_WRITE_COMMAND_INSERT, flags, operation_id, cmd_opts); + _mongoc_write_command_init_bulk (command, MONGOC_WRITE_COMMAND_INSERT, flags, operation_id, cmd_opts); /* must handle NULL document from mongoc_collection_insert_bulk */ if (document) { @@ -196,8 +186,7 @@ _mongoc_write_command_init_insert_idl (mongoc_write_command_t *command, BSON_ASSERT (command); - _mongoc_write_command_init_bulk ( - command, MONGOC_WRITE_COMMAND_INSERT, flags, operation_id, cmd_opts); + _mongoc_write_command_init_bulk (command, MONGOC_WRITE_COMMAND_INSERT, flags, operation_id, cmd_opts); /* must handle NULL document from mongoc_collection_insert_bulk */ if (document) { @@ -221,8 +210,7 @@ _mongoc_write_command_init_delete (mongoc_write_command_t *command, /* IN */ BSON_ASSERT (command); BSON_ASSERT (selector); - _mongoc_write_command_init_bulk ( - command, MONGOC_WRITE_COMMAND_DELETE, flags, operation_id, cmd_opts); + _mongoc_write_command_init_bulk (command, MONGOC_WRITE_COMMAND_DELETE, flags, operation_id, cmd_opts); _mongoc_write_command_delete_append (command, selector, opts); EXIT; @@ -243,8 +231,7 @@ _mongoc_write_command_init_delete_idl (mongoc_write_command_t *command, BSON_ASSERT (command); BSON_ASSERT (selector); - _mongoc_write_command_init_bulk ( - command, MONGOC_WRITE_COMMAND_DELETE, flags, operation_id, cmd_opts); + _mongoc_write_command_init_bulk (command, MONGOC_WRITE_COMMAND_DELETE, flags, operation_id, cmd_opts); _mongoc_write_command_delete_append (command, selector, opts); @@ -267,8 +254,7 @@ _mongoc_write_command_init_update (mongoc_write_command_t *command, /* IN */ BSON_ASSERT (selector); BSON_ASSERT (update); - _mongoc_write_command_init_bulk ( - command, MONGOC_WRITE_COMMAND_UPDATE, flags, operation_id, cmd_opts); + _mongoc_write_command_init_bulk (command, MONGOC_WRITE_COMMAND_UPDATE, flags, operation_id, cmd_opts); _mongoc_write_command_update_append (command, selector, update, opts); EXIT; @@ -289,8 +275,7 @@ _mongoc_write_command_init_update_idl (mongoc_write_command_t *command, BSON_ASSERT (command); - _mongoc_write_command_init_bulk ( - command, MONGOC_WRITE_COMMAND_UPDATE, flags, operation_id, cmd_opts); + _mongoc_write_command_init_bulk (command, MONGOC_WRITE_COMMAND_UPDATE, flags, operation_id, cmd_opts); _mongoc_write_command_update_append (command, selector, update, opts); EXIT; @@ -299,9 +284,7 @@ _mongoc_write_command_init_update_idl (mongoc_write_command_t *command, /* takes initialized bson_t *doc and begins formatting a write command */ void -_mongoc_write_command_init (bson_t *doc, - mongoc_write_command_t *command, - const char *collection) +_mongoc_write_command_init (bson_t *doc, mongoc_write_command_t *command, const char *collection) { ENTRY; @@ -313,9 +296,7 @@ _mongoc_write_command_init (bson_t *doc, BSON_APPEND_BOOL (doc, "ordered", command->flags.ordered); if (command->flags.bypass_document_validation) { - BSON_APPEND_BOOL (doc, - "bypassDocumentValidation", - command->flags.bypass_document_validation); + BSON_APPEND_BOOL (doc, "bypassDocumentValidation", command->flags.bypass_document_validation); } EXIT; @@ -343,10 +324,7 @@ _mongoc_write_command_init (bson_t *doc, */ static void -_mongoc_write_command_too_large_error (bson_error_t *error, - int32_t idx, - int32_t len, - int32_t max_bson_size) +_mongoc_write_command_too_large_error (bson_error_t *error, int32_t idx, int32_t len, int32_t max_bson_size) { bson_set_error (error, MONGOC_ERROR_BSON, @@ -366,11 +344,8 @@ _empty_error (mongoc_write_command_t *command, bson_error_t *error) MONGOC_ERROR_COLLECTION_INSERT_FAILED, MONGOC_ERROR_COLLECTION_UPDATE_FAILED}; - bson_set_error (error, - MONGOC_ERROR_COLLECTION, - codes[command->type], - "Cannot do an empty %s", - gCommandNames[command->type]); + bson_set_error ( + error, MONGOC_ERROR_COLLECTION, codes[command->type], "Cannot do an empty %s", gCommandNames[command->type]); } @@ -402,10 +377,8 @@ _mongoc_write_result_merge_arrays (uint32_t offset, 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); + 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")) { @@ -427,9 +400,7 @@ _mongoc_write_result_merge_arrays (uint32_t offset, static void -_mongoc_write_result_append_upsert (mongoc_write_result_t *result, - int32_t idx, - const bson_value_t *value) +_mongoc_write_result_append_upsert (mongoc_write_result_t *result, int32_t idx, const bson_value_t *value) { bson_t child; const char *keyptr = NULL; @@ -439,8 +410,7 @@ _mongoc_write_result_append_upsert (mongoc_write_result_t *result, BSON_ASSERT (result); BSON_ASSERT (value); - len = (int) bson_uint32_to_string ( - result->upsert_append_count, &keyptr, key, sizeof key); + len = (int) bson_uint32_to_string (result->upsert_append_count, &keyptr, key, sizeof key); bson_append_document_begin (&result->upserted, keyptr, len, &child); BSON_APPEND_INT32 (&child, "index", idx); @@ -470,14 +440,12 @@ _mongoc_write_result_merge (mongoc_write_result_t *result, /* IN */ BSON_ASSERT (result); BSON_ASSERT (reply); - if (bson_iter_init_find (&iter, reply, "n") && - BSON_ITER_HOLDS_INT32 (&iter)) { + if (bson_iter_init_find (&iter, reply, "n") && BSON_ITER_HOLDS_INT32 (&iter)) { affected = bson_iter_int32 (&iter); } - if (bson_iter_init_find (&iter, reply, "writeErrors") && - BSON_ITER_HOLDS_ARRAY (&iter) && bson_iter_recurse (&iter, &citer) && - bson_iter_next (&citer)) { + if (bson_iter_init_find (&iter, reply, "writeErrors") && BSON_ITER_HOLDS_ARRAY (&iter) && + bson_iter_recurse (&iter, &citer) && bson_iter_next (&citer)) { result->failed = true; } @@ -493,20 +461,15 @@ _mongoc_write_result_merge (mongoc_write_result_t *result, /* IN */ /* server returns each upserted _id with its index into this batch * look for "upserted": [{"index": 4, "_id": ObjectId()}, ...] */ if (bson_iter_init_find (&iter, reply, "upserted")) { - if (BSON_ITER_HOLDS_ARRAY (&iter) && - (bson_iter_recurse (&iter, &ar))) { + if (BSON_ITER_HOLDS_ARRAY (&iter) && (bson_iter_recurse (&iter, &ar))) { while (bson_iter_next (&ar)) { - if (BSON_ITER_HOLDS_DOCUMENT (&ar) && - bson_iter_recurse (&ar, &citer) && - bson_iter_find (&citer, "index") && - BSON_ITER_HOLDS_INT32 (&citer)) { + if (BSON_ITER_HOLDS_DOCUMENT (&ar) && bson_iter_recurse (&ar, &citer) && + bson_iter_find (&citer, "index") && BSON_ITER_HOLDS_INT32 (&citer)) { server_index = bson_iter_int32 (&citer); - if (bson_iter_recurse (&ar, &citer) && - bson_iter_find (&citer, "_id")) { + if (bson_iter_recurse (&ar, &citer) && bson_iter_find (&citer, "_id")) { value = bson_iter_value (&citer); - _mongoc_write_result_append_upsert ( - result, offset + server_index, value); + _mongoc_write_result_append_upsert (result, offset + server_index, value); n_upserted++; } } @@ -521,8 +484,7 @@ _mongoc_write_result_merge (mongoc_write_result_t *result, /* IN */ } else { result->nMatched += affected; } - if (bson_iter_init_find (&iter, reply, "nModified") && - BSON_ITER_HOLDS_INT32 (&iter)) { + if (bson_iter_init_find (&iter, reply, "nModified") && BSON_ITER_HOLDS_INT32 (&iter)) { result->nModified += bson_iter_int32 (&iter); } break; @@ -531,14 +493,11 @@ _mongoc_write_result_merge (mongoc_write_result_t *result, /* IN */ break; } - if (bson_iter_init_find (&iter, reply, "writeErrors") && - BSON_ITER_HOLDS_ARRAY (&iter)) { - _mongoc_write_result_merge_arrays ( - offset, result, &result->writeErrors, &iter); + if (bson_iter_init_find (&iter, reply, "writeErrors") && BSON_ITER_HOLDS_ARRAY (&iter)) { + _mongoc_write_result_merge_arrays (offset, result, &result->writeErrors, &iter); } - if (bson_iter_init_find (&iter, reply, "writeConcernError") && - BSON_ITER_HOLDS_DOCUMENT (&iter)) { + if (bson_iter_init_find (&iter, reply, "writeConcernError") && BSON_ITER_HOLDS_DOCUMENT (&iter)) { uint32_t len; const uint8_t *data; bson_t write_concern_error; @@ -550,11 +509,9 @@ _mongoc_write_result_merge (mongoc_write_result_t *result, /* IN */ bson_iter_document (&iter, &len, &data); BSON_ASSERT (bson_init_static (&write_concern_error, data, len)); - bson_uint32_to_string ( - result->n_writeConcernErrors, &key, str, sizeof str); + bson_uint32_to_string (result->n_writeConcernErrors, &key, str, sizeof str); - if (!bson_append_document ( - &result->writeConcernErrors, key, -1, &write_concern_error)) { + if (!bson_append_document (&result->writeConcernErrors, key, -1, &write_concern_error)) { MONGOC_ERROR ("Error adding \"%s\" to writeConcernErrors.\n", key); } @@ -563,8 +520,7 @@ _mongoc_write_result_merge (mongoc_write_result_t *result, /* IN */ /* If a server error ocurred, then append the raw response to the * error_replies array. */ - if (!_mongoc_cmd_check_ok ( - reply, MONGOC_ERROR_API_VERSION_2, NULL /* error */)) { + if (!_mongoc_cmd_check_ok (reply, MONGOC_ERROR_API_VERSION_2, NULL /* error */)) { char str[16]; const char *key; @@ -625,8 +581,7 @@ _mongoc_write_opmsg (mongoc_write_command_t *command, if (_mongoc_cse_is_enabled (client)) { max_msg_size = MONGOC_REDUCED_MAX_MSG_SIZE_FOR_FLE; } - max_document_count = - mongoc_server_stream_max_write_batch_size (server_stream); + max_document_count = mongoc_server_stream_max_write_batch_size (server_stream); bson_init (&cmd); _mongoc_write_command_init (&cmd, command, collection); @@ -646,10 +601,9 @@ _mongoc_write_opmsg (mongoc_write_command_t *command, /* Write commands that include multi-document operations are not retryable. * Set this explicitly so that mongoc_cmd_parts_assemble does not need to * inspect the command body later. */ - parts.allow_txn_number = - (command->flags.has_multi_write || !parts.assembled.is_acknowledged) - ? MONGOC_CMD_PARTS_ALLOW_TXN_NUMBER_NO - : MONGOC_CMD_PARTS_ALLOW_TXN_NUMBER_YES; + parts.allow_txn_number = (command->flags.has_multi_write || !parts.assembled.is_acknowledged) + ? MONGOC_CMD_PARTS_ALLOW_TXN_NUMBER_NO + : MONGOC_CMD_PARTS_ALLOW_TXN_NUMBER_YES; BSON_ASSERT (bson_iter_init (&iter, &command->cmd_opts)); if (!mongoc_cmd_parts_append_opts (&parts, &iter, error)) { @@ -675,14 +629,11 @@ _mongoc_write_opmsg (mongoc_write_command_t *command, * + Y command identifier ("documents", "deletes", "updates") ( + \0) */ - header = - 26 + parts.assembled.command->len + gCommandFieldLens[command->type] + 1; + header = 26 + parts.assembled.command->len + gCommandFieldLens[command->type] + 1; do { uint32_t ulen; - memcpy (&ulen, - command->payload.data + payload_batch_size + payload_total_offset, - 4); + memcpy (&ulen, command->payload.data + payload_batch_size + payload_total_offset, 4); ulen = BSON_UINT32_FROM_LE (ulen); // Although messageLength is an int32, it should never be negative. @@ -691,14 +642,11 @@ _mongoc_write_opmsg (mongoc_write_command_t *command, if (slen > max_bson_obj_size + BSON_OBJECT_ALLOWANCE) { /* Quit if the document is too large */ - _mongoc_write_command_too_large_error ( - error, index_offset, slen, max_bson_obj_size); + _mongoc_write_command_too_large_error (error, index_offset, slen, max_bson_obj_size); result->failed = true; break; - } else if (bson_cmp_less_equal_us (payload_batch_size + header + ulen, - max_msg_size) || - document_count == 0) { + } else if (bson_cmp_less_equal_us (payload_batch_size + header + ulen, max_msg_size) || document_count == 0) { /* The current batch is still under max batch size in bytes */ payload_batch_size += ulen; @@ -706,8 +654,7 @@ _mongoc_write_opmsg (mongoc_write_command_t *command, if (++document_count == max_document_count) { ship_it = true; /* If this document is the last document we have */ - } else if (payload_batch_size + payload_total_offset == - command->payload.len) { + } else if (payload_batch_size + payload_total_offset == command->payload.len) { ship_it = true; } else { ship_it = false; @@ -730,11 +677,8 @@ _mongoc_write_opmsg (mongoc_write_command_t *command, * retryable write command */ if (is_retryable) { bson_iter_t txn_number_iter; - BSON_ASSERT (bson_iter_init_find ( - &txn_number_iter, parts.assembled.command, "txnNumber")); - bson_iter_overwrite_int64 ( - &txn_number_iter, - ++parts.assembled.session->server_session->txn_number); + BSON_ASSERT (bson_iter_init_find (&txn_number_iter, parts.assembled.command, "txnNumber")); + bson_iter_overwrite_int64 (&txn_number_iter, ++parts.assembled.session->server_session->txn_number); } // Store the original error and reply if needed. @@ -745,12 +689,10 @@ _mongoc_write_opmsg (mongoc_write_command_t *command, } original_error = {.reply = {0}, .error = {0}, .set = false}; retry: - ret = mongoc_cluster_run_command_monitored ( - &client->cluster, &parts.assembled, &reply, error); + ret = mongoc_cluster_run_command_monitored (&client->cluster, &parts.assembled, &reply, error); if (parts.is_retryable_write) { - _mongoc_write_error_handle_labels ( - ret, error, &reply, server_stream->sd); + _mongoc_write_error_handle_labels (ret, error, &reply, server_stream->sd); } /* Add this batch size so we skip these documents next time */ @@ -763,8 +705,7 @@ _mongoc_write_opmsg (mongoc_write_command_t *command, * and allow the original error to be reported. */ error_type = _mongoc_write_error_get_type (&reply); if (is_retryable) { - _mongoc_write_error_update_if_unsupported_storage_engine ( - ret, error, &reply); + _mongoc_write_error_update_if_unsupported_storage_engine (ret, error, &reply); } if (is_retryable && error_type == MONGOC_WRITE_ERR_RETRY) { bson_error_t ignored_error; @@ -773,22 +714,17 @@ _mongoc_write_opmsg (mongoc_write_command_t *command, is_retryable = false; { - mongoc_deprioritized_servers_t *const ds = - mongoc_deprioritized_servers_new (); + mongoc_deprioritized_servers_t *const ds = mongoc_deprioritized_servers_new (); if (retry_server_stream) { mongoc_deprioritized_servers_add_if_sharded ( - ds, - retry_server_stream->topology_type, - retry_server_stream->sd); + ds, retry_server_stream->topology_type, retry_server_stream->sd); mongoc_server_stream_cleanup (retry_server_stream); } else { - mongoc_deprioritized_servers_add_if_sharded ( - ds, server_stream->topology_type, server_stream->sd); + mongoc_deprioritized_servers_add_if_sharded (ds, server_stream->topology_type, server_stream->sd); } - retry_server_stream = mongoc_cluster_stream_for_writes ( - &client->cluster, cs, ds, NULL, &ignored_error); + retry_server_stream = mongoc_cluster_stream_for_writes (&client->cluster, cs, ds, NULL, &ignored_error); mongoc_deprioritized_servers_destroy (ds); } @@ -813,16 +749,14 @@ _mongoc_write_opmsg (mongoc_write_command_t *command, result->failed = true; /* Stop for ordered bulk writes or when the server stream has been * properly invalidated (e.g., due to a network error). */ - if (command->flags.ordered || !mongoc_cluster_stream_valid ( - &client->cluster, server_stream)) { + if (command->flags.ordered || !mongoc_cluster_stream_valid (&client->cluster, server_stream)) { result->must_stop = true; } } // If a retry attempt fails with an error labeled NoWritesPerformed, // drivers MUST return the original error. - if (original_error.set && - mongoc_error_has_label (&reply, "NoWritesPerformed")) { + if (original_error.set && mongoc_error_has_label (&reply, "NoWritesPerformed")) { if (error) { *error = original_error.error; } @@ -852,8 +786,7 @@ _mongoc_write_opmsg (mongoc_write_command_t *command, if (ret) { /* if a retry succeeded, report that in the result so bulk write can * use the newly selected server. */ - result->retry_server_id = - mongoc_server_description_id (retry_server_stream->sd); + result->retry_server_id = mongoc_server_description_id (retry_server_stream->sd); } mongoc_server_stream_cleanup (retry_server_stream); } @@ -868,16 +801,15 @@ _mongoc_write_opmsg (mongoc_write_command_t *command, void -_mongoc_write_command_execute ( - mongoc_write_command_t *command, /* IN */ - mongoc_client_t *client, /* IN */ - mongoc_server_stream_t *server_stream, /* IN */ - const char *database, /* IN */ - const char *collection, /* IN */ - const mongoc_write_concern_t *write_concern, /* IN */ - uint32_t offset, /* IN */ - mongoc_client_session_t *cs, /* IN */ - mongoc_write_result_t *result) /* OUT */ +_mongoc_write_command_execute (mongoc_write_command_t *command, /* IN */ + mongoc_client_t *client, /* IN */ + mongoc_server_stream_t *server_stream, /* IN */ + const char *database, /* IN */ + const char *collection, /* IN */ + const mongoc_write_concern_t *write_concern, /* IN */ + uint32_t offset, /* IN */ + mongoc_client_session_t *cs, /* IN */ + mongoc_write_result_t *result) /* OUT */ { mongoc_crud_opts_t crud = {0}; @@ -895,10 +827,8 @@ _mongoc_write_command_execute ( } if (!mongoc_write_concern_is_valid (write_concern)) { - bson_set_error (&result->error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "The write concern is invalid."); + bson_set_error ( + &result->error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "The write concern is invalid."); result->failed = true; EXIT; } @@ -906,14 +836,7 @@ _mongoc_write_command_execute ( crud.client_session = cs; crud.writeConcern = (mongoc_write_concern_t *) write_concern; - _mongoc_write_command_execute_idl (command, - client, - server_stream, - database, - collection, - offset, - &crud, - result); + _mongoc_write_command_execute_idl (command, client, server_stream, database, collection, offset, &crud, result); EXIT; } @@ -961,11 +884,10 @@ _mongoc_write_command_execute_idl (mongoc_write_command_t *command, if (command->flags.has_update_hint) { if (server_stream->sd->max_wire_version < WIRE_VERSION_UPDATE_HINT && !mongoc_write_concern_is_acknowledged (crud->writeConcern)) { - bson_set_error ( - &result->error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION, - "The selected server does not support hint for update"); + bson_set_error (&result->error, + MONGOC_ERROR_COMMAND, + MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION, + "The selected server does not support hint for update"); result->failed = true; EXIT; } @@ -974,11 +896,10 @@ _mongoc_write_command_execute_idl (mongoc_write_command_t *command, if (command->flags.has_delete_hint) { if (server_stream->sd->max_wire_version < WIRE_VERSION_DELETE_HINT && !mongoc_write_concern_is_acknowledged (crud->writeConcern)) { - bson_set_error ( - &result->error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION, - "The selected server does not support hint for delete"); + bson_set_error (&result->error, + MONGOC_ERROR_COMMAND, + MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION, + "The selected server does not support hint for delete"); result->failed = true; EXIT; } @@ -987,17 +908,15 @@ _mongoc_write_command_execute_idl (mongoc_write_command_t *command, if (command->flags.bypass_document_validation) { if (!mongoc_write_concern_is_acknowledged (crud->writeConcern)) { result->failed = true; - bson_set_error ( - &result->error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Cannot set bypassDocumentValidation for unacknowledged writes"); + bson_set_error (&result->error, + MONGOC_ERROR_COMMAND, + MONGOC_ERROR_COMMAND_INVALID_ARG, + "Cannot set bypassDocumentValidation for unacknowledged writes"); EXIT; } } - if (crud->client_session && - !mongoc_write_concern_is_acknowledged (crud->writeConcern)) { + if (crud->client_session && !mongoc_write_concern_is_acknowledged (crud->writeConcern)) { result->failed = true; bson_set_error (&result->error, MONGOC_ERROR_COMMAND, @@ -1097,8 +1016,7 @@ _set_error_from_response (bson_t *bson_array, compound_err = bson_string_new (NULL); n_keys = bson_count_keys (bson_array); if (n_keys > 1) { - bson_string_append_printf ( - compound_err, "Multiple %s errors: ", error_type); + bson_string_append_printf (compound_err, "Multiple %s errors: ", error_type); } if (!bson_empty0 (bson_array) && bson_iter_init (&array_iter, bson_array)) { @@ -1106,8 +1024,7 @@ _set_error_from_response (bson_t *bson_array, i = 0; while (bson_iter_next (&array_iter)) { - if (BSON_ITER_HOLDS_DOCUMENT (&array_iter) && - bson_iter_recurse (&array_iter, &doc_iter)) { + if (BSON_ITER_HOLDS_DOCUMENT (&array_iter) && bson_iter_recurse (&array_iter, &doc_iter)) { /* parse doc, which is like {"code": 64, "errmsg": "duplicate"} */ while (bson_iter_next (&doc_iter)) { /* use the first error code we find */ @@ -1134,8 +1051,7 @@ _set_error_from_response (bson_t *bson_array, } if (code && compound_err->len) { - bson_set_error ( - error, domain, (uint32_t) code, "%s", compound_err->str); + bson_set_error (error, domain, (uint32_t) code, "%s", compound_err->str); } } @@ -1145,14 +1061,13 @@ _set_error_from_response (bson_t *bson_array, /* complete a write result, including only certain fields */ bool -_mongoc_write_result_complete ( - mongoc_write_result_t *result, /* IN */ - int32_t error_api_version, /* IN */ - const mongoc_write_concern_t *wc, /* IN */ - mongoc_error_domain_t err_domain_override, /* IN */ - bson_t *bson, /* OUT */ - bson_error_t *error, /* OUT */ - ...) +_mongoc_write_result_complete (mongoc_write_result_t *result, /* IN */ + int32_t error_api_version, /* IN */ + const mongoc_write_concern_t *wc, /* IN */ + mongoc_error_domain_t err_domain_override, /* IN */ + bson_t *bson, /* OUT */ + bson_error_t *error, /* OUT */ + ...) { mongoc_error_domain_t domain; va_list args; @@ -1205,13 +1120,10 @@ _mongoc_write_result_complete ( BSON_APPEND_INT32 (bson, field, result->nUpserted); } else if (!strcmp (field, "upsertedCount")) { BSON_APPEND_INT32 (bson, field, result->nUpserted); - } else if (!strcmp (field, "upserted") && - !bson_empty0 (&result->upserted)) { + } else if (!strcmp (field, "upserted") && !bson_empty0 (&result->upserted)) { BSON_APPEND_ARRAY (bson, field, &result->upserted); - } else if (!strcmp (field, "upsertedId") && - !bson_empty0 (&result->upserted) && - bson_iter_init_find (&iter, &result->upserted, "0") && - bson_iter_recurse (&iter, &child) && + } else if (!strcmp (field, "upsertedId") && !bson_empty0 (&result->upserted) && + bson_iter_init_find (&iter, &result->upserted, "0") && bson_iter_recurse (&iter, &child) && bson_iter_find (&child, "_id")) { /* "upsertedId", singular, for update_one() */ BSON_APPEND_VALUE (bson, "upsertedId", bson_iter_value (&child)); @@ -1238,8 +1150,7 @@ _mongoc_write_result_complete ( } if (result->n_writeConcernErrors) { - BSON_APPEND_ARRAY ( - bson, "writeConcernErrors", &result->writeConcernErrors); + BSON_APPEND_ARRAY (bson, "writeConcernErrors", &result->writeConcernErrors); } } @@ -1250,14 +1161,11 @@ _mongoc_write_result_complete ( } /* set bson_error_t from first write error or write concern error */ - _set_error_from_response ( - &result->writeErrors, domain, "write", &result->error); + _set_error_from_response (&result->writeErrors, domain, "write", &result->error); if (!result->error.code) { - _set_error_from_response (&result->writeConcernErrors, - MONGOC_ERROR_WRITE_CONCERN, - "write concern", - &result->error); + _set_error_from_response ( + &result->writeConcernErrors, MONGOC_ERROR_WRITE_CONCERN, "write concern", &result->error); } if (bson && !bson_empty (&result->errorLabels)) { @@ -1300,8 +1208,7 @@ _mongoc_write_error_get_type (bson_t *reply) } /* check for a server error. */ - if (_mongoc_cmd_check_ok_no_wce ( - reply, MONGOC_ERROR_API_VERSION_2, &error)) { + if (_mongoc_cmd_check_ok_no_wce (reply, MONGOC_ERROR_API_VERSION_2, &error)) { return MONGOC_WRITE_ERR_NONE; } @@ -1315,9 +1222,7 @@ _mongoc_write_error_get_type (bson_t *reply) /* Returns true and modifies reply and cmd_err. */ bool -_mongoc_write_error_update_if_unsupported_storage_engine (bool cmd_ret, - bson_error_t *cmd_err, - bson_t *reply) +_mongoc_write_error_update_if_unsupported_storage_engine (bool cmd_ret, bson_error_t *cmd_err, bson_t *reply) { bson_error_t server_error; @@ -1325,14 +1230,11 @@ _mongoc_write_error_update_if_unsupported_storage_engine (bool cmd_ret, return false; } - if (_mongoc_cmd_check_ok_no_wce ( - reply, MONGOC_ERROR_API_VERSION_2, &server_error)) { + if (_mongoc_cmd_check_ok_no_wce (reply, MONGOC_ERROR_API_VERSION_2, &server_error)) { return false; } - if (server_error.code == 20 && - strstr (server_error.message, "Transaction numbers") == - server_error.message) { + if (server_error.code == 20 && strstr (server_error.message, "Transaction numbers") == server_error.message) { const char *replacement = "This MongoDB deployment does not support " "retryable writes. Please add " "retryWrites=false to your connection string."; diff --git a/src/libmongoc/src/mongoc/mongoc-write-concern-private.h b/src/libmongoc/src/mongoc/mongoc-write-concern-private.h index aae8c35737..0aa9ae204e 100644 --- a/src/libmongoc/src/mongoc/mongoc-write-concern-private.h +++ b/src/libmongoc/src/mongoc/mongoc-write-concern-private.h @@ -42,8 +42,7 @@ struct _mongoc_write_concern_t { mongoc_write_concern_t * -_mongoc_write_concern_new_from_iter (const bson_iter_t *iter, - bson_error_t *error); +_mongoc_write_concern_new_from_iter (const bson_iter_t *iter, bson_error_t *error); const bson_t * _mongoc_write_concern_get_bson (mongoc_write_concern_t *write_concern); bool diff --git a/src/libmongoc/src/mongoc/mongoc-write-concern.c b/src/libmongoc/src/mongoc/mongoc-write-concern.c index f66c1611a9..72db6a5864 100644 --- a/src/libmongoc/src/mongoc/mongoc-write-concern.c +++ b/src/libmongoc/src/mongoc/mongoc-write-concern.c @@ -105,8 +105,7 @@ mongoc_write_concern_get_fsync (const mongoc_write_concern_t *write_concern) * write request. */ void -mongoc_write_concern_set_fsync (mongoc_write_concern_t *write_concern, - bool fsync_) +mongoc_write_concern_set_fsync (mongoc_write_concern_t *write_concern, bool fsync_) { BSON_ASSERT (write_concern); @@ -125,8 +124,7 @@ mongoc_write_concern_get_journal (const mongoc_write_concern_t *write_concern) bool -mongoc_write_concern_journal_is_set ( - const mongoc_write_concern_t *write_concern) +mongoc_write_concern_journal_is_set (const mongoc_write_concern_t *write_concern) { BSON_ASSERT (write_concern); return (write_concern->journal != MONGOC_WRITE_CONCERN_JOURNAL_DEFAULT); @@ -142,8 +140,7 @@ mongoc_write_concern_journal_is_set ( * write request. */ void -mongoc_write_concern_set_journal (mongoc_write_concern_t *write_concern, - bool journal) +mongoc_write_concern_set_journal (mongoc_write_concern_t *write_concern, bool journal) { BSON_ASSERT (write_concern); @@ -194,8 +191,7 @@ mongoc_write_concern_get_wtimeout (const mongoc_write_concern_t *write_concern) int64_t -mongoc_write_concern_get_wtimeout_int64 ( - const mongoc_write_concern_t *write_concern) +mongoc_write_concern_get_wtimeout_int64 (const mongoc_write_concern_t *write_concern) { BSON_ASSERT (write_concern); return write_concern->wtimeout; @@ -203,17 +199,14 @@ mongoc_write_concern_get_wtimeout_int64 ( void -mongoc_write_concern_set_wtimeout (mongoc_write_concern_t *write_concern, - int32_t wtimeout_msec) +mongoc_write_concern_set_wtimeout (mongoc_write_concern_t *write_concern, int32_t wtimeout_msec) { - mongoc_write_concern_set_wtimeout_int64 (write_concern, - (int64_t) wtimeout_msec); + mongoc_write_concern_set_wtimeout_int64 (write_concern, (int64_t) wtimeout_msec); } void -mongoc_write_concern_set_wtimeout_int64 (mongoc_write_concern_t *write_concern, - int64_t wtimeout_msec) +mongoc_write_concern_set_wtimeout_int64 (mongoc_write_concern_t *write_concern, int64_t wtimeout_msec) { BSON_ASSERT (write_concern); @@ -248,8 +241,7 @@ mongoc_write_concern_get_wmajority (const mongoc_write_concern_t *write_concern) * be ignored. */ void -mongoc_write_concern_set_wmajority (mongoc_write_concern_t *write_concern, - int32_t wtimeout_msec) +mongoc_write_concern_set_wmajority (mongoc_write_concern_t *write_concern, int32_t wtimeout_msec) { BSON_ASSERT (write_concern); @@ -277,8 +269,7 @@ mongoc_write_concern_get_wtag (const mongoc_write_concern_t *write_concern) void -mongoc_write_concern_set_wtag (mongoc_write_concern_t *write_concern, - const char *wtag) +mongoc_write_concern_set_wtag (mongoc_write_concern_t *write_concern, const char *wtag) { BSON_ASSERT (write_concern); @@ -379,14 +370,12 @@ _mongoc_write_concern_freeze (mongoc_write_concern_t *write_concern) * Returns: true if a getlasterror command should be sent. */ bool -mongoc_write_concern_is_acknowledged ( - const mongoc_write_concern_t *write_concern) +mongoc_write_concern_is_acknowledged (const mongoc_write_concern_t *write_concern) { if (write_concern) { return (((write_concern->w != MONGOC_WRITE_CONCERN_W_UNACKNOWLEDGED) && (write_concern->w != MONGOC_WRITE_CONCERN_W_ERRORS_IGNORED)) || - write_concern->fsync_ == true || - mongoc_write_concern_get_journal (write_concern)); + write_concern->fsync_ == true || mongoc_write_concern_get_journal (write_concern)); } return true; } @@ -409,8 +398,7 @@ mongoc_write_concern_is_valid (const mongoc_write_concern_t *write_concern) } /* Journal or fsync should require acknowledgement. */ - if ((write_concern->fsync_ == true || - mongoc_write_concern_get_journal (write_concern)) && + if ((write_concern->fsync_ == true || mongoc_write_concern_get_journal (write_concern)) && (write_concern->w == MONGOC_WRITE_CONCERN_W_UNACKNOWLEDGED || write_concern->w == MONGOC_WRITE_CONCERN_W_ERRORS_IGNORED)) { return false; @@ -425,14 +413,10 @@ mongoc_write_concern_is_valid (const mongoc_write_concern_t *write_concern) static bool -_mongoc_write_concern_validate (const mongoc_write_concern_t *write_concern, - bson_error_t *error) +_mongoc_write_concern_validate (const mongoc_write_concern_t *write_concern, bson_error_t *error) { if (write_concern && !mongoc_write_concern_is_valid (write_concern)) { - bson_set_error (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Invalid writeConcern"); + bson_set_error (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid writeConcern"); return false; } return true; @@ -454,8 +438,7 @@ _mongoc_parse_wc_err (const bson_t *doc, bson_error_t *error) bson_iter_t iter; bson_iter_t inner; - if (bson_iter_init_find (&iter, doc, "writeConcernError") && - BSON_ITER_HOLDS_DOCUMENT (&iter)) { + if (bson_iter_init_find (&iter, doc, "writeConcernError") && BSON_ITER_HOLDS_DOCUMENT (&iter)) { const char *errmsg = NULL; int32_t code = 0; BSON_ASSERT (bson_iter_recurse (&iter, &inner)); @@ -466,11 +449,7 @@ _mongoc_parse_wc_err (const bson_t *doc, bson_error_t *error) errmsg = bson_iter_utf8 (&inner, NULL); } } - bson_set_error (error, - MONGOC_ERROR_WRITE_CONCERN, - code, - "Write Concern error: %s", - errmsg); + bson_set_error (error, MONGOC_ERROR_WRITE_CONCERN, code, "Write Concern error: %s", errmsg); return true; } return false; @@ -489,18 +468,14 @@ _mongoc_parse_wc_err (const bson_t *doc, bson_error_t *error) * */ bool -mongoc_write_concern_append (mongoc_write_concern_t *write_concern, - bson_t *command) +mongoc_write_concern_append (mongoc_write_concern_t *write_concern, bson_t *command) { if (!mongoc_write_concern_is_valid (write_concern)) { MONGOC_ERROR ("Invalid writeConcern passed into " "mongoc_write_concern_append."); return false; } - if (!bson_append_document (command, - "writeConcern", - 12, - _mongoc_write_concern_get_bson (write_concern))) { + if (!bson_append_document (command, "writeConcern", 12, _mongoc_write_concern_get_bson (write_concern))) { MONGOC_ERROR ("Could not append writeConcern to command."); return false; } @@ -517,8 +492,7 @@ mongoc_write_concern_append (mongoc_write_concern_t *write_concern, * with mongoc_write_concern_destroy(). */ mongoc_write_concern_t * -_mongoc_write_concern_new_from_iter (const bson_iter_t *iter, - bson_error_t *error) +_mongoc_write_concern_new_from_iter (const bson_iter_t *iter, bson_error_t *error) { bson_iter_t inner; mongoc_write_concern_t *write_concern; @@ -547,8 +521,7 @@ _mongoc_write_concern_new_from_iter (const bson_iter_t *iter, * it is >= 0. Since we set wtimeout below, pass -1 here. */ mongoc_write_concern_set_wmajority (write_concern, -1); } else { - mongoc_write_concern_set_wtag (write_concern, - bson_iter_utf8 (&inner, NULL)); + mongoc_write_concern_set_wtag (write_concern, bson_iter_utf8 (&inner, NULL)); } } else { /* wrong type for "w" */ @@ -559,21 +532,18 @@ _mongoc_write_concern_new_from_iter (const bson_iter_t *iter, goto fail; } BEGIN_IGNORE_DEPRECATIONS - mongoc_write_concern_set_fsync (write_concern, - bson_iter_bool (&inner)); + mongoc_write_concern_set_fsync (write_concern, bson_iter_bool (&inner)); END_IGNORE_DEPRECATIONS } else if (BSON_ITER_IS_KEY (&inner, "j")) { if (!BSON_ITER_HOLDS_BOOL (&inner)) { goto fail; } - mongoc_write_concern_set_journal (write_concern, - bson_iter_bool (&inner)); + mongoc_write_concern_set_journal (write_concern, bson_iter_bool (&inner)); } else if (BSON_ITER_IS_KEY (&inner, "wtimeout")) { if (!BSON_ITER_HOLDS_INT (&inner) || bson_iter_as_int64 (&inner) < 0) { goto fail; } - mongoc_write_concern_set_wtimeout_int64 (write_concern, - bson_iter_as_int64 (&inner)); + mongoc_write_concern_set_wtimeout_int64 (write_concern, bson_iter_as_int64 (&inner)); } } @@ -585,10 +555,7 @@ _mongoc_write_concern_new_from_iter (const bson_iter_t *iter, return write_concern; fail: - bson_set_error (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Invalid writeConcern"); + bson_set_error (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid writeConcern"); mongoc_write_concern_destroy (write_concern); return NULL; } diff --git a/src/libmongoc/src/mongoc/mongoc-write-concern.h b/src/libmongoc/src/mongoc/mongoc-write-concern.h index 7961361ead..fd29e8c961 100644 --- a/src/libmongoc/src/mongoc/mongoc-write-concern.h +++ b/src/libmongoc/src/mongoc/mongoc-write-concern.h @@ -39,24 +39,19 @@ typedef struct _mongoc_write_concern_t mongoc_write_concern_t; MONGOC_EXPORT (mongoc_write_concern_t *) mongoc_write_concern_new (void) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (mongoc_write_concern_t *) -mongoc_write_concern_copy (const mongoc_write_concern_t *write_concern) - BSON_GNUC_WARN_UNUSED_RESULT; +mongoc_write_concern_copy (const mongoc_write_concern_t *write_concern) BSON_GNUC_WARN_UNUSED_RESULT; MONGOC_EXPORT (void) mongoc_write_concern_destroy (mongoc_write_concern_t *write_concern); MONGOC_EXPORT (bool) -mongoc_write_concern_get_fsync (const mongoc_write_concern_t *write_concern) - BSON_GNUC_DEPRECATED; +mongoc_write_concern_get_fsync (const mongoc_write_concern_t *write_concern) BSON_GNUC_DEPRECATED; MONGOC_EXPORT (void) -mongoc_write_concern_set_fsync (mongoc_write_concern_t *write_concern, - bool fsync_) BSON_GNUC_DEPRECATED; +mongoc_write_concern_set_fsync (mongoc_write_concern_t *write_concern, bool fsync_) BSON_GNUC_DEPRECATED; MONGOC_EXPORT (bool) mongoc_write_concern_get_journal (const mongoc_write_concern_t *write_concern); MONGOC_EXPORT (bool) -mongoc_write_concern_journal_is_set ( - const mongoc_write_concern_t *write_concern); +mongoc_write_concern_journal_is_set (const mongoc_write_concern_t *write_concern); MONGOC_EXPORT (void) -mongoc_write_concern_set_journal (mongoc_write_concern_t *write_concern, - bool journal); +mongoc_write_concern_set_journal (mongoc_write_concern_t *write_concern, bool journal); MONGOC_EXPORT (int32_t) mongoc_write_concern_get_w (const mongoc_write_concern_t *write_concern); MONGOC_EXPORT (void) @@ -64,33 +59,25 @@ mongoc_write_concern_set_w (mongoc_write_concern_t *write_concern, int32_t w); MONGOC_EXPORT (const char *) mongoc_write_concern_get_wtag (const mongoc_write_concern_t *write_concern); MONGOC_EXPORT (void) -mongoc_write_concern_set_wtag (mongoc_write_concern_t *write_concern, - const char *tag); +mongoc_write_concern_set_wtag (mongoc_write_concern_t *write_concern, const char *tag); MONGOC_EXPORT (int32_t) mongoc_write_concern_get_wtimeout (const mongoc_write_concern_t *write_concern); MONGOC_EXPORT (int64_t) -mongoc_write_concern_get_wtimeout_int64 ( - const mongoc_write_concern_t *write_concern); +mongoc_write_concern_get_wtimeout_int64 (const mongoc_write_concern_t *write_concern); MONGOC_EXPORT (void) -mongoc_write_concern_set_wtimeout (mongoc_write_concern_t *write_concern, - int32_t wtimeout_msec); +mongoc_write_concern_set_wtimeout (mongoc_write_concern_t *write_concern, int32_t wtimeout_msec); MONGOC_EXPORT (void) -mongoc_write_concern_set_wtimeout_int64 (mongoc_write_concern_t *write_concern, - int64_t wtimeout_msec); +mongoc_write_concern_set_wtimeout_int64 (mongoc_write_concern_t *write_concern, int64_t wtimeout_msec); MONGOC_EXPORT (bool) -mongoc_write_concern_get_wmajority ( - const mongoc_write_concern_t *write_concern); +mongoc_write_concern_get_wmajority (const mongoc_write_concern_t *write_concern); MONGOC_EXPORT (void) -mongoc_write_concern_set_wmajority (mongoc_write_concern_t *write_concern, - int32_t wtimeout_msec); +mongoc_write_concern_set_wmajority (mongoc_write_concern_t *write_concern, int32_t wtimeout_msec); MONGOC_EXPORT (bool) -mongoc_write_concern_is_acknowledged ( - const mongoc_write_concern_t *write_concern); +mongoc_write_concern_is_acknowledged (const mongoc_write_concern_t *write_concern); MONGOC_EXPORT (bool) mongoc_write_concern_is_valid (const mongoc_write_concern_t *write_concern); MONGOC_EXPORT (bool) -mongoc_write_concern_append (mongoc_write_concern_t *write_concern, - bson_t *doc); +mongoc_write_concern_append (mongoc_write_concern_t *write_concern, bson_t *doc); MONGOC_EXPORT (bool) mongoc_write_concern_is_default (const mongoc_write_concern_t *write_concern); diff --git a/src/libmongoc/src/mongoc/service-gcp.c b/src/libmongoc/src/mongoc/service-gcp.c index d709610eb4..d1dcdf647b 100644 --- a/src/libmongoc/src/mongoc/service-gcp.c +++ b/src/libmongoc/src/mongoc/service-gcp.c @@ -20,14 +20,10 @@ #define HOST "metadata.google.internal" -static const char *const DEFAULT_METADATA_PATH = - "/computeMetadata/v1/instance/service-accounts/default/token"; +static const char *const DEFAULT_METADATA_PATH = "/computeMetadata/v1/instance/service-accounts/default/token"; void -gcp_request_init (gcp_request *req, - const char *const opt_host, - int opt_port, - const char *const opt_extra_headers) +gcp_request_init (gcp_request *req, const char *const opt_host, int opt_port, const char *const opt_extra_headers) { BSON_ASSERT_PARAM (req); _mongoc_http_request_init (&req->req); @@ -47,8 +43,7 @@ gcp_request_init (gcp_request *req, req->req.method = "GET"; req->req.extra_headers = req->_owned_headers = - bson_strdup_printf ("Metadata-Flavor: Google\r\n%s", - opt_extra_headers ? opt_extra_headers : ""); + bson_strdup_printf ("Metadata-Flavor: Google\r\n%s", opt_extra_headers ? opt_extra_headers : ""); req->req.path = req->_owned_path = bson_strdup (DEFAULT_METADATA_PATH); } @@ -78,10 +73,7 @@ gcp_access_token_destroy (gcp_service_account_token *token) } bool -gcp_access_token_try_parse_from_json (gcp_service_account_token *out, - const char *json, - int len, - bson_error_t *error) +gcp_access_token_try_parse_from_json (gcp_service_account_token *out, const char *json, int len, bson_error_t *error) { BSON_ASSERT_PARAM (out); BSON_ASSERT_PARAM (json); @@ -99,8 +91,7 @@ gcp_access_token_try_parse_from_json (gcp_service_account_token *out, bson_iter_t iter; // access_token bool found = bson_iter_init_find (&iter, &bson, "access_token"); - const char *const access_token = - !found ? NULL : bson_iter_utf8 (&iter, NULL); + const char *const access_token = !found ? NULL : bson_iter_utf8 (&iter, NULL); // token_type found = bson_iter_init_find (&iter, &bson, "token_type"); const char *const token_type = !found ? NULL : bson_iter_utf8 (&iter, NULL); @@ -167,8 +158,7 @@ gcp_access_token_from_gcp_server (gcp_service_account_token *out, goto fail; } - if (!gcp_access_token_try_parse_from_json ( - out, resp.body, resp.body_len, error)) { + if (!gcp_access_token_try_parse_from_json (out, resp.body, resp.body_len, error)) { goto fail; } diff --git a/src/libmongoc/src/mongoc/service-gcp.h b/src/libmongoc/src/mongoc/service-gcp.h index fdf19de945..6168ab514e 100644 --- a/src/libmongoc/src/mongoc/service-gcp.h +++ b/src/libmongoc/src/mongoc/service-gcp.h @@ -57,10 +57,7 @@ typedef struct gcp_request { * @note the request must later be destroyed with gcp_request_destroy */ void -gcp_request_init (gcp_request *req, - const char *const opt_host, - int opt_port, - const char *const opt_extra_headers); +gcp_request_init (gcp_request *req, const char *const opt_host, int opt_port, const char *const opt_extra_headers); /** @@ -94,10 +91,7 @@ gcp_access_token_destroy (gcp_service_account_token *token); * @note The 'out' token must later be given to gcp_access_token_destroy */ bool -gcp_access_token_try_parse_from_json (gcp_service_account_token *out, - const char *json, - int len, - bson_error_t *error); +gcp_access_token_try_parse_from_json (gcp_service_account_token *out, const char *json, int len, bson_error_t *error); /** * @brief Attempt to obtain a new GCP service account token from a GCP metadata diff --git a/src/libmongoc/src/mongoc/utlist.h b/src/libmongoc/src/mongoc/utlist.h index 335c58eb64..30c74dfe08 100644 --- a/src/libmongoc/src/mongoc/utlist.h +++ b/src/libmongoc/src/mongoc/utlist.h @@ -519,11 +519,9 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #define LL_FOREACH_SAFE(head, el, tmp) LL_FOREACH_SAFE2 (head, el, tmp, next) -#define LL_FOREACH_SAFE2(head, el, tmp, next) \ - for ((el) = (head); (el) && (tmp = (el)->next, 1); (el) = tmp) +#define LL_FOREACH_SAFE2(head, el, tmp, next) for ((el) = (head); (el) && (tmp = (el)->next, 1); (el) = tmp) -#define LL_SEARCH_SCALAR(head, out, field, val) \ - LL_SEARCH_SCALAR2 (head, out, field, val, next) +#define LL_SEARCH_SCALAR(head, out, field, val) LL_SEARCH_SCALAR2 (head, out, field, val, next) #define LL_SEARCH_SCALAR2(head, out, field, val, next) \ do { \ @@ -675,8 +673,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /* this version is safe for deleting the elements during iteration */ #define DL_FOREACH_SAFE(head, el, tmp) DL_FOREACH_SAFE2 (head, el, tmp, next) -#define DL_FOREACH_SAFE2(head, el, tmp, next) \ - for ((el) = (head); (el) && (tmp = (el)->next, 1); (el) = tmp) +#define DL_FOREACH_SAFE2(head, el, tmp, next) for ((el) = (head); (el) && (tmp = (el)->next, 1); (el) = tmp) /* these are identical to their singly-linked list counterparts */ #define DL_SEARCH_SCALAR LL_SEARCH_SCALAR @@ -773,19 +770,15 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #define CDL_FOREACH(head, el) CDL_FOREACH2 (head, el, next) -#define CDL_FOREACH2(head, el, next) \ - for (el = head; el; el = ((el)->next == head ? 0L : (el)->next)) +#define CDL_FOREACH2(head, el, next) for (el = head; el; el = ((el)->next == head ? 0L : (el)->next)) -#define CDL_FOREACH_SAFE(head, el, tmp1, tmp2) \ - CDL_FOREACH_SAFE2 (head, el, tmp1, tmp2, prev, next) +#define CDL_FOREACH_SAFE(head, el, tmp1, tmp2) CDL_FOREACH_SAFE2 (head, el, tmp1, tmp2, prev, next) -#define CDL_FOREACH_SAFE2(head, el, tmp1, tmp2, prev, next) \ - for ((el) = (head), ((tmp1) = (head) ? ((head)->prev) : NULL); \ - (el) && ((tmp2) = (el)->next, 1); \ +#define CDL_FOREACH_SAFE2(head, el, tmp1, tmp2, prev, next) \ + for ((el) = (head), ((tmp1) = (head) ? ((head)->prev) : NULL); (el) && ((tmp2) = (el)->next, 1); \ ((el) = (((el) == (tmp1)) ? 0L : (tmp2)))) -#define CDL_SEARCH_SCALAR(head, out, field, val) \ - CDL_SEARCH_SCALAR2 (head, out, field, val, next) +#define CDL_SEARCH_SCALAR(head, out, field, val) CDL_SEARCH_SCALAR2 (head, out, field, val, next) #define CDL_SEARCH_SCALAR2(head, out, field, val, next) \ do { \ diff --git a/src/libmongoc/tests/TestSuite.c b/src/libmongoc/tests/TestSuite.c index e691accc8f..d44a4af4e9 100644 --- a/src/libmongoc/tests/TestSuite.c +++ b/src/libmongoc/tests/TestSuite.c @@ -131,14 +131,11 @@ TestSuite_Init (TestSuite *suite, const char *name, int argc, char **argv) for (i = 1; i < argc; i++) { if (0 == strcmp ("-d", argv[i])) { suite->flags |= TEST_DEBUGOUTPUT; - } else if ((0 == strcmp ("-f", argv[i])) || - (0 == strcmp ("--no-fork", argv[i]))) { + } else if ((0 == strcmp ("-f", argv[i])) || (0 == strcmp ("--no-fork", argv[i]))) { suite->flags |= TEST_NOFORK; - } else if ((0 == strcmp ("-t", argv[i])) || - (0 == strcmp ("--trace", argv[i]))) { + } else if ((0 == strcmp ("-t", argv[i])) || (0 == strcmp ("--trace", argv[i]))) { if (!MONGOC_TRACE_ENABLED) { - test_error ( - "-t requires mongoc compiled with -DENABLE_TRACING=ON."); + test_error ("-t requires mongoc compiled with -DENABLE_TRACING=ON."); } suite->flags |= TEST_TRACE; } else if (0 == strcmp ("-F", argv[i])) { @@ -158,13 +155,11 @@ TestSuite_Init (TestSuite *suite, const char *name, int argc, char **argv) test_error ("Failed to open log file: %s", filename); } } - } else if ((0 == strcmp ("-h", argv[i])) || - (0 == strcmp ("--help", argv[i]))) { + } else if ((0 == strcmp ("-h", argv[i])) || (0 == strcmp ("--help", argv[i]))) { suite->flags |= TEST_HELPTEXT; } else if (0 == strcmp ("--list-tests", argv[i])) { suite->flags |= TEST_LISTTESTS; - } else if ((0 == strcmp ("-s", argv[i])) || - (0 == strcmp ("--silent", argv[i]))) { + } else if ((0 == strcmp ("-s", argv[i])) || (0 == strcmp ("--silent", argv[i]))) { suite->silent = true; } else if ((0 == strcmp ("--ctest-run", argv[i]))) { if (suite->ctest_run) { @@ -176,8 +171,7 @@ TestSuite_Init (TestSuite *suite, const char *name, int argc, char **argv) suite->flags |= TEST_NOFORK; suite->silent = true; suite->ctest_run = bson_strdup (argv[++i]); - } else if ((0 == strcmp ("-l", argv[i])) || - (0 == strcmp ("--match", argv[i]))) { + } else if ((0 == strcmp ("-l", argv[i])) || (0 == strcmp ("--match", argv[i]))) { char *val; if (argc - 1 == i) { test_error ("%s requires an argument.", argv[i]); @@ -210,8 +204,7 @@ TestSuite_Init (TestSuite *suite, const char *name, int argc, char **argv) } else if (!strcmp (mock_server_log, "json")) { suite->mock_server_log_buf = bson_string_new (NULL); } else { - test_error ("Unrecognized option: MONGOC_TEST_SERVER_LOG=%s", - mock_server_log); + test_error ("Unrecognized option: MONGOC_TEST_SERVER_LOG=%s", mock_server_log); } bson_free (mock_server_log); @@ -266,8 +259,7 @@ TestSuite_Add (TestSuite *suite, /* IN */ const char *name, /* IN */ TestFunc func) /* IN */ { - TestSuite_AddFullWithTestFn ( - suite, name, TestSuite_AddHelper, NULL, func, TestSuite_CheckDummy); + TestSuite_AddFullWithTestFn (suite, name, TestSuite_AddHelper, NULL, func, TestSuite_CheckDummy); } @@ -276,8 +268,7 @@ TestSuite_AddLive (TestSuite *suite, /* IN */ const char *name, /* IN */ TestFunc func) /* IN */ { - TestSuite_AddFullWithTestFn ( - suite, name, TestSuite_AddHelper, NULL, func, TestSuite_CheckLive); + TestSuite_AddFullWithTestFn (suite, name, TestSuite_AddHelper, NULL, func, TestSuite_CheckLive); } @@ -286,23 +277,17 @@ _TestSuite_AddCheck (Test *test, CheckFunc check, const char *name) { test->checks[test->num_checks] = check; if (++test->num_checks > MAX_TEST_CHECK_FUNCS) { - MONGOC_STDERR_PRINTF ( - "Too many check funcs for %s, increase MAX_TEST_CHECK_FUNCS " - "to more than %d\n", - name, - MAX_TEST_CHECK_FUNCS); + MONGOC_STDERR_PRINTF ("Too many check funcs for %s, increase MAX_TEST_CHECK_FUNCS " + "to more than %d\n", + name, + MAX_TEST_CHECK_FUNCS); abort (); } } Test * -_V_TestSuite_AddFull (TestSuite *suite, - const char *name, - TestFuncWC func, - TestFuncDtor dtor, - void *ctx, - va_list ap) +_V_TestSuite_AddFull (TestSuite *suite, const char *name, TestFuncWC func, TestFuncDtor dtor, void *ctx, va_list ap) { CheckFunc check; Test *test; @@ -343,10 +328,7 @@ _V_TestSuite_AddFull (TestSuite *suite, void -_TestSuite_AddMockServerTest (TestSuite *suite, - const char *name, - TestFunc func, - ...) +_TestSuite_AddMockServerTest (TestSuite *suite, const char *name, TestFunc func, ...) { Test *test; va_list ap; @@ -405,8 +387,7 @@ _print_getlasterror_win (const char *msg) { LPTSTR err_msg; - FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, + FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError (), MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT), @@ -434,8 +415,7 @@ TestSuite_RunFuncInChild (TestSuite *suite, /* IN */ si.cb = sizeof (si); ZeroMemory (&pi, sizeof (pi)); - cmdline = bson_strdup_printf ( - "%s --silent --no-fork -l %s", suite->prgname, test->name); + cmdline = bson_strdup_printf ("%s --silent --no-fork -l %s", suite->prgname, test->name); if (!CreateProcess (NULL, cmdline, @@ -509,26 +489,14 @@ TestSuite_RunFuncInChild (TestSuite *suite, /* IN */ dup2 (pipefd[1], STDOUT_FILENO); close (pipefd[0]); close (pipefd[1]); - execle (suite->prgname, - suite->prgname, - "--no-fork", - "--silent", - "-l", - test->name, - (char *) 0, - envp); + execle (suite->prgname, suite->prgname, "--no-fork", "--silent", "-l", test->name, (char *) 0, envp); } else { /* suppress child output */ fd = open ("/dev/null", O_WRONLY); dup2 (fd, STDOUT_FILENO); close (fd); - execl (suite->prgname, - suite->prgname, - "--no-fork", - "-l", - test->name, - (char *) 0); + execl (suite->prgname, suite->prgname, "--no-fork", "-l", test->name, (char *) 0); } exit (-1); @@ -583,21 +551,19 @@ TestSuite_RunTest (TestSuite *suite, /* IN */ } for (i = 0; i < suite->failing_flaky_skips.len; i++) { - TestSkip *skip = - _mongoc_array_index (&suite->failing_flaky_skips, TestSkip *, i); + TestSkip *skip = _mongoc_array_index (&suite->failing_flaky_skips, TestSkip *, i); if (0 == strcmp (name, skip->test_name) && skip->subtest_desc == NULL) { if (suite->ctest_run) { /* Write a marker that tells CTest that we are skipping this test */ test_msg ("@@ctest-skipped@@"); } if (!suite->silent) { - bson_string_append_printf ( - buf, - " { \"status\": \"skip\", \"test_file\": \"%s\"," - " \"reason\": \"%s\" }%s", - test->name, - skip->reason, - ((*count) == 1) ? "" : ","); + bson_string_append_printf (buf, + " { \"status\": \"skip\", \"test_file\": \"%s\"," + " \"reason\": \"%s\" }%s", + test->name, + skip->reason, + ((*count) == 1) ? "" : ","); test_msg ("%s", buf->str); if (suite->outfile) { fprintf (suite->outfile, "%s", buf->str); @@ -617,10 +583,7 @@ TestSuite_RunTest (TestSuite *suite, /* IN */ } if (!suite->silent) { bson_string_append_printf ( - buf, - " { \"status\": \"skip\", \"test_file\": \"%s\" }%s", - test->name, - ((*count) == 1) ? "" : ","); + buf, " { \"status\": \"skip\", \"test_file\": \"%s\" }%s", test->name, ((*count) == 1) ? "" : ","); test_msg ("%s", buf->str); if (suite->outfile) { fprintf (suite->outfile, "%s", buf->str); @@ -711,26 +674,25 @@ TestSuite_RunTest (TestSuite *suite, /* IN */ static void TestSuite_PrintHelp (TestSuite *suite) /* IN */ { - printf ( - "usage: %s [OPTIONS]\n" - "\n" - "Options:\n" - " -h, --help Show this help menu.\n" - " --list-tests Print list of available tests.\n" - " -f, --no-fork Do not spawn a process per test (abort on " - "first error).\n" - " -l, --match PATTERN Run test by name, e.g. \"/Client/command\" or " - "\"/Client/*\". May be repeated.\n" - " --ctest-run TEST Run only the named TEST for CTest\n" - " integration.\n" - " -s, --silent Suppress all output.\n" - " -F FILENAME Write test results (JSON) to FILENAME.\n" - " -d Print debug output (useful if a test hangs).\n" - " --skip-tests FILE Skip known failing or flaky tests.\n" - " -t, --trace Enable mongoc tracing (useful to debug " - "tests).\n" - "\n", - suite->prgname); + printf ("usage: %s [OPTIONS]\n" + "\n" + "Options:\n" + " -h, --help Show this help menu.\n" + " --list-tests Print list of available tests.\n" + " -f, --no-fork Do not spawn a process per test (abort on " + "first error).\n" + " -l, --match PATTERN Run test by name, e.g. \"/Client/command\" or " + "\"/Client/*\". May be repeated.\n" + " --ctest-run TEST Run only the named TEST for CTest\n" + " integration.\n" + " -s, --silent Suppress all output.\n" + " -F FILENAME Write test results (JSON) to FILENAME.\n" + " -d Print debug output (useful if a test hangs).\n" + " --skip-tests FILE Skip known failing or flaky tests.\n" + " -t, --trace Enable mongoc tracing (useful to debug " + "tests).\n" + "\n", + suite->prgname); } @@ -884,9 +846,7 @@ TestSuite_PrintJsonHeader (TestSuite *suite, /* IN */ udspath, egetenv ("MONGOC_TEST_COMPRESSORS"), ssl ? "true" : "false", - test_framework_getenv_bool ("MONGOC_TEST_SSL_WEAK_CERT_VALIDATION") - ? "true" - : "false", + test_framework_getenv_bool ("MONGOC_TEST_SSL_WEAK_CERT_VALIDATION") ? "true" : "false", egetenv ("MONGOC_TEST_SSL_PEM_FILE"), egetenv ("MONGOC_TEST_SSL_PEM_PWD"), egetenv ("MONGOC_TEST_SSL_CA_FILE"), @@ -895,11 +855,8 @@ TestSuite_PrintJsonHeader (TestSuite *suite, /* IN */ getenv ("MONGOC_TEST_MONITORING_VERBOSE") ? "true" : "false", egetenv ("MONGOC_TEST_SERVER_LOG"), get_future_timeout_ms (), - test_framework_getenv_bool ("MONGOC_ENABLE_MAJORITY_READ_CONCERN") - ? "true" - : "false", - test_framework_getenv_bool ("MONGOC_TEST_SKIP_LIVE") ? "true" - : "false", + test_framework_getenv_bool ("MONGOC_ENABLE_MAJORITY_READ_CONCERN") ? "true" : "false", + test_framework_getenv_bool ("MONGOC_TEST_SKIP_LIVE") ? "true" : "false", test_framework_getenv_bool ("MONGOC_CHECK_IPV6") ? "true" : "false", (suite->flags & TEST_NOFORK) ? "false" : "true", (suite->flags & TEST_TRACE) ? "true" : "false", @@ -920,9 +877,7 @@ TestSuite_PrintJsonFooter (FILE *stream) /* IN */ } static bool -TestSuite_TestMatchesName (const TestSuite *suite, - const Test *test, - const char *testname) +TestSuite_TestMatchesName (const TestSuite *suite, const Test *test, const char *testname) { char name[128]; bool star = strlen (testname) && testname[strlen (testname) - 1] == '*'; @@ -1014,13 +969,11 @@ _process_skip_file (const char *filename, mongoc_array_t *skips) if (comment_char) { test_name_end = comment_char; comment_text = comment_char; - while (comment_text[0] == '#' || comment_text[0] == ' ' || - comment_text[0] == '\t') { + while (comment_text[0] == '#' || comment_text[0] == ' ' || comment_text[0] == '\t') { if (++comment_text >= (buffer + buflen)) break; } - skip->reason = - bson_strndup (comment_text, buflen - (comment_text - buffer)); + skip->reason = bson_strndup (comment_text, buflen - (comment_text - buffer)); comment_len = buflen - (comment_char - buffer); } else { skip->reason = NULL; @@ -1034,8 +987,7 @@ _process_skip_file (const char *filename, mongoc_array_t *skips) subtest_start++; /* find the second '"' that marks end of subtest name */ subtest_end = subtest_start + 1; - while (subtest_end[0] != '\0' && subtest_end[0] != '"' && - (subtest_end < buffer + new_buflen)) { + while (subtest_end[0] != '\0' && subtest_end[0] != '"' && (subtest_end < buffer + new_buflen)) { subtest_end++; } /* 'subtest_start + 1' to trim leading and trailing '"' */ @@ -1143,8 +1095,7 @@ TestSuite_Run (TestSuite *suite) /* IN */ TestSuite_PrintJsonFooter (suite->outfile); } } - MONGOC_DEBUG ("Duration of all tests (s): %" PRId64, - (bson_get_monotonic_time () - start_us) / (1000 * 1000)); + MONGOC_DEBUG ("Duration of all tests (s): %" PRId64, (bson_get_monotonic_time () - start_us) / (1000 * 1000)); return failures; } @@ -1189,8 +1140,7 @@ TestSuite_Destroy (TestSuite *suite) _mongoc_array_destroy (&suite->match_patterns); for (size_t i = 0u; i < suite->failing_flaky_skips.len; i++) { - TestSkip *val = - _mongoc_array_index (&suite->failing_flaky_skips, TestSkip *, i); + TestSkip *val = _mongoc_array_index (&suite->failing_flaky_skips, TestSkip *, i); bson_free (val->test_name); bson_free (val->subtest_desc); bson_free (val->reason); @@ -1229,8 +1179,7 @@ test_suite_mock_server_log (const char *msg, ...) va_end (ap); if (gTestSuite->mock_server_log_buf) { - bson_string_append_printf ( - gTestSuite->mock_server_log_buf, "%s\n", formatted_msg); + bson_string_append_printf (gTestSuite->mock_server_log_buf, "%s\n", formatted_msg); } else { fprintf (gTestSuite->mock_server_log, "%s\n", formatted_msg); fflush (gTestSuite->mock_server_log); diff --git a/src/libmongoc/tests/TestSuite.h b/src/libmongoc/tests/TestSuite.h index 99b1286dfb..26d2161bb0 100644 --- a/src/libmongoc/tests/TestSuite.h +++ b/src/libmongoc/tests/TestSuite.h @@ -66,9 +66,7 @@ bson_open (const char *filename, int flags, ...) { int fd = -1; - if (_sopen_s ( - &fd, filename, flags | _O_BINARY, _SH_DENYNO, _S_IREAD | _S_IWRITE) == - NO_ERROR) { + if (_sopen_s (&fd, filename, flags | _O_BINARY, _SH_DENYNO, _S_IREAD | _S_IWRITE) == NO_ERROR) { return fd; } @@ -96,13 +94,12 @@ bson_open (const char *filename, int flags, ...) #define CERT_CRL CERT_TEST_DIR "/crl.pem" #define CERT_SERVER CERT_TEST_DIR "/server.pem" /* 127.0.0.1 & localhost */ #define CERT_CLIENT CERT_TEST_DIR "/client.pem" -#define CERT_ALTNAME \ - CERT_TEST_DIR "/altname.pem" /* alternative.mongodb.org \ - */ -#define CERT_WILD CERT_TEST_DIR "/wild.pem" /* *.mongodb.org */ -#define CERT_COMMONNAME \ - CERT_TEST_DIR "/commonName.pem" /* 127.0.0.1 & localhost */ -#define CERT_EXPIRED CERT_TEST_DIR "/expired.pem" /* 127.0.0.1 & localhost */ +#define CERT_ALTNAME \ + CERT_TEST_DIR "/altname.pem" /* alternative.mongodb.org \ + */ +#define CERT_WILD CERT_TEST_DIR "/wild.pem" /* *.mongodb.org */ +#define CERT_COMMONNAME CERT_TEST_DIR "/commonName.pem" /* 127.0.0.1 & localhost */ +#define CERT_EXPIRED CERT_TEST_DIR "/expired.pem" /* 127.0.0.1 & localhost */ #define CERT_PASSWORD "qwerty" #define CERT_PASSWORD_PROTECTED CERT_TEST_DIR "/password_protected.pem" @@ -120,74 +117,62 @@ bson_open (const char *filename, int flags, ...) } else \ ((void) 0) -#define ASSERT(Cond) \ - do { \ - if (!(Cond)) { \ - MONGOC_STDERR_PRINTF ("FAIL:%s:%d %s()\n Condition '%s' failed.\n", \ - __FILE__, \ - __LINE__, \ - BSON_FUNC, \ - BSON_STR (Cond)); \ - abort (); \ - } \ +#define ASSERT(Cond) \ + do { \ + if (!(Cond)) { \ + MONGOC_STDERR_PRINTF ( \ + "FAIL:%s:%d %s()\n Condition '%s' failed.\n", __FILE__, __LINE__, BSON_FUNC, BSON_STR (Cond)); \ + abort (); \ + } \ } while (0) void _test_error (const char *format, ...) BSON_GNUC_PRINTF (1, 2); -#define test_error(...) \ - if (1) { \ - MONGOC_STDERR_PRINTF ( \ - "test error in: %s %d:%s()\n", __FILE__, __LINE__, BSON_FUNC); \ - _test_error (__VA_ARGS__); \ - abort (); /* suppress missing return errors in non-void functions */ \ - } else \ +#define test_error(...) \ + if (1) { \ + MONGOC_STDERR_PRINTF ("test error in: %s %d:%s()\n", __FILE__, __LINE__, BSON_FUNC); \ + _test_error (__VA_ARGS__); \ + abort (); /* suppress missing return errors in non-void functions */ \ + } else \ ((void) 0) -#define bson_eq_bson(bson, expected) \ - do { \ - char *bson_json, *expected_json; \ - const uint8_t *bson_data = bson_get_data ((bson)); \ - const uint8_t *expected_data = bson_get_data ((expected)); \ - int unequal; \ - unsigned o; \ - int off = -1; \ - unequal = ((expected)->len != (bson)->len) || \ - memcmp (bson_get_data ((expected)), \ - bson_get_data ((bson)), \ - (expected)->len); \ - if (unequal) { \ - bson_json = bson_as_canonical_extended_json (bson, NULL); \ - expected_json = bson_as_canonical_extended_json ((expected), NULL); \ - for (o = 0; o < (bson)->len && o < (expected)->len; o++) { \ - if (bson_data[o] != expected_data[o]) { \ - off = o; \ - break; \ - } \ - } \ - if (off == -1) { \ - off = BSON_MAX ((expected)->len, (bson)->len) - 1; \ - } \ - MONGOC_STDERR_PRINTF ( \ - "bson objects unequal (byte %u):\n(%s)\n(%s)\n", \ - off, \ - bson_json, \ - expected_json); \ - { \ - int fd1 = bson_open ("failure.bad.bson", O_RDWR | O_CREAT, 0640); \ - int fd2 = \ - bson_open ("failure.expected.bson", O_RDWR | O_CREAT, 0640); \ - ASSERT (fd1 != -1); \ - ASSERT (fd2 != -1); \ - ASSERT ((bson)->len == bson_write (fd1, bson_data, (bson)->len)); \ - ASSERT ((expected)->len == \ - bson_write (fd2, expected_data, (expected)->len)); \ - bson_close (fd1); \ - bson_close (fd2); \ - } \ - abort (); \ - } \ +#define bson_eq_bson(bson, expected) \ + do { \ + char *bson_json, *expected_json; \ + const uint8_t *bson_data = bson_get_data ((bson)); \ + const uint8_t *expected_data = bson_get_data ((expected)); \ + int unequal; \ + unsigned o; \ + int off = -1; \ + unequal = ((expected)->len != (bson)->len) || \ + memcmp (bson_get_data ((expected)), bson_get_data ((bson)), (expected)->len); \ + if (unequal) { \ + bson_json = bson_as_canonical_extended_json (bson, NULL); \ + expected_json = bson_as_canonical_extended_json ((expected), NULL); \ + for (o = 0; o < (bson)->len && o < (expected)->len; o++) { \ + if (bson_data[o] != expected_data[o]) { \ + off = o; \ + break; \ + } \ + } \ + if (off == -1) { \ + off = BSON_MAX ((expected)->len, (bson)->len) - 1; \ + } \ + MONGOC_STDERR_PRINTF ("bson objects unequal (byte %u):\n(%s)\n(%s)\n", off, bson_json, expected_json); \ + { \ + int fd1 = bson_open ("failure.bad.bson", O_RDWR | O_CREAT, 0640); \ + int fd2 = bson_open ("failure.expected.bson", O_RDWR | O_CREAT, 0640); \ + ASSERT (fd1 != -1); \ + ASSERT (fd2 != -1); \ + ASSERT ((bson)->len == bson_write (fd1, bson_data, (bson)->len)); \ + ASSERT ((expected)->len == bson_write (fd2, expected_data, (expected)->len)); \ + bson_close (fd1); \ + bson_close (fd2); \ + } \ + abort (); \ + } \ } while (0) @@ -195,179 +180,141 @@ _test_error (const char *format, ...) BSON_GNUC_PRINTF (1, 2); #undef ASSERT_OR_PRINT #endif -#define ASSERT_OR_PRINT(_statement, _err) \ - do { \ - if (!(_statement)) { \ - MONGOC_STDERR_PRINTF ("FAIL:%s:%d %s()\n %s\n %s\n\n", \ - __FILE__, \ - __LINE__, \ - BSON_FUNC, \ - BSON_STR (_statement), \ - _err.message); \ - abort (); \ - } \ +#define ASSERT_OR_PRINT(_statement, _err) \ + do { \ + if (!(_statement)) { \ + MONGOC_STDERR_PRINTF ( \ + "FAIL:%s:%d %s()\n %s\n %s\n\n", __FILE__, __LINE__, BSON_FUNC, BSON_STR (_statement), _err.message); \ + abort (); \ + } \ } while (0) -#define ASSERT_CURSOR_NEXT(_cursor, _doc) \ - do { \ - bson_error_t _err; \ - if (!mongoc_cursor_next ((_cursor), (_doc))) { \ - if (mongoc_cursor_error ((_cursor), &_err)) { \ - MONGOC_STDERR_PRINTF ("FAIL:%s:%d %s()\n %s\n\n", \ - __FILE__, \ - __LINE__, \ - BSON_FUNC, \ - _err.message); \ - } else { \ - MONGOC_STDERR_PRINTF ("FAIL:%s:%d %s()\n %s\n\n", \ - __FILE__, \ - __LINE__, \ - BSON_FUNC, \ - "empty cursor"); \ - } \ - abort (); \ - } \ +#define ASSERT_CURSOR_NEXT(_cursor, _doc) \ + do { \ + bson_error_t _err; \ + if (!mongoc_cursor_next ((_cursor), (_doc))) { \ + if (mongoc_cursor_error ((_cursor), &_err)) { \ + MONGOC_STDERR_PRINTF ("FAIL:%s:%d %s()\n %s\n\n", __FILE__, __LINE__, BSON_FUNC, _err.message); \ + } else { \ + MONGOC_STDERR_PRINTF ("FAIL:%s:%d %s()\n %s\n\n", __FILE__, __LINE__, BSON_FUNC, "empty cursor"); \ + } \ + abort (); \ + } \ } while (0) -#define ASSERT_CURSOR_DONE(_cursor) \ - do { \ - bson_error_t _err; \ - const bson_t *_doc; \ - if (mongoc_cursor_next ((_cursor), &_doc)) { \ - MONGOC_STDERR_PRINTF ("FAIL:%s:%d %s()\n %s\n\n", \ - __FILE__, \ - __LINE__, \ - BSON_FUNC, \ - "non-empty cursor"); \ - abort (); \ - } \ - if (mongoc_cursor_error ((_cursor), &_err)) { \ - MONGOC_STDERR_PRINTF ("FAIL:%s:%d %s()\n %s\n\n", \ - __FILE__, \ - __LINE__, \ - BSON_FUNC, \ - _err.message); \ - abort (); \ - } \ +#define ASSERT_CURSOR_DONE(_cursor) \ + do { \ + bson_error_t _err; \ + const bson_t *_doc; \ + if (mongoc_cursor_next ((_cursor), &_doc)) { \ + MONGOC_STDERR_PRINTF ("FAIL:%s:%d %s()\n %s\n\n", __FILE__, __LINE__, BSON_FUNC, "non-empty cursor"); \ + abort (); \ + } \ + if (mongoc_cursor_error ((_cursor), &_err)) { \ + MONGOC_STDERR_PRINTF ("FAIL:%s:%d %s()\n %s\n\n", __FILE__, __LINE__, BSON_FUNC, _err.message); \ + abort (); \ + } \ } while (0) -#define ASSERT_CMPINT_HELPER(a, eq, b, fmt, type) \ - do { \ - /* evaluate once */ \ - type _a = a; \ - type _b = b; \ - if (!((_a) eq (_b))) { \ - MONGOC_STDERR_PRINTF ("FAIL\n\nAssert Failure: %" fmt " %s %" fmt \ - "\n" \ - "%s:%d %s()\n", \ - _a, \ - BSON_STR (eq), \ - _b, \ - __FILE__, \ - __LINE__, \ - BSON_FUNC); \ - abort (); \ - } \ +#define ASSERT_CMPINT_HELPER(a, eq, b, fmt, type) \ + do { \ + /* evaluate once */ \ + type _a = a; \ + type _b = b; \ + if (!((_a) eq (_b))) { \ + MONGOC_STDERR_PRINTF ("FAIL\n\nAssert Failure: %" fmt " %s %" fmt "\n" \ + "%s:%d %s()\n", \ + _a, \ + BSON_STR (eq), \ + _b, \ + __FILE__, \ + __LINE__, \ + BSON_FUNC); \ + abort (); \ + } \ } while (0) #define ASSERT_CMPINT(a, eq, b) ASSERT_CMPINT_HELPER (a, eq, b, "d", int) -#define ASSERT_CMPUINT(a, eq, b) \ - ASSERT_CMPINT_HELPER (a, eq, b, "u", unsigned int) +#define ASSERT_CMPUINT(a, eq, b) ASSERT_CMPINT_HELPER (a, eq, b, "u", unsigned int) #define ASSERT_CMPLONG(a, eq, b) ASSERT_CMPINT_HELPER (a, eq, b, "ld", long) -#define ASSERT_CMPULONG(a, eq, b) \ - ASSERT_CMPINT_HELPER (a, eq, b, "lu", unsigned long) -#define ASSERT_CMPINT32(a, eq, b) \ - ASSERT_CMPINT_HELPER (a, eq, b, PRId32, int32_t) -#define ASSERT_CMPINT64(a, eq, b) \ - ASSERT_CMPINT_HELPER (a, eq, b, PRId64, int64_t) -#define ASSERT_CMPUINT16(a, eq, b) \ - ASSERT_CMPINT_HELPER (a, eq, b, "hu", uint16_t) -#define ASSERT_CMPUINT32(a, eq, b) \ - ASSERT_CMPINT_HELPER (a, eq, b, PRIu32, uint32_t) -#define ASSERT_CMPUINT64(a, eq, b) \ - ASSERT_CMPINT_HELPER (a, eq, b, PRIu64, uint64_t) +#define ASSERT_CMPULONG(a, eq, b) ASSERT_CMPINT_HELPER (a, eq, b, "lu", unsigned long) +#define ASSERT_CMPINT32(a, eq, b) ASSERT_CMPINT_HELPER (a, eq, b, PRId32, int32_t) +#define ASSERT_CMPINT64(a, eq, b) ASSERT_CMPINT_HELPER (a, eq, b, PRId64, int64_t) +#define ASSERT_CMPUINT16(a, eq, b) ASSERT_CMPINT_HELPER (a, eq, b, "hu", uint16_t) +#define ASSERT_CMPUINT32(a, eq, b) ASSERT_CMPINT_HELPER (a, eq, b, PRIu32, uint32_t) +#define ASSERT_CMPUINT64(a, eq, b) ASSERT_CMPINT_HELPER (a, eq, b, PRIu64, uint64_t) #define ASSERT_CMPSIZE_T(a, eq, b) ASSERT_CMPINT_HELPER (a, eq, b, "zu", size_t) -#define ASSERT_CMPSSIZE_T(a, eq, b) \ - ASSERT_CMPINT_HELPER (a, eq, b, "zd", ssize_t) +#define ASSERT_CMPSSIZE_T(a, eq, b) ASSERT_CMPINT_HELPER (a, eq, b, "zd", ssize_t) #define ASSERT_CMPDOUBLE(a, eq, b) ASSERT_CMPINT_HELPER (a, eq, b, "f", double) #define ASSERT_CMPVOID(a, eq, b) ASSERT_CMPINT_HELPER (a, eq, b, "p", void *) -#define ASSERT_MEMCMP(a, b, n) \ - do { \ - if (0 != memcmp (a, b, n)) { \ - MONGOC_STDERR_PRINTF ( \ - "Failed comparing %d bytes: \"%.*s\" != \"%.*s\"", \ - n, \ - n, \ - (char *) a, \ - n, \ - (char *) b); \ - abort (); \ - } \ +#define ASSERT_MEMCMP(a, b, n) \ + do { \ + if (0 != memcmp (a, b, n)) { \ + MONGOC_STDERR_PRINTF ("Failed comparing %d bytes: \"%.*s\" != \"%.*s\"", n, n, (char *) a, n, (char *) b); \ + abort (); \ + } \ } while (0) #ifdef ASSERT_ALMOST_EQUAL #undef ASSERT_ALMOST_EQUAL #endif -#define ASSERT_ALMOST_EQUAL(a, b) \ - do { \ - /* evaluate once */ \ - int64_t _a = (a); \ - int64_t _b = (b); \ - if (!(_a > (_b * 2) / 3 && (_a < (_b * 3) / 2))) { \ - MONGOC_STDERR_PRINTF ("FAIL\n\nAssert Failure: %" PRId64 \ - " not within 50%% of %" PRId64 "\n" \ - "%s:%d %s()\n", \ - _a, \ - _b, \ - __FILE__, \ - __LINE__, \ - BSON_FUNC); \ - abort (); \ - } \ +#define ASSERT_ALMOST_EQUAL(a, b) \ + do { \ + /* evaluate once */ \ + int64_t _a = (a); \ + int64_t _b = (b); \ + if (!(_a > (_b * 2) / 3 && (_a < (_b * 3) / 2))) { \ + MONGOC_STDERR_PRINTF ("FAIL\n\nAssert Failure: %" PRId64 " not within 50%% of %" PRId64 "\n" \ + "%s:%d %s()\n", \ + _a, \ + _b, \ + __FILE__, \ + __LINE__, \ + BSON_FUNC); \ + abort (); \ + } \ } while (0) #ifdef ASSERT_EQUAL_DOUBLE #undef ASSERT_EQUAL_DOUBLE #endif -#define ASSERT_EQUAL_DOUBLE(a, b) \ - do { \ - double _a = fabs ((double) a); \ - double _b = fabs ((double) b); \ - if (!(_a > (_b * 4) / 5 && (_a < (_b * 6) / 5))) { \ - MONGOC_STDERR_PRINTF ( \ - "FAIL\n\nAssert Failure: %f not within 20%% of %f\n" \ - "%s:%d %s()\n", \ - (double) a, \ - (double) b, \ - __FILE__, \ - __LINE__, \ - BSON_FUNC); \ - abort (); \ - } \ +#define ASSERT_EQUAL_DOUBLE(a, b) \ + do { \ + double _a = fabs ((double) a); \ + double _b = fabs ((double) b); \ + if (!(_a > (_b * 4) / 5 && (_a < (_b * 6) / 5))) { \ + MONGOC_STDERR_PRINTF ("FAIL\n\nAssert Failure: %f not within 20%% of %f\n" \ + "%s:%d %s()\n", \ + (double) a, \ + (double) b, \ + __FILE__, \ + __LINE__, \ + BSON_FUNC); \ + abort (); \ + } \ } while (0) -#define ASSERT_CMPSTR(a, b) \ - do { \ - /* evaluate once */ \ - const char *_a = a; \ - const char *_b = b; \ - if ((_a != _b) && (!_a || !_b || (strcmp (_a, _b) != 0))) { \ - MONGOC_STDERR_PRINTF ( \ - "FAIL\n\nAssert Failure:\n \"%s\"\n !=\n \"%s\"\n %s:%d " \ - " %s()\n", \ - _a ? _a : "(null)", \ - _b ? _b : "(null)", \ - __FILE__, \ - __LINE__, \ - BSON_FUNC); \ - abort (); \ - } \ +#define ASSERT_CMPSTR(a, b) \ + do { \ + /* evaluate once */ \ + const char *_a = a; \ + const char *_b = b; \ + if ((_a != _b) && (!_a || !_b || (strcmp (_a, _b) != 0))) { \ + MONGOC_STDERR_PRINTF ("FAIL\n\nAssert Failure:\n \"%s\"\n !=\n \"%s\"\n %s:%d " \ + " %s()\n", \ + _a ? _a : "(null)", \ + _b ? _b : "(null)", \ + __FILE__, \ + __LINE__, \ + BSON_FUNC); \ + abort (); \ + } \ } while (0) #define ASSERT_CMPJSON(_a, _b) \ @@ -420,119 +367,97 @@ _test_error (const char *format, ...) BSON_GNUC_PRINTF (1, 2); } while (0) -#define ASSERT_CONTAINS(a, b) \ - do { \ - char *_a_lower = bson_strdup (a); \ - char *_b_lower = bson_strdup (b); \ - mongoc_lowercase (_a_lower, _a_lower); \ - mongoc_lowercase (_b_lower, _b_lower); \ - if (NULL == strstr ((_a_lower), (_b_lower))) { \ - MONGOC_STDERR_PRINTF ("%s:%d %s(): [%s] does not contain [%s]\n", \ - __FILE__, \ - __LINE__, \ - BSON_FUNC, \ - a, \ - b); \ - abort (); \ - } \ - bson_free (_a_lower); \ - bson_free (_b_lower); \ +#define ASSERT_CONTAINS(a, b) \ + do { \ + char *_a_lower = bson_strdup (a); \ + char *_b_lower = bson_strdup (b); \ + mongoc_lowercase (_a_lower, _a_lower); \ + mongoc_lowercase (_b_lower, _b_lower); \ + if (NULL == strstr ((_a_lower), (_b_lower))) { \ + MONGOC_STDERR_PRINTF ("%s:%d %s(): [%s] does not contain [%s]\n", __FILE__, __LINE__, BSON_FUNC, a, b); \ + abort (); \ + } \ + bson_free (_a_lower); \ + bson_free (_b_lower); \ } while (0) -#define ASSERT_STARTSWITH(a, b) \ - do { \ - /* evaluate once */ \ - const char *_a = a; \ - const char *_b = b; \ - if ((_a) != strstr ((_a), (_b))) { \ - MONGOC_STDERR_PRINTF ( \ - "%s:%d %s(): : [%s] does not start with [%s]\n", \ - __FILE__, \ - __LINE__, \ - BSON_FUNC, \ - _a, \ - _b); \ - abort (); \ - } \ +#define ASSERT_STARTSWITH(a, b) \ + do { \ + /* evaluate once */ \ + const char *_a = a; \ + const char *_b = b; \ + if ((_a) != strstr ((_a), (_b))) { \ + MONGOC_STDERR_PRINTF ( \ + "%s:%d %s(): : [%s] does not start with [%s]\n", __FILE__, __LINE__, BSON_FUNC, _a, _b); \ + abort (); \ + } \ } while (0) -#define ASSERT_ERROR_CONTAINS(error, _domain, _code, _message) \ - do { \ - if (error.domain != _domain) { \ - MONGOC_STDERR_PRINTF ( \ - "%s:%d %s(): error domain %d doesn't match expected %d\n" \ - "error: \"%s\"", \ - __FILE__, \ - __LINE__, \ - BSON_FUNC, \ - error.domain, \ - _domain, \ - error.message); \ - abort (); \ - }; \ - if (error.code != _code) { \ - MONGOC_STDERR_PRINTF ( \ - "%s:%d %s(): error code %d doesn't match expected %d\n" \ - "error: \"%s\"", \ - __FILE__, \ - __LINE__, \ - BSON_FUNC, \ - error.code, \ - _code, \ - error.message); \ - abort (); \ - }; \ - ASSERT_CONTAINS (error.message, _message); \ +#define ASSERT_ERROR_CONTAINS(error, _domain, _code, _message) \ + do { \ + if (error.domain != _domain) { \ + MONGOC_STDERR_PRINTF ("%s:%d %s(): error domain %d doesn't match expected %d\n" \ + "error: \"%s\"", \ + __FILE__, \ + __LINE__, \ + BSON_FUNC, \ + error.domain, \ + _domain, \ + error.message); \ + abort (); \ + }; \ + if (error.code != _code) { \ + MONGOC_STDERR_PRINTF ("%s:%d %s(): error code %d doesn't match expected %d\n" \ + "error: \"%s\"", \ + __FILE__, \ + __LINE__, \ + BSON_FUNC, \ + error.code, \ + _code, \ + error.message); \ + abort (); \ + }; \ + ASSERT_CONTAINS (error.message, _message); \ } while (0) -#define ASSERT_CAPTURED_LOG(_info, _level, _msg) \ - do { \ - if (!has_captured_log (_level, _msg)) { \ - MONGOC_STDERR_PRINTF ("%s:%d %s(): testing %s didn't log \"%s\"\n", \ - __FILE__, \ - __LINE__, \ - BSON_FUNC, \ - _info, \ - _msg); \ - print_captured_logs ("\t"); \ - abort (); \ - } \ +#define ASSERT_CAPTURED_LOG(_info, _level, _msg) \ + do { \ + if (!has_captured_log (_level, _msg)) { \ + MONGOC_STDERR_PRINTF ( \ + "%s:%d %s(): testing %s didn't log \"%s\"\n", __FILE__, __LINE__, BSON_FUNC, _info, _msg); \ + print_captured_logs ("\t"); \ + abort (); \ + } \ } while (0) -#define ASSERT_NO_CAPTURED_LOGS(_info) \ - do { \ - if (has_captured_logs ()) { \ - MONGOC_STDERR_PRINTF ( \ - "%s:%d %s(): testing %s shouldn't have logged:\n", \ - __FILE__, \ - __LINE__, \ - BSON_FUNC, \ - _info); \ - print_captured_logs ("\t"); \ - abort (); \ - } \ +#define ASSERT_NO_CAPTURED_LOGS(_info) \ + do { \ + if (has_captured_logs ()) { \ + MONGOC_STDERR_PRINTF ( \ + "%s:%d %s(): testing %s shouldn't have logged:\n", __FILE__, __LINE__, BSON_FUNC, _info); \ + print_captured_logs ("\t"); \ + abort (); \ + } \ } while (0) -#define ASSERT_HAS_FIELD(_bson, _field) \ - do { \ - if (!bson_has_field ((_bson), (_field))) { \ - MONGOC_STDERR_PRINTF ( \ - "FAIL\n\nAssert Failure: No field \"%s\" in \"%s\"\n", \ - (_field), \ - bson_as_canonical_extended_json (_bson, NULL)); \ - abort (); \ - } \ +#define ASSERT_HAS_FIELD(_bson, _field) \ + do { \ + if (!bson_has_field ((_bson), (_field))) { \ + MONGOC_STDERR_PRINTF ("FAIL\n\nAssert Failure: No field \"%s\" in \"%s\"\n", \ + (_field), \ + bson_as_canonical_extended_json (_bson, NULL)); \ + abort (); \ + } \ } while (0) -#define ASSERT_HAS_NOT_FIELD(_bson, _field) \ - do { \ - if (bson_has_field ((_bson), (_field))) { \ - MONGOC_STDERR_PRINTF ( \ - "FAIL\n\nAssert Failure: Unexpected field \"%s\" in \"%s\"\n", \ - (_field), \ - bson_as_canonical_extended_json (_bson, NULL)); \ - abort (); \ - } \ +#define ASSERT_HAS_NOT_FIELD(_bson, _field) \ + do { \ + if (bson_has_field ((_bson), (_field))) { \ + MONGOC_STDERR_PRINTF ("FAIL\n\nAssert Failure: Unexpected field \"%s\" in \"%s\"\n", \ + (_field), \ + bson_as_canonical_extended_json (_bson, NULL)); \ + abort (); \ + } \ } while (0) #define ASSERT_CMPTIME(actual, maxduration) \ @@ -555,57 +480,53 @@ _test_error (const char *format, ...) BSON_GNUC_PRINTF (1, 2); #define gettestpid getpid #endif -#define ASSERT_OR_PRINT_ERRNO(_statement, _errcode) \ - do { \ - if (!(_statement)) { \ - MONGOC_STDERR_PRINTF ( \ - "FAIL:%s:%d %s()\n %s\n Failed with error code: %d (%s)\n\n", \ - __FILE__, \ - __LINE__, \ - BSON_FUNC, \ - BSON_STR (_statement), \ - _errcode, \ - strerror (_errcode)); \ - abort (); \ - } \ +#define ASSERT_OR_PRINT_ERRNO(_statement, _errcode) \ + do { \ + if (!(_statement)) { \ + MONGOC_STDERR_PRINTF ("FAIL:%s:%d %s()\n %s\n Failed with error code: %d (%s)\n\n", \ + __FILE__, \ + __LINE__, \ + BSON_FUNC, \ + BSON_STR (_statement), \ + _errcode, \ + strerror (_errcode)); \ + abort (); \ + } \ } while (0) -#define ASSERT_COUNT(n, collection) \ - do { \ - int count = (int) mongoc_collection_count_documents ( \ - collection, tmp_bson ("{}"), NULL, NULL, NULL, NULL); \ - if ((n) != count) { \ - MONGOC_STDERR_PRINTF ( \ - "FAIL\n\nAssert Failure: count of %s is %d, not %d\n" \ - "%s:%d %s()\n", \ - mongoc_collection_get_name (collection), \ - count, \ - n, \ - __FILE__, \ - __LINE__, \ - BSON_FUNC); \ - abort (); \ - } \ +#define ASSERT_COUNT(n, collection) \ + do { \ + int count = (int) mongoc_collection_count_documents (collection, tmp_bson ("{}"), NULL, NULL, NULL, NULL); \ + if ((n) != count) { \ + MONGOC_STDERR_PRINTF ("FAIL\n\nAssert Failure: count of %s is %d, not %d\n" \ + "%s:%d %s()\n", \ + mongoc_collection_get_name (collection), \ + count, \ + n, \ + __FILE__, \ + __LINE__, \ + BSON_FUNC); \ + abort (); \ + } \ } while (0) -#define ASSERT_CURSOR_COUNT(_n, _cursor) \ - do { \ - int _count = 0; \ - const bson_t *_doc; \ - while (mongoc_cursor_next (_cursor, &_doc)) { \ - _count++; \ - } \ - if ((_n) != _count) { \ - MONGOC_STDERR_PRINTF ( \ - "FAIL\n\nAssert Failure: cursor count is %d, not %d\n" \ - "%s:%d %s()\n", \ - _count, \ - _n, \ - __FILE__, \ - __LINE__, \ - BSON_FUNC); \ - abort (); \ - } \ +#define ASSERT_CURSOR_COUNT(_n, _cursor) \ + do { \ + int _count = 0; \ + const bson_t *_doc; \ + while (mongoc_cursor_next (_cursor, &_doc)) { \ + _count++; \ + } \ + if ((_n) != _count) { \ + MONGOC_STDERR_PRINTF ("FAIL\n\nAssert Failure: cursor count is %d, not %d\n" \ + "%s:%d %s()\n", \ + _count, \ + _n, \ + __FILE__, \ + __LINE__, \ + BSON_FUNC); \ + abort (); \ + } \ } while (0) #define WAIT_UNTIL(_pred) \ @@ -625,19 +546,15 @@ _test_error (const char *format, ...) BSON_GNUC_PRINTF (1, 2); } \ } while (0) -#define ASSERT_WITH_MSG(_statement, ...) \ - do { \ - if (!(_statement)) { \ - MONGOC_STDERR_PRINTF ("FAIL:%s:%d %s()\n %s\n\n", \ - __FILE__, \ - __LINE__, \ - BSON_FUNC, \ - BSON_STR (_statement)); \ - fprintf (stderr, __VA_ARGS__); \ - fprintf (stderr, "\n"); \ - fflush (stderr); \ - abort (); \ - } \ +#define ASSERT_WITH_MSG(_statement, ...) \ + do { \ + if (!(_statement)) { \ + MONGOC_STDERR_PRINTF ("FAIL:%s:%d %s()\n %s\n\n", __FILE__, __LINE__, BSON_FUNC, BSON_STR (_statement)); \ + fprintf (stderr, __VA_ARGS__); \ + fprintf (stderr, "\n"); \ + fflush (stderr); \ + abort (); \ + } \ } while (0) // bson_value_to_str returns a string representation of a BSON value. @@ -652,13 +569,12 @@ bson_value_eq (const bson_value_t *a, const bson_value_t *b); // ASSERT_BSONVALUE_EQ asserts that two const bson_value_t* contain equal // values. -#define ASSERT_BSONVALUE_EQ(a, b) \ - if (1) { \ - if (!bson_value_eq ((a), (b))) { \ - test_error ( \ - "%s != %s", bson_value_to_str (a), bson_value_to_str (b)); \ - } \ - } else \ +#define ASSERT_BSONVALUE_EQ(a, b) \ + if (1) { \ + if (!bson_value_eq ((a), (b))) { \ + test_error ("%s != %s", bson_value_to_str (a), bson_value_to_str (b)); \ + } \ + } else \ (void) 0 #define MAX_TEST_NAME_LENGTH 500 @@ -727,49 +643,24 @@ TestSuite_AddLive (TestSuite *suite, const char *name, TestFunc func); int TestSuite_CheckMockServerAllowed (void); void -_TestSuite_AddMockServerTest (TestSuite *suite, - const char *name, - TestFunc func, - ...); -#define TestSuite_AddMockServerTest(_suite, _name, ...) \ - _TestSuite_AddMockServerTest (_suite, _name, __VA_ARGS__, NULL) +_TestSuite_AddMockServerTest (TestSuite *suite, const char *name, TestFunc func, ...); +#define TestSuite_AddMockServerTest(_suite, _name, ...) _TestSuite_AddMockServerTest (_suite, _name, __VA_ARGS__, NULL) void -TestSuite_AddWC (TestSuite *suite, - const char *name, - TestFuncWC func, - TestFuncDtor dtor, - void *ctx); +TestSuite_AddWC (TestSuite *suite, const char *name, TestFuncWC func, TestFuncDtor dtor, void *ctx); Test * -_V_TestSuite_AddFull (TestSuite *suite, - const char *name, - TestFuncWC func, - TestFuncDtor dtor, - void *ctx, - va_list ap); +_V_TestSuite_AddFull (TestSuite *suite, const char *name, TestFuncWC func, TestFuncDtor dtor, void *ctx, va_list ap); void -_TestSuite_AddFull (TestSuite *suite, - const char *name, - TestFuncWC func, - TestFuncDtor dtor, - void *ctx, - ...); +_TestSuite_AddFull (TestSuite *suite, const char *name, TestFuncWC func, TestFuncDtor dtor, void *ctx, ...); void _TestSuite_TestFnCtxDtor (void *ctx); #define TestSuite_AddFull(_suite, _name, _func, _dtor, _ctx, ...) \ _TestSuite_AddFull (_suite, _name, _func, _dtor, _ctx, __VA_ARGS__, NULL) -#define TestSuite_AddFullWithTestFn( \ - _suite, _name, _func, _dtor, _test_fn, ...) \ - do { \ - TestFnCtx *ctx = bson_malloc (sizeof (TestFnCtx)); \ - ctx->test_fn = (TestFunc) (_test_fn); \ - ctx->dtor = _dtor; \ - _TestSuite_AddFull (_suite, \ - _name, \ - _func, \ - _TestSuite_TestFnCtxDtor, \ - ctx, \ - __VA_ARGS__, \ - NULL); \ +#define TestSuite_AddFullWithTestFn(_suite, _name, _func, _dtor, _test_fn, ...) \ + do { \ + TestFnCtx *ctx = bson_malloc (sizeof (TestFnCtx)); \ + ctx->test_fn = (TestFunc) (_test_fn); \ + ctx->dtor = _dtor; \ + _TestSuite_AddFull (_suite, _name, _func, _TestSuite_TestFnCtxDtor, ctx, __VA_ARGS__, NULL); \ } while (0) int TestSuite_Run (TestSuite *suite); diff --git a/src/libmongoc/tests/bsonutil/bson-match.c b/src/libmongoc/tests/bsonutil/bson-match.c index ed129ab16a..adf5ccfa98 100644 --- a/src/libmongoc/tests/bsonutil/bson-match.c +++ b/src/libmongoc/tests/bsonutil/bson-match.c @@ -32,8 +32,7 @@ struct _bson_matcher_t { special_functor_t *specials; }; -#define MATCH_ERR(format, ...) \ - test_set_error (error, "match error at '%s': " format, path, __VA_ARGS__) +#define MATCH_ERR(format, ...) test_set_error (error, "match error at '%s': " format, path, __VA_ARGS__) static char * get_first_key (const bson_t *bson) @@ -145,8 +144,7 @@ special_type (bson_matcher_t *matcher, } if (BSON_ITER_HOLDS_UTF8 (&iter)) { - bson_type_t expected_type = - bson_type_from_string (bson_iter_utf8 (&iter, NULL)); + bson_type_t expected_type = bson_type_from_string (bson_iter_utf8 (&iter, NULL)); if (expected_type != bson_val_type (actual)) { MATCH_ERR ("expected type: %s, got: %s", bson_type_to_string (expected_type), @@ -170,17 +168,14 @@ special_type (bson_matcher_t *matcher, goto done; } - expected_type = - bson_type_from_string (bson_iter_utf8 (&arriter, NULL)); + expected_type = bson_type_from_string (bson_iter_utf8 (&arriter, NULL)); if (expected_type == bson_val_type (actual)) { found = true; break; } } if (!found) { - MATCH_ERR ("expected one of type: %s, got %s", - tmp_json (&arr), - bson_type_to_string (bson_val_type (actual))); + MATCH_ERR ("expected one of type: %s, got %s", tmp_json (&arr), bson_type_to_string (bson_val_type (actual))); goto done; } } @@ -263,8 +258,7 @@ special_matches_hex_bytes (bson_matcher_t *matcher, goto done; } - expected_bytes = - hex_to_bin (bson_iter_utf8 (&iter, NULL), &expected_bytes_len); + expected_bytes = hex_to_bin (bson_iter_utf8 (&iter, NULL), &expected_bytes_len); actual_bytes = bson_val_to_binary (actual, &actual_bytes_len); expected_bytes_string = bin_to_hex (expected_bytes, expected_bytes_len); actual_bytes_string = bin_to_hex (actual_bytes, actual_bytes_len); @@ -282,8 +276,7 @@ special_matches_hex_bytes (bson_matcher_t *matcher, } if (0 != memcmp (expected_bytes, actual_bytes, expected_bytes_len)) { - MATCH_ERR ( - "expected %s, but got %s", expected_bytes_string, actual_bytes_string); + MATCH_ERR ("expected %s, but got %s", expected_bytes_string, actual_bytes_string); bson_free (expected_bytes); bson_free (expected_bytes_string); bson_free (actual_bytes_string); @@ -301,11 +294,8 @@ special_matches_hex_bytes (bson_matcher_t *matcher, } static bool -evaluate_special (bson_matcher_t *matcher, - const bson_t *assertion, - const bson_val_t *actual, - const char *path, - bson_error_t *error) +evaluate_special ( + bson_matcher_t *matcher, const bson_t *assertion, const bson_val_t *actual, const char *path, bson_error_t *error) { bson_iter_t iter; const char *assertion_key; @@ -318,8 +308,7 @@ evaluate_special (bson_matcher_t *matcher, LL_FOREACH (matcher->specials, special_iter) { if (0 == strcmp (assertion_key, special_iter->keyword)) { - return special_iter->fn ( - matcher, assertion, actual, special_iter->ctx, path, error); + return special_iter->fn (matcher, assertion, actual, special_iter->ctx, path, error); } } @@ -333,30 +322,22 @@ bson_matcher_new (void) { bson_matcher_t *matcher = bson_malloc0 (sizeof (bson_matcher_t)); /* Add default special functions. */ - bson_matcher_add_special ( - matcher, "$$placeholder", special_placeholder, NULL); + bson_matcher_add_special (matcher, "$$placeholder", special_placeholder, NULL); bson_matcher_add_special (matcher, "$$exists", special_exists, NULL); bson_matcher_add_special (matcher, "$$type", special_type, NULL); - bson_matcher_add_special ( - matcher, "$$unsetOrMatches", special_unset_or_matches, NULL); - bson_matcher_add_special ( - matcher, "$$matchesHexBytes", special_matches_hex_bytes, NULL); + bson_matcher_add_special (matcher, "$$unsetOrMatches", special_unset_or_matches, NULL); + bson_matcher_add_special (matcher, "$$matchesHexBytes", special_matches_hex_bytes, NULL); return matcher; } /* Add a hook function for matching a special $$ operator */ void -bson_matcher_add_special (bson_matcher_t *matcher, - const char *keyword, - special_fn special, - void *ctx) +bson_matcher_add_special (bson_matcher_t *matcher, const char *keyword, special_fn special, void *ctx) { special_functor_t *functor; if (strstr (keyword, "$$") != keyword) { - test_error ( - "unexpected special match keyword: %s. Should start with '$$'", - keyword); + test_error ("unexpected special match keyword: %s. Should start with '$$'", keyword); } functor = bson_malloc (sizeof (special_functor_t)); @@ -408,8 +389,7 @@ bson_matcher_match (bson_matcher_t *matcher, } if (bson_val_type (actual) != BSON_TYPE_DOCUMENT) { - MATCH_ERR ("expected type document, got %s", - bson_type_to_string (bson_val_type (actual))); + MATCH_ERR ("expected type document, got %s", bson_type_to_string (bson_val_type (actual))); goto done; } @@ -434,11 +414,7 @@ bson_matcher_match (bson_matcher_t *matcher, is_special_match (bson_val_to_document (expected_val))) { bool special_ret; path_child = bson_strdup_printf ("%s.%s", path, key); - special_ret = evaluate_special (matcher, - bson_val_to_document (expected_val), - actual_val, - path, - error); + special_ret = evaluate_special (matcher, bson_val_to_document (expected_val), actual_val, path, error); bson_free (path_child); bson_val_destroy (expected_val); bson_val_destroy (actual_val); @@ -456,8 +432,7 @@ bson_matcher_match (bson_matcher_t *matcher, } path_child = bson_strdup_printf ("%s.%s", path, key); - if (!bson_matcher_match ( - matcher, expected_val, actual_val, path_child, false, error)) { + if (!bson_matcher_match (matcher, expected_val, actual_val, path_child, false, error)) { bson_val_destroy (expected_val); bson_val_destroy (actual_val); bson_free (path_child); @@ -478,9 +453,7 @@ bson_matcher_match (bson_matcher_t *matcher, * This logic must also handle the case where `expected` is one of any * number of root documents within an array (i.e. cursor result). */ if (!(is_root || array_of_root_docs) && expected_keys < actual_keys) { - MATCH_ERR ("expected %" PRIu32 " keys in document, got: %" PRIu32, - expected_keys, - actual_keys); + MATCH_ERR ("expected %" PRIu32 " keys in document, got: %" PRIu32, expected_keys, actual_keys); goto done; } @@ -497,8 +470,7 @@ bson_matcher_match (bson_matcher_t *matcher, uint32_t actual_keys; if (bson_val_type (actual) != BSON_TYPE_ARRAY) { - MATCH_ERR ("expected array, but got: %s", - bson_type_to_string (bson_val_type (actual))); + MATCH_ERR ("expected array, but got: %s", bson_type_to_string (bson_val_type (actual))); goto done; } @@ -506,10 +478,7 @@ bson_matcher_match (bson_matcher_t *matcher, actual_keys = bson_count_keys (actual_bson); if (expected_keys != actual_keys) { - MATCH_ERR ("expected array of size %" PRIu32 - ", but got array of size: %" PRIu32, - expected_keys, - actual_keys); + MATCH_ERR ("expected array of size %" PRIu32 ", but got array of size: %" PRIu32, expected_keys, actual_keys); goto done; } @@ -531,12 +500,8 @@ bson_matcher_match (bson_matcher_t *matcher, actual_val = bson_val_from_iter (&actual_iter); path_child = bson_strdup_printf ("%s.%s", path, key); - if (!bson_matcher_match (matcher, - expected_val, - actual_val, - path_child, - (is_root && array_of_root_docs), - error)) { + if (!bson_matcher_match ( + matcher, expected_val, actual_val, path_child, (is_root && array_of_root_docs), error)) { bson_val_destroy (expected_val); bson_val_destroy (actual_val); bson_free (path_child); @@ -551,9 +516,7 @@ bson_matcher_match (bson_matcher_t *matcher, } if (!bson_val_eq (expected, actual, BSON_VAL_FLEXIBLE_NUMERICS)) { - MATCH_ERR ("value %s != %s", - bson_val_to_json (expected), - bson_val_to_json (actual)); + MATCH_ERR ("value %s != %s", bson_val_to_json (expected), bson_val_to_json (actual)); goto done; } @@ -576,14 +539,10 @@ bson_matcher_match (bson_matcher_t *matcher, } bool -bson_match (const bson_val_t *expected, - const bson_val_t *actual, - bool array_of_root_docs, - bson_error_t *error) +bson_match (const bson_val_t *expected, const bson_val_t *actual, bool array_of_root_docs, bson_error_t *error) { bson_matcher_t *matcher = bson_matcher_new (); - bool matched = bson_matcher_match ( - matcher, expected, actual, "", array_of_root_docs, error); + bool matched = bson_matcher_match (matcher, expected, actual, "", array_of_root_docs, error); bson_matcher_destroy (matcher); return matched; } @@ -598,36 +557,20 @@ typedef struct { static void test_match (void) { - testcase_t tests[] = { - {"int32 ==", "{'a': 1}", "{'a': 1}", true}, - {"int32 !=", "{'a': 1}", "{'a': 0}", false}, - {"$$exists", "{'a': {'$$exists': true}}", "{'a': 0}", true}, - {"$$exists fail", "{'a': {'$$exists': true}}", "{'b': 0}", false}, - {"does not $$exists", "{'a': {'$$exists': false}}", "{'b': 0}", true}, - {"$$unsetOrMatches match", - "{'a': {'$$unsetOrMatches': 1}}", - "{'a': 1}", - true}, - {"$$unsetOrMatches unset", "{'a': {'$$unsetOrMatches': 1}}", "{}", true}, - {"$$unsetOrMatches mismatch", - "{'a': {'$$unsetOrMatches': 'abc'}}", - "{'a': 1}", - false}, - {"$$type match", "{'a': {'$$type': 'string'}}", "{'a': 'abc'}", true}, - {"$$type mismatch", "{'a': {'$$type': 'string'}}", "{'a': 1}", false}, - {"$$type array match", - "{'a': {'$$type': ['string', 'int']}}", - "{'a': 1}", - true}, - {"$$type array mismatch", - "{'a': {'$$type': ['string', 'int']}}", - "{'a': 1.2}", - false}, - {"extra keys in root ok", "{'a': 1}", "{'a': 1, 'b': 2}", true}, - {"extra keys in subdoc not ok", - "{'a': {'b': 1}}", - "{'a': {'b': 1, 'c': 2}}", - false}}; + testcase_t tests[] = {{"int32 ==", "{'a': 1}", "{'a': 1}", true}, + {"int32 !=", "{'a': 1}", "{'a': 0}", false}, + {"$$exists", "{'a': {'$$exists': true}}", "{'a': 0}", true}, + {"$$exists fail", "{'a': {'$$exists': true}}", "{'b': 0}", false}, + {"does not $$exists", "{'a': {'$$exists': false}}", "{'b': 0}", true}, + {"$$unsetOrMatches match", "{'a': {'$$unsetOrMatches': 1}}", "{'a': 1}", true}, + {"$$unsetOrMatches unset", "{'a': {'$$unsetOrMatches': 1}}", "{}", true}, + {"$$unsetOrMatches mismatch", "{'a': {'$$unsetOrMatches': 'abc'}}", "{'a': 1}", false}, + {"$$type match", "{'a': {'$$type': 'string'}}", "{'a': 'abc'}", true}, + {"$$type mismatch", "{'a': {'$$type': 'string'}}", "{'a': 1}", false}, + {"$$type array match", "{'a': {'$$type': ['string', 'int']}}", "{'a': 1}", true}, + {"$$type array mismatch", "{'a': {'$$type': ['string', 'int']}}", "{'a': 1.2}", false}, + {"extra keys in root ok", "{'a': 1}", "{'a': 1, 'b': 2}", true}, + {"extra keys in subdoc not ok", "{'a': {'b': 1}}", "{'a': {'b': 1, 'c': 2}}", false}}; int i; for (i = 0; i < sizeof (tests) / sizeof (testcase_t); i++) { @@ -640,9 +583,7 @@ test_match (void) ret = bson_match (expected, actual, false, &error); if (test->expect_match) { if (!ret) { - test_error ("%s: did not match with error: %s, but should have", - test->desc, - error.message); + test_error ("%s: did not match with error: %s, but should have", test->desc, error.message); } } else { if (ret) { diff --git a/src/libmongoc/tests/bsonutil/bson-match.h b/src/libmongoc/tests/bsonutil/bson-match.h index 1fc1bda21a..6b9b8c9170 100644 --- a/src/libmongoc/tests/bsonutil/bson-match.h +++ b/src/libmongoc/tests/bsonutil/bson-match.h @@ -22,10 +22,7 @@ /* Matches bson values in accordance with the unified test format's "Evaluating * Matches" rules. */ bool -bson_match (const bson_val_t *expected, - const bson_val_t *actual, - bool array_of_root_docs, - bson_error_t *error); +bson_match (const bson_val_t *expected, const bson_val_t *actual, bool array_of_root_docs, bson_error_t *error); /* A bson_matcher_t may be used to extend the default matching behavior. */ typedef struct _bson_matcher_t bson_matcher_t; @@ -48,10 +45,7 @@ typedef bool (*special_fn) (bson_matcher_t *matcher, * expectation. */ void -bson_matcher_add_special (bson_matcher_t *matcher, - const char *keyword, - special_fn special, - void *ctx); +bson_matcher_add_special (bson_matcher_t *matcher, const char *keyword, special_fn special, void *ctx); bool bson_matcher_match (bson_matcher_t *matcher, diff --git a/src/libmongoc/tests/bsonutil/bson-parser.c b/src/libmongoc/tests/bsonutil/bson-parser.c index 52717a52a9..f554d430bb 100644 --- a/src/libmongoc/tests/bsonutil/bson-parser.c +++ b/src/libmongoc/tests/bsonutil/bson-parser.c @@ -103,14 +103,11 @@ bson_to_write_concern (bson_t *bson, bson_error_t *error) if (w_val) { if (bson_val_is_numeric (w_val)) { - mongoc_write_concern_set_w (out, - (int32_t) bson_val_convert_int64 (w_val)); - } else if (bson_val_type (w_val) == BSON_TYPE_UTF8 && - 0 == strcmp (bson_val_to_utf8 (w_val), "majority")) { + mongoc_write_concern_set_w (out, (int32_t) bson_val_convert_int64 (w_val)); + } else if (bson_val_type (w_val) == BSON_TYPE_UTF8 && 0 == strcmp (bson_val_to_utf8 (w_val), "majority")) { mongoc_write_concern_set_w (out, MONGOC_WRITE_CONCERN_W_MAJORITY); } else { - test_set_error ( - error, "unrecognized value for 'w': %s", bson_val_to_json (w_val)); + test_set_error (error, "unrecognized value for 'w': %s", bson_val_to_json (w_val)); } } @@ -181,8 +178,7 @@ bson_to_read_prefs (bson_t *bson, bson_error_t *error) parser = bson_parser_new (); bson_parser_utf8 (parser, "mode", &mode_string); bson_parser_array_optional (parser, "tagSets", &tag_sets); - bson_parser_int_optional ( - parser, "maxStalenessSeconds", &max_staleness_seconds); + bson_parser_int_optional (parser, "maxStalenessSeconds", &max_staleness_seconds); bson_parser_doc_optional (parser, "hedge", &hedge); if (!bson_parser_parse (parser, bson, error)) { @@ -241,8 +237,7 @@ static void bson_parser_entry_destroy (bson_parser_entry_t *entry, bool with_parsed_fields) { if (with_parsed_fields) { - if (entry->ptype == BSON_PARSER_DOC || - entry->ptype == BSON_PARSER_ARRAY || + if (entry->ptype == BSON_PARSER_DOC || entry->ptype == BSON_PARSER_ARRAY || entry->ptype == BSON_PARSER_ARRAY_OR_DOC) { bson_t **out; @@ -328,11 +323,7 @@ bson_parser_destroy_with_parsed_fields (bson_parser_t *parser) } static void -bson_parser_add_entry (bson_parser_t *parser, - const char *key, - void *out, - bson_parser_type_t ptype, - bool optional) +bson_parser_add_entry (bson_parser_t *parser, const char *key, void *out, bson_parser_type_t ptype, bool optional) { bson_parser_entry_t *e = NULL; bson_parser_entry_t *match = NULL; @@ -394,9 +385,7 @@ bson_parser_array (bson_parser_t *parser, const char *key, bson_t **out) bson_parser_add_entry (parser, key, (void *) out, BSON_PARSER_ARRAY, false); } void -bson_parser_array_optional (bson_parser_t *parser, - const char *key, - bson_t **out) +bson_parser_array_optional (bson_parser_t *parser, const char *key, bson_t **out) { *out = NULL; bson_parser_add_entry (parser, key, (void *) out, BSON_PARSER_ARRAY, true); @@ -406,17 +395,13 @@ void bson_parser_array_or_doc (bson_parser_t *parser, const char *key, bson_t **out) { *out = NULL; - bson_parser_add_entry ( - parser, key, (void *) out, BSON_PARSER_ARRAY_OR_DOC, false); + bson_parser_add_entry (parser, key, (void *) out, BSON_PARSER_ARRAY_OR_DOC, false); } void -bson_parser_array_or_doc_optional (bson_parser_t *parser, - const char *key, - bson_t **out) +bson_parser_array_or_doc_optional (bson_parser_t *parser, const char *key, bson_t **out) { *out = NULL; - bson_parser_add_entry ( - parser, key, (void *) out, BSON_PARSER_ARRAY_OR_DOC, true); + bson_parser_add_entry (parser, key, (void *) out, BSON_PARSER_ARRAY_OR_DOC, true); } void @@ -465,69 +450,53 @@ void bson_parser_write_concern (bson_parser_t *bp, mongoc_write_concern_t **out) { *out = NULL; - bson_parser_add_entry ( - bp, "writeConcern", (void *) out, BSON_PARSER_WRITE_CONCERN, false); + bson_parser_add_entry (bp, "writeConcern", (void *) out, BSON_PARSER_WRITE_CONCERN, false); } void -bson_parser_write_concern_optional (bson_parser_t *bp, - mongoc_write_concern_t **out) +bson_parser_write_concern_optional (bson_parser_t *bp, mongoc_write_concern_t **out) { *out = NULL; - bson_parser_add_entry ( - bp, "writeConcern", (void *) out, BSON_PARSER_WRITE_CONCERN, true); + bson_parser_add_entry (bp, "writeConcern", (void *) out, BSON_PARSER_WRITE_CONCERN, true); } void bson_parser_read_concern (bson_parser_t *bp, mongoc_read_concern_t **out) { *out = NULL; - bson_parser_add_entry ( - bp, "readConcern", (void *) out, BSON_PARSER_READ_CONCERN, false); + bson_parser_add_entry (bp, "readConcern", (void *) out, BSON_PARSER_READ_CONCERN, false); } void -bson_parser_read_concern_optional (bson_parser_t *bp, - mongoc_read_concern_t **out) +bson_parser_read_concern_optional (bson_parser_t *bp, mongoc_read_concern_t **out) { *out = NULL; - bson_parser_add_entry ( - bp, "readConcern", (void *) out, BSON_PARSER_READ_CONCERN, true); + bson_parser_add_entry (bp, "readConcern", (void *) out, BSON_PARSER_READ_CONCERN, true); } void bson_parser_read_prefs (bson_parser_t *bp, mongoc_read_prefs_t **out) { *out = NULL; - bson_parser_add_entry ( - bp, "readPreference", (void *) out, BSON_PARSER_READ_PREFS, false); + bson_parser_add_entry (bp, "readPreference", (void *) out, BSON_PARSER_READ_PREFS, false); } void bson_parser_read_prefs_optional (bson_parser_t *bp, mongoc_read_prefs_t **out) { *out = NULL; - bson_parser_add_entry ( - bp, "readPreference", (void *) out, BSON_PARSER_READ_PREFS, true); + bson_parser_add_entry (bp, "readPreference", (void *) out, BSON_PARSER_READ_PREFS, true); } void -marshal_error (const char *key, - bson_type_t btype, - bson_parser_type_t ptype, - bson_error_t *error) +marshal_error (const char *key, bson_type_t btype, bson_parser_type_t ptype, bson_error_t *error) { - test_set_error (error, - "expecting %s for '%s' but got: %s", - parser_type_to_string (ptype), - key, - bson_type_to_string (btype)); + test_set_error ( + error, "expecting %s for '%s' but got: %s", parser_type_to_string (ptype), key, bson_type_to_string (btype)); } bool -entry_marshal (bson_parser_entry_t *entry, - bson_iter_t *iter, - bson_error_t *error) +entry_marshal (bson_parser_entry_t *entry, bson_iter_t *iter, bson_error_t *error) { bool ret = false; const char *key; @@ -655,8 +624,7 @@ entry_marshal (bson_parser_entry_t *entry, bson_iter_bson (iter, &tmp); *out = bson_to_read_prefs (&tmp, error); } else { - test_set_error ( - error, "unimplemented parser type: %s", parser_type_to_string (ptype)); + test_set_error (error, "unimplemented parser type: %s", parser_type_to_string (ptype)); goto done; } @@ -694,8 +662,7 @@ bson_parser_parse (bson_parser_t *parser, bson_t *in, bson_error_t *error) } else if (parser->allow_extra) { BSON_APPEND_VALUE (parser->extra, key, bson_iter_value (&iter)); } else { - test_set_error ( - error, "Extra field '%s' found parsing: %s", key, tmp_json (in)); + test_set_error (error, "Extra field '%s' found parsing: %s", key, tmp_json (in)); return false; } } @@ -706,10 +673,7 @@ bson_parser_parse (bson_parser_t *parser, bson_t *in, bson_error_t *error) LL_FOREACH (parser->entries, entry) { if (!entry->optional && !entry->set) { - test_set_error (error, - "Required field '%s' was not found parsing: %s", - entry->key, - tmp_json (in)); + test_set_error (error, "Required field '%s' was not found parsing: %s", entry->key, tmp_json (in)); return false; } } diff --git a/src/libmongoc/tests/bsonutil/bson-parser.h b/src/libmongoc/tests/bsonutil/bson-parser.h index 1380e73040..7cd73467e5 100644 --- a/src/libmongoc/tests/bsonutil/bson-parser.h +++ b/src/libmongoc/tests/bsonutil/bson-parser.h @@ -84,9 +84,7 @@ bson_parser_array_optional (bson_parser_t *bp, const char *key, bson_t **out); void bson_parser_array_or_doc (bson_parser_t *bp, const char *key, bson_t **out); void -bson_parser_array_or_doc_optional (bson_parser_t *bp, - const char *key, - bson_t **out); +bson_parser_array_or_doc_optional (bson_parser_t *bp, const char *key, bson_t **out); void bson_parser_bool (bson_parser_t *bp, const char *key, bool **out); @@ -107,14 +105,12 @@ bson_parser_any_optional (bson_parser_t *bp, const char *key, bson_val_t **out); void bson_parser_write_concern (bson_parser_t *bp, mongoc_write_concern_t **out); void -bson_parser_write_concern_optional (bson_parser_t *bp, - mongoc_write_concern_t **out); +bson_parser_write_concern_optional (bson_parser_t *bp, mongoc_write_concern_t **out); void bson_parser_read_concern (bson_parser_t *bp, mongoc_read_concern_t **out); void -bson_parser_read_concern_optional (bson_parser_t *bp, - mongoc_read_concern_t **out); +bson_parser_read_concern_optional (bson_parser_t *bp, mongoc_read_concern_t **out); void bson_parser_read_prefs (bson_parser_t *bp, mongoc_read_prefs_t **out); diff --git a/src/libmongoc/tests/bsonutil/bson-val.c b/src/libmongoc/tests/bsonutil/bson-val.c index efd4c1b9ae..ab6875ac09 100644 --- a/src/libmongoc/tests/bsonutil/bson-val.c +++ b/src/libmongoc/tests/bsonutil/bson-val.c @@ -37,10 +37,8 @@ bson_val_from_value (const bson_value_t *value) val = bson_malloc0 (sizeof (bson_val_t)); bson_value_copy (value, &val->value); - if (value->value_type == BSON_TYPE_DOCUMENT || - value->value_type == BSON_TYPE_ARRAY) { - val->as_bson = bson_new_from_data (value->value.v_doc.data, - value->value.v_doc.data_len); + if (value->value_type == BSON_TYPE_DOCUMENT || value->value_type == BSON_TYPE_ARRAY) { + val->as_bson = bson_new_from_data (value->value.v_doc.data, value->value.v_doc.data_len); } val->type = value->value_type; @@ -70,8 +68,7 @@ bson_val_from_json (const char *single_quoted_json) bson_error_t error; if (!bson_init_from_json (&as_bson, double_quoted, -1, &error)) { - test_error ("unable to construct bson value from: %s", - single_quoted_json); + test_error ("unable to construct bson value from: %s", single_quoted_json); } val = bson_val_from_bson (&as_bson); @@ -175,15 +172,12 @@ bson_val_destroy (bson_val_t *val) } bool -bson_val_eq (const bson_val_t *a, - const bson_val_t *b, - bson_val_comparison_flags_t flags) +bson_val_eq (const bson_val_t *a, const bson_val_t *b, bson_val_comparison_flags_t flags) { bson_type_t vtype; vtype = a->type; - if (vtype == BSON_TYPE_DOUBLE || vtype == BSON_TYPE_INT32 || - vtype == BSON_TYPE_INT64) { + if (vtype == BSON_TYPE_DOUBLE || vtype == BSON_TYPE_INT32 || vtype == BSON_TYPE_INT64) { if (flags & BSON_VAL_FLEXIBLE_NUMERICS) { return bson_val_convert_int64 (a) == bson_val_convert_int64 (b); } @@ -210,10 +204,8 @@ bson_val_eq (const bson_val_t *a, bool scope_equal; bson_t *a_scope, *a_scope_sorted, *b_scope, *b_scope_sorted; - a_scope = bson_new_from_data (a->value.value.v_codewscope.scope_data, - a->value.value.v_codewscope.scope_len); - b_scope = bson_new_from_data (b->value.value.v_codewscope.scope_data, - b->value.value.v_codewscope.scope_len); + a_scope = bson_new_from_data (a->value.value.v_codewscope.scope_data, a->value.value.v_codewscope.scope_len); + b_scope = bson_new_from_data (b->value.value.v_codewscope.scope_data, b->value.value.v_codewscope.scope_len); a_scope_sorted = bson_copy_and_sort (a_scope); b_scope_sorted = bson_copy_and_sort (b_scope); @@ -228,8 +220,7 @@ bson_val_eq (const bson_val_t *a, return false; } - return 0 == strcmp (a->value.value.v_codewscope.code, - b->value.value.v_codewscope.code); + return 0 == strcmp (a->value.value.v_codewscope.code, b->value.value.v_codewscope.code); } /* All other cases, compare exact match by looking at canonical extended JSON @@ -247,8 +238,7 @@ const bson_t * bson_val_to_document (const bson_val_t *val) { if (val->type != BSON_TYPE_DOCUMENT) { - test_error ("expected document, got: %s", - bson_type_to_string (val->type)); + test_error ("expected document, got: %s", bson_type_to_string (val->type)); } return val->as_bson; } @@ -267,8 +257,7 @@ const bson_t * bson_val_to_bson (const bson_val_t *val) { if (val->type != BSON_TYPE_ARRAY && val->type != BSON_TYPE_DOCUMENT) { - test_error ("expected document or array, got: %s", - bson_type_to_string (val->type)); + test_error ("expected document or array, got: %s", bson_type_to_string (val->type)); } return val->as_bson; } @@ -299,8 +288,7 @@ bson_val_to_utf8 (const bson_val_t *val) bool bson_val_is_numeric (const bson_val_t *val) { - return (val->type == BSON_TYPE_INT32 || val->type == BSON_TYPE_INT64 || - val->type == BSON_TYPE_DOUBLE); + return (val->type == BSON_TYPE_INT32 || val->type == BSON_TYPE_INT64 || val->type == BSON_TYPE_DOUBLE); } int64_t @@ -316,8 +304,7 @@ bson_val_convert_int64 (const bson_val_t *val) return (int64_t) val->value.value.v_double; } - test_error ("expected int64, int32, or double, got: %s", - bson_type_to_string (val->type)); + test_error ("expected int64, int32, or double, got: %s", bson_type_to_string (val->type)); return 0; } diff --git a/src/libmongoc/tests/bsonutil/bson-val.h b/src/libmongoc/tests/bsonutil/bson-val.h index caa84b98eb..1b706ec621 100644 --- a/src/libmongoc/tests/bsonutil/bson-val.h +++ b/src/libmongoc/tests/bsonutil/bson-val.h @@ -23,10 +23,7 @@ * bson_val_t is a convenience wrapper around a bson_value_t. */ typedef struct _bson_val_t bson_val_t; -typedef enum { - BSON_VAL_FLEXIBLE_NUMERICS = 1 << 0, - BSON_VAL_UNORDERED = 1 << 1 -} bson_val_comparison_flags_t; +typedef enum { BSON_VAL_FLEXIBLE_NUMERICS = 1 << 0, BSON_VAL_UNORDERED = 1 << 1 } bson_val_comparison_flags_t; bson_val_t * bson_val_from_value (const bson_value_t *value); @@ -80,9 +77,7 @@ int64_t bson_val_convert_int64 (const bson_val_t *val); bool -bson_val_eq (const bson_val_t *a, - const bson_val_t *b, - bson_val_comparison_flags_t flags); +bson_val_eq (const bson_val_t *a, const bson_val_t *b, bson_val_comparison_flags_t flags); bson_type_t bson_val_type (const bson_val_t *val); diff --git a/src/libmongoc/tests/debug-stream.c b/src/libmongoc/tests/debug-stream.c index 8d4b8c92c1..4783bf5b69 100644 --- a/src/libmongoc/tests/debug-stream.c +++ b/src/libmongoc/tests/debug-stream.c @@ -64,17 +64,9 @@ _mongoc_stream_debug_failed (mongoc_stream_t *stream) static int -_mongoc_stream_debug_setsockopt (mongoc_stream_t *stream, - int level, - int optname, - void *optval, - mongoc_socklen_t optlen) +_mongoc_stream_debug_setsockopt (mongoc_stream_t *stream, int level, int optname, void *optval, mongoc_socklen_t optlen) { - return mongoc_stream_setsockopt (((mongoc_stream_debug_t *) stream)->wrapped, - level, - optname, - optval, - optlen); + return mongoc_stream_setsockopt (((mongoc_stream_debug_t *) stream)->wrapped, level, optname, optval, optlen); } @@ -86,36 +78,24 @@ _mongoc_stream_debug_flush (mongoc_stream_t *stream) static ssize_t -_mongoc_stream_debug_readv (mongoc_stream_t *stream, - mongoc_iovec_t *iov, - size_t iovcnt, - size_t min_bytes, - int32_t timeout_msec) +_mongoc_stream_debug_readv ( + mongoc_stream_t *stream, mongoc_iovec_t *iov, size_t iovcnt, size_t min_bytes, int32_t timeout_msec) { - return mongoc_stream_readv (((mongoc_stream_debug_t *) stream)->wrapped, - iov, - iovcnt, - min_bytes, - timeout_msec); + return mongoc_stream_readv (((mongoc_stream_debug_t *) stream)->wrapped, iov, iovcnt, min_bytes, timeout_msec); } static ssize_t -_mongoc_stream_debug_writev (mongoc_stream_t *stream, - mongoc_iovec_t *iov, - size_t iovcnt, - int32_t timeout_msec) +_mongoc_stream_debug_writev (mongoc_stream_t *stream, mongoc_iovec_t *iov, size_t iovcnt, int32_t timeout_msec) { - return mongoc_stream_writev ( - ((mongoc_stream_debug_t *) stream)->wrapped, iov, iovcnt, timeout_msec); + return mongoc_stream_writev (((mongoc_stream_debug_t *) stream)->wrapped, iov, iovcnt, timeout_msec); } static bool _mongoc_stream_debug_check_closed (mongoc_stream_t *stream) { - return mongoc_stream_check_closed ( - ((mongoc_stream_debug_t *) stream)->wrapped); + return mongoc_stream_check_closed (((mongoc_stream_debug_t *) stream)->wrapped); } @@ -129,8 +109,7 @@ _mongoc_stream_debug_timed_out (mongoc_stream_t *stream) static bool _mongoc_stream_debug_should_retry (mongoc_stream_t *stream) { - return mongoc_stream_should_retry ( - ((mongoc_stream_debug_t *) stream)->wrapped); + return mongoc_stream_should_retry (((mongoc_stream_debug_t *) stream)->wrapped); } @@ -181,26 +160,21 @@ debug_stream_new (mongoc_stream_t *stream, debug_stream_stats_t *stats) mongoc_stream_t * -debug_stream_initiator (const mongoc_uri_t *uri, - const mongoc_host_list_t *host, - void *user_data, - bson_error_t *error) +debug_stream_initiator (const mongoc_uri_t *uri, const mongoc_host_list_t *host, void *user_data, bson_error_t *error) { debug_stream_stats_t *stats; mongoc_stream_t *default_stream; stats = (debug_stream_stats_t *) user_data; - default_stream = - mongoc_client_default_stream_initiator (uri, host, stats->client, error); + default_stream = mongoc_client_default_stream_initiator (uri, host, stats->client, error); return debug_stream_new (default_stream, stats); } void -test_framework_set_debug_stream (mongoc_client_t *client, - debug_stream_stats_t *stats) +test_framework_set_debug_stream (mongoc_client_t *client, debug_stream_stats_t *stats) { BSON_ASSERT_PARAM (client); diff --git a/src/libmongoc/tests/json-test-monitoring.c b/src/libmongoc/tests/json-test-monitoring.c index b6ee39ab61..281ea23ef1 100644 --- a/src/libmongoc/tests/json-test-monitoring.c +++ b/src/libmongoc/tests/json-test-monitoring.c @@ -72,17 +72,14 @@ assert_host_in_uri (const mongoc_host_list_t *host, const mongoc_uri_t *uri) hosts = hosts->next; } - test_error ("Host \"%s\" not in \"%s\"", - host->host_and_port, - mongoc_uri_get_string (uri)); + test_error ("Host \"%s\" not in \"%s\"", host->host_and_port, mongoc_uri_get_string (uri)); } static void started_cb (const mongoc_apm_command_started_t *event) { - json_test_ctx_t *ctx = - (json_test_ctx_t *) mongoc_apm_command_started_get_context (event); + json_test_ctx_t *ctx = (json_test_ctx_t *) mongoc_apm_command_started_get_context (event); bson_t *events = &ctx->events; char str[16]; const char *key; @@ -140,8 +137,7 @@ started_cb (const mongoc_apm_command_started_t *event) static void succeeded_cb (const mongoc_apm_command_succeeded_t *event) { - json_test_ctx_t *ctx = - (json_test_ctx_t *) mongoc_apm_command_succeeded_get_context (event); + json_test_ctx_t *ctx = (json_test_ctx_t *) mongoc_apm_command_succeeded_get_context (event); char str[16]; const char *key; bson_t *new_event; @@ -185,8 +181,7 @@ succeeded_cb (const mongoc_apm_command_succeeded_t *event) static void failed_cb (const mongoc_apm_command_failed_t *event) { - json_test_ctx_t *ctx = - (json_test_ctx_t *) mongoc_apm_command_failed_get_context (event); + json_test_ctx_t *ctx = (json_test_ctx_t *) mongoc_apm_command_failed_get_context (event); char str[16]; const char *key; bson_t *new_event; @@ -195,10 +190,7 @@ failed_cb (const mongoc_apm_command_failed_t *event) char *reply_json; reply_json = bson_as_canonical_extended_json (event->reply, NULL); - MONGOC_DEBUG ("<-- %s COMMAND FAILED: %s\nREPLY: %s\n", - event->command_name, - event->error->message, - reply_json); + MONGOC_DEBUG ("<-- %s COMMAND FAILED: %s\nREPLY: %s\n", event->command_name, event->error->message, reply_json); bson_free (reply_json); } @@ -249,8 +241,7 @@ server_changed_cb (const mongoc_apm_server_changed_t *event) if (sd->type == MONGOC_SERVER_UNKNOWN) { ctx->total_ServerMarkedUnknownEvent++; } - if (sd->type == MONGOC_SERVER_RS_PRIMARY && - !_mongoc_host_list_compare_one (&sd->host, &ctx->primary_host)) { + if (sd->type == MONGOC_SERVER_RS_PRIMARY && !_mongoc_host_list_compare_one (&sd->host, &ctx->primary_host)) { ctx->total_PrimaryChangedEvent++; memcpy (&ctx->primary_host, &sd->host, sizeof (mongoc_host_list_t)); } @@ -316,13 +307,10 @@ apm_match_visitor_ctx_reset (apm_match_visitor_ctx_t *ctx) static match_action_t -apm_match_visitor (match_ctx_t *ctx, - bson_iter_t *pattern_iter, - bson_iter_t *doc_iter) +apm_match_visitor (match_ctx_t *ctx, bson_iter_t *pattern_iter, bson_iter_t *doc_iter) { const char *key = bson_iter_key (pattern_iter); - apm_match_visitor_ctx_t *visitor_ctx = - (apm_match_visitor_ctx_t *) ctx->visitor_ctx; + apm_match_visitor_ctx_t *visitor_ctx = (apm_match_visitor_ctx_t *) ctx->visitor_ctx; #define SHOULD_EXIST \ do { \ @@ -333,15 +321,13 @@ apm_match_visitor (match_ctx_t *ctx, } while (0) #define IS_COMMAND(cmd) (ends_with (ctx->path, "command") && !strcmp (key, cmd)) - if (ends_with (ctx->path, "command") && !visitor_ctx->command_name && - doc_iter) { + if (ends_with (ctx->path, "command") && !visitor_ctx->command_name && doc_iter) { visitor_ctx->command_name = bson_strdup (bson_iter_key (doc_iter)); } // Subdocuments in `command` should not have extra fields. if (NULL != strstr (ctx->path, ".command") && doc_iter) { - if (BSON_ITER_HOLDS_DOCUMENT (doc_iter) && - BSON_ITER_HOLDS_DOCUMENT (pattern_iter)) { + if (BSON_ITER_HOLDS_DOCUMENT (doc_iter) && BSON_ITER_HOLDS_DOCUMENT (pattern_iter)) { bson_t doc_subdoc; bson_iter_bson (doc_iter, &doc_subdoc); bson_iter_t doc_subdoc_iter; @@ -355,24 +341,20 @@ apm_match_visitor (match_ctx_t *ctx, bool skip = false; if (ends_with (ctx->path, "updates") && - (0 == strcmp ("multi", subdoc_key) || - 0 == strcmp ("upsert", subdoc_key))) { + (0 == strcmp ("multi", subdoc_key) || 0 == strcmp ("upsert", subdoc_key))) { // libmongoc includes `multi: false` and `upsert: false`. // Some tests do not include `multi: false` and `upsert: false` // in expectations. See DRIVERS-2271 and DRIVERS-976. skip = true; } - if (!skip && !bson_iter_init_find (&pattern_subdoc_iter, - &pattern_subdoc, - subdoc_key)) { - match_err ( - ctx, - "unexpected extra field '%s' in captured event " - "command subdocument of field '%s'. pattern_subdoc=%s", - subdoc_key, - key, - tmp_json (&pattern_subdoc)); + if (!skip && !bson_iter_init_find (&pattern_subdoc_iter, &pattern_subdoc, subdoc_key)) { + match_err (ctx, + "unexpected extra field '%s' in captured event " + "command subdocument of field '%s'. pattern_subdoc=%s", + subdoc_key, + key, + tmp_json (&pattern_subdoc)); return MATCH_ACTION_ABORT; } } @@ -409,8 +391,7 @@ apm_match_visitor (match_ctx_t *ctx, visitor_ctx->cursor_id = bson_iter_as_int64 (doc_iter); } else if (visitor_ctx->cursor_id != bson_iter_as_int64 (doc_iter)) { match_err (ctx, - "cursor requested in getMore (%" PRId64 - ") does not match previously seen (%" PRId64 ")", + "cursor requested in getMore (%" PRId64 ") does not match previously seen (%" PRId64 ")", bson_iter_as_int64 (doc_iter), visitor_ctx->cursor_id); return MATCH_ACTION_ABORT; @@ -427,20 +408,17 @@ apm_match_visitor (match_ctx_t *ctx, * includes an lsid with the value "session0" or "session1". Tests MUST * assert that the command's actual lsid matches the id of the correct * ClientSession named session0 or session1." */ - if (!strcmp (session_name, "session0") && - !lsids_match (&visitor_ctx->lsids[0], &lsid)) { + if (!strcmp (session_name, "session0") && !lsids_match (&visitor_ctx->lsids[0], &lsid)) { fail = true; } - if (!strcmp (session_name, "session1") && - !lsids_match (&visitor_ctx->lsids[1], &lsid)) { + if (!strcmp (session_name, "session1") && !lsids_match (&visitor_ctx->lsids[1], &lsid)) { fail = true; } if (fail) { char *str = bson_as_json (&lsid, NULL); - match_err ( - ctx, "expected %s, but used session: %s", session_name, str); + match_err (ctx, "expected %s, but used session: %s", session_name, str); bson_free (str); return MATCH_ACTION_ABORT; } else { @@ -457,8 +435,7 @@ apm_match_visitor (match_ctx_t *ctx, if (!strcmp (key, "upsert") && !bson_iter_bool (pattern_iter)) { return MATCH_ACTION_SKIP; } - } else if (visitor_ctx->command_name && - !strcmp (visitor_ctx->command_name, "findAndModify") && + } else if (visitor_ctx->command_name && !strcmp (visitor_ctx->command_name, "findAndModify") && !strcmp (key, "new")) { /* transaction tests expect "new: false" explicitly; we don't send it */ return MATCH_ACTION_SKIP; @@ -654,8 +631,7 @@ test_apm_matching (void) match_ctx.visitor_ctx = &match_visitor_ctx; BSON_ASSERT (match_bson_with_ctx (tmp_bson (e1), tmp_bson (e1), &match_ctx)); - BSON_ASSERT ( - !match_bson_with_ctx (tmp_bson (e2), tmp_bson (e2), &match_ctx)); + BSON_ASSERT (!match_bson_with_ctx (tmp_bson (e2), tmp_bson (e2), &match_ctx)); ASSERT_CONTAINS (match_ctx.errmsg, "cursor requested in getMore"); apm_match_visitor_ctx_reset (&match_visitor_ctx); } @@ -670,16 +646,13 @@ test_apm_matching_extra_fields (void) apm_match_visitor_ctx_t match_visitor_ctx = {0}; match_ctx_t match_ctx = {{0}}; - const char *event = BSON_STR ( - {"command_started_event" : {"command" : {"a" : 1, "b" : 2}}}); - const char *pattern = - BSON_STR ({"command_started_event" : {"command" : {"a" : 1}}}); + const char *event = BSON_STR ({"command_started_event" : {"command" : {"a" : 1, "b" : 2}}}); + const char *pattern = BSON_STR ({"command_started_event" : {"command" : {"a" : 1}}}); match_ctx.visitor_fn = apm_match_visitor; match_ctx.visitor_ctx = &match_visitor_ctx; - bool matched = - match_bson_with_ctx (tmp_bson (event), tmp_bson (pattern), &match_ctx); + bool matched = match_bson_with_ctx (tmp_bson (event), tmp_bson (pattern), &match_ctx); ASSERT (matched); apm_match_visitor_ctx_reset (&match_visitor_ctx); } @@ -689,17 +662,13 @@ test_apm_matching_extra_fields (void) apm_match_visitor_ctx_t match_visitor_ctx = {0}; match_ctx_t match_ctx = {{0}}; - const char *event = BSON_STR ({ - "command_started_event" : {"command" : {"subdoc" : {"a" : 1, "b" : 2}}} - }); - const char *pattern = BSON_STR ( - {"command_started_event" : {"command" : {"subdoc" : {"a" : 1}}}}); + const char *event = BSON_STR ({"command_started_event" : {"command" : {"subdoc" : {"a" : 1, "b" : 2}}}}); + const char *pattern = BSON_STR ({"command_started_event" : {"command" : {"subdoc" : {"a" : 1}}}}); match_ctx.visitor_fn = apm_match_visitor; match_ctx.visitor_ctx = &match_visitor_ctx; - bool matched = - match_bson_with_ctx (tmp_bson (event), tmp_bson (pattern), &match_ctx); + bool matched = match_bson_with_ctx (tmp_bson (event), tmp_bson (pattern), &match_ctx); ASSERT (!matched); ASSERT_CONTAINS (match_ctx.errmsg, "unexpected extra field 'b'"); apm_match_visitor_ctx_reset (&match_visitor_ctx); @@ -710,19 +679,13 @@ test_apm_matching_extra_fields (void) apm_match_visitor_ctx_t match_visitor_ctx = {0}; match_ctx_t match_ctx = {{0}}; - const char *event = BSON_STR ({ - "command_started_event" : - {"command" : {"subarray" : [ {"a" : 1, "b" : 2} ]}} - }); - const char *pattern = BSON_STR ({ - "command_started_event" : {"command" : {"subarray" : [ {"a" : 1} ]}} - }); + const char *event = BSON_STR ({"command_started_event" : {"command" : {"subarray" : [ {"a" : 1, "b" : 2} ]}}}); + const char *pattern = BSON_STR ({"command_started_event" : {"command" : {"subarray" : [ {"a" : 1} ]}}}); match_ctx.visitor_fn = apm_match_visitor; match_ctx.visitor_ctx = &match_visitor_ctx; - bool matched = - match_bson_with_ctx (tmp_bson (event), tmp_bson (pattern), &match_ctx); + bool matched = match_bson_with_ctx (tmp_bson (event), tmp_bson (pattern), &match_ctx); ASSERT (!matched); ASSERT_CONTAINS (match_ctx.errmsg, "unexpected extra field 'b'"); apm_match_visitor_ctx_reset (&match_visitor_ctx); @@ -734,6 +697,5 @@ void test_apm_install (TestSuite *suite) { TestSuite_Add (suite, "/apm_test_matching", test_apm_matching); - TestSuite_Add ( - suite, "/apm_test_matching/extra_fields", test_apm_matching_extra_fields); + TestSuite_Add (suite, "/apm_test_matching/extra_fields", test_apm_matching_extra_fields); } diff --git a/src/libmongoc/tests/json-test-operations.c b/src/libmongoc/tests/json-test-operations.c index 7fef813d9b..8398fd4df7 100644 --- a/src/libmongoc/tests/json-test-operations.c +++ b/src/libmongoc/tests/json-test-operations.c @@ -108,8 +108,7 @@ static BSON_THREAD_FUN (json_test_worker_thread_run, wt_void) op = (bson_t *) q_get_nowait (wt->queue); shutdown = wt->shutdown_requested; while (!op && !shutdown) { - mongoc_cond_timedwait ( - &wt->cond, &wt->mutex, WORKER_THREAD_WAIT_TIMEOUT_MS); + mongoc_cond_timedwait (&wt->cond, &wt->mutex, WORKER_THREAD_WAIT_TIMEOUT_MS); shutdown = wt->shutdown_requested; op = q_get_nowait (wt->queue); } @@ -118,12 +117,7 @@ static BSON_THREAD_FUN (json_test_worker_thread_run, wt_void) if (op) { bson_t reply; - json_test_operation (wt->ctx, - wt->ctx->config->scenario, - op, - wt->ctx->collection, - NULL /* session */, - &reply); + json_test_operation (wt->ctx, wt->ctx->config->scenario, op, wt->ctx->collection, NULL /* session */, &reply); bson_destroy (op); op = NULL; bson_destroy (&reply); @@ -140,8 +134,7 @@ static void start_thread (json_test_worker_thread_t *wt) { wt->shutdown_requested = false; - int ret = - mcommon_thread_create (&wt->thread, json_test_worker_thread_run, wt); + int ret = mcommon_thread_create (&wt->thread, json_test_worker_thread_run, wt); ASSERT_CMPINT (0, ==, ret); } @@ -196,8 +189,7 @@ json_test_ctx_init (json_test_ctx_t *ctx, bson_init (&ctx->lsids[1]); ctx->sessions[0] = NULL; ctx->sessions[1] = NULL; - ctx->has_sessions = test_framework_session_timeout_minutes () > -1 && - test_framework_skip_if_no_crypto (); + ctx->has_sessions = test_framework_session_timeout_minutes () > -1 && test_framework_skip_if_no_crypto (); /* transactions tests require two sessions named session0 and session1, * retryable writes use one explicit session or none */ @@ -206,16 +198,13 @@ json_test_ctx_init (json_test_ctx_t *ctx, session_name = bson_strdup_printf ("session%d", i); session_opts_path = bson_strdup_printf ("sessionOptions.session%d", i); if (bson_has_field (test, session_opts_path)) { - ctx->sessions[i] = - bson_lookup_session (test, session_opts_path, client); + ctx->sessions[i] = bson_lookup_session (test, session_opts_path, client); } else { - ctx->sessions[i] = - mongoc_client_start_session (client, NULL, &error); + ctx->sessions[i] = mongoc_client_start_session (client, NULL, &error); } ASSERT_OR_PRINT (ctx->sessions[i], error); - bson_concat (&ctx->lsids[i], - mongoc_client_session_get_lsid (ctx->sessions[i])); + bson_concat (&ctx->lsids[i], mongoc_client_session_get_lsid (ctx->sessions[i])); bson_free (session_name); bson_free (session_opts_path); @@ -273,8 +262,7 @@ value_to_str (const bson_value_t *value) { bson_t doc; - if (value->value_type == BSON_TYPE_DOCUMENT || - value->value_type == BSON_TYPE_ARRAY) { + if (value->value_type == BSON_TYPE_DOCUMENT || value->value_type == BSON_TYPE_ARRAY) { bson_init_from_value (&doc, value); return bson_as_json (&doc, NULL); } else { @@ -345,16 +333,13 @@ convert_bulk_write_result (const bson_t *doc, bson_t *r) /* convert from spec result in JSON test to a libmongoc result */ static void -convert_spec_result (const char *op_name, - const bson_value_t *spec_result, - bson_value_t *converted) +convert_spec_result (const char *op_name, const bson_value_t *spec_result, bson_value_t *converted) { bson_t doc; bson_t r; bson_iter_t iter; - if (spec_result->value_type != BSON_TYPE_DOCUMENT && - spec_result->value_type != BSON_TYPE_ARRAY) { + if (spec_result->value_type != BSON_TYPE_DOCUMENT && spec_result->value_type != BSON_TYPE_ARRAY) { bson_value_copy (spec_result, converted); return; } @@ -372,13 +357,10 @@ convert_spec_result (const char *op_name, while (bson_iter_next (&iter)) { if (BSON_ITER_IS_KEY (&iter, "upsertedCount")) { if (bson_iter_as_int64 (&iter) != 0) { - BSON_APPEND_INT64 ( - &r, "upsertedCount", bson_iter_as_int64 (&iter)); + BSON_APPEND_INT64 (&r, "upsertedCount", bson_iter_as_int64 (&iter)); } - } else if (!BSON_ITER_IS_KEY (&iter, "insertedId") && - !BSON_ITER_IS_KEY (&iter, "insertedIds")) { - BSON_APPEND_VALUE ( - &r, bson_iter_key (&iter), bson_iter_value (&iter)); + } else if (!BSON_ITER_IS_KEY (&iter, "insertedId") && !BSON_ITER_IS_KEY (&iter, "insertedIds")) { + BSON_APPEND_VALUE (&r, bson_iter_key (&iter), bson_iter_value (&iter)); } } } @@ -434,16 +416,12 @@ get_result (const bson_t *test, const bson_t *operation, bson_value_t *value) static void -check_success_expected (const bson_t *operation, - bool succeeded, - bool expected, - const bson_error_t *error) +check_success_expected (const bson_t *operation, bool succeeded, bool expected, const bson_error_t *error) { char *json = bson_as_json (operation, NULL); if (!succeeded && expected) { - test_error ( - "Expected success, got error \"%s\":\n%s", error->message, json); + test_error ("Expected success, got error \"%s\":\n%s", error->message, json); } if (succeeded && !expected) { test_error ("Expected error, got success:\n%s", json); @@ -496,10 +474,7 @@ check_error_code_name (const bson_t *operation, const bson_error_t *error) code_name = bson_lookup_utf8 (operation, "errorCodeName"); expected_error_code = error_code_from_name (code_name); if (error->code != expected_error_code) { - test_error ("Expected error code %d : %s but got error code %d\n", - expected_error_code, - code_name, - error->code); + test_error ("Expected error code %d : %s but got error code %d\n", expected_error_code, code_name, error->code); } } @@ -535,8 +510,7 @@ check_error_labels_contain (const bson_t *operation, const bson_value_t *result) BSON_ASSERT (result); BSON_ASSERT (bson_iter_init (&operation_iter, operation)); - BSON_ASSERT (bson_iter_find_descendant ( - &operation_iter, "errorLabelsContain", &expected_labels)); + BSON_ASSERT (bson_iter_find_descendant (&operation_iter, "errorLabelsContain", &expected_labels)); BSON_ASSERT (bson_iter_recurse (&expected_labels, &expected_label)); /* if the test has "errorLabelsContain" then result must be an error reply */ @@ -546,9 +520,7 @@ check_error_labels_contain (const bson_t *operation, const bson_value_t *result) while (bson_iter_next (&expected_label)) { expected_label_str = bson_iter_utf8 (&expected_label, NULL); if (!mongoc_error_has_label (&reply, expected_label_str)) { - test_error ("Expected label \"%s\" not found in %s", - expected_label_str, - bson_as_json (&reply, NULL)); + test_error ("Expected label \"%s\" not found in %s", expected_label_str, bson_as_json (&reply, NULL)); } } } @@ -580,11 +552,9 @@ check_error_labels_omit (const bson_t *operation, const bson_value_t *result) bson_lookup_doc (operation, "errorLabelsOmit", &omitted_labels); BSON_ASSERT (bson_iter_init (&omitted_label, &omitted_labels)); while (bson_iter_next (&omitted_label)) { - if (mongoc_error_has_label (&reply, - bson_iter_utf8 (&omitted_label, NULL))) { - test_error ("Label \"%s\" should have been omitted %s", - bson_iter_utf8 (&omitted_label, NULL), - value_to_str (result)); + if (mongoc_error_has_label (&reply, bson_iter_utf8 (&omitted_label, NULL))) { + test_error ( + "Label \"%s\" should have been omitted %s", bson_iter_utf8 (&omitted_label, NULL), value_to_str (result)); } } } @@ -620,11 +590,8 @@ check_error_labels_omit (const bson_t *operation, const bson_value_t *result) */ void -check_result (const bson_t *test, - const bson_t *operation, - bool succeeded, - const bson_value_t *result, - const bson_error_t *error) +check_result ( + const bson_t *test, const bson_t *operation, bool succeeded, const bson_value_t *result, const bson_error_t *error) { bson_t expected_doc; bson_value_t expected_value; @@ -638,10 +605,8 @@ check_result (const bson_t *test, if (expected_value.value_type == BSON_TYPE_DOCUMENT) { bson_init_from_value (&expected_doc, &expected_value); - if (bson_has_field (&expected_doc, "errorCodeName") || - bson_has_field (&expected_doc, "errorContains") || - bson_has_field (&expected_doc, "errorLabelsContain") || - bson_has_field (&expected_doc, "errorLabelsOmit")) { + if (bson_has_field (&expected_doc, "errorCodeName") || bson_has_field (&expected_doc, "errorContains") || + bson_has_field (&expected_doc, "errorLabelsContain") || bson_has_field (&expected_doc, "errorLabelsOmit")) { /* Expect the operation has failed. Transactions tests specify errors * per-operation, with one or more details: * operations: @@ -671,10 +636,7 @@ check_result (const bson_t *test, * error: true */ - check_success_expected (operation, - succeeded, - !_mongoc_lookup_bool (test, "outcome.error", false), - error); + check_success_expected (operation, succeeded, !_mongoc_lookup_bool (test, "outcome.error", false), error); BSON_ASSERT (result); @@ -696,9 +658,7 @@ check_result (const bson_t *test, static bool -add_request_to_bulk (mongoc_bulk_operation_t *bulk, - const bson_t *request, - bson_error_t *error) +add_request_to_bulk (mongoc_bulk_operation_t *bulk, const bson_t *request, bson_error_t *error) { const char *name; bson_t args; @@ -733,22 +693,19 @@ add_request_to_bulk (mongoc_bulk_operation_t *bulk, bson_lookup_doc (&args, "filter", &filter); - r = mongoc_bulk_operation_remove_many_with_opts ( - bulk, &filter, &opts, error); + r = mongoc_bulk_operation_remove_many_with_opts (bulk, &filter, &opts, error); } else if (!strcmp (name, "deleteOne")) { bson_t filter; bson_lookup_doc (&args, "filter", &filter); - r = mongoc_bulk_operation_remove_one_with_opts ( - bulk, &filter, &opts, error); + r = mongoc_bulk_operation_remove_one_with_opts (bulk, &filter, &opts, error); } else if (!strcmp (name, "insertOne")) { bson_t document; bson_lookup_doc (&args, "document", &document); - r = - mongoc_bulk_operation_insert_with_opts (bulk, &document, &opts, error); + r = mongoc_bulk_operation_insert_with_opts (bulk, &document, &opts, error); } else if (!strcmp (name, "replaceOne")) { bson_t filter; bson_t replacement; @@ -757,12 +714,10 @@ add_request_to_bulk (mongoc_bulk_operation_t *bulk, bson_lookup_doc (&args, "replacement", &replacement); if (bson_has_field (&args, "upsert")) { - BSON_APPEND_BOOL ( - &opts, "upsert", _mongoc_lookup_bool (&args, "upsert", false)); + BSON_APPEND_BOOL (&opts, "upsert", _mongoc_lookup_bool (&args, "upsert", false)); } - r = mongoc_bulk_operation_replace_one_with_opts ( - bulk, &filter, &replacement, &opts, error); + r = mongoc_bulk_operation_replace_one_with_opts (bulk, &filter, &replacement, &opts, error); } else if (!strcmp (name, "updateMany")) { bson_t filter; bson_t update; @@ -771,12 +726,10 @@ add_request_to_bulk (mongoc_bulk_operation_t *bulk, bson_lookup_doc (&args, "update", &update); if (bson_has_field (&args, "upsert")) { - BSON_APPEND_BOOL ( - &opts, "upsert", _mongoc_lookup_bool (&args, "upsert", false)); + BSON_APPEND_BOOL (&opts, "upsert", _mongoc_lookup_bool (&args, "upsert", false)); } - r = mongoc_bulk_operation_update_many_with_opts ( - bulk, &filter, &update, &opts, error); + r = mongoc_bulk_operation_update_many_with_opts (bulk, &filter, &update, &opts, error); } else if (!strcmp (name, "updateOne")) { bson_t filter; bson_t update; @@ -785,12 +738,10 @@ add_request_to_bulk (mongoc_bulk_operation_t *bulk, bson_lookup_doc (&args, "update", &update); if (bson_has_field (&args, "upsert")) { - BSON_APPEND_BOOL ( - &opts, "upsert", _mongoc_lookup_bool (&args, "upsert", false)); + BSON_APPEND_BOOL (&opts, "upsert", _mongoc_lookup_bool (&args, "upsert", false)); } - r = mongoc_bulk_operation_update_one_with_opts ( - bulk, &filter, &update, &opts, error); + r = mongoc_bulk_operation_update_one_with_opts (bulk, &filter, &update, &opts, error); } else { test_error ("unrecognized request name %s", name); } @@ -802,10 +753,7 @@ add_request_to_bulk (mongoc_bulk_operation_t *bulk, static void -execute_bulk_operation (mongoc_bulk_operation_t *bulk, - const bson_t *test, - const bson_t *operation, - bson_t *reply) +execute_bulk_operation (mongoc_bulk_operation_t *bulk, const bson_t *test, const bson_t *operation, bson_t *reply) { uint32_t server_id; bson_error_t error; @@ -819,9 +767,7 @@ execute_bulk_operation (mongoc_bulk_operation_t *bulk, static bson_t * -create_bulk_write_opts (const bson_t *operation, - mongoc_client_session_t *session, - mongoc_write_concern_t *wc) +create_bulk_write_opts (const bson_t *operation, mongoc_client_session_t *session, mongoc_write_concern_t *wc) { bson_t *opts; bson_t tmp; @@ -885,9 +831,7 @@ bulk_write (mongoc_collection_t *collection, } -#define COPY_EXCEPT(...) \ - bson_copy_to_excluding_noinit ( \ - &args, &opts, "session", "readPreference", __VA_ARGS__, NULL) +#define COPY_EXCEPT(...) bson_copy_to_excluding_noinit (&args, &opts, "session", "readPreference", __VA_ARGS__, NULL) static bool @@ -915,44 +859,38 @@ single_write (mongoc_collection_t *collection, bson_t filter; bson_lookup_doc (&args, "filter", &filter); COPY_EXCEPT ("filter"); - r = mongoc_collection_delete_many ( - collection, &filter, &opts, reply, &error); + r = mongoc_collection_delete_many (collection, &filter, &opts, reply, &error); } else if (!strcmp (name, "deleteOne")) { bson_t filter; bson_lookup_doc (&args, "filter", &filter); COPY_EXCEPT ("filter"); - r = mongoc_collection_delete_one ( - collection, &filter, &opts, reply, &error); + r = mongoc_collection_delete_one (collection, &filter, &opts, reply, &error); } else if (!strcmp (name, "insertOne")) { bson_t document; bson_lookup_doc (&args, "document", &document); COPY_EXCEPT ("document"); - r = mongoc_collection_insert_one ( - collection, &document, &opts, reply, &error); + r = mongoc_collection_insert_one (collection, &document, &opts, reply, &error); } else if (!strcmp (name, "replaceOne")) { bson_t filter; bson_t replacement; bson_lookup_doc (&args, "filter", &filter); bson_lookup_doc (&args, "replacement", &replacement); COPY_EXCEPT ("filter", "replacement"); - r = mongoc_collection_replace_one ( - collection, &filter, &replacement, &opts, reply, &error); + r = mongoc_collection_replace_one (collection, &filter, &replacement, &opts, reply, &error); } else if (!strcmp (name, "updateMany")) { bson_t filter; bson_t update; bson_lookup_doc (&args, "filter", &filter); bson_lookup_doc (&args, "update", &update); COPY_EXCEPT ("filter", "update"); - r = mongoc_collection_update_many ( - collection, &filter, &update, &opts, reply, &error); + r = mongoc_collection_update_many (collection, &filter, &update, &opts, reply, &error); } else if (!strcmp (name, "updateOne")) { bson_t filter; bson_t update; bson_lookup_doc (&args, "filter", &filter); bson_lookup_doc (&args, "update", &update); COPY_EXCEPT ("filter", "update"); - r = mongoc_collection_update_one ( - collection, &filter, &update, &opts, reply, &error); + r = mongoc_collection_update_one (collection, &filter, &update, &opts, reply, &error); } else { test_error ("unrecognized request name %s", name); } @@ -1025,8 +963,7 @@ create_find_and_modify_opts (const char *name, bson_value_destroy (&temp); } - if (bson_has_field (args, "returnDocument") && - !strcmp ("After", bson_lookup_utf8 (args, "returnDocument"))) { + if (bson_has_field (args, "returnDocument") && !strcmp ("After", bson_lookup_utf8 (args, "returnDocument"))) { flags |= MONGOC_FIND_AND_MODIFY_RETURN_NEW; } @@ -1070,8 +1007,7 @@ find_and_modify (mongoc_collection_t *collection, opts = create_find_and_modify_opts (name, &args, session, wc); - r = mongoc_collection_find_and_modify_with_opts ( - collection, &filter, opts, reply, &error); + r = mongoc_collection_find_and_modify_with_opts (collection, &filter, opts, reply, &error); /* Transactions Tests have findAndModify results like: @@ -1148,15 +1084,11 @@ insert_many (mongoc_collection_t *collection, * - { _id: 2, x: 22 } * options: { ordered: false } */ - BSON_APPEND_BOOL ( - &opts, - "ordered", - _mongoc_lookup_bool (&args, "options.ordered", true /* default */)); + BSON_APPEND_BOOL (&opts, "ordered", _mongoc_lookup_bool (&args, "options.ordered", true /* default */)); COPY_EXCEPT ("documents", "options"); - r = mongoc_collection_insert_many ( - collection, (const bson_t **) doc_ptrs, n, &opts, reply, &error); + r = mongoc_collection_insert_many (collection, (const bson_t **) doc_ptrs, n, &opts, reply, &error); /* CRUD tests may specify a write result even if an error is expected. * From the CRUD spec test readme: @@ -1272,12 +1204,10 @@ count (mongoc_collection_t *collection, bson_lookup_doc (operation, "arguments.filter", &filter); } if (bson_has_field (operation, "arguments.skip")) { - BSON_APPEND_INT64 ( - &opts, "skip", bson_lookup_int32 (operation, "arguments.skip")); + BSON_APPEND_INT64 (&opts, "skip", bson_lookup_int32 (operation, "arguments.skip")); } if (bson_has_field (operation, "arguments.limit")) { - BSON_APPEND_INT64 ( - &opts, "limit", bson_lookup_int32 (operation, "arguments.limit")); + BSON_APPEND_INT64 (&opts, "limit", bson_lookup_int32 (operation, "arguments.limit")); } if (bson_has_field (operation, "arguments.collation")) { bson_t collation; @@ -1288,21 +1218,12 @@ count (mongoc_collection_t *collection, name = bson_lookup_utf8 (operation, "name"); if (!strcmp (name, "countDocuments")) { - r = mongoc_collection_count_documents ( - collection, &filter, &opts, read_prefs, reply, &error); + r = mongoc_collection_count_documents (collection, &filter, &opts, read_prefs, reply, &error); } else if (!strcmp (name, "estimatedDocumentCount")) { - r = mongoc_collection_estimated_document_count ( - collection, &opts, read_prefs, reply, &error); + r = mongoc_collection_estimated_document_count (collection, &opts, read_prefs, reply, &error); } else if (!strcmp (name, "count")) { /* deprecated old count function */ - r = mongoc_collection_count_with_opts (collection, - MONGOC_QUERY_NONE, - &filter, - 0, - 0, - &opts, - read_prefs, - &error); + r = mongoc_collection_count_with_opts (collection, MONGOC_QUERY_NONE, &filter, 0, 0, &opts, read_prefs, &error); /* fake a reply for the test framework's sake */ bson_init (reply); } else { @@ -1352,8 +1273,7 @@ distinct (mongoc_collection_t *collection, r = mongoc_collection_read_command_with_opts ( collection, - tmp_bson ( - "{'distinct': '%s', 'key': '%s'}", collection->collection, field_name), + tmp_bson ("{'distinct': '%s', 'key': '%s'}", collection->collection, field_name), read_prefs, &opts, reply, @@ -1380,9 +1300,7 @@ distinct (mongoc_collection_t *collection, static void -check_cursor (mongoc_cursor_t *cursor, - const bson_t *test, - const bson_t *operation) +check_cursor (mongoc_cursor_t *cursor, const bson_t *test, const bson_t *operation) { const bson_t *doc; bson_error_t error; @@ -1457,8 +1375,7 @@ find (mongoc_collection_t *collection, bson_lookup_doc (&args, "modifiers", &modifiers); bson_concat (query, &modifiers); - r = _mongoc_cursor_translate_dollar_query_opts ( - query, &opts, &unwrapped, &error); + r = _mongoc_cursor_translate_dollar_query_opts (query, &opts, &unwrapped, &error); ASSERT_OR_PRINT (r, error); bson_destroy (&unwrapped); } @@ -1466,8 +1383,7 @@ find (mongoc_collection_t *collection, COPY_EXCEPT ("filter", "modifiers"); append_session (session, &opts); - cursor = - mongoc_collection_find_with_opts (collection, &filter, &opts, read_prefs); + cursor = mongoc_collection_find_with_opts (collection, &filter, &opts, read_prefs); check_cursor (cursor, test, operation); mongoc_cursor_destroy (cursor); @@ -1497,8 +1413,7 @@ find_one (mongoc_collection_t *collection, bson_lookup_doc (operation, "arguments.filter", &filter); - cursor = - mongoc_collection_find_with_opts (collection, &filter, &opts, read_prefs); + cursor = mongoc_collection_find_with_opts (collection, &filter, &opts, read_prefs); if (mongoc_cursor_next (cursor, &doc)) { value_init_from_doc (&value, doc); @@ -1526,8 +1441,7 @@ _is_aggregate_out (const bson_t *pipeline) ASSERT (bson_iter_init (&iter, pipeline)); while (bson_iter_next (&iter)) { - if (BSON_ITER_HOLDS_DOCUMENT (&iter) && - bson_iter_recurse (&iter, &stage)) { + if (BSON_ITER_HOLDS_DOCUMENT (&iter) && bson_iter_recurse (&iter, &stage)) { if (bson_iter_find (&stage, "$out")) { return true; } @@ -1559,8 +1473,7 @@ aggregate (mongoc_collection_t *collection, append_session (session, &opts); COPY_EXCEPT ("pipeline"); - cursor = mongoc_collection_aggregate ( - collection, MONGOC_QUERY_NONE, &pipeline, &opts, read_prefs); + cursor = mongoc_collection_aggregate (collection, MONGOC_QUERY_NONE, &pipeline, &opts, read_prefs); /* Driver CRUD API Spec: "$out is a special pipeline stage that causes no * results to be returned from the server. As such, the iterable here would @@ -1674,8 +1587,7 @@ command (mongoc_database_t *db, COPY_EXCEPT ("command"); append_session (session, &opts); - r = mongoc_database_command_with_opts ( - db, &cmd, read_prefs, &opts, reply, &error); + r = mongoc_database_command_with_opts (db, &cmd, read_prefs, &opts, reply, &error); value_init_from_doc (&value, reply); check_result (test, operation, r, &value, &error); @@ -1688,10 +1600,7 @@ command (mongoc_database_t *db, static bool -start_transaction (mongoc_client_session_t *session, - const bson_t *test, - const bson_t *operation, - bson_t *reply) +start_transaction (mongoc_client_session_t *session, const bson_t *test, const bson_t *operation, bson_t *reply) { mongoc_transaction_opt_t *opts = NULL; bson_error_t error; @@ -1716,10 +1625,7 @@ start_transaction (mongoc_client_session_t *session, static bool -commit_transaction (mongoc_client_session_t *session, - const bson_t *test, - const bson_t *operation, - bson_t *reply) +commit_transaction (mongoc_client_session_t *session, const bson_t *test, const bson_t *operation, bson_t *reply) { bson_value_t value; bson_error_t error; @@ -1735,10 +1641,7 @@ commit_transaction (mongoc_client_session_t *session, static bool -abort_transaction (mongoc_client_session_t *session, - const bson_t *test, - const bson_t *operation, - bson_t *reply) +abort_transaction (mongoc_client_session_t *session, const bson_t *test, const bson_t *operation, bson_t *reply) { bson_value_t value; bson_error_t error; @@ -1794,12 +1697,10 @@ list_database_names (mongoc_client_t *client, bson_init (&opts); append_session (session, &opts); - database_names = - mongoc_client_get_database_names_with_opts (client, &opts, &error); + database_names = mongoc_client_get_database_names_with_opts (client, &opts, &error); bson_destroy (&opts); - check_result ( - test, operation, database_names != NULL, NULL /* result */, &error); + check_result (test, operation, database_names != NULL, NULL /* result */, &error); bson_init (reply); bson_strfreev (database_names); return true; @@ -1831,11 +1732,8 @@ list_indexes (mongoc_collection_t *collection, static bool -list_collections (mongoc_database_t *db, - const bson_t *test, - const bson_t *operation, - mongoc_client_session_t *session, - bson_t *reply) +list_collections ( + mongoc_database_t *db, const bson_t *test, const bson_t *operation, mongoc_client_session_t *session, bson_t *reply) { mongoc_cursor_t *cursor; bson_t opts; @@ -1855,11 +1753,8 @@ list_collections (mongoc_database_t *db, } static bool -list_collection_names (mongoc_database_t *db, - const bson_t *test, - const bson_t *operation, - mongoc_client_session_t *session, - bson_t *reply) +list_collection_names ( + mongoc_database_t *db, const bson_t *test, const bson_t *operation, mongoc_client_session_t *session, bson_t *reply) { char **collection_names; bson_t opts; @@ -1868,13 +1763,11 @@ list_collection_names (mongoc_database_t *db, bson_init (&opts); append_session (session, &opts); - collection_names = - mongoc_database_get_collection_names_with_opts (db, &opts, &error); + collection_names = mongoc_database_get_collection_names_with_opts (db, &opts, &error); bson_destroy (&opts); - check_result ( - test, operation, collection_names != NULL, NULL /* result */, &error); + check_result (test, operation, collection_names != NULL, NULL /* result */, &error); bson_init (reply); bson_strfreev (collection_names); @@ -1917,11 +1810,8 @@ gridfs_download (mongoc_database_t *db, static bool -create_collection (mongoc_database_t *db, - const bson_t *test, - const bson_t *operation, - mongoc_client_session_t *session, - bson_t *reply) +create_collection ( + mongoc_database_t *db, const bson_t *test, const bson_t *operation, mongoc_client_session_t *session, bson_t *reply) { bson_t args; bson_t opts = BSON_INITIALIZER; @@ -1940,8 +1830,7 @@ create_collection (mongoc_database_t *db, collection_name = bson_lookup_utf8 (&args, "collection"); COPY_EXCEPT ("collection"); - collection = - mongoc_database_create_collection (db, collection_name, &opts, &error); + collection = mongoc_database_create_collection (db, collection_name, &opts, &error); bson_destroy (&opts); @@ -1956,11 +1845,8 @@ create_collection (mongoc_database_t *db, static bool -drop_collection (mongoc_database_t *db, - const bson_t *test, - const bson_t *operation, - mongoc_client_session_t *session, - bson_t *reply) +drop_collection ( + mongoc_database_t *db, const bson_t *test, const bson_t *operation, mongoc_client_session_t *session, bson_t *reply) { bson_t args; bson_t opts = BSON_INITIALIZER; @@ -2019,10 +1905,8 @@ create_index (mongoc_collection_t *collection, name = bson_lookup_utf8 (&args, "name"); COPY_EXCEPT ("keys", "name"); - mongoc_index_model_t *im = - mongoc_index_model_new (&keys, tmp_bson ("{'name': '%s'}", name)); - r = mongoc_collection_create_indexes_with_opts ( - collection, &im, 1, &opts, NULL /* reply */, &error); + mongoc_index_model_t *im = mongoc_index_model_new (&keys, tmp_bson ("{'name': '%s'}", name)); + r = mongoc_collection_create_indexes_with_opts (collection, &im, 1, &opts, NULL /* reply */, &error); mongoc_index_model_destroy (im); bson_destroy (&opts); @@ -2055,9 +1939,7 @@ collection_exists (mongoc_client_t *client, const bson_t *operation) names = mongoc_database_get_collection_names_with_opts (db, NULL, &error); if (!names) { - test_error ("expected error checking if collection '%s' exists: %s", - collection_name, - error.message); + test_error ("expected error checking if collection '%s' exists: %s", collection_name, error.message); } for (i = 0; names && names[i] != NULL; i++) { @@ -2093,14 +1975,12 @@ index_exists (mongoc_client_t *client, const bson_t *operation) collection_name = bson_lookup_utf8 (&args, "collection"); index_name = bson_lookup_utf8 (&args, "index"); - collection = - mongoc_client_get_collection (client, database_name, collection_name); + collection = mongoc_client_get_collection (client, database_name, collection_name); indexes = mongoc_collection_find_indexes_with_opts (collection, NULL); while (mongoc_cursor_next (indexes, &doc)) { - if (bson_iter_init (&index, doc) && bson_iter_find (&index, "name") && - BSON_ITER_HOLDS_UTF8 (&index) && + if (bson_iter_init (&index, doc) && bson_iter_find (&index, "name") && BSON_ITER_HOLDS_UTF8 (&index) && !strcmp (bson_iter_utf8 (&index, NULL), index_name)) { found = true; } @@ -2139,11 +2019,9 @@ wait_for_event (json_test_ctx_t *ctx, const bson_t *operation) int64_t measured = 0; int64_t total = 0; - const char *const event_name = - bson_lookup_utf8 (operation, "arguments.event"); + const char *const event_name = bson_lookup_utf8 (operation, "arguments.event"); const int32_t count = bson_lookup_int32 (operation, "arguments.count"); - const int64_t expires_us = - bson_get_monotonic_time () + WAIT_FOR_EVENT_TIMEOUT_MS * 1000; + const int64_t expires_us = bson_get_monotonic_time () + WAIT_FOR_EVENT_TIMEOUT_MS * 1000; while (!satisfied && bson_get_monotonic_time () < expires_us) { if (0 == strcmp (event_name, "ServerMarkedUnknownEvent")) { @@ -2179,9 +2057,8 @@ wait_for_event (json_test_ctx_t *ctx, const bson_t *operation) } if (!satisfied) { - test_error ("did not see enough %s events after 10s. %" PRId64 - " total occurred. %" PRId64 " accounted for. But %" PRId32 - " more expected", + test_error ("did not see enough %s events after 10s. %" PRId64 " total occurred. %" PRId64 + " accounted for. But %" PRId32 " more expected", event_name, total, measured, @@ -2196,8 +2073,7 @@ wait_for_primary_change (json_test_ctx_t *ctx, const bson_t *operation) int64_t measured = 0; int64_t total = 0; - const int32_t timeout_ms = - bson_lookup_int32 (operation, "arguments.timeoutMS"); + const int32_t timeout_ms = bson_lookup_int32 (operation, "arguments.timeoutMS"); const int64_t expires_us = bson_get_monotonic_time () + timeout_ms * 1000; while (!satisfied && bson_get_monotonic_time () < expires_us) { @@ -2219,8 +2095,7 @@ wait_for_primary_change (json_test_ctx_t *ctx, const bson_t *operation) } if (!satisfied) { - test_error ("did not see any primary change events after %" PRId32 - "ms. %" PRId64 " total occurred. " + test_error ("did not see any primary change events after %" PRId32 "ms. %" PRId64 " total occurred. " "%" PRId64 " accounted for.", timeout_ms, total, @@ -2233,8 +2108,7 @@ assert_event_count (json_test_ctx_t *ctx, const bson_t *operation) { int64_t total = 0; - const char *const event_name = - bson_lookup_utf8 (operation, "arguments.event"); + const char *const event_name = bson_lookup_utf8 (operation, "arguments.event"); const int32_t count = bson_lookup_int32 (operation, "arguments.count"); if (0 == strcmp (event_name, "ServerMarkedUnknownEvent")) { @@ -2246,11 +2120,7 @@ assert_event_count (json_test_ctx_t *ctx, const bson_t *operation) } if (count != total) { - test_error ("event count %s mismatched. Expected %" PRId32 - ", but have %" PRId64, - event_name, - count, - total); + test_error ("event count %s mismatched. Expected %" PRId32 ", but have %" PRId64, event_name, count, total); } } @@ -2260,52 +2130,41 @@ assert_session_transaction_state (json_test_ctx_t *ctx, const bson_t *operation) const char *expected_state; const mongoc_client_session_t *session; mongoc_transaction_state_t state; - char *state_strings[] = { - "none", "starting", "in progress", "committed", "aborted"}; + char *state_strings[] = {"none", "starting", "in progress", "committed", "aborted"}; expected_state = bson_lookup_utf8 (operation, "arguments.state"); - session = session_from_name ( - ctx, bson_lookup_utf8 (operation, "arguments.session")); + session = session_from_name (ctx, bson_lookup_utf8 (operation, "arguments.session")); state = mongoc_client_session_get_transaction_state (session); if (!strcmp (expected_state, "none")) { if (state != MONGOC_TRANSACTION_NONE) { - test_error ("expected session transaction state none, but have %s", - state_strings[state]); + test_error ("expected session transaction state none, but have %s", state_strings[state]); } } else if (!strcmp (expected_state, "starting")) { if (state != MONGOC_TRANSACTION_STARTING) { - test_error ("expected session transaction state starting, but have %s", - state_strings[state]); + test_error ("expected session transaction state starting, but have %s", state_strings[state]); } } else if (!strcmp (expected_state, "in_progress")) { if (state != MONGOC_TRANSACTION_IN_PROGRESS) { - test_error ( - "expected session transaction state in progress, but have %s", - state_strings[state]); + test_error ("expected session transaction state in progress, but have %s", state_strings[state]); } } else if (!strcmp (expected_state, "committed")) { if (state != MONGOC_TRANSACTION_COMMITTED) { - test_error ( - "expected session transaction state committed, but have %s", - state_strings[state]); + test_error ("expected session transaction state committed, but have %s", state_strings[state]); } } else if (!strcmp (expected_state, "aborted")) { if (state != MONGOC_TRANSACTION_ABORTED) { - test_error ("expected session transaction state aborted, but have %s", - state_strings[state]); + test_error ("expected session transaction state aborted, but have %s", state_strings[state]); } } else { - test_error ("unrecognized state %s for assertSessionTransactionState", - expected_state); + test_error ("unrecognized state %s for assertSessionTransactionState", expected_state); } } static bool op_error (const bson_t *operation) { - return bson_has_field (operation, "error") && - bson_lookup_bool (operation, "error"); + return bson_has_field (operation, "error") && bson_lookup_bool (operation, "error"); } bool @@ -2343,8 +2202,7 @@ json_test_operation (json_test_ctx_t *ctx, read_prefs = bson_lookup_read_prefs (operation, "read_preference"); } else if (bson_has_field (operation, "arguments.readPreference")) { /* transactions tests */ - read_prefs = - bson_lookup_read_prefs (operation, "arguments.readPreference"); + read_prefs = bson_lookup_read_prefs (operation, "arguments.readPreference"); } if (bson_has_field (operation, "arguments.writeConcern")) { @@ -2356,15 +2214,10 @@ json_test_operation (json_test_ctx_t *ctx, if (!strcmp (obj_name, "collection")) { if (!strcmp (op_name, "bulkWrite")) { res = bulk_write (c, test, operation, session, wc, reply); - } else if (!strcmp (op_name, "deleteOne") || - !strcmp (op_name, "deleteMany") || - !strcmp (op_name, "insertOne") || - !strcmp (op_name, "replaceOne") || - !strcmp (op_name, "updateOne") || - !strcmp (op_name, "updateMany")) { + } else if (!strcmp (op_name, "deleteOne") || !strcmp (op_name, "deleteMany") || !strcmp (op_name, "insertOne") || + !strcmp (op_name, "replaceOne") || !strcmp (op_name, "updateOne") || !strcmp (op_name, "updateMany")) { res = single_write (c, test, operation, session, wc, reply); - } else if (!strcmp (op_name, "findOneAndDelete") || - !strcmp (op_name, "findOneAndReplace") || + } else if (!strcmp (op_name, "findOneAndDelete") || !strcmp (op_name, "findOneAndReplace") || !strcmp (op_name, "findOneAndUpdate")) { res = find_and_modify (c, test, operation, session, wc, reply); } else if (!strcmp (op_name, "insertMany")) { @@ -2387,8 +2240,7 @@ json_test_operation (json_test_ctx_t *ctx, res = find_one (c, test, operation, session, read_prefs, reply); } else if (!strcmp (op_name, "aggregate")) { res = aggregate (c, test, operation, session, read_prefs, reply); - } else if (!strcmp (op_name, "listIndexes") || - !strcmp (op_name, "listIndexNames")) { + } else if (!strcmp (op_name, "listIndexes") || !strcmp (op_name, "listIndexNames")) { res = list_indexes (c, test, operation, session, reply); } else if (!strcmp (op_name, "watch")) { bson_t pipeline = BSON_INITIALIZER; @@ -2442,8 +2294,7 @@ json_test_operation (json_test_ctx_t *ctx, test_error ("unrecognized database operation name %s", op_name); } } else if (!strncmp (obj_name, "session", 7)) { - mongoc_client_session_t *named_session = - session_from_name (ctx, obj_name); + mongoc_client_session_t *named_session = session_from_name (ctx, obj_name); if (!strcmp (op_name, "startTransaction")) { res = start_transaction (named_session, test, operation, reply); @@ -2477,8 +2328,7 @@ json_test_operation (json_test_ctx_t *ctx, client = test_framework_client_new_from_uri (ctx->client->uri, NULL); test_framework_set_ssl_opts (client); - activate_fail_point ( - client, session->server_id, operation, "arguments.failPoint"); + activate_fail_point (client, session->server_id, operation, "arguments.failPoint"); mongoc_client_destroy (client); } else if (!strcmp (op_name, "assertSessionNotDirty")) { @@ -2546,8 +2396,7 @@ json_test_operation (json_test_ctx_t *ctx, client = test_framework_client_new_from_uri (ctx->client->uri, NULL); test_framework_set_ssl_opts (client); - activate_fail_point ( - client, 0 /* primary */, operation, "arguments.failPoint"); + activate_fail_point (client, 0 /* primary */, operation, "arguments.failPoint"); mongoc_client_destroy (client); } else if (!strcmp (op_name, "wait")) { @@ -2578,22 +2427,19 @@ json_test_operation (json_test_ctx_t *ctx, } else if (!strcmp (op_name, "startThread")) { json_test_worker_thread_t *wt; - wt = thread_from_name (ctx, - bson_lookup_utf8 (operation, "arguments.name")); + wt = thread_from_name (ctx, bson_lookup_utf8 (operation, "arguments.name")); start_thread (wt); } else if (!strcmp (op_name, "waitForThread")) { json_test_worker_thread_t *wt; - wt = thread_from_name (ctx, - bson_lookup_utf8 (operation, "arguments.name")); + wt = thread_from_name (ctx, bson_lookup_utf8 (operation, "arguments.name")); wait_for_thread (wt); } else if (!strcmp (op_name, "runOnThread")) { json_test_worker_thread_t *wt; bson_t op; bson_lookup_doc (operation, "arguments.operation", &op); - wt = thread_from_name (ctx, - bson_lookup_utf8 (operation, "arguments.name")); + wt = thread_from_name (ctx, bson_lookup_utf8 (operation, "arguments.name")); run_on_thread (wt, &op); } else if (!strcmp (op_name, "assertSessionTransactionState")) { assert_session_transaction_state (ctx, operation); @@ -2625,8 +2471,7 @@ json_test_operation (json_test_ctx_t *ctx, } } else if (!strcmp (obj_name, "gridfsbucket")) { if (!strcmp (op_name, "download")) { - res = - gridfs_download (db, test, operation, session, read_prefs, reply); + res = gridfs_download (db, test, operation, session, read_prefs, reply); } else if (!strcmp (op_name, "download_by_name")) { test_error ("download_by_name is part of the optional advanced API " "and not implemented in libmongoc"); @@ -2647,9 +2492,7 @@ json_test_operation (json_test_ctx_t *ctx, static void -one_operation (json_test_ctx_t *ctx, - const bson_t *test, - const bson_t *operation) +one_operation (json_test_ctx_t *ctx, const bson_t *test, const bson_t *operation) { const char *op_name; mongoc_write_concern_t *wc = NULL; @@ -2666,8 +2509,7 @@ one_operation (json_test_ctx_t *ctx, if (bson_has_field (operation, "arguments.writeConcern")) { wc = bson_lookup_write_concern (operation, "arguments.writeConcern"); } else if (bson_has_field (operation, "collectionOptions.writeConcern")) { - wc = bson_lookup_write_concern (operation, - "collectionOptions.writeConcern"); + wc = bson_lookup_write_concern (operation, "collectionOptions.writeConcern"); } if (wc) { diff --git a/src/libmongoc/tests/json-test-operations.h b/src/libmongoc/tests/json-test-operations.h index 4e1ab61589..3c6b4b4e9e 100644 --- a/src/libmongoc/tests/json-test-operations.h +++ b/src/libmongoc/tests/json-test-operations.h @@ -83,9 +83,7 @@ json_test_ctx_end_sessions (json_test_ctx_t *ctx); void json_test_ctx_cleanup (json_test_ctx_t *ctx); -typedef bool (*json_test_operation_cb_t) (json_test_ctx_t *ctx, - const bson_t *test, - const bson_t *operation); +typedef bool (*json_test_operation_cb_t) (json_test_ctx_t *ctx, const bson_t *test, const bson_t *operation); typedef void (*json_test_cb_t) (json_test_ctx_t *ctx, const bson_t *test); @@ -101,11 +99,8 @@ void json_test_operations (json_test_ctx_t *ctx, const bson_t *test); void -check_result (const bson_t *test, - const bson_t *operation, - bool succeeded, - const bson_value_t *result, - const bson_error_t *error); +check_result ( + const bson_t *test, const bson_t *operation, bool succeeded, const bson_value_t *result, const bson_error_t *error); json_test_worker_thread_t * worker_thread_new (json_test_ctx_t *ctx); diff --git a/src/libmongoc/tests/json-test.c b/src/libmongoc/tests/json-test.c index 497f819560..b69c288919 100644 --- a/src/libmongoc/tests/json-test.c +++ b/src/libmongoc/tests/json-test.c @@ -135,15 +135,13 @@ optype_from_test (const char *op) *----------------------------------------------------------------------- */ const mongoc_server_description_t * -server_description_by_hostname (const mongoc_topology_description_t *topology, - const char *address) +server_description_by_hostname (const mongoc_topology_description_t *topology, const char *address) { const mongoc_set_t *set = mc_tpld_servers_const (topology); const mongoc_server_description_t *server_iter; for (size_t i = 0; i < set->items_len; i++) { - server_iter = - mongoc_set_get_item_const (mc_tpld_servers_const (topology), i); + server_iter = mongoc_set_get_item_const (mc_tpld_servers_const (topology), i); if (strcasecmp (address, server_iter->connection_address) == 0) { return server_iter; @@ -221,18 +219,14 @@ process_sdam_test_hello_responses (bson_t *phase, mongoc_topology_t *topology) /* send hello through the topology description's handler */ capture_logs (true); - mongoc_topology_description_handle_hello ( - tdmod.new_td, sd->id, &response, 1, NULL); + mongoc_topology_description_handle_hello (tdmod.new_td, sd->id, &response, 1, NULL); if (mc_tpld_servers_const (tdmod.new_td)->items_len == 0) { - ASSERT_CAPTURED_LOG ("topology", - MONGOC_LOG_LEVEL_WARNING, - "Last server removed from topology"); + ASSERT_CAPTURED_LOG ("topology", MONGOC_LOG_LEVEL_WARNING, "Last server removed from topology"); } capture_logs (false); mc_tpld_modify_commit (tdmod); } - } else if (bson_iter_init_find ( - &phase_field_iter, phase, "applicationErrors")) { + } else if (bson_iter_init_find (&phase_field_iter, phase, "applicationErrors")) { bson_t app_errors; bson_iter_t app_error_iter; bson_t app_error; @@ -266,8 +260,7 @@ process_sdam_test_hello_responses (bson_t *phase, mongoc_topology_t *topology) continue; } - if (bson_iter_init_find ( - &app_error_field_iter, &app_error, "generation")) { + if (bson_iter_init_find (&app_error_field_iter, &app_error, "generation")) { BSON_ASSERT (BSON_ITER_HOLDS_INT32 (&app_error_field_iter)); generation = bson_iter_int32 (&app_error_field_iter); } else { @@ -275,13 +268,11 @@ process_sdam_test_hello_responses (bson_t *phase, mongoc_topology_t *topology) generation = mc_tpl_sd_get_generation (sd, &kZeroServiceId); } - BSON_ASSERT (bson_iter_init_find ( - &app_error_field_iter, &app_error, "maxWireVersion")); + BSON_ASSERT (bson_iter_init_find (&app_error_field_iter, &app_error, "maxWireVersion")); BSON_ASSERT (BSON_ITER_HOLDS_INT32 (&app_error_field_iter)); max_wire_version = bson_iter_int32 (&app_error_field_iter); - BSON_ASSERT ( - bson_iter_init_find (&app_error_field_iter, &app_error, "when")); + BSON_ASSERT (bson_iter_init_find (&app_error_field_iter, &app_error, "when")); BSON_ASSERT (BSON_ITER_HOLDS_UTF8 (&app_error_field_iter)); when_str = bson_iter_utf8 (&app_error_field_iter, 0); if (0 == strcmp (when_str, "beforeHandshakeCompletes")) { @@ -292,8 +283,7 @@ process_sdam_test_hello_responses (bson_t *phase, mongoc_topology_t *topology) test_error ("unexpected 'when' value: %s", when_str); } - BSON_ASSERT ( - bson_iter_init_find (&app_error_field_iter, &app_error, "type")); + BSON_ASSERT (bson_iter_init_find (&app_error_field_iter, &app_error, "type")); BSON_ASSERT (BSON_ITER_HOLDS_UTF8 (&app_error_field_iter)); type_str = bson_iter_utf8 (&app_error_field_iter, 0); if (0 == strcmp (type_str, "command")) { @@ -307,22 +297,14 @@ process_sdam_test_hello_responses (bson_t *phase, mongoc_topology_t *topology) } if (MONGOC_SDAM_APP_ERROR_COMMAND == type) { - BSON_ASSERT (bson_iter_init_find ( - &app_error_field_iter, &app_error, "response")); + BSON_ASSERT (bson_iter_init_find (&app_error_field_iter, &app_error, "response")); BSON_ASSERT (BSON_ITER_HOLDS_DOCUMENT (&app_error_field_iter)); bson_iter_bson (&app_error_field_iter, &response); } memset (&err, 0, sizeof (bson_error_t)); - _mongoc_topology_handle_app_error (topology, - sd->id, - handshake_complete, - type, - &response, - &err, - max_wire_version, - generation, - &kZeroServiceId); + _mongoc_topology_handle_app_error ( + topology, sd->id, handshake_complete, type, &response, &err, max_wire_version, generation, &kZeroServiceId); mc_tpld_drop_ref (&td); } } @@ -368,13 +350,11 @@ test_server_selection_logic_cb (bson_t *test) bool matched_servers[50]; mongoc_array_t selected_servers; - _mongoc_array_init (&selected_servers, - sizeof (mongoc_server_description_t *)); + _mongoc_array_init (&selected_servers, sizeof (mongoc_server_description_t *)); BSON_ASSERT (test); - expected_error = - bson_iter_init_find (&iter, test, "error") && bson_iter_as_bool (&iter); + expected_error = bson_iter_init_find (&iter, test, "error") && bson_iter_as_bool (&iter); heartbeat_msec = MONGOC_TOPOLOGY_HEARTBEAT_FREQUENCY_MS_SINGLE_THREADED; @@ -390,12 +370,10 @@ test_server_selection_logic_cb (bson_t *test) BSON_ASSERT (bson_iter_init_find (&topology_iter, &test_topology, "type")); mongoc_topology_description_init (&topology, heartbeat_msec); - topology.type = - topology_type_from_test (bson_iter_utf8 (&topology_iter, NULL)); + topology.type = topology_type_from_test (bson_iter_utf8 (&topology_iter, NULL)); /* for each server description in test, add server to our topology */ - BSON_ASSERT ( - bson_iter_init_find (&topology_iter, &test_topology, "servers")); + BSON_ASSERT (bson_iter_init_find (&topology_iter, &test_topology, "servers")); bson_iter_bson (&topology_iter, &test_servers); bson_iter_init (&server_iter, &test_servers); @@ -425,10 +403,8 @@ test_server_selection_logic_cb (bson_t *test) } if (bson_iter_init_find (&sd_iter, &server, "lastWrite")) { - BSON_ASSERT (BSON_ITER_HOLDS_DOCUMENT (&sd_iter) && - bson_iter_recurse (&sd_iter, &last_write_iter) && - bson_iter_find (&last_write_iter, "lastWriteDate") && - BSON_ITER_HOLDS_INT (&last_write_iter)); + BSON_ASSERT (BSON_ITER_HOLDS_DOCUMENT (&sd_iter) && bson_iter_recurse (&sd_iter, &last_write_iter) && + bson_iter_find (&last_write_iter, "lastWriteDate") && BSON_ITER_HOLDS_INT (&last_write_iter)); sd->last_write_date_ms = bson_iter_as_int64 (&last_write_iter); } @@ -456,8 +432,7 @@ test_server_selection_logic_cb (bson_t *test) if (bson_iter_init_find (&read_pref_iter, &test_read_pref, "tag_sets")) { /* ignore "tag_sets: [{}]" */ - if (bson_iter_recurse (&read_pref_iter, &tag_sets_iter) && - bson_iter_next (&tag_sets_iter) && + if (bson_iter_recurse (&read_pref_iter, &tag_sets_iter) && bson_iter_next (&tag_sets_iter) && BSON_ITER_HOLDS_DOCUMENT (&tag_sets_iter)) { bson_iter_bson (&tag_sets_iter, &first_tag_set); if (!bson_empty (&first_tag_set)) { @@ -468,10 +443,8 @@ test_server_selection_logic_cb (bson_t *test) } } - if (bson_iter_init_find ( - &read_pref_iter, &test_read_pref, "maxStalenessSeconds")) { - mongoc_read_prefs_set_max_staleness_seconds ( - read_prefs, bson_iter_as_int64 (&read_pref_iter)); + if (bson_iter_init_find (&read_pref_iter, &test_read_pref, "maxStalenessSeconds")) { + mongoc_read_prefs_set_max_staleness_seconds (read_prefs, bson_iter_as_int64 (&read_pref_iter)); } /* get operation type */ @@ -496,13 +469,7 @@ test_server_selection_logic_cb (bson_t *test) /* TODO: use topology_select instead? */ mongoc_topology_description_suitable_servers ( - &selected_servers, - op, - &topology, - read_prefs, - NULL, - NULL, - MONGOC_TOPOLOGY_LOCAL_THRESHOLD_MS); + &selected_servers, op, &topology, read_prefs, NULL, NULL, MONGOC_TOPOLOGY_LOCAL_THRESHOLD_MS); /* check each server in expected_servers is in selected_servers */ memset (matched_servers, 0, sizeof (matched_servers)); @@ -515,19 +482,16 @@ test_server_selection_logic_cb (bson_t *test) BSON_ASSERT (bson_iter_find (&host, "address")); for (i = 0; i < selected_servers.len; i++) { - sd = _mongoc_array_index ( - &selected_servers, mongoc_server_description_t *, i); + sd = _mongoc_array_index (&selected_servers, mongoc_server_description_t *, i); - if (strcmp (sd->host.host_and_port, bson_iter_utf8 (&host, NULL)) == - 0) { + if (strcmp (sd->host.host_and_port, bson_iter_utf8 (&host, NULL)) == 0) { found = true; break; } } if (!found) { - test_error ("Should have been selected but wasn't: %s", - bson_iter_utf8 (&host, NULL)); + test_error ("Should have been selected but wasn't: %s", bson_iter_utf8 (&host, NULL)); } matched_servers[i] = true; @@ -536,11 +500,9 @@ test_server_selection_logic_cb (bson_t *test) /* check each server in selected_servers is in expected_servers */ for (i = 0; i < selected_servers.len; i++) { if (!matched_servers[i]) { - sd = _mongoc_array_index ( - &selected_servers, mongoc_server_description_t *, i); + sd = _mongoc_array_index (&selected_servers, mongoc_server_description_t *, i); - test_error ("Shouldn't have been selected but was: %s", - sd->host.host_and_port); + test_error ("Shouldn't have been selected but was: %s", sd->host.host_and_port); } } @@ -563,9 +525,7 @@ test_server_selection_logic_cb (bson_t *test) *----------------------------------------------------------------------- */ void -assemble_path (const char *parent_path, - const char *child_name, - char *dst /* OUT */) +assemble_path (const char *parent_path, const char *child_name, char *dst /* OUT */) { char *p; int path_len = (int) strlen (parent_path); @@ -624,8 +584,7 @@ collect_tests_from_dir (char (*paths)[MAX_TEST_NAME_LENGTH] /* OUT */, /* recursively call on child directories */ if (strcmp (info.name, "..") != 0 && strcmp (info.name, ".") != 0) { assemble_path (dir_path, info.name, child_path); - paths_index = collect_tests_from_dir ( - paths, child_path, paths_index, max_paths); + paths_index = collect_tests_from_dir (paths, child_path, paths_index, max_paths); } } else if (strstr (info.name, ".json")) { /* if this is a JSON test, collect its path */ @@ -656,8 +615,7 @@ collect_tests_from_dir (char (*paths)[MAX_TEST_NAME_LENGTH] /* OUT */, while ((entry = readdir (dir))) { BSON_ASSERT (paths_index < max_paths); - if (strcmp (entry->d_name, "..") == 0 || - strcmp (entry->d_name, ".") == 0) { + if (strcmp (entry->d_name, "..") == 0 || strcmp (entry->d_name, ".") == 0) { continue; } @@ -665,8 +623,7 @@ collect_tests_from_dir (char (*paths)[MAX_TEST_NAME_LENGTH] /* OUT */, if (0 == stat (child_path, &dir_stat) && S_ISDIR (dir_stat.st_mode)) { /* recursively call on child directories */ - paths_index = - collect_tests_from_dir (paths, child_path, paths_index, max_paths); + paths_index = collect_tests_from_dir (paths, child_path, paths_index, max_paths); } else if (strstr (entry->d_name, ".json")) { /* if this is a JSON test, collect its path */ assemble_path (dir_path, entry->d_name, paths[paths_index++]); @@ -809,8 +766,7 @@ check_version_info (const bson_t *scenario, bool print_reason) /* If we didn't match any of the listed topologies, skip */ if (print_reason && test_suite_debug_output ()) { - printf (" SKIP, test topologies do not match current %s setup\n", - current_topology); + printf (" SKIP, test topologies do not match current %s setup\n", current_topology); fflush (stdout); } @@ -893,8 +849,7 @@ check_test_version (const bson_t *test) server_version = test_framework_get_server_version (); if (server_version > test_version) { if (test_suite_debug_output ()) { - printf (" SKIP, ignore_if_server_version_greater_than %s\n", - s); + printf (" SKIP, ignore_if_server_version_greater_than %s\n", s); fflush (stdout); } return false; @@ -983,9 +938,7 @@ check_topology_type (const bson_t *test) * https://github.com/mongodb/specifications/tree/d68e85c33c5a3b02bcd8a32a0bec9f11471e41ad/source/client-side-encryption/tests#spec-test-format */ static void -_recreate (const char *db_name, - const char *collection_name, - const bson_t *scenario) +_recreate (const char *db_name, const char *collection_name, const bson_t *scenario) { mongoc_client_t *client; mongoc_collection_t *collection; @@ -1007,8 +960,7 @@ _recreate (const char *db_name, bson_t encrypted_fields; bson_iter_bson (&iter, &encrypted_fields); - BCON_APPEND ( - drop_opts, "encryptedFields", BCON_DOCUMENT (&encrypted_fields)); + BCON_APPEND (drop_opts, "encryptedFields", BCON_DOCUMENT (&encrypted_fields)); } if (!mongoc_collection_drop_with_opts (collection, drop_opts, &error)) { /* Ignore "namespace does not exist" error. */ @@ -1024,12 +976,7 @@ _recreate (const char *db_name, bson_t json_schema; bson_iter_bson (&iter, &json_schema); - BCON_APPEND (opts, - "validator", - "{", - "$jsonSchema", - BCON_DOCUMENT (&json_schema), - "}"); + BCON_APPEND (opts, "validator", "{", "$jsonSchema", BCON_DOCUMENT (&json_schema), "}"); } if (bson_iter_init_find (&iter, scenario, "encrypted_fields")) { @@ -1040,8 +987,7 @@ _recreate (const char *db_name, } db = mongoc_client_get_database (client, db_name); - collection = - mongoc_database_create_collection (db, collection_name, opts, &error); + collection = mongoc_database_create_collection (db, collection_name, opts, &error); ASSERT_OR_PRINT (collection, error); bson_destroy (opts); mongoc_collection_destroy (collection); @@ -1060,24 +1006,21 @@ _insert_data (mongoc_collection_t *collection, bson_t *documents) uint32_t server_id; bson_error_t error; - mongoc_collection_delete_many ( - collection, tmp_bson ("{}"), majority, NULL, NULL); + mongoc_collection_delete_many (collection, tmp_bson ("{}"), majority, NULL, NULL); if (!bson_count_keys (documents)) { return; } bson_iter_init (&iter, documents); - bulk = - mongoc_collection_create_bulk_operation_with_opts (collection, majority); + bulk = mongoc_collection_create_bulk_operation_with_opts (collection, majority); while (bson_iter_next (&iter)) { bson_t document; bson_t opts = BSON_INITIALIZER; bson_iter_bson (&iter, &document); - r = mongoc_bulk_operation_insert_with_opts ( - bulk, &document, &opts, &error); + r = mongoc_bulk_operation_insert_with_opts (bulk, &document, &opts, &error); ASSERT_OR_PRINT (r, error); bson_destroy (&opts); @@ -1092,9 +1035,7 @@ _insert_data (mongoc_collection_t *collection, bson_t *documents) /* insert the documents in a spec test scenario's "data" array */ void -insert_data (const char *db_name, - const char *collection_name, - const bson_t *scenario) +insert_data (const char *db_name, const char *collection_name, const bson_t *scenario) { mongoc_client_t *client; mongoc_database_t *db; @@ -1108,8 +1049,7 @@ insert_data (const char *db_name, db = mongoc_client_get_database (client, db_name); collection = mongoc_database_get_collection (db, collection_name); - mongoc_collection_delete_many ( - collection, tmp_bson ("{}"), majority, NULL, NULL); + mongoc_collection_delete_many (collection, tmp_bson ("{}"), majority, NULL, NULL); if (!bson_has_field (scenario, "data")) { goto DONE; @@ -1127,8 +1067,7 @@ insert_data (const char *db_name, bson_t collection_documents; mongoc_collection_destroy (collection); - collection = - mongoc_database_get_collection (db, bson_iter_key (&iter)); + collection = mongoc_database_get_collection (db, bson_iter_key (&iter)); bson_iter_bson (&iter, &collection_documents); _insert_data (collection, &collection_documents); } @@ -1213,8 +1152,7 @@ execute_test (const json_test_config_t *config, } /* Select a primary for testing */ - server_id = mongoc_topology_select_server_id ( - client->topology, MONGOC_SS_WRITE, NULL, NULL, NULL, &error); + server_id = mongoc_topology_select_server_id (client->topology, MONGOC_SS_WRITE, NULL, NULL, NULL, &error); ASSERT_OR_PRINT (server_id, error); json_test_ctx_init (&ctx, test, client, db, collection, config); @@ -1257,15 +1195,11 @@ execute_test (const json_test_config_t *config, outcome_client = test_framework_new_default_client (); if (bson_has_field (test, "outcome.collection.name")) { outcome_coll = mongoc_client_get_collection ( - outcome_client, - mongoc_database_get_name (db), - bson_lookup_utf8 (test, "outcome.collection.name")); + outcome_client, mongoc_database_get_name (db), bson_lookup_utf8 (test, "outcome.collection.name")); } else { outcome_coll = mongoc_client_get_collection ( - outcome_client, - mongoc_database_get_name (db), - mongoc_collection_get_name (collection)); + outcome_client, mongoc_database_get_name (db), mongoc_collection_get_name (collection)); } check_outcome_collection (outcome_coll, test); mongoc_collection_destroy (outcome_coll); @@ -1290,10 +1224,7 @@ execute_test (const json_test_config_t *config, void -activate_fail_point (mongoc_client_t *client, - const uint32_t server_id, - const bson_t *test, - const char *key) +activate_fail_point (mongoc_client_t *client, const uint32_t server_id, const bson_t *test, const char *key) { bson_t command; bson_error_t error; @@ -1305,16 +1236,10 @@ activate_fail_point (mongoc_client_t *client, ASSERT_CMPSTR (_mongoc_get_command_name (&command), "configureFailPoint"); if (server_id) { - r = mongoc_client_command_simple_with_server_id ( - client, "admin", &command, NULL, server_id, NULL, &error); + r = mongoc_client_command_simple_with_server_id (client, "admin", &command, NULL, server_id, NULL, &error); } else { /* Use default "primary" read preference. */ - r = mongoc_client_command_simple (client, - "admin", - &command, - NULL /* read prefs */, - NULL /* reply */, - &error); + r = mongoc_client_command_simple (client, "admin", &command, NULL /* read prefs */, NULL /* reply */, &error); } ASSERT_OR_PRINT (r, error); } @@ -1353,19 +1278,16 @@ deactivate_fail_points (mongoc_client_t *client, uint32_t server_id) } if (sd->type == MONGOC_SERVER_RS_PRIMARY) { - command = - tmp_bson ("{'configureFailPoint': 'onPrimaryTransactionalWrite'," - " 'mode': 'off'}"); + command = tmp_bson ("{'configureFailPoint': 'onPrimaryTransactionalWrite'," + " 'mode': 'off'}"); - r = mongoc_client_command_simple_with_server_id ( - client, "admin", command, NULL, sd->id, NULL, &error); + r = mongoc_client_command_simple_with_server_id (client, "admin", command, NULL, sd->id, NULL, &error); ASSERT_OR_PRINT (r, error); command = tmp_bson ("{'configureFailPoint': 'failCommand'," " 'mode': 'off'}"); - r = mongoc_client_command_simple_with_server_id ( - client, "admin", command, NULL, sd->id, NULL, &error); + r = mongoc_client_command_simple_with_server_id (client, "admin", command, NULL, sd->id, NULL, &error); /* ignore error from servers that predate "failCommand" fail point */ if (!r && !strstr (error.message, "failCommand not found")) { @@ -1377,8 +1299,7 @@ deactivate_fail_points (mongoc_client_t *client, uint32_t server_id) /* failGetMoreAfterCursorCheckout added in 4.4 */ command = tmp_bson ("{'configureFailPoint': " "'failGetMoreAfterCursorCheckout', 'mode': 'off'}"); - r = mongoc_client_command_simple_with_server_id ( - client, "admin", command, NULL, sd->id, NULL, &error); + r = mongoc_client_command_simple_with_server_id (client, "admin", command, NULL, sd->id, NULL, &error); ASSERT_OR_PRINT (r, error); } @@ -1401,11 +1322,9 @@ set_uri_opts_from_bson (mongoc_uri_t *uri, const bson_t *opts) if (BSON_ITER_HOLDS_UTF8 (&iter)) { mongoc_write_concern_set_wtag (wc, bson_iter_utf8 (&iter, NULL)); } else if (BSON_ITER_HOLDS_INT (&iter)) { - mongoc_write_concern_set_w (wc, - (int32_t) bson_iter_as_int64 (&iter)); + mongoc_write_concern_set_w (wc, (int32_t) bson_iter_as_int64 (&iter)); } else { - test_error ("Unrecognized type for 'w': %d", - bson_iter_type (&iter)); + test_error ("Unrecognized type for 'w': %d", bson_iter_type (&iter)); } mongoc_uri_set_write_concern (uri, wc); @@ -1416,15 +1335,13 @@ set_uri_opts_from_bson (mongoc_uri_t *uri, const bson_t *opts) mongoc_uri_set_read_concern (uri, rc); mongoc_read_concern_destroy (rc); } else if (!strcmp (key, "readPreference")) { - mongoc_read_prefs_t *read_prefs = mongoc_read_prefs_new ( - read_mode_from_test (bson_iter_utf8 (&iter, NULL))); + mongoc_read_prefs_t *read_prefs = mongoc_read_prefs_new (read_mode_from_test (bson_iter_utf8 (&iter, NULL))); mongoc_uri_set_read_prefs_t (uri, read_prefs); mongoc_read_prefs_destroy (read_prefs); } else if (!strcmp (key, "autoEncryptOpts")) { /* Auto encrypt options are set on constructed client, not in URI. */ } else if (!strcmp (key, "writeConcern")) { - mongoc_write_concern_t *wc = - bson_lookup_write_concern (opts, "writeConcern"); + mongoc_write_concern_t *wc = bson_lookup_write_concern (opts, "writeConcern"); mongoc_uri_set_write_concern (uri, wc); mongoc_write_concern_destroy (wc); } else if (mongoc_uri_option_is_bool (key)) { @@ -1434,9 +1351,7 @@ set_uri_opts_from_bson (mongoc_uri_t *uri, const bson_t *opts) } else if (mongoc_uri_option_is_utf8 (key)) { mongoc_uri_set_option_as_utf8 (uri, key, bson_iter_utf8 (&iter, NULL)); } else { - test_error ("Unsupported clientOptions field \"%s\" in %s", - key, - bson_as_json (opts, NULL)); + test_error ("Unsupported clientOptions field \"%s\" in %s", key, bson_as_json (opts, NULL)); } } } @@ -1466,35 +1381,24 @@ set_auto_encryption_opts (mongoc_client_t *client, bson_t *test) bson_t tmp; bson_iter_bson (&iter, &tmp); - bson_copy_to_excluding (&tmp, - &kms_providers, - "aws", - "awsTemporary", - "awsTemporaryNoSessionToken", - "azure", - "gcp", - "kmip", - NULL); + bson_copy_to_excluding ( + &tmp, &kms_providers, "aws", "awsTemporary", "awsTemporaryNoSessionToken", "azure", "gcp", "kmip", NULL); /* AWS credentials are set from environment variables. */ if (bson_has_field (&opts, "kmsProviders.aws")) { - char *const secret_access_key = - test_framework_getenv ("MONGOC_TEST_AWS_SECRET_ACCESS_KEY"); - char *const access_key_id = - test_framework_getenv ("MONGOC_TEST_AWS_ACCESS_KEY_ID"); + char *const secret_access_key = test_framework_getenv ("MONGOC_TEST_AWS_SECRET_ACCESS_KEY"); + char *const access_key_id = test_framework_getenv ("MONGOC_TEST_AWS_ACCESS_KEY_ID"); if (!secret_access_key || !access_key_id) { - test_error ( - "Set MONGOC_TEST_AWS_SECRET_ACCESS_KEY and " - "MONGOC_TEST_AWS_ACCESS_KEY_ID environment variables to " - "run Client Side Encryption tests."); + test_error ("Set MONGOC_TEST_AWS_SECRET_ACCESS_KEY and " + "MONGOC_TEST_AWS_ACCESS_KEY_ID environment variables to " + "run Client Side Encryption tests."); } { bson_t aws = BSON_INITIALIZER; - BSON_ASSERT ( - BSON_APPEND_UTF8 (&aws, "secretAccessKey", secret_access_key)); + BSON_ASSERT (BSON_APPEND_UTF8 (&aws, "secretAccessKey", secret_access_key)); BSON_ASSERT (BSON_APPEND_UTF8 (&aws, "accessKeyId", access_key_id)); BSON_APPEND_DOCUMENT (&kms_providers, "aws", &aws); @@ -1506,25 +1410,19 @@ set_auto_encryption_opts (mongoc_client_t *client, bson_t *test) bson_free (access_key_id); } - const bool need_aws_with_session_token = - bson_has_field (&opts, "kmsProviders.awsTemporary"); + const bool need_aws_with_session_token = bson_has_field (&opts, "kmsProviders.awsTemporary"); const bool need_aws_with_temp_creds = - need_aws_with_session_token || - bson_has_field (&opts, "kmsProviders.awsTemporaryNoSessionToken"); + need_aws_with_session_token || bson_has_field (&opts, "kmsProviders.awsTemporaryNoSessionToken"); if (need_aws_with_temp_creds) { - char *const secret_access_key = - test_framework_getenv ("MONGOC_TEST_AWS_TEMP_SECRET_ACCESS_KEY"); - char *const access_key_id = - test_framework_getenv ("MONGOC_TEST_AWS_TEMP_ACCESS_KEY_ID"); - char *const session_token = - test_framework_getenv ("MONGOC_TEST_AWS_TEMP_SESSION_TOKEN"); + char *const secret_access_key = test_framework_getenv ("MONGOC_TEST_AWS_TEMP_SECRET_ACCESS_KEY"); + char *const access_key_id = test_framework_getenv ("MONGOC_TEST_AWS_TEMP_ACCESS_KEY_ID"); + char *const session_token = test_framework_getenv ("MONGOC_TEST_AWS_TEMP_SESSION_TOKEN"); if (!secret_access_key || !access_key_id) { - test_error ( - "Set MONGOC_TEST_AWS_TEMP_SECRET_ACCESS_KEY and " - "MONGOC_TEST_AWS_TEMP_ACCESS_KEY_ID environment variables " - "to run Client Side Encryption tests."); + test_error ("Set MONGOC_TEST_AWS_TEMP_SECRET_ACCESS_KEY and " + "MONGOC_TEST_AWS_TEMP_ACCESS_KEY_ID environment variables " + "to run Client Side Encryption tests."); } // Only require session token when requested. @@ -1536,13 +1434,11 @@ set_auto_encryption_opts (mongoc_client_t *client, bson_t *test) { bson_t aws = BSON_INITIALIZER; - BSON_ASSERT ( - BSON_APPEND_UTF8 (&aws, "secretAccessKey", secret_access_key)); + BSON_ASSERT (BSON_APPEND_UTF8 (&aws, "secretAccessKey", secret_access_key)); BSON_ASSERT (BSON_APPEND_UTF8 (&aws, "accessKeyId", access_key_id)); if (need_aws_with_session_token) { - BSON_ASSERT ( - BSON_APPEND_UTF8 (&aws, "sessionToken", session_token)); + BSON_ASSERT (BSON_APPEND_UTF8 (&aws, "sessionToken", session_token)); } BSON_APPEND_DOCUMENT (&kms_providers, "aws", &aws); @@ -1560,12 +1456,9 @@ set_auto_encryption_opts (mongoc_client_t *client, bson_t *test) char *azure_client_id; char *azure_client_secret; - azure_tenant_id = - test_framework_getenv ("MONGOC_TEST_AZURE_TENANT_ID"); - azure_client_id = - test_framework_getenv ("MONGOC_TEST_AZURE_CLIENT_ID"); - azure_client_secret = - test_framework_getenv ("MONGOC_TEST_AZURE_CLIENT_SECRET"); + azure_tenant_id = test_framework_getenv ("MONGOC_TEST_AZURE_TENANT_ID"); + azure_client_id = test_framework_getenv ("MONGOC_TEST_AZURE_CLIENT_ID"); + azure_client_secret = test_framework_getenv ("MONGOC_TEST_AZURE_CLIENT_SECRET"); if (!azure_tenant_id || !azure_client_id || !azure_client_secret) { test_error ("Set MONGOC_TEST_AZURE_TENANT_ID, " @@ -1599,11 +1492,8 @@ set_auto_encryption_opts (mongoc_client_t *client, bson_t *test) "tests."); } - bson_concat ( - &kms_providers, - tmp_bson ("{ 'gcp': { 'email': '%s', 'privateKey': '%s' }}", - gcp_email, - gcp_privatekey)); + bson_concat (&kms_providers, + tmp_bson ("{ 'gcp': { 'email': '%s', 'privateKey': '%s' }}", gcp_email, gcp_privatekey)); bson_free (gcp_email); bson_free (gcp_privatekey); @@ -1613,18 +1503,15 @@ set_auto_encryption_opts (mongoc_client_t *client, bson_t *test) char *kmip_tls_ca_file; char *kmip_tls_certificate_key_file; - kmip_tls_ca_file = - test_framework_getenv ("MONGOC_TEST_CSFLE_TLS_CA_FILE"); - kmip_tls_certificate_key_file = test_framework_getenv ( - "MONGOC_TEST_CSFLE_TLS_CERTIFICATE_KEY_FILE"); + kmip_tls_ca_file = test_framework_getenv ("MONGOC_TEST_CSFLE_TLS_CA_FILE"); + kmip_tls_certificate_key_file = test_framework_getenv ("MONGOC_TEST_CSFLE_TLS_CERTIFICATE_KEY_FILE"); if (!kmip_tls_ca_file || !kmip_tls_certificate_key_file) { test_error ("Set MONGOC_TEST_CSFLE_TLS_CA_FILE, and " "MONGOC_TEST_CSFLE_TLS_CERTIFICATE_KEY_FILE to enable " "CSFLE tests."); } - bson_concat (&kms_providers, - tmp_bson ("{ 'kmip': { 'endpoint': 'localhost:5698' }}")); + bson_concat (&kms_providers, tmp_bson ("{ 'kmip': { 'endpoint': 'localhost:5698' }}")); bson_concat (&tls_opts, tmp_bson ("{'kmip': { 'tlsCAFile': '%s', " @@ -1636,10 +1523,8 @@ set_auto_encryption_opts (mongoc_client_t *client, bson_t *test) bson_free (kmip_tls_certificate_key_file); } - mongoc_auto_encryption_opts_set_kms_providers (auto_encryption_opts, - &kms_providers); - mongoc_auto_encryption_opts_set_tls_opts (auto_encryption_opts, - &tls_opts); + mongoc_auto_encryption_opts_set_kms_providers (auto_encryption_opts, &kms_providers); + mongoc_auto_encryption_opts_set_tls_opts (auto_encryption_opts, &tls_opts); bson_destroy (&kms_providers); bson_destroy (&tls_opts); } @@ -1648,19 +1533,16 @@ set_auto_encryption_opts (mongoc_client_t *client, bson_t *test) bson_t schema_map; bson_iter_bson (&iter, &schema_map); - mongoc_auto_encryption_opts_set_schema_map (auto_encryption_opts, - &schema_map); + mongoc_auto_encryption_opts_set_schema_map (auto_encryption_opts, &schema_map); bson_destroy (&schema_map); } if (bson_iter_init_find (&iter, &opts, "bypassAutoEncryption")) { - mongoc_auto_encryption_opts_set_bypass_auto_encryption ( - auto_encryption_opts, bson_iter_as_bool (&iter)); + mongoc_auto_encryption_opts_set_bypass_auto_encryption (auto_encryption_opts, bson_iter_as_bool (&iter)); } if (bson_iter_init_find (&iter, &opts, "bypassQueryAnalysis")) { - mongoc_auto_encryption_opts_set_bypass_query_analysis ( - auto_encryption_opts, bson_iter_as_bool (&iter)); + mongoc_auto_encryption_opts_set_bypass_query_analysis (auto_encryption_opts, bson_iter_as_bool (&iter)); } if (bson_iter_init_find (&iter, &opts, "keyVaultNamespace")) { @@ -1675,16 +1557,14 @@ set_auto_encryption_opts (mongoc_client_t *client, bson_t *test) BSON_ASSERT (dot); db_name = bson_strndup (keyvault_ns, dot - keyvault_ns); coll_name = bson_strdup (dot + 1); - mongoc_auto_encryption_opts_set_keyvault_namespace ( - auto_encryption_opts, db_name, coll_name); + mongoc_auto_encryption_opts_set_keyvault_namespace (auto_encryption_opts, db_name, coll_name); bson_free (db_name); bson_free (coll_name); } else { /* "If ``autoEncryptOpts`` does not include ``keyVaultNamespace``, default * it to ``keyvault.datakeys``" */ - mongoc_auto_encryption_opts_set_keyvault_namespace ( - auto_encryption_opts, "keyvault", "datakeys"); + mongoc_auto_encryption_opts_set_keyvault_namespace (auto_encryption_opts, "keyvault", "datakeys"); } if (bson_iter_init_find (&iter, &opts, "extra")) { @@ -1701,8 +1581,7 @@ set_auto_encryption_opts (mongoc_client_t *client, bson_t *test) bson_t efm; bson_iter_bson (&iter, &efm); - mongoc_auto_encryption_opts_set_encrypted_fields_map ( - auto_encryption_opts, &efm); + mongoc_auto_encryption_opts_set_encrypted_fields_map (auto_encryption_opts, &efm); bson_destroy (&efm); } @@ -1713,8 +1592,7 @@ set_auto_encryption_opts (mongoc_client_t *client, bson_t *test) BSON_APPEND_BOOL (&extra, "mongocryptdBypassSpawn", true); } - char *env_cryptSharedLibPath = - test_framework_getenv ("MONGOC_TEST_CRYPT_SHARED_LIB_PATH"); + char *env_cryptSharedLibPath = test_framework_getenv ("MONGOC_TEST_CRYPT_SHARED_LIB_PATH"); if (env_cryptSharedLibPath) { BSON_APPEND_UTF8 (&extra, "cryptSharedLibPath", env_cryptSharedLibPath); bson_free (env_cryptSharedLibPath); @@ -1723,8 +1601,7 @@ set_auto_encryption_opts (mongoc_client_t *client, bson_t *test) mongoc_auto_encryption_opts_set_extra (auto_encryption_opts, &extra); bson_destroy (&extra); - ret = mongoc_client_enable_auto_encryption ( - client, auto_encryption_opts, &error); + ret = mongoc_client_enable_auto_encryption (client, auto_encryption_opts, &error); ASSERT_OR_PRINT (ret, error); mongoc_auto_encryption_opts_destroy (auto_encryption_opts); } @@ -1785,20 +1662,14 @@ run_json_general_test (const json_test_config_t *config) return; } - db_name = bson_has_field (scenario, "database_name") - ? bson_lookup_utf8 (scenario, "database_name") - : "test"; - collection_name = bson_has_field (scenario, "collection_name") - ? bson_lookup_utf8 (scenario, "collection_name") - : "test"; + db_name = bson_has_field (scenario, "database_name") ? bson_lookup_utf8 (scenario, "database_name") : "test"; + collection_name = + bson_has_field (scenario, "collection_name") ? bson_lookup_utf8 (scenario, "collection_name") : "test"; /* database2_name/collection2_name are optional. */ - db2_name = bson_has_field (scenario, "database2_name") - ? bson_lookup_utf8 (scenario, "database2_name") - : NULL; - collection2_name = bson_has_field (scenario, "collection2_name") - ? bson_lookup_utf8 (scenario, "collection2_name") - : NULL; + db2_name = bson_has_field (scenario, "database2_name") ? bson_lookup_utf8 (scenario, "database2_name") : NULL; + collection2_name = + bson_has_field (scenario, "collection2_name") ? bson_lookup_utf8 (scenario, "collection2_name") : NULL; ASSERT (bson_iter_init_find (&scenario_iter, scenario, "tests")); @@ -1825,27 +1696,22 @@ run_json_general_test (const json_test_config_t *config) selected_test = test_framework_getenv ("MONGOC_JSON_SUBTEST"); description = bson_lookup_utf8 (&test, "description"); if (selected_test && strcmp (selected_test, description) != 0) { - fprintf ( - stderr, " - %s SKIPPED by MONGOC_JSON_SUBTEST\n", description); + fprintf (stderr, " - %s SKIPPED by MONGOC_JSON_SUBTEST\n", description); bson_free (selected_test); continue; } bson_free (selected_test); if (bson_has_field (&test, "skipReason")) { - fprintf (stderr, - " - %s SKIPPED, reason: %s\n", - description, - bson_lookup_utf8 (&test, "skipReason")); + fprintf (stderr, " - %s SKIPPED, reason: %s\n", description, bson_lookup_utf8 (&test, "skipReason")); continue; } if (_should_skip_due_to_unsupported_operation (&test)) { - fprintf ( - stderr, - " - %s SKIPPED, reason: test requires operation that libmongoc" - " does not provide\n", - description); + fprintf (stderr, + " - %s SKIPPED, reason: test requires operation that libmongoc" + " does not provide\n", + description); continue; } @@ -1861,31 +1727,22 @@ run_json_general_test (const json_test_config_t *config) } if (should_skip) { - fprintf (stderr, - " - %s SKIPPED, due to reason: %s\n", - description, - iter->reason); + fprintf (stderr, " - %s SKIPPED, due to reason: %s\n", description, iter->reason); continue; } } - uri = (config->uri_str != NULL) ? mongoc_uri_new (config->uri_str) - : test_framework_get_uri (); + uri = (config->uri_str != NULL) ? mongoc_uri_new (config->uri_str) : test_framework_get_uri (); /* If we are using multiple mongos, hardcode them in, for now, but keep * the other URI components (CDRIVER-3285) */ - if (bson_iter_init_find (&uri_iter, &test, "useMultipleMongoses") && - bson_iter_as_bool (&uri_iter)) { + if (bson_iter_init_find (&uri_iter, &test, "useMultipleMongoses") && bson_iter_as_bool (&uri_iter)) { if (test_framework_is_loadbalanced ()) { mongoc_uri_destroy (uri); uri = test_framework_get_uri_multi_mongos_loadbalanced (); } else { - ASSERT_OR_PRINT ( - mongoc_uri_upsert_host_and_port (uri, "localhost:27017", &error), - error); - ASSERT_OR_PRINT ( - mongoc_uri_upsert_host_and_port (uri, "localhost:27018", &error), - error); + ASSERT_OR_PRINT (mongoc_uri_upsert_host_and_port (uri, "localhost:27017", &error), error); + ASSERT_OR_PRINT (mongoc_uri_upsert_host_and_port (uri, "localhost:27018", &error), error); } } @@ -1905,23 +1762,15 @@ run_json_general_test (const json_test_config_t *config) mongoc_uri_destroy (uri); /* clean up in case a previous test aborted */ - server_id = mongoc_topology_select_server_id ( - client->topology, MONGOC_SS_WRITE, NULL, NULL, NULL, &error); + server_id = mongoc_topology_select_server_id (client->topology, MONGOC_SS_WRITE, NULL, NULL, NULL, &error); ASSERT_OR_PRINT (server_id, error); deactivate_fail_points (client, server_id); - r = mongoc_client_command_with_opts (client, - "admin", - tmp_bson ("{'killAllSessions': []}"), - NULL, - NULL, - NULL, - &error); + r = mongoc_client_command_with_opts ( + client, "admin", tmp_bson ("{'killAllSessions': []}"), NULL, NULL, NULL, &error); /* expect "operation was interrupted", ignore "command not found" or "is * not supported" */ - if (!r && - (error.domain != MONGOC_ERROR_SERVER || - (error.code != 11601 && error.code != 59)) && + if (!r && (error.domain != MONGOC_ERROR_SERVER || (error.code != 11601 && error.code != 59)) && (strstr (error.message, "is unsupported") == NULL)) { MONGOC_WARNING ("Error in killAllSessions: %s", error.message); } @@ -1971,19 +1820,17 @@ _skip_if_unsupported (const char *test_name, bson_t *original) { int i; bool skip = false; - const char *unsupported_tests[] = { - "/retryable_reads/legacy/gridfs-downloadByName", - "/retryable_reads/legacy/gridfs-downloadByName-serverErrors", - "/retryable_reads/legacy/listCollectionObjects", - "/retryable_reads/legacy/listCollectionObjects-serverErrors", - "/retryable_reads/legacy/listDatabaseObjects", - "/retryable_reads/legacy/listDatabaseObjects-serverErrors", - "/retryable_reads/legacy/listIndexNames", - "/retryable_reads/legacy/listIndexNames-serverErrors", - "/retryable_reads/legacy/mapReduce"}; - - for (i = 0; i < sizeof (unsupported_tests) / sizeof (unsupported_tests[0]); - i++) { + const char *unsupported_tests[] = {"/retryable_reads/legacy/gridfs-downloadByName", + "/retryable_reads/legacy/gridfs-downloadByName-serverErrors", + "/retryable_reads/legacy/listCollectionObjects", + "/retryable_reads/legacy/listCollectionObjects-serverErrors", + "/retryable_reads/legacy/listDatabaseObjects", + "/retryable_reads/legacy/listDatabaseObjects-serverErrors", + "/retryable_reads/legacy/listIndexNames", + "/retryable_reads/legacy/listIndexNames-serverErrors", + "/retryable_reads/legacy/mapReduce"}; + + for (i = 0; i < sizeof (unsupported_tests) / sizeof (unsupported_tests[0]); i++) { if (0 == strcmp (test_name, unsupported_tests[i])) { skip = true; break; @@ -2004,14 +1851,10 @@ _skip_if_unsupported (const char *test_name, bson_t *original) bson_t modified_test; bson_iter_bson (&iter, &original_test); - bson_array_builder_append_document_begin (modified_tests, - &modified_test); + bson_array_builder_append_document_begin (modified_tests, &modified_test); bson_concat (&modified_test, &original_test); - BSON_APPEND_UTF8 (&modified_test, - "skipReason", - "libmongoc does not support required operation."); - bson_array_builder_append_document_end (modified_tests, - &modified_test); + BSON_APPEND_UTF8 (&modified_test, "skipReason", "libmongoc does not support required operation."); + bson_array_builder_append_document_end (modified_tests, &modified_test); } bson_append_array_builder_end (modified, modified_tests); bson_destroy (original); @@ -2035,11 +1878,7 @@ _skip_if_unsupported (const char *test_name, bson_t *original) *----------------------------------------------------------------------- */ void -_install_json_test_suite_with_check (TestSuite *suite, - const char *base, - const char *subdir, - test_hook callback, - ...) +_install_json_test_suite_with_check (TestSuite *suite, const char *base, const char *subdir, test_hook callback, ...) { char test_paths[MAX_NUM_TESTS][MAX_TEST_NAME_LENGTH]; int num_tests; @@ -2060,13 +1899,11 @@ _install_json_test_suite_with_check (TestSuite *suite, } } - num_tests = - collect_tests_from_dir (&test_paths[0], resolved, 0, MAX_NUM_TESTS); + num_tests = collect_tests_from_dir (&test_paths[0], resolved, 0, MAX_NUM_TESTS); for (int i = 0; i < num_tests; i++) { test = get_bson_from_json_file (test_paths[i]); - skip_json = COALESCE (strstr (test_paths[i], "/json"), - strstr (test_paths[i], "\\json")); + skip_json = COALESCE (strstr (test_paths[i], "/json"), strstr (test_paths[i], "\\json")); BSON_ASSERT (skip_json); skip_json += strlen ("/json"); ext = strstr (skip_json, ".json"); @@ -2075,8 +1912,7 @@ _install_json_test_suite_with_check (TestSuite *suite, test = _skip_if_unsupported (skip_json, test); for (size_t j = 0u; j < suite->failing_flaky_skips.len; j++) { - TestSkip *skip = - _mongoc_array_index (&suite->failing_flaky_skips, TestSkip *, j); + TestSkip *skip = _mongoc_array_index (&suite->failing_flaky_skips, TestSkip *, j); if (0 == strcmp (skip_json, skip->test_name)) { /* Modify the test file to give applicable entries a skipReason */ bson_t *modified = bson_new (); @@ -2084,8 +1920,7 @@ _install_json_test_suite_with_check (TestSuite *suite, bson_iter_t iter; bson_copy_to_excluding_noinit (test, modified, "tests", NULL); - BSON_APPEND_ARRAY_BUILDER_BEGIN ( - modified, "tests", &modified_tests); + BSON_APPEND_ARRAY_BUILDER_BEGIN (modified, "tests", &modified_tests); BSON_ASSERT (bson_iter_init_find (&iter, test, "tests")); for (bson_iter_recurse (&iter, &iter); bson_iter_next (&iter);) { bson_iter_t desc_iter; @@ -2098,18 +1933,12 @@ _install_json_test_suite_with_check (TestSuite *suite, bson_iter_init_find (&desc_iter, &original_test, "description"); desc = bson_iter_utf8 (&desc_iter, &desc_len); - bson_array_builder_append_document_begin (modified_tests, - &modified_test); + bson_array_builder_append_document_begin (modified_tests, &modified_test); bson_concat (&modified_test, &original_test); - if (!skip->subtest_desc || - 0 == strcmp (skip->subtest_desc, desc)) { - BSON_APPEND_UTF8 (&modified_test, - "skipReason", - skip->reason != NULL ? skip->reason - : "(null)"); + if (!skip->subtest_desc || 0 == strcmp (skip->subtest_desc, desc)) { + BSON_APPEND_UTF8 (&modified_test, "skipReason", skip->reason != NULL ? skip->reason : "(null)"); } - bson_array_builder_append_document_end (modified_tests, - &modified_test); + bson_array_builder_append_document_end (modified_tests, &modified_test); } bson_append_array_builder_end (modified, modified_tests); bson_destroy (test); @@ -2118,12 +1947,7 @@ _install_json_test_suite_with_check (TestSuite *suite, } /* list of "check" functions that decide whether to skip the test */ va_start (ap, callback); - _V_TestSuite_AddFull (suite, - skip_json, - (void (*) (void *)) callback, - (void (*) (void *)) bson_destroy, - test, - ap); + _V_TestSuite_AddFull (suite, skip_json, (void (*) (void *)) callback, (void (*) (void *)) bson_destroy, test, ap); va_end (ap); } @@ -2145,11 +1969,7 @@ _install_json_test_suite_with_check (TestSuite *suite, *----------------------------------------------------------------------- */ void -install_json_test_suite (TestSuite *suite, - const char *base, - const char *subdir, - test_hook callback) +install_json_test_suite (TestSuite *suite, const char *base, const char *subdir, test_hook callback) { - install_json_test_suite_with_check ( - suite, base, subdir, callback, TestSuite_CheckLive); + install_json_test_suite_with_check (suite, base, subdir, callback, TestSuite_CheckLive); } diff --git a/src/libmongoc/tests/json-test.h b/src/libmongoc/tests/json-test.h index 669e9b3f82..872bf4cb22 100644 --- a/src/libmongoc/tests/json-test.h +++ b/src/libmongoc/tests/json-test.h @@ -65,16 +65,13 @@ collect_tests_from_dir (char (*paths)[MAX_TEST_NAME_LENGTH] /* OUT */, int max_paths); void -assemble_path (const char *parent_path, - const char *child_name, - char *dst /* OUT */); +assemble_path (const char *parent_path, const char *child_name, char *dst /* OUT */); mongoc_topology_description_type_t topology_type_from_test (const char *type); const mongoc_server_description_t * -server_description_by_hostname (const mongoc_topology_description_t *topology, - const char *address); +server_description_by_hostname (const mongoc_topology_description_t *topology, const char *address); void process_sdam_test_hello_responses (bson_t *phase, mongoc_topology_t *topology); @@ -86,10 +83,7 @@ mongoc_server_description_type_t server_type_from_test (const char *type); void -activate_fail_point (mongoc_client_t *client, - const uint32_t server_id, - const bson_t *test, - const char *key); +activate_fail_point (mongoc_client_t *client, const uint32_t server_id, const bson_t *test, const char *key); void deactivate_fail_points (mongoc_client_t *client, uint32_t server_id); @@ -101,29 +95,19 @@ void json_test_config_cleanup (json_test_config_t *config); void -_install_json_test_suite_with_check (TestSuite *suite, - const char *base, - const char *subdir, - test_hook callback, - ...); +_install_json_test_suite_with_check (TestSuite *suite, const char *base, const char *subdir, test_hook callback, ...); void -install_json_test_suite (TestSuite *suite, - const char *base, - const char *subdir, - test_hook callback); +install_json_test_suite (TestSuite *suite, const char *base, const char *subdir, test_hook callback); #define install_json_test_suite_with_check(_suite, _base, _subdir, ...) \ - _install_json_test_suite_with_check ( \ - _suite, _base, _subdir, __VA_ARGS__, NULL) + _install_json_test_suite_with_check (_suite, _base, _subdir, __VA_ARGS__, NULL) void set_uri_opts_from_bson (mongoc_uri_t *uri, const bson_t *opts); void -insert_data (const char *db_name, - const char *collection_name, - const bson_t *scenario); +insert_data (const char *db_name, const char *collection_name, const bson_t *scenario); bool check_scenario_version (const bson_t *scenario); diff --git a/src/libmongoc/tests/mock_server/mock-rs.c b/src/libmongoc/tests/mock_server/mock-rs.c index 89876d31b6..96223cae12 100644 --- a/src/libmongoc/tests/mock_server/mock-rs.c +++ b/src/libmongoc/tests/mock_server/mock-rs.c @@ -113,9 +113,7 @@ make_uri (mongoc_array_t *servers) static char * -hello_json (mock_rs_t *rs, - mongoc_server_description_type_t type, - const bson_t *tags) +hello_json (mock_rs_t *rs, mongoc_server_description_type_t type, const bson_t *tags) { char *server_type; char *tags_json; @@ -139,28 +137,27 @@ hello_json (mock_rs_t *rs, hosts_str = hosts (&rs->servers); - json = bson_strdup_printf ( - "{'ok': 1," - " %s" - " '$clusterTime': {" - " 'clusterTime': {'$timestamp': {'t': 1, 'i': 1}}," - " 'signature': {" - " 'hash': {'$binary': {'subType': '0', 'base64': ''}}," - " 'keyId': {'$numberLong': '6446735049323708417'}" - " }," - " 'operationTime': {'$timestamp': {'t': 1, 'i': 1}}" - " }," - "'logicalSessionTimeoutMinutes': 30," - " 'tags': %s," - " 'minWireVersion': %d," - " 'maxWireVersion': %d," - " 'setName': 'rs'," - " 'hosts': [%s]}", - server_type, - tags_json, - WIRE_VERSION_MIN, - rs->max_wire_version, - hosts_str); + json = bson_strdup_printf ("{'ok': 1," + " %s" + " '$clusterTime': {" + " 'clusterTime': {'$timestamp': {'t': 1, 'i': 1}}," + " 'signature': {" + " 'hash': {'$binary': {'subType': '0', 'base64': ''}}," + " 'keyId': {'$numberLong': '6446735049323708417'}" + " }," + " 'operationTime': {'$timestamp': {'t': 1, 'i': 1}}" + " }," + "'logicalSessionTimeoutMinutes': 30," + " 'tags': %s," + " 'minWireVersion': %d," + " 'maxWireVersion': %d," + " 'setName': 'rs'," + " 'hosts': [%s]}", + server_type, + tags_json, + WIRE_VERSION_MIN, + rs->max_wire_version, + hosts_str); bson_free (tags_json); bson_free (hosts_str); @@ -179,8 +176,7 @@ primary_json (mock_rs_t *rs) static char * secondary_json (mock_rs_t *rs, int server_number) { - return hello_json ( - rs, MONGOC_SERVER_RS_SECONDARY, rs->secondary_tags[server_number]); + return hello_json (rs, MONGOC_SERVER_RS_SECONDARY, rs->secondary_tags[server_number]); } @@ -208,17 +204,13 @@ arbiter_json (mock_rs_t *rs) */ mock_rs_t * -mock_rs_with_auto_hello (int32_t max_wire_version, - bool has_primary, - int n_secondaries, - int n_arbiters) +mock_rs_with_auto_hello (int32_t max_wire_version, bool has_primary, int n_secondaries, int n_arbiters) { int i; mock_rs_t *rs = BSON_ALIGNED_ALLOC0 (mock_rs_t); ASSERT_WITH_MSG (max_wire_version >= WIRE_VERSION_MIN, - "max_wire_version %" PRId32 - " must be greater than or equal to minimum wire version %d", + "max_wire_version %" PRId32 " must be greater than or equal to minimum wire version %d", max_wire_version, WIRE_VERSION_MIN); @@ -344,8 +336,7 @@ mock_rs_run (mock_rs_t *rs) * runs last, after auto_hello. */ for (size_t i = 0u; i < rs->servers.len; i++) { - mock_server_autoresponds ( - get_server (&rs->servers, i), rs_q_append, (void *) rs, NULL); + mock_server_autoresponds (get_server (&rs->servers, i), rs_q_append, (void *) rs, NULL); } @@ -454,8 +445,7 @@ _mock_rs_receives_msg (mock_rs_t *rs, uint32_t flags, ...) request = (request_t *) q_get (rs->q, rs->request_timeout_msec); - ASSERT_WITH_MSG (request, - "expected an OP_MSG request but did not receive one!"); + ASSERT_WITH_MSG (request, "expected an OP_MSG request but did not receive one!"); va_start (args, flags); r = request_matches_msgv (request, flags, &args); @@ -551,8 +541,7 @@ mock_rs_request_is_to_primary (mock_rs_t *rs, request_t *request) { BSON_ASSERT (request); - return MONGOC_SERVER_RS_PRIMARY == - _mock_rs_server_type (rs, request_get_server_port (request)); + return MONGOC_SERVER_RS_PRIMARY == _mock_rs_server_type (rs, request_get_server_port (request)); } @@ -577,8 +566,7 @@ mock_rs_request_is_to_secondary (mock_rs_t *rs, request_t *request) { BSON_ASSERT (request); - return MONGOC_SERVER_RS_SECONDARY == - _mock_rs_server_type (rs, request_get_server_port (request)); + return MONGOC_SERVER_RS_SECONDARY == _mock_rs_server_type (rs, request_get_server_port (request)); } @@ -598,8 +586,7 @@ mock_rs_stepdown (mock_rs_t *rs) BSON_ASSERT (rs->primary); rs->n_secondaries++; - rs->secondary_tags = - bson_realloc (rs->secondary_tags, rs->n_secondaries * sizeof (bson_t *)); + rs->secondary_tags = bson_realloc (rs->secondary_tags, rs->n_secondaries * sizeof (bson_t *)); rs->secondary_tags[rs->n_secondaries - 1] = bson_copy (&rs->primary_tags); bson_reinit (&rs->primary_tags); diff --git a/src/libmongoc/tests/mock_server/mock-rs.h b/src/libmongoc/tests/mock_server/mock-rs.h index 7d39d4ca6d..0b2e558b1f 100644 --- a/src/libmongoc/tests/mock_server/mock-rs.h +++ b/src/libmongoc/tests/mock_server/mock-rs.h @@ -24,10 +24,7 @@ typedef struct _mock_rs_t mock_rs_t; mock_rs_t * -mock_rs_with_auto_hello (int32_t max_wire_version, - bool has_primary, - int n_secondaries, - int n_arbiters); +mock_rs_with_auto_hello (int32_t max_wire_version, bool has_primary, int n_secondaries, int n_arbiters); void @@ -51,8 +48,7 @@ mock_rs_receives_kill_cursors (mock_rs_t *rs, int64_t cursor_id); request_t * _mock_rs_receives_msg (mock_rs_t *rs, uint32_t flags, ...); -#define mock_rs_receives_msg(_rs, _flags, ...) \ - _mock_rs_receives_msg (_rs, _flags, __VA_ARGS__, NULL) +#define mock_rs_receives_msg(_rs, _flags, ...) _mock_rs_receives_msg (_rs, _flags, __VA_ARGS__, NULL) bool mock_rs_request_is_to_primary (mock_rs_t *rs, request_t *request); diff --git a/src/libmongoc/tests/mock_server/mock-server.c b/src/libmongoc/tests/mock_server/mock-server.c index 882ff37d0d..d75f5e9fc0 100644 --- a/src/libmongoc/tests/mock_server/mock-server.c +++ b/src/libmongoc/tests/mock_server/mock-server.c @@ -100,9 +100,7 @@ static BSON_THREAD_FUN (main_thread, data); static BSON_THREAD_FUN (worker_thread, data); static void -_mock_server_reply_with_stream (mock_server_t *server, - reply_t *reply, - mongoc_stream_t *client); +_mock_server_reply_with_stream (mock_server_t *server, reply_t *reply, mongoc_stream_t *client); void autoresponder_handle_destroy (autoresponder_handle_t *handle); @@ -131,12 +129,10 @@ get_port (mongoc_socket_t *sock); mock_server_t * mock_server_new (void) { - mock_server_t *server = - (mock_server_t *) bson_malloc0 (sizeof (mock_server_t)); + mock_server_t *server = (mock_server_t *) bson_malloc0 (sizeof (mock_server_t)); server->request_timeout_msec = get_future_timeout_ms (); - _mongoc_array_init (&server->autoresponders, - sizeof (autoresponder_handle_t)); + _mongoc_array_init (&server->autoresponders, sizeof (autoresponder_handle_t)); _mongoc_array_init (&server->worker_threads, sizeof (bson_thread_t)); mongoc_cond_init (&server->cond); bson_mutex_init (&server->mutex); @@ -170,8 +166,7 @@ mock_server_with_auto_hello (int32_t max_wire_version) mock_server_t *server = mock_server_new (); ASSERT_WITH_MSG (max_wire_version >= WIRE_VERSION_MIN, - "max_wire_version %" PRId32 - " must be greater than or equal to minimum wire version %d", + "max_wire_version %" PRId32 " must be greater than or equal to minimum wire version %d", max_wire_version, WIRE_VERSION_MIN); @@ -210,28 +205,26 @@ mock_mongos_new (int32_t max_wire_version) mock_server_t *server = mock_server_new (); ASSERT_WITH_MSG (max_wire_version >= WIRE_VERSION_MIN, - "max_wire_version %" PRId32 - " must be greater than or equal to minimum wire version %d", + "max_wire_version %" PRId32 " must be greater than or equal to minimum wire version %d", max_wire_version, WIRE_VERSION_MIN); - mock_server_auto_hello ( - server, - "{'ok': 1.0," - " 'isWritablePrimary': true," - " 'msg': 'isdbgrid'," - " 'minWireVersion': %d," - " 'maxWireVersion': %d," - " '$clusterTime': {" - " 'clusterTime': {'$timestamp': {'t': 1, 'i': 1}}," - " 'signature': {" - " 'hash': {'$binary': {'subType': '0', 'base64': ''}}," - " 'keyId': {'$numberLong': '6446735049323708417'}" - " }," - " 'operationTime': {'$timestamp': {'t': 1, 'i': 1}}}," - " 'logicalSessionTimeoutMinutes': 30}", - WIRE_VERSION_MIN, - max_wire_version); + mock_server_auto_hello (server, + "{'ok': 1.0," + " 'isWritablePrimary': true," + " 'msg': 'isdbgrid'," + " 'minWireVersion': %d," + " 'maxWireVersion': %d," + " '$clusterTime': {" + " 'clusterTime': {'$timestamp': {'t': 1, 'i': 1}}," + " 'signature': {" + " 'hash': {'$binary': {'subType': '0', 'base64': ''}}," + " 'keyId': {'$numberLong': '6446735049323708417'}" + " }," + " 'operationTime': {'$timestamp': {'t': 1, 'i': 1}}}," + " 'logicalSessionTimeoutMinutes': 30}", + WIRE_VERSION_MIN, + max_wire_version); return server; } @@ -329,22 +322,17 @@ mock_server_run (mock_server_t *server) size_t bind_addr_len = 0; int r; - ssock = mongoc_socket_new ( - server->bind_opts.family ? server->bind_opts.family : AF_INET, - SOCK_STREAM, - 0); + ssock = mongoc_socket_new (server->bind_opts.family ? server->bind_opts.family : AF_INET, SOCK_STREAM, 0); if (!ssock) { perror ("Failed to create socket."); return 0; } optval = 1; - mongoc_socket_setsockopt ( - ssock, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval); + mongoc_socket_setsockopt (ssock, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval); optval = server->bind_opts.ipv6_only; - mongoc_socket_setsockopt ( - ssock, IPPROTO_IPV6, IPV6_V6ONLY, &optval, sizeof (optval)); + mongoc_socket_setsockopt (ssock, IPPROTO_IPV6, IPV6_V6ONLY, &optval, sizeof (optval)); memset (&default_bind_addr, 0, sizeof default_bind_addr); @@ -367,9 +355,7 @@ mock_server_run (mock_server_t *server) // should not use values larger than 2^32 - 1. BSON_ASSERT (bson_in_range_unsigned (uint32_t, bind_addr_len)); - if (-1 == mongoc_socket_bind (ssock, - (struct sockaddr *) bind_addr, - (uint32_t) bind_addr_len)) { + if (-1 == mongoc_socket_bind (ssock, (struct sockaddr *) bind_addr, (uint32_t) bind_addr_len)) { perror ("Failed to bind socket"); return 0; } @@ -392,10 +378,9 @@ mock_server_run (mock_server_t *server) server->sock = ssock; server->port = bound_port; /* TODO: configurable timeouts, perhaps from env */ - server->uri_str = bson_strdup_printf ( - "mongodb://127.0.0.1:%hu/?serverselectiontimeoutms=10000&" - "sockettimeoutms=10000", - bound_port); + server->uri_str = bson_strdup_printf ("mongodb://127.0.0.1:%hu/?serverselectiontimeoutms=10000&" + "sockettimeoutms=10000", + bound_port); server->uri = mongoc_uri_new (server->uri_str); // Many mock server tests do not expect retryable handshakes. Disable by @@ -403,8 +388,7 @@ mock_server_run (mock_server_t *server) mongoc_uri_set_option_as_bool (server->uri, MONGOC_URI_RETRYREADS, false); mongoc_uri_set_option_as_bool (server->uri, MONGOC_URI_RETRYWRITES, false); - r = mcommon_thread_create ( - &server->main_thread, main_thread, (void *) server); + r = mcommon_thread_create (&server->main_thread, main_thread, (void *) server); BSON_ASSERT (r == 0); while (!server->running) { mongoc_cond_wait (&server->cond, &server->mutex); @@ -443,10 +427,7 @@ mock_server_run (mock_server_t *server) */ int -mock_server_autoresponds (mock_server_t *server, - autoresponder_t responder, - void *data, - destructor_t destructor) +mock_server_autoresponds (mock_server_t *server, autoresponder_t responder, void *data, destructor_t destructor) { autoresponder_handle_t handle = {responder, data, destructor}; int id; @@ -504,9 +485,7 @@ mock_server_remove_autoresponder (mock_server_t *server, int id) static bool -auto_hello_generate_response (request_t *request, - void *data, - bson_t *hello_response) +auto_hello_generate_response (request_t *request, void *data, bson_t *hello_response) { const char *response_json = (const char *) data; char *quotes_replaced; @@ -541,8 +520,7 @@ auto_hello (request_t *request, void *data) /* Check whether we've got "hello" or legacy hello */ is_hello = strcasecmp (request->command_name, "hello") == 0; - is_legacy_hello = - strcasecmp (request->command_name, HANDSHAKE_CMD_LEGACY_HELLO) == 0; + is_legacy_hello = strcasecmp (request->command_name, HANDSHAKE_CMD_LEGACY_HELLO) == 0; if (!is_hello && !is_legacy_hello) { return false; @@ -554,10 +532,8 @@ auto_hello (request_t *request, void *data) /* Convert responses for legacy hello */ if (bson_iter_init_find (&iter, &response, "isWritablePrimary")) { - BSON_APPEND_BOOL ( - &response, HANDSHAKE_RESPONSE_LEGACY_HELLO, bson_iter_bool (&iter)); - } else if (bson_iter_init_find ( - &iter, &response, HANDSHAKE_RESPONSE_LEGACY_HELLO)) { + BSON_APPEND_BOOL (&response, HANDSHAKE_RESPONSE_LEGACY_HELLO, bson_iter_bool (&iter)); + } else if (bson_iter_init_find (&iter, &response, HANDSHAKE_RESPONSE_LEGACY_HELLO)) { BSON_APPEND_BOOL (&response, "isWritablePrimary", bson_iter_bool (&iter)); } @@ -608,8 +584,7 @@ mock_server_auto_hello_callback (mock_server_t *server, callback->data = data; callback->destructor = destructor; - return mock_server_autoresponds ( - server, auto_hello, (void *) callback, hello_callback_free); + return mock_server_autoresponds (server, auto_hello, (void *) callback, hello_callback_free); } /*-------------------------------------------------------------------------- @@ -638,10 +613,8 @@ mock_server_auto_hello (mock_server_t *server, const char *response_json, ...) formatted_response_json = bson_strdupv_printf (response_json, args); va_end (args); - return mock_server_auto_hello_callback (server, - auto_hello_generate_response, - (void *) formatted_response_json, - bson_free); + return mock_server_auto_hello_callback ( + server, auto_hello_generate_response, (void *) formatted_response_json, bson_free); } @@ -650,8 +623,7 @@ auto_endsessions (request_t *request, void *data) { BSON_UNUSED (data); - if (!request->is_command || - strcasecmp (request->command_name, "endSessions") != 0) { + if (!request->is_command || strcasecmp (request->command_name, "endSessions") != 0) { return false; } @@ -791,8 +763,7 @@ mock_server_get_request_timeout_msec (mock_server_t *server) */ void -mock_server_set_request_timeout_msec (mock_server_t *server, - int64_t request_timeout_msec) +mock_server_set_request_timeout_msec (mock_server_t *server, int64_t request_timeout_msec) { bson_mutex_lock (&server->mutex); server->request_timeout_msec = request_timeout_msec; @@ -920,11 +891,8 @@ mock_server_receives_request (mock_server_t *server) *-------------------------------------------------------------------------- */ request_t * -mock_server_receives_bulk_msg (mock_server_t *server, - uint32_t flags, - const bson_t *msg_pattern, - const bson_t *doc_pattern, - size_t n_docs) +mock_server_receives_bulk_msg ( + mock_server_t *server, uint32_t flags, const bson_t *msg_pattern, const bson_t *doc_pattern, size_t n_docs) { request_t *request; bool r; @@ -974,11 +942,8 @@ mock_server_receives_bulk_msg (mock_server_t *server, MONGOC_PRINTF_FORMAT (4, 5) request_t * -mock_server_receives_command (mock_server_t *server, - const char *database_name, - mongoc_query_flags_t flags, - const char *command_json, - ...) +mock_server_receives_command ( + mock_server_t *server, const char *database_name, mongoc_query_flags_t flags, const char *command_json, ...) { va_list args; char *formatted_command_json = NULL; @@ -995,9 +960,7 @@ mock_server_receives_command (mock_server_t *server, request = mock_server_receives_request (server); - if (request && - !request_matches_query ( - request, ns, flags, 0, 1, formatted_command_json, NULL, true)) { + if (request && !request_matches_query (request, ns, flags, 0, 1, formatted_command_json, NULL, true)) { request_destroy (request); request = NULL; } @@ -1050,9 +1013,7 @@ _mock_server_receives_msg (mock_server_t *server, uint32_t flags, ...) } request_t * -_mock_server_receives_single_msg (mock_server_t *server, - uint32_t flags, - const bson_t *doc) +_mock_server_receives_single_msg (mock_server_t *server, uint32_t flags, const bson_t *doc) { request_t *request; bool r; @@ -1088,8 +1049,7 @@ mock_server_matches_any_hello_with_json (request_t *request, like to abort the program when checks fail: */ if (MONGOC_OPCODE_MSG == request->opcode) { bson_t *hello_doc = NULL; - const char *hello_str = - "{'hello': 1, 'maxAwaitTimeMS': { '$exists': false }}"; + const char *hello_str = "{'hello': 1, 'maxAwaitTimeMS': { '$exists': false }}"; if (NULL != match_json_op_msg) hello_doc = tmp_bson (match_json_op_msg); @@ -1104,8 +1064,7 @@ mock_server_matches_any_hello_with_json (request_t *request, } } - if (mock_server_matches_legacy_hello ( - request, match_json_op_query ? match_json_op_query : NULL)) { + if (mock_server_matches_legacy_hello (request, match_json_op_query ? match_json_op_query : NULL)) { return request; } @@ -1162,8 +1121,7 @@ mock_server_matches_legacy_hello (request_t *request, const char *match_json) return NULL; } - if (strcasecmp (request->command_name, "hello") && - strcasecmp (request->command_name, HANDSHAKE_CMD_LEGACY_HELLO)) { + if (strcasecmp (request->command_name, "hello") && strcasecmp (request->command_name, HANDSHAKE_CMD_LEGACY_HELLO)) { request_destroy (request); fprintf (stderr, @@ -1175,8 +1133,7 @@ mock_server_matches_legacy_hello (request_t *request, const char *match_json) } formatted_command_json = - bson_strdup_printf ("{'%s': 1, 'maxAwaitTimeMS': { '$exists': false }}", - request->command_name); + bson_strdup_printf ("{'%s': 1, 'maxAwaitTimeMS': { '$exists': false }}", request->command_name); /* request_matches_query() always checks for OPCODE_QUERY, used by legacy * hello: */ @@ -1216,11 +1173,9 @@ mock_server_matches_legacy_hello (request_t *request, const char *match_json) */ request_t * -mock_server_receives_legacy_hello (mock_server_t *server, - const char *match_json) +mock_server_receives_legacy_hello (mock_server_t *server, const char *match_json) { - return mock_server_matches_legacy_hello ( - mock_server_receives_request (server), match_json); + return mock_server_matches_legacy_hello (mock_server_receives_request (server), match_json); } @@ -1245,10 +1200,7 @@ request_t * mock_server_receives_hello (mock_server_t *server) { return mock_server_receives_command ( - server, - "admin", - MONGOC_QUERY_SECONDARY_OK, - "{'hello': 1, 'maxAwaitTimeMS': { '$exists': false }}"); + server, "admin", MONGOC_QUERY_SECONDARY_OK, "{'hello': 1, 'maxAwaitTimeMS': { '$exists': false }}"); } /*-------------------------------------------------------------------------- @@ -1284,8 +1236,7 @@ mock_server_receives_any_hello_with_match (mock_server_t *server, return NULL; } - return mock_server_matches_any_hello_with_json ( - request, match_json_op_msg, match_json_op_query); + return mock_server_matches_any_hello_with_json (request, match_json_op_msg, match_json_op_query); } /*-------------------------------------------------------------------------- @@ -1319,9 +1270,7 @@ mock_server_receives_query (mock_server_t *server, request = mock_server_receives_request (server); - if (request && - !request_matches_query ( - request, ns, flags, skip, n_return, query_json, fields_json, false)) { + if (request && !request_matches_query (request, ns, flags, skip, n_return, query_json, fields_json, false)) { request_destroy (request); return NULL; } @@ -1350,9 +1299,7 @@ request_t * mock_server_receives_hello_op_msg (mock_server_t *server) { return _mock_server_receives_single_msg ( - server, - 0, - tmp_bson ("{'hello': 1, 'maxAwaitTimeMS': { '$exists': false }}")); + server, 0, tmp_bson ("{'hello': 1, 'maxAwaitTimeMS': { '$exists': false }}")); } @@ -1525,9 +1472,7 @@ reply_to_request_simple (request_t *request, const char *docs_json) /* To specify additional flags for OP_MSG replies. */ void -reply_to_op_msg_request (request_t *request, - mongoc_op_msg_flags_t flags, - const bson_t *doc) +reply_to_op_msg_request (request_t *request, mongoc_op_msg_flags_t flags, const bson_t *doc) { reply_t *reply; @@ -1617,21 +1562,19 @@ reply_to_find_request (request_t *request, assert_request_matches_flags (request, flags); if (is_command) { - find_reply = - bson_strdup_printf ("{'ok': 1," - " 'cursor': {" - " 'id': {'$numberLong': '%" PRId64 "'}," - " 'ns': '%s'," - " 'firstBatch': [%s]}}", - cursor_id, - ns, - reply_json); + find_reply = bson_strdup_printf ("{'ok': 1," + " 'cursor': {" + " 'id': {'$numberLong': '%" PRId64 "'}," + " 'ns': '%s'," + " 'firstBatch': [%s]}}", + cursor_id, + ns, + reply_json); reply_to_request_simple (request, find_reply); bson_free (find_reply); } else { - reply_to_request ( - request, MONGOC_REPLY_NONE, cursor_id, 0, number_returned, reply_json); + reply_to_request (request, MONGOC_REPLY_NONE, cursor_id, 0, number_returned, reply_json); } bson_free (db); } @@ -1694,8 +1637,7 @@ mock_server_destroy (mock_server_t *server) _mongoc_array_destroy (&server->worker_threads); for (i = 0; i < server->autoresponders.len; i++) { - handle = &_mongoc_array_index ( - &server->autoresponders, autoresponder_handle_t, i); + handle = &_mongoc_array_index (&server->autoresponders, autoresponder_handle_t, i); autoresponder_handle_destroy (handle); } @@ -1723,8 +1665,7 @@ get_port (mongoc_socket_t *sock) struct sockaddr_storage bound_addr = {0}; mongoc_socklen_t addr_len = (mongoc_socklen_t) sizeof bound_addr; - if (mongoc_socket_getsockname ( - sock, (struct sockaddr *) &bound_addr, &addr_len) < 0) { + if (mongoc_socket_getsockname (sock, (struct sockaddr *) &bound_addr, &addr_len) < 0) { perror ("Failed to get listening port number"); return 0; } @@ -1775,8 +1716,7 @@ static BSON_THREAD_FUN (main_thread, data) bson_mutex_unlock (&server->mutex); for (;;) { - client_sock = mongoc_socket_accept_ex ( - server->sock, bson_get_monotonic_time () + 100 * 1000, &port); + client_sock = mongoc_socket_accept_ex (server->sock, bson_get_monotonic_time () + 100 * 1000, &port); if (_mock_server_stopping (server)) { mongoc_socket_destroy (client_sock); @@ -1785,10 +1725,7 @@ static BSON_THREAD_FUN (main_thread, data) if (client_sock) { test_suite_mock_server_log ( - "%5.2f %hu -> server port %hu (connected)", - mock_server_get_uptime_sec (server), - port, - server->port); + "%5.2f %hu -> server port %hu (connected)", mock_server_get_uptime_sec (server), port, server->port); client_stream = mongoc_stream_socket_new (client_sock); @@ -1797,8 +1734,7 @@ static BSON_THREAD_FUN (main_thread, data) if (server->ssl) { mongoc_stream_t *tls_stream; server->ssl_opts.weak_cert_validation = 1; - tls_stream = mongoc_stream_tls_new_with_hostname ( - client_stream, NULL, &server->ssl_opts, 0); + tls_stream = mongoc_stream_tls_new_with_hostname (client_stream, NULL, &server->ssl_opts, 0); if (!tls_stream) { mongoc_stream_destroy (client_stream); bson_mutex_unlock (&server->mutex); @@ -1829,8 +1765,7 @@ static BSON_THREAD_FUN (main_thread, data) bson_mutex_unlock (&server->mutex); for (i = 0; i < worker_threads.len; i++) { - mcommon_thread_join ( - _mongoc_array_index (&worker_threads, bson_thread_t, i)); + mcommon_thread_join (_mongoc_array_index (&worker_threads, bson_thread_t, i)); } _mongoc_array_destroy (&worker_threads); @@ -1889,8 +1824,7 @@ static BSON_THREAD_FUN (worker_thread, data) bson_mutex_unlock (&server->mutex); if (ssl) { - if (!mongoc_stream_tls_handshake_block ( - client_stream, "localhost", TIMEOUT, &error)) { + if (!mongoc_stream_tls_handshake_block (client_stream, "localhost", TIMEOUT, &error)) { mongoc_stream_close (client_stream); mongoc_stream_destroy (client_stream); bson_free (closure); @@ -1916,8 +1850,7 @@ static BSON_THREAD_FUN (worker_thread, data) GOTO (failure); } - if (_mongoc_buffer_fill ( - &buffer, client_stream, (size_t) msg_len, -1, &error) == -1) { + 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); } @@ -1925,8 +1858,7 @@ static BSON_THREAD_FUN (worker_thread, data) BSON_ASSERT (buffer.len >= (unsigned) msg_len); /* copies message from buffer */ - request = request_new ( - &buffer, msg_len, server, client_stream, closure->port, replies); + request = request_new (&buffer, msg_len, server, client_stream, closure->port, replies); memmove (buffer.data, buffer.data + msg_len, buffer.len - msg_len); buffer.len -= msg_len; @@ -1935,18 +1867,14 @@ static BSON_THREAD_FUN (worker_thread, data) _mongoc_array_copy (&autoresponders, &server->autoresponders); bson_mutex_unlock (&server->mutex); - test_suite_mock_server_log ("%5.2f %hu -> %hu %s", - mock_server_get_uptime_sec (server), - closure->port, - server->port, - request->as_str); + test_suite_mock_server_log ( + "%5.2f %hu -> %hu %s", mock_server_get_uptime_sec (server), closure->port, server->port, request->as_str); /* run responders most-recently-added-first */ handled = false; for (i = server->autoresponders.len - 1u; i >= 0; i--) { - handle = _mongoc_array_index ( - &server->autoresponders, autoresponder_handle_t, i); + handle = _mongoc_array_index (&server->autoresponders, autoresponder_handle_t, i); if (handle.responder (request, handle.data)) { /* responder destroyed request and enqueued a reply in "replies" */ @@ -2000,11 +1928,8 @@ static BSON_THREAD_FUN (worker_thread, data) /* enqueue server reply for this connection's worker thread to send to client */ void -reply_to_request_with_multiple_docs (request_t *request, - mongoc_reply_flags_t flags, - const bson_t *docs, - int n_docs, - int64_t cursor_id) +reply_to_request_with_multiple_docs ( + request_t *request, mongoc_reply_flags_t flags, const bson_t *docs, int n_docs, int64_t cursor_id) { reply_t *reply; int i; @@ -2016,8 +1941,7 @@ reply_to_request_with_multiple_docs (request_t *request, reply->type = REPLY; reply->flags = flags; reply->n_docs = n_docs; - reply->docs = bson_aligned_alloc0 (BSON_ALIGNOF (bson_t), - (size_t) n_docs * sizeof (bson_t)); + reply->docs = bson_aligned_alloc0 (BSON_ALIGNOF (bson_t), (size_t) n_docs * sizeof (bson_t)); for (i = 0; i < n_docs; i++) { bson_copy_to (&docs[i], &reply->docs[i]); @@ -2039,9 +1963,7 @@ reply_to_request_with_multiple_docs (request_t *request, static void -_mock_server_reply_with_stream (mock_server_t *server, - reply_t *reply, - mongoc_stream_t *client) +_mock_server_reply_with_stream (mock_server_t *server, reply_t *reply, mongoc_stream_t *client) { char *doc_json; bson_string_t *docs_json; @@ -2063,8 +1985,7 @@ _mock_server_reply_with_stream (mock_server_t *server, no_linger.l_linger = 0; /* send RST packet to client */ - mongoc_stream_setsockopt ( - client, SOL_SOCKET, SO_LINGER, &no_linger, sizeof no_linger); + mongoc_stream_setsockopt (client, SOL_SOCKET, SO_LINGER, &no_linger, sizeof no_linger); mongoc_stream_close (client); return; @@ -2107,8 +2028,7 @@ _mock_server_reply_with_stream (mock_server_t *server, bson_mutex_lock (&server->mutex); - if (!(reply->request_opcode == MONGOC_OPCODE_QUERY && - reply->query_flags & MONGOC_QUERY_EXHAUST)) { + if (!(reply->request_opcode == MONGOC_OPCODE_QUERY && reply->query_flags & MONGOC_QUERY_EXHAUST)) { server->last_response_id++; } @@ -2169,8 +2089,7 @@ mock_server_set_bind_opts (mock_server_t *server, mock_server_bind_opts_t *opts) } void -rs_response_to_hello ( - mock_server_t *server, int max_wire_version, bool primary, int has_tags, ...) +rs_response_to_hello (mock_server_t *server, int max_wire_version, bool primary, int has_tags, ...) { va_list ap; bson_string_t *hosts; @@ -2178,8 +2097,7 @@ rs_response_to_hello ( mock_server_t *host; ASSERT_WITH_MSG (max_wire_version >= WIRE_VERSION_MIN, - "max_wire_version %" PRId32 - " must be greater than or equal to minimum wire version %d", + "max_wire_version %" PRId32 " must be greater than or equal to minimum wire version %d", max_wire_version, WIRE_VERSION_MIN); @@ -2195,8 +2113,7 @@ rs_response_to_hello ( bson_string_append (hosts, ","); } - bson_string_append_printf ( - hosts, "'%s'", mock_server_get_host_and_port (host)); + bson_string_append_printf (hosts, "'%s'", mock_server_get_host_and_port (host)); } va_end (ap); diff --git a/src/libmongoc/tests/mock_server/mock-server.h b/src/libmongoc/tests/mock_server/mock-server.h index d6c5938296..320af92450 100644 --- a/src/libmongoc/tests/mock_server/mock-server.h +++ b/src/libmongoc/tests/mock_server/mock-server.h @@ -41,9 +41,7 @@ typedef struct _mock_server_bind_opts_t { typedef bool (*autoresponder_t) (request_t *request, void *data); -typedef bool (*hello_callback_func_t) (request_t *request, - void *data, - bson_t *hello_response); +typedef bool (*hello_callback_func_t) (request_t *request, void *data, bson_t *hello_response); typedef void (*destructor_t) (void *data); @@ -60,10 +58,7 @@ mock_server_t * mock_server_down (void); int -mock_server_autoresponds (mock_server_t *server, - autoresponder_t responder, - void *data, - destructor_t destructor); +mock_server_autoresponds (mock_server_t *server, autoresponder_t responder, void *data, destructor_t destructor); void mock_server_remove_autoresponder (mock_server_t *server, int id); @@ -88,8 +83,7 @@ mock_server_set_ssl_opts (mock_server_t *server, mongoc_ssl_opt_t *opts); #endif void -mock_server_set_bind_opts (mock_server_t *server, - mock_server_bind_opts_t *opts); +mock_server_set_bind_opts (mock_server_t *server, mock_server_bind_opts_t *opts); uint16_t mock_server_run (mock_server_t *server); @@ -104,8 +98,7 @@ uint16_t mock_server_get_port (mock_server_t *server); void -mock_server_set_request_timeout_msec (mock_server_t *server, - int64_t request_timeout_msec); +mock_server_set_request_timeout_msec (mock_server_t *server, int64_t request_timeout_msec); bool mock_server_get_rand_delay (mock_server_t *server); @@ -117,18 +110,14 @@ request_t * mock_server_receives_request (mock_server_t *server); request_t * -mock_server_receives_command (mock_server_t *server, - const char *database_name, - mongoc_query_flags_t flags, - const char *command_json, - ...); +mock_server_receives_command ( + mock_server_t *server, const char *database_name, mongoc_query_flags_t flags, const char *command_json, ...); request_t * mock_server_receives_any_hello (mock_server_t *server); request_t * -mock_server_receives_legacy_hello (mock_server_t *server, - const char *match_json); +mock_server_receives_legacy_hello (mock_server_t *server, const char *match_json); request_t * mock_server_receives_hello (mock_server_t *server); @@ -155,15 +144,11 @@ mock_server_receives_kill_cursors (mock_server_t *server, int64_t cursor_id); request_t * _mock_server_receives_msg (mock_server_t *server, uint32_t flags, ...); -#define mock_server_receives_msg(_server, _flags, ...) \ - _mock_server_receives_msg (_server, _flags, __VA_ARGS__, NULL) +#define mock_server_receives_msg(_server, _flags, ...) _mock_server_receives_msg (_server, _flags, __VA_ARGS__, NULL) request_t * -mock_server_receives_bulk_msg (mock_server_t *server, - uint32_t flags, - const bson_t *msg_json, - const bson_t *doc_json, - size_t n_docs); +mock_server_receives_bulk_msg ( + mock_server_t *server, uint32_t flags, const bson_t *msg_json, const bson_t *doc_json, size_t n_docs); void reply_to_request_with_hang_up (request_t *request); @@ -195,29 +180,19 @@ reply_to_find_request (request_t *request, bool is_command); void -reply_to_op_msg_request (request_t *request, - mongoc_op_msg_flags_t flags, - const bson_t *doc); +reply_to_op_msg_request (request_t *request, mongoc_op_msg_flags_t flags, const bson_t *doc); void -reply_to_request_with_multiple_docs (request_t *request, - mongoc_reply_flags_t flags, - const bson_t *docs, - int n_docs, - int64_t cursor_id); +reply_to_request_with_multiple_docs ( + request_t *request, mongoc_reply_flags_t flags, const bson_t *docs, int n_docs, int64_t cursor_id); void mock_server_destroy (mock_server_t *server); void -rs_response_to_hello (mock_server_t *server, - int max_wire_version, - bool primary, - int has_tags, - ...); +rs_response_to_hello (mock_server_t *server, int max_wire_version, bool primary, int has_tags, ...); #define RS_RESPONSE_TO_HELLO(server, max_wire_version, primary, has_tags, ...) \ - rs_response_to_hello ( \ - server, max_wire_version, primary, has_tags, __VA_ARGS__, NULL) + rs_response_to_hello (server, max_wire_version, primary, has_tags, __VA_ARGS__, NULL) #endif /* MOCK_SERVER_H */ diff --git a/src/libmongoc/tests/mock_server/request.c b/src/libmongoc/tests/mock_server/request.c index 2a9ab43a7a..4226adc4e3 100644 --- a/src/libmongoc/tests/mock_server/request.c +++ b/src/libmongoc/tests/mock_server/request.c @@ -64,8 +64,7 @@ request_new (const mongoc_buffer_t *buffer, memcpy (request->data, buffer->data, request->data_len); const void *data_end = NULL; - request->rpc = - mcd_rpc_message_from_data (request->data, request->data_len, &data_end); + request->rpc = mcd_rpc_message_from_data (request->data, request->data_len, &data_end); if (!request->rpc) { test_error ("failed to parse incoming message due to byte %zu of %zu", @@ -160,8 +159,7 @@ request_matches_query (const request_t *request, doc_as_json = NULL; } - if (!match_json ( - doc, is_command, __FILE__, __LINE__, BSON_FUNC, query_json)) { + if (!match_json (doc, is_command, __FILE__, __LINE__, BSON_FUNC, query_json)) { /* match_json has logged the err */ goto done; } @@ -192,31 +190,22 @@ request_matches_query (const request_t *request, goto done; } - const char *const request_ns = - mcd_rpc_op_query_get_full_collection_name (request->rpc); + const char *const request_ns = mcd_rpc_op_query_get_full_collection_name (request->rpc); if (0 != strcmp (request_ns, ns)) { - test_error ("request's namespace is '%s', expected '%s': %s", - request_ns, - ns, - doc_as_json); + test_error ("request's namespace is '%s', expected '%s': %s", request_ns, ns, doc_as_json); goto done; } assert_request_matches_flags (request, flags); - const int32_t request_skip = - mcd_rpc_op_query_get_number_to_skip (request->rpc); + const int32_t request_skip = mcd_rpc_op_query_get_number_to_skip (request->rpc); if (bson_cmp_not_equal_su (request_skip, skip)) { - test_error ("requests's skip = %" PRId32 ", expected %" PRIu32 ": %s", - request_skip, - skip, - doc_as_json); + test_error ("requests's skip = %" PRId32 ", expected %" PRIu32 ": %s", request_skip, skip, doc_as_json); goto done; } - const int32_t request_n_return = - mcd_rpc_op_query_get_number_to_return (request->rpc); + const int32_t request_n_return = mcd_rpc_op_query_get_number_to_return (request->rpc); bool n_return_equal = (request_n_return == n_return); if (!n_return_equal && abs (request_n_return) == 1) { @@ -227,10 +216,8 @@ request_matches_query (const request_t *request, } if (!n_return_equal) { - test_error ("requests's n_return = %" PRId32 ", expected %" PRId32 ": %s", - request_n_return, - n_return, - doc_as_json); + test_error ( + "requests's n_return = %" PRId32 ", expected %" PRId32 ": %s", request_n_return, n_return, doc_as_json); goto done; } @@ -249,25 +236,19 @@ request_matches_kill_cursors (const request_t *request, int64_t cursor_id) BSON_ASSERT (request); if (request->opcode != MONGOC_OPCODE_KILL_CURSORS) { - test_error ("request's opcode does not match KILL_CURSORS, got: %d", - request->opcode); + test_error ("request's opcode does not match KILL_CURSORS, got: %d", request->opcode); return false; } - const int32_t request_n_cursors = - mcd_rpc_op_kill_cursors_get_number_of_cursor_ids (request->rpc); + const int32_t request_n_cursors = mcd_rpc_op_kill_cursors_get_number_of_cursor_ids (request->rpc); if (request_n_cursors != 1) { - test_error ("request's n_cursors is %" PRId32 ", expected 1", - request_n_cursors); + test_error ("request's n_cursors is %" PRId32 ", expected 1", request_n_cursors); return false; } - const int64_t request_cursor_id = - mcd_rpc_op_kill_cursors_get_cursor_ids (request->rpc)[0]; + const int64_t request_cursor_id = mcd_rpc_op_kill_cursors_get_cursor_ids (request->rpc)[0]; if (request_cursor_id != cursor_id) { - test_error ("request's cursor_id %" PRId64 ", expected %" PRId64, - request_cursor_id, - cursor_id); + test_error ("request's cursor_id %" PRId64 ", expected %" PRId64, request_cursor_id, cursor_id); return false; } @@ -295,10 +276,7 @@ request_matches_kill_cursors (const request_t *request, int64_t cursor_id) */ bool -request_matches_msg (const request_t *request, - uint32_t flags, - const bson_t **docs, - size_t n_docs) +request_matches_msg (const request_t *request, uint32_t flags, const bson_t **docs, size_t n_docs) { const bson_t *doc; const bson_t *pattern; @@ -317,23 +295,16 @@ request_matches_msg (const request_t *request, /* make sure the pattern is reasonable, e.g. that we didn't pass a string * instead of a bson_t* by mistake */ - ASSERT_WITH_MSG (bson_validate_with_error (pattern, - BSON_VALIDATE_EMPTY_KEYS | - BSON_VALIDATE_UTF8, - &bson_error), + ASSERT_WITH_MSG (bson_validate_with_error (pattern, BSON_VALIDATE_EMPTY_KEYS | BSON_VALIDATE_UTF8, &bson_error), "invalid argument at position %zu (note: must be " - "bson_t*, not char*):\ndomain: %" PRIu32 - ", code: %" PRIu32 ", message: %s\n", + "bson_t*, not char*):\ndomain: %" PRIu32 ", code: %" PRIu32 ", message: %s\n", i, bson_error.domain, bson_error.code, bson_error.message); if (i > request->docs.len) { - fprintf (stderr, - "Expected at least %zu documents in request, got %zu\n", - i, - request->docs.len); + fprintf (stderr, "Expected at least %zu documents in request, got %zu\n", i, request->docs.len); return false; } @@ -344,19 +315,13 @@ request_matches_msg (const request_t *request, } if (n_docs < request->docs.len) { - fprintf (stderr, - "Expected %zu documents in request, got %zu\n", - n_docs, - request->docs.len); + fprintf (stderr, "Expected %zu documents in request, got %zu\n", n_docs, request->docs.len); return false; } const uint32_t request_flags = mcd_rpc_op_msg_get_flag_bits (request->rpc); if (request_flags != flags) { - fprintf (stderr, - "Expected OP_MSG flags %" PRIu32 ", got %" PRIu32 "\n", - flags, - request_flags); + fprintf (stderr, "Expected OP_MSG flags %" PRIu32 ", got %" PRIu32 "\n", flags, request_flags); return false; } @@ -569,15 +534,11 @@ request_from_query (request_t *request) char *str; const int32_t request_flags = mcd_rpc_op_query_get_flags (request->rpc); - const char *const request_coll = - mcd_rpc_op_query_get_full_collection_name (request->rpc); - const int32_t request_skip = - mcd_rpc_op_query_get_number_to_skip (request->rpc); - const int32_t request_return = - mcd_rpc_op_query_get_number_to_return (request->rpc); + const char *const request_coll = mcd_rpc_op_query_get_full_collection_name (request->rpc); + const int32_t request_skip = mcd_rpc_op_query_get_number_to_skip (request->rpc); + const int32_t request_return = mcd_rpc_op_query_get_number_to_return (request->rpc); const void *const request_query = mcd_rpc_op_query_get_query (request->rpc); - const void *const request_fields = - mcd_rpc_op_query_get_return_fields_selector (request->rpc); + const void *const request_fields = mcd_rpc_op_query_get_return_fields_selector (request->rpc); { const int32_t len = length_prefix (request_query); @@ -625,8 +586,7 @@ request_from_query (request_t *request) } if (request_return) { - bson_string_append_printf ( - query_as_str, " n_return=%" PRId32, request_return); + bson_string_append_printf (query_as_str, " n_return=%" PRId32, request_return); } request->as_str = bson_string_free (query_as_str, false); @@ -637,30 +597,24 @@ static void request_from_killcursors (request_t *request) { /* protocol allows multiple cursor ids but we only implement one */ - BSON_ASSERT ( - mcd_rpc_op_kill_cursors_get_number_of_cursor_ids (request->rpc) == 1); - request->as_str = bson_strdup_printf ( - "OP_KILLCURSORS %" PRId64, - mcd_rpc_op_kill_cursors_get_cursor_ids (request->rpc)[0]); + BSON_ASSERT (mcd_rpc_op_kill_cursors_get_number_of_cursor_ids (request->rpc) == 1); + request->as_str = + bson_strdup_printf ("OP_KILLCURSORS %" PRId64, mcd_rpc_op_kill_cursors_get_cursor_ids (request->rpc)[0]); } static void request_from_getmore (request_t *request) { - request->as_str = bson_strdup_printf ( - "OP_GETMORE %s %" PRId64 " n_return=%d", - mcd_rpc_op_get_more_get_full_collection_name (request->rpc), - mcd_rpc_op_get_more_get_cursor_id (request->rpc), - mcd_rpc_op_get_more_get_number_to_return (request->rpc)); + request->as_str = bson_strdup_printf ("OP_GETMORE %s %" PRId64 " n_return=%d", + mcd_rpc_op_get_more_get_full_collection_name (request->rpc), + mcd_rpc_op_get_more_get_cursor_id (request->rpc), + mcd_rpc_op_get_more_get_number_to_return (request->rpc)); } static void -parse_op_msg_doc (request_t *request, - const uint8_t *data, - size_t data_len, - bson_string_t *msg_as_str) +parse_op_msg_doc (request_t *request, const uint8_t *data, size_t data_len, bson_string_t *msg_as_str) { const uint8_t *pos = data; while (pos < data + data_len) { @@ -687,34 +641,26 @@ request_from_op_msg (request_t *request) { bson_string_t *msg_as_str = bson_string_new ("OP_MSG"); - const size_t sections_count = - mcd_rpc_op_msg_get_sections_count (request->rpc); + const size_t sections_count = mcd_rpc_op_msg_get_sections_count (request->rpc); BSON_ASSERT (sections_count <= 2u); for (size_t index = 0; index < sections_count; ++index) { bson_string_append (msg_as_str, (index > 0 ? ", " : " ")); - const uint8_t kind = - mcd_rpc_op_msg_section_get_kind (request->rpc, index); + const uint8_t kind = mcd_rpc_op_msg_section_get_kind (request->rpc, index); switch (kind) { case 0: { /* a single BSON document */ - const void *const body = - mcd_rpc_op_msg_section_get_body (request->rpc, index); - parse_op_msg_doc ( - request, body, (size_t) length_prefix (body), msg_as_str); + const void *const body = mcd_rpc_op_msg_section_get_body (request->rpc, index); + parse_op_msg_doc (request, body, (size_t) length_prefix (body), msg_as_str); break; } case 1: { /* a sequence of BSON documents */ - bson_string_append ( - msg_as_str, - mcd_rpc_op_msg_section_get_identifier (request->rpc, index)); + bson_string_append (msg_as_str, mcd_rpc_op_msg_section_get_identifier (request->rpc, index)); bson_string_append (msg_as_str, ": ["); - parse_op_msg_doc ( - request, - mcd_rpc_op_msg_section_get_document_sequence (request->rpc, index), - mcd_rpc_op_msg_section_get_document_sequence_length (request->rpc, - index), - msg_as_str); + parse_op_msg_doc (request, + mcd_rpc_op_msg_section_get_document_sequence (request->rpc, index), + mcd_rpc_op_msg_section_get_document_sequence_length (request->rpc, index), + msg_as_str); bson_string_append (msg_as_str, "]"); break; diff --git a/src/libmongoc/tests/mock_server/request.h b/src/libmongoc/tests/mock_server/request.h index 7e50fb879c..896539ae9c 100644 --- a/src/libmongoc/tests/mock_server/request.h +++ b/src/libmongoc/tests/mock_server/request.h @@ -73,10 +73,7 @@ bool request_matches_kill_cursors (const request_t *request, int64_t cursor_id); bool -request_matches_msg (const request_t *request, - uint32_t flags, - const bson_t **docs, - size_t n_docs); +request_matches_msg (const request_t *request, uint32_t flags, const bson_t **docs, size_t n_docs); bool request_matches_msgv (const request_t *request, uint32_t flags, va_list *args); diff --git a/src/libmongoc/tests/ssl-test.c b/src/libmongoc/tests/ssl-test.c index 04475ae696..43ee2791b7 100644 --- a/src/libmongoc/tests/ssl-test.c +++ b/src/libmongoc/tests/ssl-test.c @@ -56,13 +56,11 @@ static BSON_THREAD_FUN (ssl_test_server, ptr) server_addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK); server_addr.sin_port = htons (0); - r = mongoc_socket_bind ( - listen_sock, (struct sockaddr *) &server_addr, sizeof server_addr); + r = mongoc_socket_bind (listen_sock, (struct sockaddr *) &server_addr, sizeof server_addr); BSON_ASSERT (r == 0); sock_len = sizeof (server_addr); - r = mongoc_socket_getsockname ( - listen_sock, (struct sockaddr *) &server_addr, &sock_len); + r = mongoc_socket_getsockname (listen_sock, (struct sockaddr *) &server_addr, &sock_len); BSON_ASSERT (r == 0); r = mongoc_socket_listen (listen_sock, 10); @@ -78,8 +76,7 @@ static BSON_THREAD_FUN (ssl_test_server, ptr) sock_stream = mongoc_stream_socket_new (conn_sock); BSON_ASSERT (sock_stream); - ssl_stream = - mongoc_stream_tls_new_with_hostname (sock_stream, NULL, data->server, 0); + ssl_stream = mongoc_stream_tls_new_with_hostname (sock_stream, NULL, data->server, 0); if (!ssl_stream) { #ifdef MONGOC_ENABLE_SSL_OPENSSL unsigned long err = ERR_get_error (); @@ -91,9 +88,7 @@ static BSON_THREAD_FUN (ssl_test_server, ptr) data->server_result->ssl_err = err; data->server_result->result = SSL_TEST_SSL_INIT; #ifdef MONGOC_ENABLE_SSL_OPENSSL - MONGOC_ERROR ("ERRORED (line: %d): %s\n", - __LINE__, - ERR_error_string (ERR_get_error (), NULL)); + MONGOC_ERROR ("ERRORED (line: %d): %s\n", __LINE__, ERR_error_string (ERR_get_error (), NULL)); #endif mongoc_stream_destroy (sock_stream); mongoc_socket_destroy (listen_sock); @@ -102,8 +97,7 @@ static BSON_THREAD_FUN (ssl_test_server, ptr) } BSON_ASSERT (ssl_stream); - r = mongoc_stream_tls_handshake_block ( - ssl_stream, data->host, TIMEOUT, &error); + r = mongoc_stream_tls_handshake_block (ssl_stream, data->host, TIMEOUT, &error); if (!r) { unsigned long err = 43; @@ -125,8 +119,7 @@ static BSON_THREAD_FUN (ssl_test_server, ptr) if (r < 0) { data->server_result->err = errno; data->server_result->result = SSL_TEST_TIMEOUT; - MONGOC_ERROR ( - "ERRORED (line: %d): %s\n", __LINE__, "mongoc_stream_readv failed."); + MONGOC_ERROR ("ERRORED (line: %d): %s\n", __LINE__, "mongoc_stream_readv failed."); mongoc_stream_destroy (ssl_stream); mongoc_socket_destroy (listen_sock); @@ -196,17 +189,14 @@ static BSON_THREAD_FUN (ssl_test_client, ptr) server_addr.sin_port = htons (data->server_port); server_addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK); - r = mongoc_socket_connect ( - conn_sock, (struct sockaddr *) &server_addr, sizeof (server_addr), -1); + r = mongoc_socket_connect (conn_sock, (struct sockaddr *) &server_addr, sizeof (server_addr), -1); if (r != 0) { - test_error ( - "mongoc_socket_connect returned %zd: \"%s\"", r, strerror (errno)); + test_error ("mongoc_socket_connect returned %zd: \"%s\"", r, strerror (errno)); } sock_stream = mongoc_stream_socket_new (conn_sock); BSON_ASSERT (sock_stream); - ssl_stream = mongoc_stream_tls_new_with_hostname ( - sock_stream, data->host, data->client, 1); + ssl_stream = mongoc_stream_tls_new_with_hostname (sock_stream, data->host, data->client, 1); if (!ssl_stream) { #ifdef MONGOC_ENABLE_SSL_OPENSSL unsigned long err = ERR_get_error (); @@ -217,9 +207,7 @@ static BSON_THREAD_FUN (ssl_test_client, ptr) data->client_result->ssl_err = err; data->client_result->result = SSL_TEST_SSL_INIT; - MONGOC_ERROR ("ERRORED (line: %d): %s\n", - __LINE__, - "mongoc_stream_tls_new_with_hostname failed."); + MONGOC_ERROR ("ERRORED (line: %d): %s\n", __LINE__, "mongoc_stream_tls_new_with_hostname failed."); mongoc_stream_destroy (sock_stream); @@ -227,8 +215,7 @@ static BSON_THREAD_FUN (ssl_test_client, ptr) } BSON_ASSERT (ssl_stream); - r = mongoc_stream_tls_handshake_block ( - ssl_stream, data->host, TIMEOUT, &error); + r = mongoc_stream_tls_handshake_block (ssl_stream, data->host, TIMEOUT, &error); if (!r) { unsigned long err = 45; diff --git a/src/libmongoc/tests/test-atlas-executor.c b/src/libmongoc/tests/test-atlas-executor.c index 5bdcccf3c5..237c6ab39e 100644 --- a/src/libmongoc/tests/test-atlas-executor.c +++ b/src/libmongoc/tests/test-atlas-executor.c @@ -73,17 +73,11 @@ main (int argc, char **argv) TestSuite_Init_Atlas (&suite, argc, argv); bson_error_t error; - bson_t *const bson = - bson_new_from_json ((const uint8_t *) argv[1], -1, &error); + bson_t *const bson = bson_new_from_json ((const uint8_t *) argv[1], -1, &error); ASSERT_OR_PRINT (bson, error); - TestSuite_AddFull (&suite, - "test", - (TestFuncWC) &run_one_test_file, - (TestFuncDtor) &bson_destroy, - bson, - TestSuite_CheckLive, - NULL); + TestSuite_AddFull ( + &suite, "test", (TestFuncWC) &run_one_test_file, (TestFuncDtor) &bson_destroy, bson, TestSuite_CheckLive, NULL); mongoc_init (); TestSuite_Run_Atlas (&suite); diff --git a/src/libmongoc/tests/test-awsauth.c b/src/libmongoc/tests/test-awsauth.c index 44cd22acb2..121e4807e8 100644 --- a/src/libmongoc/tests/test-awsauth.c +++ b/src/libmongoc/tests/test-awsauth.c @@ -32,43 +32,34 @@ } else \ ((void) 0) -#define ASSERT(Cond) \ - if (1) { \ - if (!(Cond)) { \ - MONGOC_STDERR_PRINTF ("FAIL:%s:%d %s()\n Condition '%s' failed.\n", \ - __FILE__, \ - __LINE__, \ - BSON_FUNC, \ - BSON_STR (Cond)); \ - abort (); \ - } \ - } else \ +#define ASSERT(Cond) \ + if (1) { \ + if (!(Cond)) { \ + MONGOC_STDERR_PRINTF ( \ + "FAIL:%s:%d %s()\n Condition '%s' failed.\n", __FILE__, __LINE__, BSON_FUNC, BSON_STR (Cond)); \ + abort (); \ + } \ + } else \ ((void) 0) -#define ASSERTF(Cond, Fmt, ...) \ - if (1) { \ - if (!(Cond)) { \ - MONGOC_STDERR_PRINTF ("FAIL:%s:%d %s()\n Condition '%s' failed.\n", \ - __FILE__, \ - __LINE__, \ - BSON_FUNC, \ - BSON_STR (Cond)); \ - MONGOC_STDERR_PRINTF ("MESSAGE: " Fmt "\n", __VA_ARGS__); \ - abort (); \ - } \ - } else \ +#define ASSERTF(Cond, Fmt, ...) \ + if (1) { \ + if (!(Cond)) { \ + MONGOC_STDERR_PRINTF ( \ + "FAIL:%s:%d %s()\n Condition '%s' failed.\n", __FILE__, __LINE__, BSON_FUNC, BSON_STR (Cond)); \ + MONGOC_STDERR_PRINTF ("MESSAGE: " Fmt "\n", __VA_ARGS__); \ + abort (); \ + } \ + } else \ ((void) 0) -#define FAILF(Fmt, ...) \ - if (1) { \ - MONGOC_STDERR_PRINTF ("FAIL:%s:%d %s()\n Condition '%s' failed.\n", \ - __FILE__, \ - __LINE__, \ - BSON_FUNC, \ - BSON_STR (Cond)); \ - MONGOC_STDERR_PRINTF ("MESSAGE: " Fmt "\n", __VA_ARGS__); \ - abort (); \ - } else \ +#define FAILF(Fmt, ...) \ + if (1) { \ + MONGOC_STDERR_PRINTF ( \ + "FAIL:%s:%d %s()\n Condition '%s' failed.\n", __FILE__, __LINE__, BSON_FUNC, BSON_STR (Cond)); \ + MONGOC_STDERR_PRINTF ("MESSAGE: " Fmt "\n", __VA_ARGS__); \ + abort (); \ + } else \ ((void) 0) static void @@ -76,12 +67,8 @@ test_auth (mongoc_database_t *db, bool expect_failure) { bson_error_t error; bson_t *ping = BCON_NEW ("ping", BCON_INT32 (1)); - bool ok = mongoc_database_command_with_opts (db, - ping, - NULL /* read_prefs */, - NULL /* opts */, - NULL /* reply */, - &error); + bool ok = + mongoc_database_command_with_opts (db, ping, NULL /* read_prefs */, NULL /* opts */, NULL /* reply */, &error); if (expect_failure) { ASSERTF (!ok, "%s", "Expected auth failure, but got success"); } else { @@ -110,8 +97,7 @@ creds_eq (_mongoc_aws_credentials_t *a, _mongoc_aws_credentials_t *b) return false; } if (a->expiration.set) { - if (mcd_time_compare (a->expiration.value.expire_at, - b->expiration.value.expire_at) != 0) { + if (mcd_time_compare (a->expiration.value.expire_at, b->expiration.value.expire_at) != 0) { return false; } } @@ -155,10 +141,8 @@ do_find (mongoc_client_t *client, bson_error_t *error) ASSERT (client); bson_t *filter = bson_new (); - mongoc_collection_t *coll = - mongoc_client_get_collection (client, "aws", "coll"); - mongoc_cursor_t *cursor = mongoc_collection_find_with_opts ( - coll, filter, NULL /* opts */, NULL /* read prefs */); + mongoc_collection_t *coll = mongoc_client_get_collection (client, "aws", "coll"); + mongoc_cursor_t *cursor = mongoc_collection_find_with_opts (coll, filter, NULL /* opts */, NULL /* read prefs */); const bson_t *doc; while (mongoc_cursor_next (cursor, &doc)) ; @@ -190,8 +174,7 @@ test_cache (const mongoc_uri_t *uri) ASSERT (client); // Ensure that a ``find`` operation adds credentials to the cache. - ASSERTF ( - do_find (client, &error), "expected success, got: %s", error.message); + ASSERTF (do_find (client, &error), "expected success, got: %s", error.message); bool found = _mongoc_aws_credentials_cache_get (&creds); ASSERT (found); _mongoc_aws_credentials_cleanup (&creds); @@ -204,10 +187,8 @@ test_cache (const mongoc_uri_t *uri) ASSERT (mongoc_aws_credentials_cache.cached.set); mongoc_aws_credentials_cache.cached.value.expiration.set = true; mongoc_aws_credentials_cache.cached.value.expiration.value = - mcd_timer_expire_after (mcd_milliseconds ( - 60 * 1000 - MONGOC_AWS_CREDENTIALS_EXPIRATION_WINDOW_MS)); - _mongoc_aws_credentials_copy_to ( - &mongoc_aws_credentials_cache.cached.value, &first_cached); + mcd_timer_expire_after (mcd_milliseconds (60 * 1000 - MONGOC_AWS_CREDENTIALS_EXPIRATION_WINDOW_MS)); + _mongoc_aws_credentials_copy_to (&mongoc_aws_credentials_cache.cached.value, &first_cached); } // Create a new client. @@ -216,14 +197,12 @@ test_cache (const mongoc_uri_t *uri) mongoc_client_t *client = mongoc_client_new_from_uri (uri); ASSERT (client); // Ensure that a ``find`` operation updates the credentials in the cache. - ASSERTF ( - do_find (client, &error), "expected success, got: %s", error.message); + ASSERTF (do_find (client, &error), "expected success, got: %s", error.message); bool found = _mongoc_aws_credentials_cache_get (&creds); ASSERT (found); - ASSERTF ( - !creds_eq (&first_cached, &mongoc_aws_credentials_cache.cached.value), - "%s", - "expected unequal credentials, got equal"); + ASSERTF (!creds_eq (&first_cached, &mongoc_aws_credentials_cache.cached.value), + "%s", + "expected unequal credentials, got equal"); _mongoc_aws_credentials_cleanup (&creds); mongoc_client_destroy (client); } @@ -233,8 +212,7 @@ test_cache (const mongoc_uri_t *uri) { ASSERT (mongoc_aws_credentials_cache.cached.set); bson_free (mongoc_aws_credentials_cache.cached.value.access_key_id); - mongoc_aws_credentials_cache.cached.value.access_key_id = - bson_strdup ("invalid"); + mongoc_aws_credentials_cache.cached.value.access_key_id = bson_strdup ("invalid"); } // Create a new client. @@ -256,8 +234,7 @@ test_cache (const mongoc_uri_t *uri) _mongoc_aws_credentials_cleanup (&creds); // Ensure that a subsequent ``find`` operation succeeds. - ASSERTF ( - do_find (client, &error), "expected success, got: %s", error.message); + ASSERTF (do_find (client, &error), "expected success, got: %s", error.message); // Ensure that the cache has been set. found = _mongoc_aws_credentials_cache_get (&creds); @@ -289,22 +266,15 @@ test_cache_with_env (const mongoc_uri_t *uri) ASSERT (client); // Ensure that a ``find`` operation adds credentials to the cache. - ASSERTF ( - do_find (client, &error), "expected success, got: %s", error.message); + ASSERTF (do_find (client, &error), "expected success, got: %s", error.message); bool found = _mongoc_aws_credentials_cache_get (&creds); ASSERT (found); _mongoc_aws_credentials_cleanup (&creds); // Set the AWS environment variables based on the cached credentials. - ASSERT (_mongoc_setenv ( - "AWS_ACCESS_KEY_ID", - mongoc_aws_credentials_cache.cached.value.access_key_id)); - ASSERT (_mongoc_setenv ( - "AWS_SECRET_ACCESS_KEY", - mongoc_aws_credentials_cache.cached.value.secret_access_key)); - ASSERT (_mongoc_setenv ( - "AWS_SESSION_TOKEN", - mongoc_aws_credentials_cache.cached.value.session_token)); + ASSERT (_mongoc_setenv ("AWS_ACCESS_KEY_ID", mongoc_aws_credentials_cache.cached.value.access_key_id)); + ASSERT (_mongoc_setenv ("AWS_SECRET_ACCESS_KEY", mongoc_aws_credentials_cache.cached.value.secret_access_key)); + ASSERT (_mongoc_setenv ("AWS_SESSION_TOKEN", mongoc_aws_credentials_cache.cached.value.session_token)); // Clear the cache. _mongoc_aws_credentials_cache_clear (); @@ -318,8 +288,7 @@ test_cache_with_env (const mongoc_uri_t *uri) ASSERT (client); // Ensure that a ``find`` operation succeeds and does not add credentials // to the cache. - ASSERTF ( - do_find (client, &error), "expected success, got: %s", error.message); + ASSERTF (do_find (client, &error), "expected success, got: %s", error.message); bool found = _mongoc_aws_credentials_cache_get (&creds); ASSERT (!found); _mongoc_aws_credentials_cleanup (&creds); @@ -355,8 +324,7 @@ test_cache_with_env (const mongoc_uri_t *uri) ASSERT (client); // Ensure that a ``find`` operation adds credentials to the cache. - ASSERTF ( - do_find (client, &error), "expected success, got: %s", error.message); + ASSERTF (do_find (client, &error), "expected success, got: %s", error.message); bool found = _mongoc_aws_credentials_cache_get (&creds); ASSERT (found); _mongoc_aws_credentials_cleanup (&creds); @@ -373,8 +341,7 @@ test_cache_with_env (const mongoc_uri_t *uri) ASSERT (client); // Ensure that a ``find`` operation succeeds. - ASSERTF ( - do_find (client, &error), "expected success, got: %s", error.message); + ASSERTF (do_find (client, &error), "expected success, got: %s", error.message); bool found = _mongoc_aws_credentials_cache_get (&creds); ASSERT (found); _mongoc_aws_credentials_cleanup (&creds); @@ -394,8 +361,7 @@ BSON_THREAD_FUN (auth_fn, uri_void) ASSERT (client); // Ensure that a ``find`` operation succeeds. - ASSERTF ( - do_find (client, &error), "expected success, got: %s", error.message); + ASSERTF (do_find (client, &error), "expected success, got: %s", error.message); mongoc_client_destroy (client); BSON_THREAD_RETURN; @@ -425,10 +391,7 @@ test_multithreaded (const mongoc_uri_t *uri) } static void -log_func (mongoc_log_level_t log_level, - const char *log_domain, - const char *message, - void *user_data) +log_func (mongoc_log_level_t log_level, const char *log_domain, const char *message, void *user_data) { if (log_level != MONGOC_LOG_LEVEL_TRACE) { mongoc_log_default_handler (log_level, log_domain, message, user_data); @@ -470,9 +433,7 @@ main (int argc, char *argv[]) } else if (0 == strcmp (argv[2], "EXPECT_SUCCESS")) { expect_failure = false; } else { - FAILF ( - "Expected 'EXPECT_FAILURE' or 'EXPECT_SUCCESS' for argument. Got: %s", - argv[2]); + FAILF ("Expected 'EXPECT_FAILURE' or 'EXPECT_SUCCESS' for argument. Got: %s", argv[2]); } client = mongoc_client_new_from_uri (uri); diff --git a/src/libmongoc/tests/test-azurekms.c b/src/libmongoc/tests/test-azurekms.c index 52c1121b49..13705d44f5 100644 --- a/src/libmongoc/tests/test-azurekms.c +++ b/src/libmongoc/tests/test-azurekms.c @@ -19,19 +19,16 @@ main (void) mongoc_client_t *keyvault_client = mongoc_client_new (mongodb_uri); MONGOC_DEBUG ("libmongoc version: %s", mongoc_get_version ()); - mongoc_client_encryption_opts_t *ceopts = - mongoc_client_encryption_opts_new (); + mongoc_client_encryption_opts_t *ceopts = mongoc_client_encryption_opts_new (); mongoc_client_encryption_opts_set_keyvault_client (ceopts, keyvault_client); - mongoc_client_encryption_opts_set_keyvault_namespace ( - ceopts, "keyvault", "datakeys"); + mongoc_client_encryption_opts_set_keyvault_namespace (ceopts, "keyvault", "datakeys"); bson_t *kms_providers = BCON_NEW ("azure", "{", "}"); mongoc_client_encryption_opts_set_kms_providers (ceopts, kms_providers); bson_error_t error; - mongoc_client_encryption_t *ce = - mongoc_client_encryption_new (ceopts, &error); + mongoc_client_encryption_t *ce = mongoc_client_encryption_new (ceopts, &error); if (!ce) { MONGOC_ERROR ("Error in mongoc_client_encryption_new: %s", error.message); return EXIT_FAILURE; @@ -39,32 +36,24 @@ main (void) mongoc_client_encryption_datakey_opts_t *dkopts; dkopts = mongoc_client_encryption_datakey_opts_new (); - bson_t *masterkey = BCON_NEW ("keyVaultEndpoint", - BCON_UTF8 (keyVaultEndpoint), - "keyName", - BCON_UTF8 (keyName)); + bson_t *masterkey = BCON_NEW ("keyVaultEndpoint", BCON_UTF8 (keyVaultEndpoint), "keyName", BCON_UTF8 (keyName)); mongoc_client_encryption_datakey_opts_set_masterkey (dkopts, masterkey); bson_value_t keyid; - bool got = mongoc_client_encryption_create_datakey ( - ce, "azure", dkopts, &keyid, &error); + bool got = mongoc_client_encryption_create_datakey (ce, "azure", dkopts, &keyid, &error); if (NULL != expect_error) { if (got) { - MONGOC_ERROR ("Expected error to contain %s, but got success", - expect_error); + MONGOC_ERROR ("Expected error to contain %s, but got success", expect_error); return EXIT_FAILURE; } if (NULL == strstr (error.message, expect_error)) { - MONGOC_ERROR ("Expected error to contain %s, but got: %s", - expect_error, - error.message); + MONGOC_ERROR ("Expected error to contain %s, but got: %s", expect_error, error.message); return EXIT_FAILURE; } } else { if (!got) { - MONGOC_ERROR ("Expected to create data key, but got error: %s", - error.message); + MONGOC_ERROR ("Expected to create data key, but got error: %s", error.message); return EXIT_FAILURE; } MONGOC_DEBUG ("Created key\n"); diff --git a/src/libmongoc/tests/test-conveniences.c b/src/libmongoc/tests/test-conveniences.c index 4c1afd022b..4dba1337a9 100644 --- a/src/libmongoc/tests/test-conveniences.c +++ b/src/libmongoc/tests/test-conveniences.c @@ -192,8 +192,7 @@ bson_iter_bson (const bson_iter_t *iter, bson_t *bson) uint32_t len; const uint8_t *data; - BSON_ASSERT (BSON_ITER_HOLDS_DOCUMENT (iter) || - BSON_ITER_HOLDS_ARRAY (iter)); + BSON_ASSERT (BSON_ITER_HOLDS_DOCUMENT (iter) || BSON_ITER_HOLDS_ARRAY (iter)); if (BSON_ITER_HOLDS_DOCUMENT (iter)) { bson_iter_document (iter, &len, &data); @@ -219,10 +218,7 @@ bson_lookup_utf8 (const bson_t *b, const char *key) bson_iter_t iter; bson_lookup (b, key, &iter); - ASSERT_WITH_MSG (BSON_ITER_HOLDS_UTF8 (&iter), - "'%s' is not a string: %s", - key, - tmp_json (b)); + ASSERT_WITH_MSG (BSON_ITER_HOLDS_UTF8 (&iter), "'%s' is not a string: %s", key, tmp_json (b)); return bson_iter_utf8 (&iter, NULL); } @@ -307,10 +303,7 @@ bson_lookup_bool (const bson_t *b, const char *key) bson_iter_t iter; bson_lookup (b, key, &iter); - ASSERT_WITH_MSG (BSON_ITER_HOLDS_BOOL (&iter), - "'%s' is not a bool: %s", - key, - tmp_json (b)); + ASSERT_WITH_MSG (BSON_ITER_HOLDS_BOOL (&iter), "'%s' is not a bool: %s", key, tmp_json (b)); return bson_iter_bool (&iter); } @@ -330,10 +323,7 @@ bson_lookup_int32 (const bson_t *b, const char *key) bson_iter_t iter; bson_lookup (b, key, &iter); - ASSERT_WITH_MSG (BSON_ITER_HOLDS_INT32 (&iter), - "'%s' is not a int32: %s", - key, - tmp_json (b)); + ASSERT_WITH_MSG (BSON_ITER_HOLDS_INT32 (&iter), "'%s' is not a int32: %s", key, tmp_json (b)); return bson_iter_int32 (&iter); } @@ -353,10 +343,7 @@ bson_lookup_int64 (const bson_t *b, const char *key) bson_iter_t iter; bson_lookup (b, key, &iter); - ASSERT_WITH_MSG (BSON_ITER_HOLDS_INT64 (&iter), - "'%s' is not a int64: %s", - key, - tmp_json (b)); + ASSERT_WITH_MSG (BSON_ITER_HOLDS_INT64 (&iter), "'%s' is not a int64: %s", key, tmp_json (b)); return bson_iter_int64 (&iter); } @@ -422,8 +409,7 @@ bson_lookup_write_concern (const bson_t *b, const char *key) } if (bson_has_field (&doc, "wtimeout")) { - mongoc_write_concern_set_wtimeout_int64 ( - wc, bson_lookup_int32 (&doc, "wtimeout")); + mongoc_write_concern_set_wtimeout_int64 (wc, bson_lookup_int32 (&doc, "wtimeout")); } if (bson_has_field (&doc, "j")) { @@ -480,9 +466,7 @@ bson_lookup_read_prefs (const bson_t *b, const char *key) *-------------------------------------------------------------------------- */ void -bson_lookup_database_opts (const bson_t *b, - const char *key, - mongoc_database_t *database) +bson_lookup_database_opts (const bson_t *b, const char *key, mongoc_database_t *database) { bson_t doc; mongoc_read_concern_t *rc; @@ -520,9 +504,7 @@ bson_lookup_database_opts (const bson_t *b, *-------------------------------------------------------------------------- */ void -bson_lookup_collection_opts (const bson_t *b, - const char *key, - mongoc_collection_t *collection) +bson_lookup_collection_opts (const bson_t *b, const char *key, mongoc_collection_t *collection) { bson_t doc; mongoc_read_concern_t *rc; @@ -616,8 +598,7 @@ bson_lookup_session_opts (const bson_t *b, const char *key) bson_lookup_doc (b, key, &doc); opts = mongoc_session_opts_new (); - mongoc_session_opts_set_causal_consistency ( - opts, _mongoc_lookup_bool (&doc, "causalConsistency", true)); + mongoc_session_opts_set_causal_consistency (opts, _mongoc_lookup_bool (&doc, "causalConsistency", true)); if (bson_has_field (&doc, "defaultTransactionOptions")) { mongoc_transaction_opt_t *txn_opts; @@ -669,12 +650,7 @@ static bool is_empty_doc_or_array (const bson_value_t *value); static bool -find (bson_iter_t *iter, - const bson_t *doc, - const char *key, - bool is_command, - bool is_first, - bool retain_dots_in_keys); +find (bson_iter_t *iter, const bson_t *doc, const char *key, bool is_command, bool is_first, bool retain_dots_in_keys); /*-------------------------------------------------------------------------- @@ -745,8 +721,7 @@ match_json (const bson_t *doc, bool matches; va_start (args, json_pattern); - json_pattern_formatted = - bson_strdupv_printf (json_pattern ? json_pattern : "{}", args); + json_pattern_formatted = bson_strdupv_printf (json_pattern ? json_pattern : "{}", args); va_end (args); double_quoted = single_quotes_to_double (json_pattern_formatted); @@ -760,8 +735,7 @@ match_json (const bson_t *doc, matches = match_bson_with_ctx (doc, pattern, &ctx); if (!matches) { - char *as_string = - doc ? bson_as_canonical_extended_json (doc, NULL) : NULL; + char *as_string = doc ? bson_as_canonical_extended_json (doc, NULL) : NULL; fprintf (stderr, "ASSERT_MATCH failed with document:\n\n" "%s\n" @@ -827,8 +801,7 @@ match_err (match_ctx_t *ctx, const char *fmt, ...) formatted = bson_strdupv_printf (fmt, args); va_end (args); - bson_snprintf ( - ctx->errmsg, sizeof ctx->errmsg, "%s: %s", ctx->path, formatted); + bson_snprintf (ctx->errmsg, sizeof ctx->errmsg, "%s: %s", ctx->path, formatted); bson_free (formatted); } @@ -846,8 +819,7 @@ derive (match_ctx_t *ctx, match_ctx_t *derived, const char *key) derived->strict_numeric_types = ctx->strict_numeric_types; if (strlen (ctx->path) > 0) { - bson_snprintf ( - derived->path, sizeof derived->path, "%s.%s", ctx->path, key); + bson_snprintf (derived->path, sizeof derived->path, "%s.%s", ctx->path, key); } else { bson_snprintf (derived->path, sizeof derived->path, "%s", key); } @@ -922,12 +894,7 @@ match_bson_with_ctx (const bson_t *doc, const bson_t *pattern, match_ctx_t *ctx) key = bson_iter_key (&pattern_iter); value = bson_iter_value (&pattern_iter); - found = find (&doc_iter, - doc, - key, - ctx->is_command, - is_first, - ctx->retain_dots_in_keys); + found = find (&doc_iter, doc, key, ctx->is_command, is_first, ctx->retain_dots_in_keys); if (found) { bson_value_copy (bson_iter_value (&doc_iter), &doc_value); } @@ -944,8 +911,7 @@ match_bson_with_ctx (const bson_t *doc, const bson_t *pattern, match_ctx_t *ctx) derive (ctx, &derived, key); if (ctx->visitor_fn) { - match_action_t action = - ctx->visitor_fn (ctx, &pattern_iter, found ? &doc_iter : NULL); + match_action_t action = ctx->visitor_fn (ctx, &pattern_iter, found ? &doc_iter : NULL); if (action == MATCH_ACTION_ABORT) { // Visitor encountered a match error. goto fail; @@ -1023,12 +989,8 @@ match_bson_with_ctx (const bson_t *doc, const bson_t *pattern, match_ctx_t *ctx) */ static bool -find (bson_iter_t *iter_out, - const bson_t *doc, - const char *key, - bool is_command, - bool is_first, - bool retain_dots_in_keys) +find ( + bson_iter_t *iter_out, const bson_t *doc, const char *key, bool is_command, bool is_first, bool retain_dots_in_keys) { bson_iter_t iter; bson_iter_t descendent; @@ -1058,8 +1020,7 @@ find (bson_iter_t *iter_out, bool bson_init_from_value (bson_t *b, const bson_value_t *v) { - BSON_ASSERT (v->value_type == BSON_TYPE_ARRAY || - v->value_type == BSON_TYPE_DOCUMENT); + BSON_ASSERT (v->value_type == BSON_TYPE_ARRAY || v->value_type == BSON_TYPE_DOCUMENT); return bson_init_static (b, v->value.v_doc.data, v->value.v_doc.data_len); } @@ -1071,8 +1032,7 @@ _is_operator (const char *op_name, const bson_value_t *value, bool *op_val) bson_t bson; bson_iter_t iter; - if (value->value_type == BSON_TYPE_DOCUMENT && - bson_init_from_value (&bson, value) && + if (value->value_type == BSON_TYPE_DOCUMENT && bson_init_from_value (&bson, value) && bson_iter_init_find (&iter, &bson, op_name)) { *op_val = bson_iter_as_bool (&iter); return true; @@ -1163,8 +1123,7 @@ get_type_operator (const bson_value_t *value, bson_type_t *out) /* See list of aliases on this page: * https://www.mongodb.com/docs/manual/reference/bson-types/ */ - if (value->value_type == BSON_TYPE_DOCUMENT && - bson_init_from_value (&bson, value) && + if (value->value_type == BSON_TYPE_DOCUMENT && bson_init_from_value (&bson, value) && bson_iter_init_find (&iter, &bson, "$$type")) { value_string = bson_iter_utf8 (&iter, NULL); if (0 == strcasecmp ("double", value_string)) { @@ -1233,12 +1192,10 @@ is_empty_doc_or_array (const bson_value_t *value) { bson_t doc; - if (!(value->value_type == BSON_TYPE_ARRAY || - value->value_type == BSON_TYPE_DOCUMENT)) { + if (!(value->value_type == BSON_TYPE_ARRAY || value->value_type == BSON_TYPE_DOCUMENT)) { return false; } - BSON_ASSERT (bson_init_static ( - &doc, value->value.v_doc.data, value->value.v_doc.data_len)); + BSON_ASSERT (bson_init_static (&doc, value->value.v_doc.data, value->value.v_doc.data_len)); return bson_count_keys (&doc) == 0; } @@ -1259,10 +1216,7 @@ match_bson_arrays (const bson_t *array, const bson_t *pattern, match_ctx_t *ctx) pattern_count = bson_count_keys (pattern); if (array_count != pattern_count) { - match_err (ctx, - "expected %" PRIu32 " keys, not %" PRIu32, - pattern_count, - array_count); + match_err (ctx, "expected %" PRIu32 " keys, not %" PRIu32, pattern_count, array_count); return false; } @@ -1277,8 +1231,7 @@ match_bson_arrays (const bson_t *array, const bson_t *pattern, match_ctx_t *ctx) derive (ctx, &derived, bson_iter_key (&array_iter)); if (ctx && ctx->visitor_fn) { - match_action_t action = - ctx->visitor_fn (ctx, &pattern_iter, &array_iter); + match_action_t action = ctx->visitor_fn (ctx, &pattern_iter, &array_iter); if (action == MATCH_ACTION_ABORT) { // Visitor encountered a match error. return false; @@ -1320,16 +1273,13 @@ bson_value_as_int64 (const bson_value_t *value) } else if (value->value_type == BSON_TYPE_INT64) { return value->value.v_int64; } else { - test_error ("bson_value_as_int64 called on value of type %d", - value->value_type); + test_error ("bson_value_as_int64 called on value of type %d", value->value_type); } } bool -match_bson_value (const bson_value_t *doc, - const bson_value_t *pattern, - match_ctx_t *ctx) +match_bson_value (const bson_value_t *doc, const bson_value_t *pattern, match_ctx_t *ctx) { bson_t subdoc; bson_t pattern_subdoc; @@ -1340,12 +1290,10 @@ match_bson_value (const bson_value_t *doc, if (ctx && ctx->allow_placeholders) { /* The change streams spec tests use the value 42 as a placeholder. */ bool is_placeholder = false; - if (is_number_type (pattern->value_type) && - bson_value_as_int64 (pattern) == 42) { + if (is_number_type (pattern->value_type) && bson_value_as_int64 (pattern) == 42) { is_placeholder = true; } - if (pattern->value_type == BSON_TYPE_UTF8 && - !strcmp (pattern->value.v_utf8.str, "42")) { + if (pattern->value_type == BSON_TYPE_UTF8 && !strcmp (pattern->value.v_utf8.str, "42")) { is_placeholder = true; } if (is_placeholder) { @@ -1353,17 +1301,12 @@ match_bson_value (const bson_value_t *doc, } } - if (is_number_type (doc->value_type) && - is_number_type (pattern->value_type) && ctx && - !ctx->strict_numeric_types) { + if (is_number_type (doc->value_type) && is_number_type (pattern->value_type) && ctx && !ctx->strict_numeric_types) { doc_int64 = bson_value_as_int64 (doc); pattern_int64 = bson_value_as_int64 (pattern); if (doc_int64 != pattern_int64) { - match_err (ctx, - "expected %" PRId64 ", got %" PRId64, - pattern_int64, - doc_int64); + match_err (ctx, "expected %" PRId64 ", got %" PRId64, pattern_int64, doc_int64); return false; } @@ -1404,42 +1347,32 @@ match_bson_value (const bson_value_t *doc, case BSON_TYPE_BINARY: ret = doc->value.v_binary.data_len == pattern->value.v_binary.data_len && - !memcmp (doc->value.v_binary.data, - pattern->value.v_binary.data, - doc->value.v_binary.data_len); + !memcmp (doc->value.v_binary.data, pattern->value.v_binary.data, doc->value.v_binary.data_len); break; case BSON_TYPE_BOOL: ret = doc->value.v_bool == pattern->value.v_bool; if (!ret) { - match_err (ctx, - "expected %d, got %d", - pattern->value.v_bool, - doc->value.v_bool); + match_err (ctx, "expected %d, got %d", pattern->value.v_bool, doc->value.v_bool); } return ret; case BSON_TYPE_CODE: ret = doc->value.v_code.code_len == pattern->value.v_code.code_len && - !memcmp (doc->value.v_code.code, - pattern->value.v_code.code, - doc->value.v_code.code_len); + !memcmp (doc->value.v_code.code, pattern->value.v_code.code, doc->value.v_code.code_len); break; case BSON_TYPE_CODEWSCOPE: - ret = doc->value.v_codewscope.code_len == - pattern->value.v_codewscope.code_len && - !memcmp (doc->value.v_codewscope.code, - pattern->value.v_codewscope.code, - doc->value.v_codewscope.code_len) && - doc->value.v_codewscope.scope_len == - pattern->value.v_codewscope.scope_len && - !memcmp (doc->value.v_codewscope.scope_data, - pattern->value.v_codewscope.scope_data, - doc->value.v_codewscope.scope_len); + ret = + doc->value.v_codewscope.code_len == pattern->value.v_codewscope.code_len && + !memcmp (doc->value.v_codewscope.code, pattern->value.v_codewscope.code, doc->value.v_codewscope.code_len) && + doc->value.v_codewscope.scope_len == pattern->value.v_codewscope.scope_len && + !memcmp (doc->value.v_codewscope.scope_data, + pattern->value.v_codewscope.scope_data, + doc->value.v_codewscope.scope_len); break; @@ -1447,10 +1380,7 @@ match_bson_value (const bson_value_t *doc, ret = doc->value.v_datetime == pattern->value.v_datetime; if (!ret) { - match_err (ctx, - "expected %" PRId64 ", got %" PRId64, - pattern->value.v_datetime, - doc->value.v_datetime); + match_err (ctx, "expected %" PRId64 ", got %" PRId64, pattern->value.v_datetime, doc->value.v_datetime); } return ret; @@ -1459,10 +1389,7 @@ match_bson_value (const bson_value_t *doc, ret = doc->value.v_double == pattern->value.v_double; if (!ret) { - match_err (ctx, - "expected %f, got %f", - pattern->value.v_double, - doc->value.v_double); + match_err (ctx, "expected %f, got %f", pattern->value.v_double, doc->value.v_double); } return ret; @@ -1471,10 +1398,7 @@ match_bson_value (const bson_value_t *doc, ret = doc->value.v_int32 == pattern->value.v_int32; if (!ret) { - match_err (ctx, - "expected %" PRId32 ", got %" PRId32, - pattern->value.v_int32, - doc->value.v_int32); + match_err (ctx, "expected %" PRId32 ", got %" PRId32, pattern->value.v_int32, doc->value.v_int32); } return ret; @@ -1483,10 +1407,7 @@ match_bson_value (const bson_value_t *doc, ret = doc->value.v_int64 == pattern->value.v_int64; if (!ret) { - match_err (ctx, - "expected %" PRId64 ", got %" PRId64, - pattern->value.v_int64, - doc->value.v_int64); + match_err (ctx, "expected %" PRId64 ", got %" PRId64, pattern->value.v_int64, doc->value.v_int64); } return ret; @@ -1496,39 +1417,29 @@ match_bson_value (const bson_value_t *doc, break; case BSON_TYPE_REGEX: - ret = - !strcmp (doc->value.v_regex.regex, pattern->value.v_regex.regex) && - !strcmp (doc->value.v_regex.options, pattern->value.v_regex.options); + ret = !strcmp (doc->value.v_regex.regex, pattern->value.v_regex.regex) && + !strcmp (doc->value.v_regex.options, pattern->value.v_regex.options); break; case BSON_TYPE_SYMBOL: ret = doc->value.v_symbol.len == pattern->value.v_symbol.len && - !strncmp (doc->value.v_symbol.symbol, - pattern->value.v_symbol.symbol, - doc->value.v_symbol.len); + !strncmp (doc->value.v_symbol.symbol, pattern->value.v_symbol.symbol, doc->value.v_symbol.len); break; case BSON_TYPE_TIMESTAMP: - ret = doc->value.v_timestamp.timestamp == - pattern->value.v_timestamp.timestamp && - doc->value.v_timestamp.increment == - pattern->value.v_timestamp.increment; + ret = doc->value.v_timestamp.timestamp == pattern->value.v_timestamp.timestamp && + doc->value.v_timestamp.increment == pattern->value.v_timestamp.increment; break; case BSON_TYPE_UTF8: ret = doc->value.v_utf8.len == pattern->value.v_utf8.len && - !strncmp (doc->value.v_utf8.str, - pattern->value.v_utf8.str, - doc->value.v_utf8.len); + !strncmp (doc->value.v_utf8.str, pattern->value.v_utf8.str, doc->value.v_utf8.len); if (!ret) { - match_err (ctx, - "expected \"%s\", got \"%s\"", - pattern->value.v_utf8.str, - doc->value.v_utf8.str); + match_err (ctx, "expected \"%s\", got \"%s\"", pattern->value.v_utf8.str, doc->value.v_utf8.str); } return ret; @@ -1543,10 +1454,8 @@ match_bson_value (const bson_value_t *doc, return true; case BSON_TYPE_DBPOINTER: - ret = (0 == strcmp (doc->value.v_dbpointer.collection, - pattern->value.v_dbpointer.collection) && - bson_oid_equal (&doc->value.v_dbpointer.oid, - &pattern->value.v_dbpointer.oid)); + ret = (0 == strcmp (doc->value.v_dbpointer.collection, pattern->value.v_dbpointer.collection) && + bson_oid_equal (&doc->value.v_dbpointer.oid, &pattern->value.v_dbpointer.oid)); break; case BSON_TYPE_DECIMAL128: @@ -1559,28 +1468,22 @@ match_bson_value (const bson_value_t *doc, } break; default: - test_error ("unexpected value type %d: %s", - doc->value_type, - _mongoc_bson_type_to_str (doc->value_type)); + test_error ("unexpected value type %d: %s", doc->value_type, _mongoc_bson_type_to_str (doc->value_type)); } if (!ret) { - match_err (ctx, - "%s values mismatch", - _mongoc_bson_type_to_str (pattern->value_type)); + match_err (ctx, "%s values mismatch", _mongoc_bson_type_to_str (pattern->value_type)); } return ret; } bool -mongoc_write_concern_append_bad (mongoc_write_concern_t *write_concern, - bson_t *command) +mongoc_write_concern_append_bad (mongoc_write_concern_t *write_concern, bson_t *command) { mongoc_write_concern_t *wc = mongoc_write_concern_copy (write_concern); - if (!bson_append_document ( - command, "writeConcern", 12, _mongoc_write_concern_get_bson (wc))) { + if (!bson_append_document (command, "writeConcern", 12, _mongoc_write_concern_get_bson (wc))) { MONGOC_ERROR ("Could not append writeConcern to command."); mongoc_write_concern_destroy (wc); return false; @@ -1679,11 +1582,8 @@ assert_no_duplicate_keys (const bson_t *doc) BSON_ASSERT (bson_iter_init (&iter, doc)); while (bson_iter_next (&iter)) { - if (mongoc_set_find_item ( - keys, find_key, (void *) bson_iter_key (&iter))) { - test_error ("Duplicate key \"%s\" in document:\n%s", - bson_iter_key (&iter), - bson_as_json (doc, NULL)); + if (mongoc_set_find_item (keys, find_key, (void *) bson_iter_key (&iter))) { + test_error ("Duplicate key \"%s\" in document:\n%s", bson_iter_key (&iter), bson_as_json (doc, NULL)); } mongoc_set_add (keys, 0 /* index */, (void *) bson_iter_key (&iter)); @@ -1737,11 +1637,9 @@ bson_with_all_types (void) bson_oid_init_from_string (&oid, "000000000000000000000000"); BSON_ASSERT (BSON_APPEND_DOUBLE (bson, "double", 1.0)); BSON_ASSERT (BSON_APPEND_UTF8 (bson, "string", "string_example")); - BSON_ASSERT ( - BSON_APPEND_DOCUMENT (bson, "document", tmp_bson ("{'x': 'y'}"))); + BSON_ASSERT (BSON_APPEND_DOCUMENT (bson, "document", tmp_bson ("{'x': 'y'}"))); BSON_ASSERT (BSON_APPEND_ARRAY (bson, "document", tmp_bson ("{'0': 'x'}"))); - BSON_ASSERT (BSON_APPEND_BINARY ( - bson, "binary", BSON_SUBTYPE_BINARY, (uint8_t *) "data", 4)); + BSON_ASSERT (BSON_APPEND_BINARY (bson, "binary", BSON_SUBTYPE_BINARY, (uint8_t *) "data", 4)); BSON_ASSERT (BSON_APPEND_UNDEFINED (bson, "undefined")); BSON_ASSERT (BSON_APPEND_OID (bson, "oid", &oid)); BSON_ASSERT (BSON_APPEND_BOOL (bson, "bool", true)); @@ -1752,8 +1650,7 @@ bson_with_all_types (void) BSON_ASSERT (BSON_APPEND_CODE (bson, "code", "var x = 1;")); BSON_ASSERT (BSON_APPEND_SYMBOL (bson, "symbol", "symbol_example")); BSON_ASSERT (BSON_APPEND_CODE (bson, "code", "var x = 1;")); - BSON_ASSERT (BSON_APPEND_CODE_WITH_SCOPE ( - bson, "code_w_scope", "var x = 1;", tmp_bson ("{}"))); + BSON_ASSERT (BSON_APPEND_CODE_WITH_SCOPE (bson, "code_w_scope", "var x = 1;", tmp_bson ("{}"))); BSON_ASSERT (BSON_APPEND_INT32 (bson, "int32", 1)); BSON_ASSERT (BSON_APPEND_TIMESTAMP (bson, "timestamp", 2, 3)); BSON_ASSERT (BSON_APPEND_INT64 (bson, "int64", 4)); @@ -1854,18 +1751,13 @@ json_with_all_types (void) void assert_wc_oob_error (bson_error_t *error) { - if (test_framework_get_server_version () >= - test_framework_str_to_version ("4.3.3")) { + if (test_framework_get_server_version () >= test_framework_str_to_version ("4.3.3")) { /* Error reporting changed in SERVER-45584 */ ASSERT_ERROR_CONTAINS ( - (*error), - MONGOC_ERROR_SERVER, - 9, - "w has to be a non-negative number and not greater than 50"); + (*error), MONGOC_ERROR_SERVER, 9, "w has to be a non-negative number and not greater than 50"); } else { if (test_framework_is_replset ()) { /* replset */ - ASSERT_ERROR_CONTAINS ( - (*error), MONGOC_ERROR_WRITE_CONCERN, 100, "Write Concern error:"); + ASSERT_ERROR_CONTAINS ((*error), MONGOC_ERROR_WRITE_CONCERN, 100, "Write Concern error:"); } else { /* standalone */ ASSERT_CMPINT (error->domain, ==, MONGOC_ERROR_SERVER); ASSERT_CMPINT (error->code, ==, 2); @@ -1906,10 +1798,8 @@ server_semver (mongoc_client_t *client, semver_t *out) ASSERT (client); - ASSERT_OR_PRINT ( - mongoc_client_command_simple ( - client, "admin", tmp_bson ("{'buildinfo': 1}"), NULL, &reply, &error), - error); + ASSERT_OR_PRINT (mongoc_client_command_simple (client, "admin", tmp_bson ("{'buildinfo': 1}"), NULL, &reply, &error), + error); server_version_str = bson_lookup_utf8 (&reply, "version"); semver_parse (server_version_str, out); diff --git a/src/libmongoc/tests/test-conveniences.h b/src/libmongoc/tests/test-conveniences.h index 242289296c..580d5d11d3 100644 --- a/src/libmongoc/tests/test-conveniences.h +++ b/src/libmongoc/tests/test-conveniences.h @@ -78,8 +78,7 @@ json_with_all_types (void); #endif #ifdef _WIN32 -#define realpath(path, expanded) \ - GetFullPathName (path, PATH_MAX, expanded, NULL) +#define realpath(path, expanded) GetFullPathName (path, PATH_MAX, expanded, NULL) #endif const char * @@ -119,14 +118,10 @@ mongoc_read_prefs_t * bson_lookup_read_prefs (const bson_t *b, const char *key); void -bson_lookup_database_opts (const bson_t *b, - const char *key, - mongoc_database_t *database); +bson_lookup_database_opts (const bson_t *b, const char *key, mongoc_database_t *database); void -bson_lookup_collection_opts (const bson_t *b, - const char *key, - mongoc_collection_t *collection); +bson_lookup_collection_opts (const bson_t *b, const char *key, mongoc_collection_t *collection); mongoc_transaction_opt_t * bson_lookup_txn_opts (const bson_t *b, const char *key); @@ -152,9 +147,7 @@ typedef enum { struct _match_ctx_t; /* doc_iter may be null if the pattern field is not found. */ -typedef match_action_t (*match_visitor_fn) (struct _match_ctx_t *ctx, - bson_iter_t *pattern_iter, - bson_iter_t *doc_iter); +typedef match_action_t (*match_visitor_fn) (struct _match_ctx_t *ctx, bson_iter_t *pattern_iter, bson_iter_t *doc_iter); typedef struct _match_ctx_t { char errmsg[1000]; @@ -175,18 +168,17 @@ typedef struct _match_ctx_t { bool is_command; } match_ctx_t; -#define assert_match_bson(doc, pattern, _is_command) \ - if (1) { \ - match_ctx_t _ctx = {.strict_numeric_types = true, \ - .is_command = _is_command}; \ - \ - if (!match_bson_with_ctx (doc, pattern, &_ctx)) { \ - test_error ("Expected: %s\n, Got: %s\n, %s\n", \ - bson_as_canonical_extended_json (pattern, NULL), \ - bson_as_canonical_extended_json (doc, NULL), \ - _ctx.errmsg); \ - } \ - } else \ +#define assert_match_bson(doc, pattern, _is_command) \ + if (1) { \ + match_ctx_t _ctx = {.strict_numeric_types = true, .is_command = _is_command}; \ + \ + if (!match_bson_with_ctx (doc, pattern, &_ctx)) { \ + test_error ("Expected: %s\n, Got: %s\n, %s\n", \ + bson_as_canonical_extended_json (pattern, NULL), \ + bson_as_canonical_extended_json (doc, NULL), \ + _ctx.errmsg); \ + } \ + } else \ (void) 0 bool @@ -196,14 +188,10 @@ int64_t bson_value_as_int64 (const bson_value_t *value); bool -match_bson_value (const bson_value_t *doc, - const bson_value_t *pattern, - match_ctx_t *ctx); +match_bson_value (const bson_value_t *doc, const bson_value_t *pattern, match_ctx_t *ctx); bool -match_bson_with_ctx (const bson_t *doc, - const bson_t *pattern, - match_ctx_t *ctx); +match_bson_with_ctx (const bson_t *doc, const bson_t *pattern, match_ctx_t *ctx); bool match_json (const bson_t *doc, @@ -214,15 +202,13 @@ match_json (const bson_t *doc, const char *json_pattern, ...); -#define ASSERT_MATCH(doc, ...) \ - do { \ - BSON_ASSERT ( \ - match_json (doc, false, __FILE__, __LINE__, BSON_FUNC, __VA_ARGS__)); \ +#define ASSERT_MATCH(doc, ...) \ + do { \ + BSON_ASSERT (match_json (doc, false, __FILE__, __LINE__, BSON_FUNC, __VA_ARGS__)); \ } while (0) bool -mongoc_write_concern_append_bad (mongoc_write_concern_t *write_concern, - bson_t *command); +mongoc_write_concern_append_bad (mongoc_write_concern_t *write_concern, bson_t *command); #define FOUR_MB 1024 * 1024 * 4 @@ -283,13 +269,11 @@ semver_to_string (semver_t *str); * printf ("%d: %s", bson_iter_key (&iter), tmp_json (&el)); * } */ -#define BSON_FOREACH(bson, iter_varname) \ - for (bson_iter_init (&(iter_varname), (bson)); \ - bson_iter_next (&(iter_varname));) +#define BSON_FOREACH(bson, iter_varname) \ + for (bson_iter_init (&(iter_varname), (bson)); bson_iter_next (&(iter_varname));) #define TEST_ERROR_DOMAIN 123456 #define TEST_ERROR_CODE 654321 -#define test_set_error(error, ...) \ - bson_set_error (error, TEST_ERROR_DOMAIN, TEST_ERROR_CODE, __VA_ARGS__) +#define test_set_error(error, ...) bson_set_error (error, TEST_ERROR_DOMAIN, TEST_ERROR_CODE, __VA_ARGS__) #endif /* TEST_CONVENIENCES_H */ diff --git a/src/libmongoc/tests/test-gcpkms.c b/src/libmongoc/tests/test-gcpkms.c index 900b4eb9ed..2038cad46f 100644 --- a/src/libmongoc/tests/test-gcpkms.c +++ b/src/libmongoc/tests/test-gcpkms.c @@ -30,8 +30,7 @@ main (void) char *expect_error = getenv ("EXPECT_ERROR"); if (!mongodb_uri) { - MONGOC_ERROR ( - "Error: expecting MONGODB_URI environment variable to be set. "); + MONGOC_ERROR ("Error: expecting MONGODB_URI environment variable to be set. "); return EXIT_FAILURE; } @@ -39,16 +38,13 @@ main (void) mongoc_client_t *keyvault_client = mongoc_client_new (mongodb_uri); MONGOC_DEBUG ("libmongoc version: %s", mongoc_get_version ()); - mongoc_client_encryption_opts_t *ceopts = - mongoc_client_encryption_opts_new (); + mongoc_client_encryption_opts_t *ceopts = mongoc_client_encryption_opts_new (); mongoc_client_encryption_opts_set_keyvault_client (ceopts, keyvault_client); - mongoc_client_encryption_opts_set_keyvault_namespace ( - ceopts, "keyvault", "datakeys"); + mongoc_client_encryption_opts_set_keyvault_namespace (ceopts, "keyvault", "datakeys"); bson_t *kms_providers = BCON_NEW ("gcp", "{", "}"); mongoc_client_encryption_opts_set_kms_providers (ceopts, kms_providers); - mongoc_client_encryption_t *ce = - mongoc_client_encryption_new (ceopts, &error); + mongoc_client_encryption_t *ce = mongoc_client_encryption_new (ceopts, &error); if (!ce) { MONGOC_ERROR ("Error in mongoc_client_encryption_new: %s", error.message); @@ -68,24 +64,19 @@ main (void) mongoc_client_encryption_datakey_opts_set_masterkey (dkopts, masterkey); bson_value_t keyid; - bool got = mongoc_client_encryption_create_datakey ( - ce, "gcp", dkopts, &keyid, &error); + bool got = mongoc_client_encryption_create_datakey (ce, "gcp", dkopts, &keyid, &error); if (NULL != expect_error) { if (got) { - MONGOC_ERROR ("Expected an error to contain %s, but got success", - expect_error); + MONGOC_ERROR ("Expected an error to contain %s, but got success", expect_error); return EXIT_FAILURE; } if (NULL == strstr (error.message, expect_error)) { - MONGOC_ERROR ("Expected error to contain %s, but got: %s", - expect_error, - error.message); + MONGOC_ERROR ("Expected error to contain %s, but got: %s", expect_error, error.message); return EXIT_FAILURE; } } else { if (!got) { - MONGOC_ERROR ("Expected to create data key, but got error: %s", - error.message); + MONGOC_ERROR ("Expected to create data key, but got error: %s", error.message); return EXIT_FAILURE; } } diff --git a/src/libmongoc/tests/test-happy-eyeballs.c b/src/libmongoc/tests/test-happy-eyeballs.c index d194f77f97..c0975a8678 100644 --- a/src/libmongoc/tests/test-happy-eyeballs.c +++ b/src/libmongoc/tests/test-happy-eyeballs.c @@ -56,9 +56,7 @@ typedef struct he_testcase { he_testcase_state_t state; } he_testcase_t; -typedef ssize_t (*poll_fn_t) (mongoc_stream_poll_t *streams, - size_t nstreams, - int32_t timeout); +typedef ssize_t (*poll_fn_t) (mongoc_stream_poll_t *streams, size_t nstreams, int32_t timeout); static poll_fn_t gOriginalPoll; static he_testcase_t *gCurrentTestCase; @@ -66,13 +64,11 @@ static he_testcase_t *gCurrentTestCase; /* if the server testcase specifies a delay or hangup, overwrite the poll * response. */ static int -_override_poll_response (he_testcase_server_t *server, - mongoc_stream_poll_t *poller) +_override_poll_response (he_testcase_server_t *server, mongoc_stream_poll_t *poller) { if (server->listen_delay_ms) { int64_t now = bson_get_monotonic_time (); - if (gCurrentTestCase->state.start + server->listen_delay_ms * 1000 > - now) { + if (gCurrentTestCase->state.start + server->listen_delay_ms * 1000 > now) { /* should still "sleep". */ int delta = 0; if (poller->revents) { @@ -130,8 +126,7 @@ _mock_poll (mongoc_stream_poll_t *streams, size_t nstreams, int32_t timeout) /* check if any of the poll responses need to be overwritten. */ for (size_t i = 0u; i < nstreams; i++) { - mongoc_stream_t *stream = - mongoc_stream_get_root_stream (streams[i].stream); + mongoc_stream_t *stream = mongoc_stream_get_root_stream (streams[i].stream); he_testcase_server_t *server = _server_for_client (stream); if (server) { @@ -158,11 +153,8 @@ _mock_initiator (mongoc_async_cmd_t *acmd) } static void -_test_scanner_callback (uint32_t id, - const bson_t *bson, - int64_t rtt_msec, - void *data, - const bson_error_t *error /* IN */) +_test_scanner_callback ( + uint32_t id, const bson_t *bson, int64_t rtt_msec, void *data, const bson_error_t *error /* IN */) { he_testcase_t *testcase = (he_testcase_t *) data; int should_succeed = strcmp (testcase->expected.conn_succeeds_to, "neither"); @@ -174,10 +166,7 @@ _test_scanner_callback (uint32_t id, if (should_succeed) { ASSERT_OR_PRINT (!error->code, (*error)); } else { - ASSERT_ERROR_CONTAINS ((*error), - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_CONNECT, - "connection refused"); + ASSERT_ERROR_CONTAINS ((*error), MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_CONNECT, "connection refused"); } } @@ -255,18 +244,14 @@ _testcase_setup (he_testcase_t *testcase) mock_server_set_bind_opts (mock_server, &opts); mock_server_run (mock_server); - _init_host (&testcase->state.host, - mock_server_get_port (mock_server), - testcase->client.type); + _init_host (&testcase->state.host, mock_server_get_port (mock_server), testcase->client.type); - testcase->state.ts = mongoc_topology_scanner_new ( - NULL, NULL, &_test_scanner_callback, testcase, TIMEOUT); + testcase->state.ts = mongoc_topology_scanner_new (NULL, NULL, &_test_scanner_callback, testcase, TIMEOUT); testcase->state.mock_server = mock_server; if (testcase->client.dns_cache_timeout_ms > 0) { - _mongoc_topology_scanner_set_dns_cache_timeout ( - testcase->state.ts, testcase->client.dns_cache_timeout_ms); + _mongoc_topology_scanner_set_dns_cache_timeout (testcase->state.ts, testcase->client.dns_cache_timeout_ms); } } @@ -283,16 +268,12 @@ _check_stream (mongoc_stream_t *stream, const char *expected, char *message) /* check the socket that the scanner found. */ char *actual = "neither"; if (stream) { - mongoc_socket_t *sock = - mongoc_stream_socket_get_socket ((mongoc_stream_socket_t *) stream); + mongoc_socket_t *sock = mongoc_stream_socket_get_socket ((mongoc_stream_socket_t *) stream); actual = (sock->domain == AF_INET) ? "ipv4" : "ipv6"; } - ASSERT_WITH_MSG (strcmp (expected, actual) == 0, - "%s: expected %s stream but got %s stream\n", - message, - expected, - actual); + ASSERT_WITH_MSG ( + strcmp (expected, actual) == 0, "%s: expected %s stream but got %s stream\n", message, expected, actual); } static void @@ -310,8 +291,7 @@ _testcase_run (he_testcase_t *testcase) gCurrentTestCase = testcase; testcase->state.start = bson_get_monotonic_time (); - mongoc_topology_scanner_add ( - ts, &testcase->state.host, 1 /* any server id is ok. */, false); + mongoc_topology_scanner_add (ts, &testcase->state.host, 1 /* any server id is ok. */, false); mongoc_topology_scanner_scan (ts, 1); /* how many commands should we have initially? */ ASSERT_CMPINT ((int) (ts->async->ncmds), ==, expected->initial_acmds); @@ -333,8 +313,7 @@ _testcase_run (he_testcase_t *testcase) { bool within_expected_duration = - duration_ms >= expected->duration_min_ms && - duration_ms < expected->duration_max_ms; + duration_ms >= expected->duration_min_ms && duration_ms < expected->duration_max_ms; if (!within_expected_duration) { /* this is a timing failure, this may have been a fluke, retry once. */ ASSERT_WITH_MSG (!testcase->state.last_duration, @@ -353,9 +332,7 @@ _testcase_run (he_testcase_t *testcase) #endif node = mongoc_topology_scanner_get_node (ts, 1); - _check_stream (node->stream, - expected->conn_succeeds_to, - "checking client's final connection"); + _check_stream (node->stream, expected->conn_succeeds_to, "checking client's final connection"); } #define CLIENT(client) \ @@ -536,41 +513,35 @@ test_happy_eyeballs_install (TestSuite *suite) fails} */ { CLIENT (both), - SERVERS (DELAYED_SERVER (ipv4, LISTEN, DELAY_MS (2 * HE)), - DELAYED_SERVER (ipv6, LISTEN, HE)), + SERVERS (DELAYED_SERVER (ipv4, LISTEN, DELAY_MS (2 * HE)), DELAYED_SERVER (ipv6, LISTEN, HE)), EXPECT (ipv6, NCMDS (2), DURATION_MS (HE, HE + E)), }, { CLIENT (both), - SERVERS (DELAYED_SERVER (ipv4, LISTEN, DELAY_MS (2 * HE)), - DELAYED_SERVER (ipv6, HANGUP, DELAY_MS (HE))), + SERVERS (DELAYED_SERVER (ipv4, LISTEN, DELAY_MS (2 * HE)), DELAYED_SERVER (ipv6, HANGUP, DELAY_MS (HE))), EXPECT (ipv4, NCMDS (2), DURATION_MS (2 * HE, 2 * HE + E)), }, { CLIENT (both), - SERVERS (DELAYED_SERVER (ipv4, HANGUP, DELAY_MS (2 * HE)), - DELAYED_SERVER (ipv6, HANGUP, DELAY_MS (HE))), + SERVERS (DELAYED_SERVER (ipv4, HANGUP, DELAY_MS (2 * HE)), DELAYED_SERVER (ipv6, HANGUP, DELAY_MS (HE))), EXPECT (neither, NCMDS (2), DURATION_MS (2 * HE, 2 * HE + E)), }, /* ipv4 {succeeds,fails} after ipv6 {succeeds, fails}. */ { CLIENT (both), - SERVERS (SERVER (ipv4, LISTEN), - DELAYED_SERVER (ipv6, LISTEN, DELAY_MS (HE + E))), + SERVERS (SERVER (ipv4, LISTEN), DELAYED_SERVER (ipv6, LISTEN, DELAY_MS (HE + E))), /* ipv6 is delayed too long, ipv4 succeeds. */ EXPECT (ipv4, NCMDS (2), DURATION_MS (HE, HE + E)), }, { CLIENT (both), - SERVERS (SERVER (ipv4, HANGUP), - DELAYED_SERVER (ipv6, LISTEN, DELAY_MS (HE + E))), + SERVERS (SERVER (ipv4, HANGUP), DELAYED_SERVER (ipv6, LISTEN, DELAY_MS (HE + E))), /* ipv6 is delayed, but ipv4 fails. */ EXPECT (ipv6, NCMDS (2), DURATION_MS (HE + E, HE + 2 * E)), }, { CLIENT (both), - SERVERS (SERVER (ipv4, HANGUP), - DELAYED_SERVER (ipv6, HANGUP, DELAY_MS (HE + E))), + SERVERS (SERVER (ipv4, HANGUP), DELAYED_SERVER (ipv6, HANGUP, DELAY_MS (HE + E))), EXPECT (neither, NCMDS (2), DURATION_MS (HE + E, HE + 2 * E)), }, }; diff --git a/src/libmongoc/tests/test-libmongoc.c b/src/libmongoc/tests/test-libmongoc.c index e20df0ccb0..43ad2ed145 100644 --- a/src/libmongoc/tests/test-libmongoc.c +++ b/src/libmongoc/tests/test-libmongoc.c @@ -170,16 +170,9 @@ print_captured_logs (const char *prefix) for (i = 0; i < captured_logs.len; i++) { log_entry = _mongoc_array_index (&captured_logs, log_entry_t *, i); if (prefix) { - fprintf (stderr, - "%s%s %s\n", - prefix, - mongoc_log_level_str (log_entry->level), - log_entry->msg); + fprintf (stderr, "%s%s %s\n", prefix, mongoc_log_level_str (log_entry->level), log_entry->msg); } else { - fprintf (stderr, - "%s %s\n", - mongoc_log_level_str (log_entry->level), - log_entry->msg); + fprintf (stderr, "%s %s\n", mongoc_log_level_str (log_entry->level), log_entry->msg); } } bson_mutex_unlock (&captured_logs_mutex); @@ -191,15 +184,11 @@ print_captured_logs (const char *prefix) int64_t get_future_timeout_ms (void) { - return test_framework_getenv_int64 ("MONGOC_TEST_FUTURE_TIMEOUT_MS", - DEFAULT_FUTURE_TIMEOUT_MS); + return test_framework_getenv_int64 ("MONGOC_TEST_FUTURE_TIMEOUT_MS", DEFAULT_FUTURE_TIMEOUT_MS); } static void -log_handler (mongoc_log_level_t log_level, - const char *log_domain, - const char *message, - void *user_data) +log_handler (mongoc_log_level_t log_level, const char *log_domain, const char *message, void *user_data) { TestSuite *suite; log_entry_t *log_entry; @@ -219,8 +208,7 @@ log_handler (mongoc_log_level_t log_level, if (!suite->silent) { mongoc_log_default_handler (log_level, log_domain, message, NULL); } - } else if (log_level == MONGOC_LOG_LEVEL_DEBUG && - test_suite_debug_output ()) { + } else if (log_level == MONGOC_LOG_LEVEL_DEBUG && test_suite_debug_output ()) { mongoc_log_default_handler (log_level, log_domain, message, NULL); } } @@ -236,10 +224,7 @@ get_test_database (mongoc_client_t *client) char * gen_collection_name (const char *str) { - return bson_strdup_printf ("%s_%u_%u", - str, - (uint32_t) bson_get_monotonic_time (), - (uint32_t) gettestpid ()); + return bson_strdup_printf ("%s_%u_%u", str, (uint32_t) bson_get_monotonic_time (), (uint32_t) gettestpid ()); } @@ -303,10 +288,7 @@ test_framework_getenv_bool (const char *name) } else if (!strcasecmp (value, "") || !strcasecmp (value, "on")) { ret = true; } else { - test_error ( - "Unrecognized value for %s: \"%s\". Use \"on\" or \"off\".", - name, - value); + test_error ("Unrecognized value for %s: \"%s\". Use \"on\" or \"off\".", name, value); } } @@ -362,8 +344,7 @@ test_framework_get_unix_domain_socket_path (void) return path; } - return bson_strdup_printf ("/tmp/mongodb-%d.sock", - test_framework_get_port ()); + return bson_strdup_printf ("/tmp/mongodb-%d.sock", test_framework_get_port ()); } @@ -414,8 +395,7 @@ static char * _uri_str_from_env (void) { if (test_framework_getenv_bool ("MONGOC_TEST_LOADBALANCED")) { - char *loadbalanced_uri_str = - test_framework_getenv ("SINGLE_MONGOS_LB_URI"); + char *loadbalanced_uri_str = test_framework_getenv ("SINGLE_MONGOS_LB_URI"); if (!loadbalanced_uri_str) { test_error ("SINGLE_MONGOS_LB_URI and MULTI_MONGOS_LB_URI must be set " "when MONGOC_TEST_LOADBALANCED is enabled"); @@ -468,9 +448,7 @@ test_framework_get_host (void) if (env_uri) { /* choose first host */ hosts = mongoc_uri_get_hosts (env_uri); - ASSERT_WITH_MSG (hosts, - "could not obtain hosts from URI [%s]", - mongoc_uri_get_string (env_uri)); + ASSERT_WITH_MSG (hosts, "could not obtain hosts from URI [%s]", mongoc_uri_get_string (env_uri)); host = bson_strdup (hosts->host); mongoc_uri_destroy (env_uri); return host; @@ -676,12 +654,9 @@ test_framework_get_user_password (char **user, char **password) *-------------------------------------------------------------------------- */ char * -test_framework_add_user_password (const char *uri_str, - const char *user, - const char *password) +test_framework_add_user_password (const char *uri_str, const char *user, const char *password) { - return bson_strdup_printf ( - "mongodb://%s:%s@%s", user, password, uri_str + strlen ("mongodb://")); + return bson_strdup_printf ("mongodb://%s:%s@%s", user, password, uri_str + strlen ("mongodb://")); } @@ -833,8 +808,7 @@ test_framework_get_unix_domain_socket_uri_str (void) char *test_uri_str_auth; path = test_framework_get_unix_domain_socket_path_escaped (); - test_uri_str = bson_strdup_printf ( - "mongodb://%s/%s", path, test_framework_get_ssl () ? "?ssl=true" : ""); + test_uri_str = bson_strdup_printf ("mongodb://%s/%s", path, test_framework_get_ssl () ? "?ssl=true" : ""); test_uri_str_auth = test_framework_add_user_password_from_env (test_uri_str); @@ -868,28 +842,19 @@ call_hello_with_host_and_port (const char *host_and_port, bson_t *reply) bson_error_t error; if (test_framework_get_user_password (&user, &password)) { - uri_str = - bson_strdup_printf ("mongodb://%s:%s@%s%s", - user, - password, - host_and_port, - test_framework_get_ssl () ? "/?ssl=true" : ""); + uri_str = bson_strdup_printf ( + "mongodb://%s:%s@%s%s", user, password, host_and_port, test_framework_get_ssl () ? "/?ssl=true" : ""); bson_free (user); bson_free (password); } else { - uri_str = - bson_strdup_printf ("mongodb://%s%s", - host_and_port, - test_framework_get_ssl () ? "/?ssl=true" : ""); + uri_str = bson_strdup_printf ("mongodb://%s%s", host_and_port, test_framework_get_ssl () ? "/?ssl=true" : ""); } uri = mongoc_uri_new (uri_str); BSON_ASSERT (uri); mongoc_uri_set_option_as_int32 (uri, MONGOC_URI_CONNECTTIMEOUTMS, 10000); - mongoc_uri_set_option_as_int32 ( - uri, MONGOC_URI_SERVERSELECTIONTIMEOUTMS, 10000); - mongoc_uri_set_option_as_bool ( - uri, MONGOC_URI_SERVERSELECTIONTRYONCE, false); + mongoc_uri_set_option_as_int32 (uri, MONGOC_URI_SERVERSELECTIONTIMEOUTMS, 10000); + mongoc_uri_set_option_as_bool (uri, MONGOC_URI_SERVERSELECTIONTRYONCE, false); if (test_framework_has_compressors ()) { char *compressors = test_framework_get_compressors (); @@ -907,17 +872,11 @@ call_hello_with_host_and_port (const char *host_and_port, bson_t *reply) test_framework_set_ssl_opts (client); #endif - if (!mongoc_client_command_simple ( - client, "admin", tmp_bson ("{'hello': 1}"), NULL, reply, &error)) { + if (!mongoc_client_command_simple (client, "admin", tmp_bson ("{'hello': 1}"), NULL, reply, &error)) { bson_destroy (reply); if (!mongoc_client_command_simple ( - client, - "admin", - tmp_bson ("{'" HANDSHAKE_CMD_LEGACY_HELLO "': 1}"), - NULL, - reply, - &error)) { + client, "admin", tmp_bson ("{'" HANDSHAKE_CMD_LEGACY_HELLO "': 1}"), NULL, reply, &error)) { test_error ("error calling legacy hello: '%s'\n" "URI = %s", error.message, @@ -979,11 +938,7 @@ uri_str_has_db (bson_string_t *uri_string) const bool is_standard = strstr (str, standard) == str; const bool is_srv = strstr (str, srv) == str; - ASSERT_WITH_MSG (is_standard || is_srv, - "[%s] does not start with [%s] or [%s]", - uri_string->str, - standard, - srv); + ASSERT_WITH_MSG (is_standard || is_srv, "[%s] does not start with [%s] or [%s]", uri_string->str, standard, srv); if (is_standard) { return strchr (str + strlen (standard), '/') != NULL; @@ -994,9 +949,7 @@ uri_str_has_db (bson_string_t *uri_string) static void -add_option_to_uri_str (bson_string_t *uri_string, - const char *option, - const char *value) +add_option_to_uri_str (bson_string_t *uri_string, const char *option, const char *value) { if (strchr (uri_string->str, '?')) { /* already has some options */ @@ -1115,8 +1068,7 @@ test_framework_get_uri_str_no_auth (const char *database_name) // Required by test-atlas-executor. Not required by normal unified test // runner, but make tests a little more resilient to transient errors. - add_option_to_uri_str ( - uri_string, MONGOC_URI_SERVERSELECTIONTRYONCE, "false"); + add_option_to_uri_str (uri_string, MONGOC_URI_SERVERSELECTIONTRYONCE, "false"); return bson_string_free (uri_string, false); } @@ -1212,9 +1164,7 @@ test_framework_get_uri_multi_mongos_loadbalanced (void) } bool -test_framework_uri_apply_multi_mongos (mongoc_uri_t *uri, - bool use_multi, - bson_error_t *error) +test_framework_uri_apply_multi_mongos (mongoc_uri_t *uri, bool use_multi, bson_error_t *error) { bool ret = false; @@ -1331,24 +1281,17 @@ test_framework_replset_member_count (void) size_t count = 0; client = test_framework_new_default_client (); - r = mongoc_client_command_simple (client, - "admin", - tmp_bson ("{'replSetGetStatus': 1}"), - NULL, - &reply, - &error); + r = mongoc_client_command_simple (client, "admin", tmp_bson ("{'replSetGetStatus': 1}"), NULL, &reply, &error); if (r) { - if (bson_iter_init_find (&iter, &reply, "members") && - BSON_ITER_HOLDS_ARRAY (&iter)) { + if (bson_iter_init_find (&iter, &reply, "members") && BSON_ITER_HOLDS_ARRAY (&iter)) { bson_iter_recurse (&iter, &array); while (bson_iter_next (&array)) { ++count; } } } else if (!strstr (error.message, "not running with --replSet") && - !strstr (error.message, - "replSetGetStatus is not supported through mongos")) { + !strstr (error.message, "replSetGetStatus is not supported through mongos")) { /* failed for some other reason */ ASSERT_OR_PRINT (false, error); } @@ -1442,9 +1385,8 @@ test_framework_set_ssl_opts (mongoc_client_t *client) if (test_framework_get_ssl ()) { #ifndef MONGOC_ENABLE_SSL - test_error ( - "SSL test config variables are specified in the environment, but" - " SSL isn't enabled"); + test_error ("SSL test config variables are specified in the environment, but" + " SSL isn't enabled"); #else mongoc_client_set_ssl_opts (client, &gSSLOptions); #endif @@ -1562,13 +1504,11 @@ test_framework_client_new (const char *uri_str, const mongoc_server_api_t *api) } if (api) { - ASSERT_OR_PRINT (mongoc_client_set_server_api (client, api, &error), - error); + ASSERT_OR_PRINT (mongoc_client_set_server_api (client, api, &error), error); } else { default_api = test_framework_get_default_server_api (); if (default_api) { - ASSERT_OR_PRINT ( - mongoc_client_set_server_api (client, default_api, &error), error); + ASSERT_OR_PRINT (mongoc_client_set_server_api (client, default_api, &error), error); } } @@ -1599,8 +1539,7 @@ test_framework_client_new (const char *uri_str, const mongoc_server_api_t *api) *-------------------------------------------------------------------------- */ mongoc_client_t * -test_framework_client_new_from_uri (const mongoc_uri_t *uri, - const mongoc_server_api_t *api) +test_framework_client_new_from_uri (const mongoc_uri_t *uri, const mongoc_server_api_t *api) { mongoc_client_t *client = mongoc_client_new_from_uri (uri); bson_error_t error; @@ -1611,13 +1550,11 @@ test_framework_client_new_from_uri (const mongoc_uri_t *uri, } if (api) { - ASSERT_OR_PRINT (mongoc_client_set_server_api (client, api, &error), - error); + ASSERT_OR_PRINT (mongoc_client_set_server_api (client, api, &error), error); } else { default_api = test_framework_get_default_server_api (); if (default_api) { - ASSERT_OR_PRINT ( - mongoc_client_set_server_api (client, default_api, &error), error); + ASSERT_OR_PRINT (mongoc_client_set_server_api (client, default_api, &error), error); } } @@ -1674,9 +1611,8 @@ test_framework_set_pool_ssl_opts (mongoc_client_pool_t *pool) if (test_framework_get_ssl ()) { #ifndef MONGOC_ENABLE_SSL - test_error ( - "SSL test config variables are specified in the environment, but" - " SSL isn't enabled"); + test_error ("SSL test config variables are specified in the environment, but" + " SSL isn't enabled"); #else mongoc_client_pool_set_ssl_opts (pool, &gSSLOptions); #endif @@ -1703,8 +1639,7 @@ mongoc_client_pool_t * test_framework_new_default_client_pool (void) { mongoc_uri_t *test_uri = test_framework_get_uri (); - mongoc_client_pool_t *pool = - test_framework_client_pool_new_from_uri (test_uri, NULL); + mongoc_client_pool_t *pool = test_framework_client_pool_new_from_uri (test_uri, NULL); BSON_ASSERT (pool); test_framework_set_pool_ssl_opts (pool); @@ -1736,8 +1671,7 @@ test_framework_new_default_client_pool (void) *-------------------------------------------------------------------------- */ mongoc_client_pool_t * -test_framework_client_pool_new_from_uri (const mongoc_uri_t *uri, - const mongoc_server_api_t *api) +test_framework_client_pool_new_from_uri (const mongoc_uri_t *uri, const mongoc_server_api_t *api) { mongoc_client_pool_t *pool = mongoc_client_pool_new (uri); bson_error_t error; @@ -1748,14 +1682,11 @@ test_framework_client_pool_new_from_uri (const mongoc_uri_t *uri, } if (api) { - ASSERT_OR_PRINT (mongoc_client_pool_set_server_api (pool, api, &error), - error); + ASSERT_OR_PRINT (mongoc_client_pool_set_server_api (pool, api, &error), error); } else { default_api = test_framework_get_default_server_api (); if (default_api) { - ASSERT_OR_PRINT ( - mongoc_client_pool_set_server_api (pool, default_api, &error), - error); + ASSERT_OR_PRINT (mongoc_client_pool_set_server_api (pool, default_api, &error), error); } } @@ -1775,8 +1706,7 @@ test_framework_global_ssl_opts_init (void) gSSLOptions.ca_file = test_framework_getenv ("MONGOC_TEST_SSL_CA_FILE"); gSSLOptions.ca_dir = test_framework_getenv ("MONGOC_TEST_SSL_CA_DIR"); gSSLOptions.crl_file = test_framework_getenv ("MONGOC_TEST_SSL_CRL_FILE"); - gSSLOptions.weak_cert_validation = - test_framework_getenv_bool ("MONGOC_TEST_SSL_WEAK_CERT_VALIDATION"); + gSSLOptions.weak_cert_validation = test_framework_getenv_bool ("MONGOC_TEST_SSL_WEAK_CERT_VALIDATION"); } static void @@ -1800,8 +1730,7 @@ test_framework_is_mongos (void) call_hello (&reply); - is_mongos = (bson_iter_init_find (&iter, &reply, "msg") && - BSON_ITER_HOLDS_UTF8 (&iter) && + is_mongos = (bson_iter_init_find (&iter, &reply, "msg") && BSON_ITER_HOLDS_UTF8 (&iter) && !strcasecmp (bson_iter_utf8 (&iter, NULL), "isdbgrid")); bson_destroy (&reply); @@ -1827,14 +1756,12 @@ test_framework_server_is_secondary (mongoc_client_t *client, uint32_t server_id) ASSERT (client); - sd = mongoc_topology_description_server_by_id_const ( - client->topology->_shared_descr_.ptr, server_id, &error); + sd = mongoc_topology_description_server_by_id_const (client->topology->_shared_descr_.ptr, server_id, &error); ASSERT_OR_PRINT (sd, error); call_hello_with_host_and_port (sd->host.host_and_port, &reply); - ret = bson_iter_init_find (&iter, &reply, "secondary") && - bson_iter_as_bool (&iter); + ret = bson_iter_init_find (&iter, &reply, "secondary") && bson_iter_as_bool (&iter); bson_destroy (&reply); @@ -2050,17 +1977,13 @@ test_framework_skip_if_no_uds (void) int test_framework_skip_if_no_txns (void) { - if (test_framework_skip_if_no_crypto () && - test_framework_skip_if_no_sessions () && - test_framework_skip_if_not_replset () && - test_framework_skip_if_max_wire_version_less_than_7 ()) { + if (test_framework_skip_if_no_crypto () && test_framework_skip_if_no_sessions () && + test_framework_skip_if_not_replset () && test_framework_skip_if_max_wire_version_less_than_7 ()) { return 1; } - if (test_framework_skip_if_no_crypto () && - test_framework_skip_if_no_sessions () && - test_framework_skip_if_not_mongos () && - test_framework_skip_if_max_wire_version_less_than_8 ()) { + if (test_framework_skip_if_no_crypto () && test_framework_skip_if_no_sessions () && + test_framework_skip_if_not_mongos () && test_framework_skip_if_max_wire_version_less_than_8 ()) { return 1; } @@ -2116,8 +2039,7 @@ _parse_server_version (const bson_t *buildinfo) /* Server returns a 4-part version like [3, 2, 0, 0], or like [3, 2, 0, -49] * for an RC. Ignore the 4th part since RCs are equivalent to non-RCs for * testing purposes. */ - for (i = 0; i < N_SERVER_VERSION_PARTS && bson_iter_next (&array_iter); - i++) { + for (i = 0; i < N_SERVER_VERSION_PARTS && bson_iter_next (&array_iter); i++) { ret *= 1000; ret += 100 + bson_iter_as_int64 (&array_iter); } @@ -2135,10 +2057,8 @@ test_framework_get_server_version_with_client (mongoc_client_t *client) ASSERT (client); - ASSERT_OR_PRINT ( - mongoc_client_command_simple ( - client, "admin", tmp_bson ("{'buildinfo': 1}"), NULL, &reply, &error), - error); + ASSERT_OR_PRINT (mongoc_client_command_simple (client, "admin", tmp_bson ("{'buildinfo': 1}"), NULL, &reply, &error), + error); ret = _parse_server_version (&reply); @@ -2206,25 +2126,20 @@ test_version_cmp (void) server_version_t v3_2_0 = 103102100; ASSERT (v2_6_12 == test_framework_str_to_version ("2.6.12")); - ASSERT (v2_6_12 == _parse_server_version ( - tmp_bson ("{'versionArray': [2, 6, 12, 0]}"))); + ASSERT (v2_6_12 == _parse_server_version (tmp_bson ("{'versionArray': [2, 6, 12, 0]}"))); ASSERT (v3_0_0 == test_framework_str_to_version ("3")); - ASSERT (v3_0_0 == - _parse_server_version (tmp_bson ("{'versionArray': [3, 0, 0, 0]}"))); + ASSERT (v3_0_0 == _parse_server_version (tmp_bson ("{'versionArray': [3, 0, 0, 0]}"))); ASSERT (v3_0_1 == test_framework_str_to_version ("3.0.1")); - ASSERT (v3_0_1 == - _parse_server_version (tmp_bson ("{'versionArray': [3, 0, 1, 0]}"))); + ASSERT (v3_0_1 == _parse_server_version (tmp_bson ("{'versionArray': [3, 0, 1, 0]}"))); ASSERT (v3_0_10 == test_framework_str_to_version ("3.0.10")); - ASSERT (v3_0_10 == _parse_server_version ( - tmp_bson ("{'versionArray': [3, 0, 10, 0]}"))); + ASSERT (v3_0_10 == _parse_server_version (tmp_bson ("{'versionArray': [3, 0, 10, 0]}"))); /* release candidates should be equivalent to non-rcs. */ ASSERT (v3_2_0 == test_framework_str_to_version ("3.2.0.-49")); - ASSERT (v3_2_0 == _parse_server_version ( - tmp_bson ("{'versionArray': [3, 2, 0, -49]}"))); + ASSERT (v3_2_0 == _parse_server_version (tmp_bson ("{'versionArray': [3, 2, 0, -49]}"))); ASSERT (v3_2_0 > test_framework_str_to_version ("3.1.9")); ASSERT (v3_2_0 == test_framework_str_to_version ("3.2")); @@ -2301,40 +2216,34 @@ test_framework_skip_if_not_replset (void) } /* convenience skip functions based on the wire version. */ -#define WIRE_VERSION_CHECKS(wv) \ - int test_framework_skip_if_max_wire_version_more_than_##wv (void) \ - { \ - if (!TestSuite_CheckLive ()) { \ - return 0; \ - } \ - return test_framework_max_wire_version_at_least (wv + 1) ? 0 : 1; \ - } \ - int test_framework_skip_if_max_wire_version_less_than_##wv (void) \ - { \ - if (!TestSuite_CheckLive ()) { \ - return 0; \ - } \ - return test_framework_max_wire_version_at_least (wv); \ - } \ - int test_framework_skip_if_not_rs_version_##wv (void) \ - { \ - if (!TestSuite_CheckLive ()) { \ - return 0; \ - } \ - return (test_framework_max_wire_version_at_least (wv) && \ - test_framework_is_replset ()) \ - ? 1 \ - : 0; \ - } \ - int test_framework_skip_if_rs_version_##wv (void) \ - { \ - if (!TestSuite_CheckLive ()) { \ - return 0; \ - } \ - return (test_framework_max_wire_version_at_least (wv) && \ - test_framework_is_replset ()) \ - ? 0 \ - : 1; \ +#define WIRE_VERSION_CHECKS(wv) \ + int test_framework_skip_if_max_wire_version_more_than_##wv (void) \ + { \ + if (!TestSuite_CheckLive ()) { \ + return 0; \ + } \ + return test_framework_max_wire_version_at_least (wv + 1) ? 0 : 1; \ + } \ + int test_framework_skip_if_max_wire_version_less_than_##wv (void) \ + { \ + if (!TestSuite_CheckLive ()) { \ + return 0; \ + } \ + return test_framework_max_wire_version_at_least (wv); \ + } \ + int test_framework_skip_if_not_rs_version_##wv (void) \ + { \ + if (!TestSuite_CheckLive ()) { \ + return 0; \ + } \ + return (test_framework_max_wire_version_at_least (wv) && test_framework_is_replset ()) ? 1 : 0; \ + } \ + int test_framework_skip_if_rs_version_##wv (void) \ + { \ + if (!TestSuite_CheckLive ()) { \ + return 0; \ + } \ + return (test_framework_max_wire_version_at_least (wv) && test_framework_is_replset ()) ? 0 : 1; \ } WIRE_VERSION_CHECKS (7) @@ -2417,14 +2326,13 @@ test_framework_skip_if_no_failpoint (void) client = test_framework_new_default_client (); mongoc_client_set_error_api (client, MONGOC_ERROR_API_VERSION_2); - ret = mongoc_client_command_simple ( - client, - "admin", - tmp_bson ("{'configureFailPoint': 'failCommand', 'mode': 'off', 'data': " - "{'errorCode': 10107, 'failCommands': ['count']}}"), - NULL, - NULL, - &error); + ret = mongoc_client_command_simple (client, + "admin", + tmp_bson ("{'configureFailPoint': 'failCommand', 'mode': 'off', 'data': " + "{'errorCode': 10107, 'failCommands': ['count']}}"), + NULL, + NULL, + &error); mongoc_client_destroy (client); if (!ret) { @@ -2438,19 +2346,18 @@ test_framework_skip_if_no_failpoint (void) int test_framework_skip_if_no_client_side_encryption (void) { - const char *required_env_vars[] = { - "MONGOC_TEST_AWS_SECRET_ACCESS_KEY", - "MONGOC_TEST_AWS_ACCESS_KEY_ID", - "MONGOC_TEST_AWSNAME2_SECRET_ACCESS_KEY", - "MONGOC_TEST_AWSNAME2_ACCESS_KEY_ID", - "MONGOC_TEST_AZURE_TENANT_ID", - "MONGOC_TEST_AZURE_CLIENT_ID", - "MONGOC_TEST_AZURE_CLIENT_SECRET", - "MONGOC_TEST_GCP_EMAIL", - "MONGOC_TEST_GCP_PRIVATEKEY", - "MONGOC_TEST_CSFLE_TLS_CA_FILE", - "MONGOC_TEST_CSFLE_TLS_CERTIFICATE_KEY_FILE", - NULL}; + const char *required_env_vars[] = {"MONGOC_TEST_AWS_SECRET_ACCESS_KEY", + "MONGOC_TEST_AWS_ACCESS_KEY_ID", + "MONGOC_TEST_AWSNAME2_SECRET_ACCESS_KEY", + "MONGOC_TEST_AWSNAME2_ACCESS_KEY_ID", + "MONGOC_TEST_AZURE_TENANT_ID", + "MONGOC_TEST_AZURE_CLIENT_ID", + "MONGOC_TEST_AZURE_CLIENT_SECRET", + "MONGOC_TEST_GCP_EMAIL", + "MONGOC_TEST_GCP_PRIVATEKEY", + "MONGOC_TEST_CSFLE_TLS_CA_FILE", + "MONGOC_TEST_CSFLE_TLS_CERTIFICATE_KEY_FILE", + NULL}; const char **iter; bool has_creds = true; @@ -2520,10 +2427,8 @@ test_framework_skip_if_serverless (void) int test_framework_skip_due_to_cdriver3708 (void) { - if (0 == test_framework_skip_if_auth () && - 0 == test_framework_skip_if_replset () && - test_framework_get_server_version () > - test_framework_str_to_version ("4.4.0")) { + if (0 == test_framework_skip_if_auth () && 0 == test_framework_skip_if_replset () && + test_framework_get_server_version () > test_framework_str_to_version ("4.4.0")) { /* If auth is enabled, we're using a replica set, and using a > 4.4 * server, skip test. */ return 0; @@ -2553,21 +2458,13 @@ windows_exception_handler (EXCEPTION_POINTERS *pExceptionInfo) char exception_string[128]; bson_snprintf (exception_string, sizeof (exception_string), - (exception_code == EXCEPTION_ACCESS_VIOLATION) - ? "(access violation)" - : "0x%08X", + (exception_code == EXCEPTION_ACCESS_VIOLATION) ? "(access violation)" : "0x%08X", exception_code); char address_string[32]; - bson_snprintf (address_string, - sizeof (address_string), - "0x%p", - pExceptionInfo->ExceptionRecord->ExceptionAddress); + bson_snprintf (address_string, sizeof (address_string), "0x%p", pExceptionInfo->ExceptionRecord->ExceptionAddress); - fprintf (stderr, - "exception '%s' at '%s', terminating\n", - exception_string, - address_string); + fprintf (stderr, "exception '%s' at '%s', terminating\n", exception_string, address_string); STACKFRAME64 stack_frame; memset (&stack_frame, 0, sizeof (stack_frame)); @@ -2603,10 +2500,7 @@ windows_exception_handler (EXCEPTION_POINTERS *pExceptionInfo) NULL)) { DWORD64 displacement = 0; - if (SymFromAddr (process, - (DWORD64) stack_frame.AddrPC.Offset, - &displacement, - symbol)) { + if (SymFromAddr (process, (DWORD64) stack_frame.AddrPC.Offset, &displacement, symbol)) { IMAGEHLP_MODULE64 moduleInfo; memset (&moduleInfo, 0, sizeof (moduleInfo)); moduleInfo.SizeOfStruct = sizeof (moduleInfo); @@ -2621,8 +2515,7 @@ windows_exception_handler (EXCEPTION_POINTERS *pExceptionInfo) line.SizeOfStruct = sizeof (IMAGEHLP_LINE); DWORD offset_ln = 0; - if (SymGetLineFromAddr ( - process, (DWORD64) stack_frame.AddrPC.Offset, &offset_ln, &line)) { + if (SymGetLineFromAddr (process, (DWORD64) stack_frame.AddrPC.Offset, &offset_ln, &line)) { fprintf (stderr, " %s:%d ", line.FileName, line.LineNumber); } @@ -2636,21 +2529,15 @@ windows_exception_handler (EXCEPTION_POINTERS *pExceptionInfo) void -test_libmongoc_init (TestSuite *suite, - BSON_MAYBE_UNUSED const char *name, - int argc, - char **argv) +test_libmongoc_init (TestSuite *suite, BSON_MAYBE_UNUSED const char *name, int argc, char **argv) { #if defined(_MSC_VER) && defined(_WIN64) SetUnhandledExceptionFilter (windows_exception_handler); #endif mongoc_init (); - bson_snprintf (MONGOC_TEST_UNIQUE, - sizeof MONGOC_TEST_UNIQUE, - "test_%u_%u", - (unsigned) time (NULL), - (unsigned) gettestpid ()); + bson_snprintf ( + MONGOC_TEST_UNIQUE, sizeof MONGOC_TEST_UNIQUE, "test_%u_%u", (unsigned) time (NULL), (unsigned) gettestpid ()); bson_mutex_init (&captured_logs_mutex); _mongoc_array_init (&captured_logs, sizeof (log_entry_t *)); diff --git a/src/libmongoc/tests/test-libmongoc.h b/src/libmongoc/tests/test-libmongoc.h index dc2a5b1df2..8d4b3d6fe6 100644 --- a/src/libmongoc/tests/test-libmongoc.h +++ b/src/libmongoc/tests/test-libmongoc.h @@ -25,10 +25,7 @@ struct _server_version_t; void -test_libmongoc_init (struct _TestSuite *suite, - const char *name, - int argc, - char **argv); +test_libmongoc_init (struct _TestSuite *suite, const char *name, int argc, char **argv); void test_libmongoc_destroy (struct _TestSuite *suite); @@ -74,9 +71,7 @@ test_framework_get_admin_password (void); bool test_framework_get_ssl (void); char * -test_framework_add_user_password (const char *uri_str, - const char *user, - const char *password); +test_framework_add_user_password (const char *uri_str, const char *user, const char *password); char * test_framework_add_user_password_from_env (const char *uri_str); char * @@ -92,9 +87,7 @@ test_framework_get_uri (void); mongoc_uri_t * test_framework_get_uri_multi_mongos_loadbalanced (void); bool -test_framework_uri_apply_multi_mongos (mongoc_uri_t *uri, - bool use_multi, - bson_error_t *error); +test_framework_uri_apply_multi_mongos (mongoc_uri_t *uri, bool use_multi, bson_error_t *error); size_t test_framework_mongos_count (void); char * @@ -125,14 +118,12 @@ test_framework_client_new_no_server_api (void); mongoc_client_t * test_framework_client_new (const char *uri_str, const mongoc_server_api_t *api); mongoc_client_t * -test_framework_client_new_from_uri (const mongoc_uri_t *uri, - const mongoc_server_api_t *api); +test_framework_client_new_from_uri (const mongoc_uri_t *uri, const mongoc_server_api_t *api); mongoc_client_pool_t * test_framework_new_default_client_pool (void); mongoc_client_pool_t * -test_framework_client_pool_new_from_uri (const mongoc_uri_t *uri, - const mongoc_server_api_t *api); +test_framework_client_pool_new_from_uri (const mongoc_uri_t *uri, const mongoc_server_api_t *api); bool test_framework_is_mongos (void); @@ -144,8 +135,7 @@ test_framework_is_replset (void); bool test_framework_is_mongohouse (void); bool -test_framework_server_is_secondary (mongoc_client_t *client, - uint32_t server_id); +test_framework_server_is_secondary (mongoc_client_t *client, uint32_t server_id); int64_t test_framework_session_timeout_minutes (void); void @@ -229,8 +219,7 @@ typedef struct _debug_stream_stats_t { } debug_stream_stats_t; void -test_framework_set_debug_stream (mongoc_client_t *client, - debug_stream_stats_t *stats); +test_framework_set_debug_stream (mongoc_client_t *client, debug_stream_stats_t *stats); typedef int64_t server_version_t; diff --git a/src/libmongoc/tests/test-mcd-azure-imds.c b/src/libmongoc/tests/test-mcd-azure-imds.c index fe9077e2fa..968790c075 100644 --- a/src/libmongoc/tests/test-mcd-azure-imds.c +++ b/src/libmongoc/tests/test-mcd-azure-imds.c @@ -12,29 +12,19 @@ _test_oauth_parse (void) // Test that we can correctly parse a JSON document from the IMDS sever bson_error_t error; mcd_azure_access_token token; - ASSERT (!mcd_azure_access_token_try_init_from_json_str ( - &token, "invalid json", -1, &error)); + ASSERT (!mcd_azure_access_token_try_init_from_json_str (&token, "invalid json", -1, &error)); ASSERT_CMPUINT32 (error.domain, ==, BSON_ERROR_JSON); - ASSERT (!mcd_azure_access_token_try_init_from_json_str ( - &token, "{}", -1, &error)); - ASSERT_ERROR_CONTAINS ( - error, MONGOC_ERROR_AZURE, MONGOC_ERROR_KMS_SERVER_BAD_JSON, ""); + ASSERT (!mcd_azure_access_token_try_init_from_json_str (&token, "{}", -1, &error)); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_AZURE, MONGOC_ERROR_KMS_SERVER_BAD_JSON, ""); - ASSERT (!mcd_azure_access_token_try_init_from_json_str ( - &token, RAW_STRING ({"access_token" : null}), -1, &error)); - ASSERT_ERROR_CONTAINS ( - error, MONGOC_ERROR_AZURE, MONGOC_ERROR_KMS_SERVER_BAD_JSON, ""); + ASSERT (!mcd_azure_access_token_try_init_from_json_str (&token, RAW_STRING ({"access_token" : null}), -1, &error)); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_AZURE, MONGOC_ERROR_KMS_SERVER_BAD_JSON, ""); error = (bson_error_t){0}; ASSERT (mcd_azure_access_token_try_init_from_json_str ( &token, - RAW_STRING ({ - "access_token" : "meow", - "resource" : "something", - "expires_in" : "1234", - "token_type" : "Bearer" - }), + RAW_STRING ({"access_token" : "meow", "resource" : "something", "expires_in" : "1234", "token_type" : "Bearer"}), -1, &error)); ASSERT_ERROR_CONTAINS (error, 0, 0, ""); @@ -79,19 +69,15 @@ _run_http_test_case (const char *case_, { bson_error_t error = {0}; struct _mongoc_host_list_t host; - _mongoc_host_list_from_string_with_err ( - &host, _get_test_imds_host (), &error); + _mongoc_host_list_from_string_with_err (&host, _get_test_imds_host (), &error); ASSERT_ERROR_CONTAINS (error, 0, 0, ""); mcd_azure_access_token token = {0}; - char *const header = - bson_strdup_printf ("X-MongoDB-HTTP-TestParams: case=%s\r\n", case_); - mcd_azure_access_token_from_imds ( - &token, host.host, host.port, header, &error); + char *const header = bson_strdup_printf ("X-MongoDB-HTTP-TestParams: case=%s\r\n", case_); + mcd_azure_access_token_from_imds (&token, host.host, host.port, header, &error); bson_free (header); mcd_azure_access_token_destroy (&token); - ASSERT_ERROR_CONTAINS ( - error, expect_domain, expect_code, expect_error_message); + ASSERT_ERROR_CONTAINS (error, expect_domain, expect_code, expect_error_message); } static void @@ -100,16 +86,11 @@ _test_with_mock_server (void *ctx) BSON_UNUSED (ctx); _run_http_test_case ("", 0, 0, ""); // (No error) - _run_http_test_case ( - "404", MONGOC_ERROR_AZURE, MONGOC_ERROR_KMS_SERVER_HTTP, ""); - _run_http_test_case ( - "slow", MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "Timeout"); - _run_http_test_case ( - "empty-json", MONGOC_ERROR_AZURE, MONGOC_ERROR_KMS_SERVER_BAD_JSON, ""); - _run_http_test_case ( - "bad-json", MONGOC_ERROR_CLIENT, MONGOC_ERROR_STREAM_INVALID_TYPE, ""); - _run_http_test_case ( - "giant", MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "too large"); + _run_http_test_case ("404", MONGOC_ERROR_AZURE, MONGOC_ERROR_KMS_SERVER_HTTP, ""); + _run_http_test_case ("slow", MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "Timeout"); + _run_http_test_case ("empty-json", MONGOC_ERROR_AZURE, MONGOC_ERROR_KMS_SERVER_BAD_JSON, ""); + _run_http_test_case ("bad-json", MONGOC_ERROR_CLIENT, MONGOC_ERROR_STREAM_INVALID_TYPE, ""); + _run_http_test_case ("giant", MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "too large"); } static int @@ -124,10 +105,5 @@ test_mcd_azure_imds_install (TestSuite *suite) { TestSuite_Add (suite, "/azure/imds/http/parse", _test_oauth_parse); TestSuite_Add (suite, "/azure/imds/http/request", _test_http_req); - TestSuite_AddFull (suite, - "/azure/imds/http/talk", - _test_with_mock_server, - NULL, - NULL, - have_mock_server_env); + TestSuite_AddFull (suite, "/azure/imds/http/talk", _test_with_mock_server, NULL, NULL, have_mock_server_env); } diff --git a/src/libmongoc/tests/test-mcd-rpc.c b/src/libmongoc/tests/test-mcd-rpc.c index f4a9ae5b27..323f85f976 100644 --- a/src/libmongoc/tests/test-mcd-rpc.c +++ b/src/libmongoc/tests/test-mcd-rpc.c @@ -309,24 +309,22 @@ // clang-format on -#define ASSERT_RPC_MESSAGE_RESULT(rpc, data_begin, data_end, data_len) \ - if (1) { \ - const size_t parsed_len = \ - (size_t) ((const uint8_t *) data_end - data_begin); \ - if (rpc) { \ - ASSERT_WITH_MSG ( \ - parsed_len == data_len, \ - "converted only %zu bytes despite %zu bytes of valid input data", \ - parsed_len, \ - data_len); \ - } else { \ - ASSERT_WITH_MSG (rpc, \ - "failed to convert valid input data into an RPC " \ - "message due to byte %zu of %zu", \ - parsed_len, \ - data_len); \ - } \ - } else \ +#define ASSERT_RPC_MESSAGE_RESULT(rpc, data_begin, data_end, data_len) \ + if (1) { \ + const size_t parsed_len = (size_t) ((const uint8_t *) data_end - data_begin); \ + if (rpc) { \ + ASSERT_WITH_MSG (parsed_len == data_len, \ + "converted only %zu bytes despite %zu bytes of valid input data", \ + parsed_len, \ + data_len); \ + } else { \ + ASSERT_WITH_MSG (rpc, \ + "failed to convert valid input data into an RPC " \ + "message due to byte %zu of %zu", \ + parsed_len, \ + data_len); \ + } \ + } else \ (void) 0 @@ -354,35 +352,25 @@ test_rpc_message_from_data_op_compressed_valid (void) // Valid test input data. { const void *data_end = NULL; - mcd_rpc_message *const rpc = - mcd_rpc_message_from_data (data, data_len, &data_end); + mcd_rpc_message *const rpc = mcd_rpc_message_from_data (data, data_len, &data_end); ASSERT_RPC_MESSAGE_RESULT (rpc, data, data_end, data_len); ASSERT (bson_in_range_unsigned (int32_t, data_len)); - ASSERT_CMPINT32 ( - mcd_rpc_header_get_message_length (rpc), ==, (int32_t) data_len); + ASSERT_CMPINT32 (mcd_rpc_header_get_message_length (rpc), ==, (int32_t) data_len); ASSERT_CMPINT32 (mcd_rpc_header_get_request_id (rpc), ==, 16909060); ASSERT_CMPINT32 (mcd_rpc_header_get_response_to (rpc), ==, 84281096); - ASSERT_CMPINT32 ( - mcd_rpc_header_get_op_code (rpc), ==, MONGOC_OP_CODE_COMPRESSED); + ASSERT_CMPINT32 (mcd_rpc_header_get_op_code (rpc), ==, MONGOC_OP_CODE_COMPRESSED); - ASSERT_CMPINT32 (mcd_rpc_op_compressed_get_original_opcode (rpc), - ==, - MONGOC_OP_CODE_MSG); + ASSERT_CMPINT32 (mcd_rpc_op_compressed_get_original_opcode (rpc), ==, MONGOC_OP_CODE_MSG); - ASSERT_CMPINT32 ( - mcd_rpc_op_compressed_get_uncompressed_size (rpc), ==, 20); + ASSERT_CMPINT32 (mcd_rpc_op_compressed_get_uncompressed_size (rpc), ==, 20); - ASSERT_CMPUINT (mcd_rpc_op_compressed_get_compressor_id (rpc), - ==, - MONGOC_OP_COMPRESSED_COMPRESSOR_ID_NOOP); + ASSERT_CMPUINT (mcd_rpc_op_compressed_get_compressor_id (rpc), ==, MONGOC_OP_COMPRESSED_COMPRESSOR_ID_NOOP); - const uint8_t *const compressed_message = - mcd_rpc_op_compressed_get_compressed_message (rpc); + const uint8_t *const compressed_message = mcd_rpc_op_compressed_get_compressed_message (rpc); ASSERT_CMPSIZE_T ((size_t) (compressed_message - data), ==, 25u); - ASSERT_CMPSIZE_T ( - mcd_rpc_op_compressed_get_compressed_message_length (rpc), ==, 20u); + ASSERT_CMPSIZE_T (mcd_rpc_op_compressed_get_compressed_message_length (rpc), ==, 20u); mcd_rpc_message_destroy (rpc); } @@ -391,12 +379,9 @@ test_rpc_message_from_data_op_compressed_valid (void) { data[24] = MONGOC_OP_COMPRESSED_COMPRESSOR_ID_SNAPPY; - mcd_rpc_message *const rpc = - mcd_rpc_message_from_data (data, data_len, NULL); + mcd_rpc_message *const rpc = mcd_rpc_message_from_data (data, data_len, NULL); ASSERT (rpc); - ASSERT_CMPUINT (mcd_rpc_op_compressed_get_compressor_id (rpc), - ==, - MONGOC_OP_COMPRESSED_COMPRESSOR_ID_SNAPPY); + ASSERT_CMPUINT (mcd_rpc_op_compressed_get_compressor_id (rpc), ==, MONGOC_OP_COMPRESSED_COMPRESSOR_ID_SNAPPY); mcd_rpc_message_destroy (rpc); data[24] = MONGOC_OP_COMPRESSED_COMPRESSOR_ID_NOOP; @@ -407,13 +392,10 @@ test_rpc_message_from_data_op_compressed_valid (void) static void _test_rpc_message_from_data_op_msg_valid (uint8_t *data, size_t data_len, - void (*test) (const uint8_t *data, - size_t data_len, - bool with_checksum)) + void (*test) (const uint8_t *data, size_t data_len, bool with_checksum)) { - ASSERT_WITH_MSG ( - (data[16] & MONGOC_OP_MSG_FLAG_CHECKSUM_PRESENT) != 0, - "test input data did not set MONGOC_OP_MSG_FLAG_CHECKSUM_PRESENT"); + ASSERT_WITH_MSG ((data[16] & MONGOC_OP_MSG_FLAG_CHECKSUM_PRESENT) != 0, + "test input data did not set MONGOC_OP_MSG_FLAG_CHECKSUM_PRESENT"); // Test with and without the optional checksum by temporarily modifying the // data and data length accordingly. @@ -431,29 +413,22 @@ _test_rpc_message_from_data_op_msg_valid (uint8_t *data, } static void -_test_rpc_message_from_data_op_msg_valid_kind_0 (const uint8_t *data, - size_t data_len, - bool with_checksum) +_test_rpc_message_from_data_op_msg_valid_kind_0 (const uint8_t *data, size_t data_len, bool with_checksum) { const void *data_end = NULL; - mcd_rpc_message *const rpc = - mcd_rpc_message_from_data (data, data_len, &data_end); + mcd_rpc_message *const rpc = mcd_rpc_message_from_data (data, data_len, &data_end); ASSERT_RPC_MESSAGE_RESULT (rpc, data, data_end, data_len); ASSERT (bson_in_range_unsigned (int32_t, data_len)); - ASSERT_CMPINT32 ( - mcd_rpc_header_get_message_length (rpc), ==, (int32_t) data_len); + ASSERT_CMPINT32 (mcd_rpc_header_get_message_length (rpc), ==, (int32_t) data_len); ASSERT_CMPINT32 (mcd_rpc_header_get_request_id (rpc), ==, 16909060); ASSERT_CMPINT32 (mcd_rpc_header_get_response_to (rpc), ==, 84281096); ASSERT_CMPINT32 (mcd_rpc_header_get_op_code (rpc), ==, MONGOC_OP_CODE_MSG); if (with_checksum) { - ASSERT_CMPUINT32 (mcd_rpc_op_msg_get_flag_bits (rpc), - ==, - MONGOC_OP_MSG_FLAG_CHECKSUM_PRESENT); + ASSERT_CMPUINT32 (mcd_rpc_op_msg_get_flag_bits (rpc), ==, MONGOC_OP_MSG_FLAG_CHECKSUM_PRESENT); } else { - ASSERT_CMPUINT32 ( - mcd_rpc_op_msg_get_flag_bits (rpc), ==, MONGOC_OP_MSG_FLAG_NONE); + ASSERT_CMPUINT32 (mcd_rpc_op_msg_get_flag_bits (rpc), ==, MONGOC_OP_MSG_FLAG_NONE); } ASSERT_CMPSIZE_T (mcd_rpc_op_msg_get_sections_count (rpc), ==, 1u); @@ -484,34 +459,26 @@ test_rpc_message_from_data_op_msg_valid_kind_0 (void) { uint8_t data[] = {TEST_DATA_OP_MSG_KIND_0}; - _test_rpc_message_from_data_op_msg_valid ( - data, sizeof (data), _test_rpc_message_from_data_op_msg_valid_kind_0); + _test_rpc_message_from_data_op_msg_valid (data, sizeof (data), _test_rpc_message_from_data_op_msg_valid_kind_0); } static void -_test_rpc_message_from_data_op_msg_valid_kind_1_single (const uint8_t *data, - size_t data_len, - bool with_checksum) +_test_rpc_message_from_data_op_msg_valid_kind_1_single (const uint8_t *data, size_t data_len, bool with_checksum) { const void *data_end = NULL; - mcd_rpc_message *const rpc = - mcd_rpc_message_from_data (data, data_len, &data_end); + mcd_rpc_message *const rpc = mcd_rpc_message_from_data (data, data_len, &data_end); ASSERT_RPC_MESSAGE_RESULT (rpc, data, data_end, data_len); ASSERT (bson_in_range_unsigned (int32_t, data_len)); - ASSERT_CMPINT32 ( - mcd_rpc_header_get_message_length (rpc), ==, (int32_t) data_len); + ASSERT_CMPINT32 (mcd_rpc_header_get_message_length (rpc), ==, (int32_t) data_len); ASSERT_CMPINT32 (mcd_rpc_header_get_request_id (rpc), ==, 16909060); ASSERT_CMPINT32 (mcd_rpc_header_get_response_to (rpc), ==, 84281096); ASSERT_CMPINT32 (mcd_rpc_header_get_op_code (rpc), ==, MONGOC_OP_CODE_MSG); if (with_checksum) { - ASSERT_CMPUINT32 (mcd_rpc_op_msg_get_flag_bits (rpc), - ==, - MONGOC_OP_MSG_FLAG_CHECKSUM_PRESENT); + ASSERT_CMPUINT32 (mcd_rpc_op_msg_get_flag_bits (rpc), ==, MONGOC_OP_MSG_FLAG_CHECKSUM_PRESENT); } else { - ASSERT_CMPUINT32 ( - mcd_rpc_op_msg_get_flag_bits (rpc), ==, MONGOC_OP_MSG_FLAG_NONE); + ASSERT_CMPUINT32 (mcd_rpc_op_msg_get_flag_bits (rpc), ==, MONGOC_OP_MSG_FLAG_NONE); } ASSERT_CMPSIZE_T (mcd_rpc_op_msg_get_sections_count (rpc), ==, 2u); @@ -535,13 +502,9 @@ _test_rpc_message_from_data_op_msg_valid_kind_1_single (const uint8_t *data, const int32_t section_len = mcd_rpc_op_msg_section_get_length (rpc, 1u); ASSERT_CMPINT32 (section_len, ==, 26); ASSERT_CMPSTR (mcd_rpc_op_msg_section_get_identifier (rpc, 1u), "single"); - const void *const sequence = - mcd_rpc_op_msg_section_get_document_sequence (rpc, 1u); + const void *const sequence = mcd_rpc_op_msg_section_get_document_sequence (rpc, 1u); ASSERT (sequence); - ASSERT_CMPSIZE_T ( - mcd_rpc_op_msg_section_get_document_sequence_length (rpc, 1u), - ==, - 15u); + ASSERT_CMPSIZE_T (mcd_rpc_op_msg_section_get_document_sequence_length (rpc, 1u), ==, 15u); const int32_t bson_len = _int32_from_le (sequence); ASSERT_CMPINT32 (bson_len, ==, 15); @@ -568,35 +531,26 @@ test_rpc_message_from_data_op_msg_valid_kind_1_single (void) uint8_t data[] = {TEST_DATA_OP_MSG_KIND_1_SINGLE}; _test_rpc_message_from_data_op_msg_valid ( - data, - sizeof (data), - _test_rpc_message_from_data_op_msg_valid_kind_1_single); + data, sizeof (data), _test_rpc_message_from_data_op_msg_valid_kind_1_single); } static void -_test_rpc_message_from_data_op_msg_valid_kind_1_multiple (const uint8_t *data, - size_t data_len, - bool with_checksum) +_test_rpc_message_from_data_op_msg_valid_kind_1_multiple (const uint8_t *data, size_t data_len, bool with_checksum) { const void *data_end = NULL; - mcd_rpc_message *const rpc = - mcd_rpc_message_from_data (data, data_len, &data_end); + mcd_rpc_message *const rpc = mcd_rpc_message_from_data (data, data_len, &data_end); ASSERT_RPC_MESSAGE_RESULT (rpc, data, data_end, data_len); ASSERT (bson_in_range_unsigned (int32_t, data_len)); - ASSERT_CMPINT32 ( - mcd_rpc_header_get_message_length (rpc), ==, (int32_t) data_len); + ASSERT_CMPINT32 (mcd_rpc_header_get_message_length (rpc), ==, (int32_t) data_len); ASSERT_CMPINT32 (mcd_rpc_header_get_request_id (rpc), ==, 16909060); ASSERT_CMPINT32 (mcd_rpc_header_get_response_to (rpc), ==, 84281096); ASSERT_CMPINT32 (mcd_rpc_header_get_op_code (rpc), ==, MONGOC_OP_CODE_MSG); if (with_checksum) { - ASSERT_CMPUINT32 (mcd_rpc_op_msg_get_flag_bits (rpc), - ==, - MONGOC_OP_MSG_FLAG_CHECKSUM_PRESENT); + ASSERT_CMPUINT32 (mcd_rpc_op_msg_get_flag_bits (rpc), ==, MONGOC_OP_MSG_FLAG_CHECKSUM_PRESENT); } else { - ASSERT_CMPUINT32 ( - mcd_rpc_op_msg_get_flag_bits (rpc), ==, MONGOC_OP_MSG_FLAG_NONE); + ASSERT_CMPUINT32 (mcd_rpc_op_msg_get_flag_bits (rpc), ==, MONGOC_OP_MSG_FLAG_NONE); } ASSERT_CMPSIZE_T (mcd_rpc_op_msg_get_sections_count (rpc), ==, 3u); @@ -620,8 +574,7 @@ _test_rpc_message_from_data_op_msg_valid_kind_1_multiple (const uint8_t *data, const int32_t section_len = mcd_rpc_op_msg_section_get_length (rpc, 1u); ASSERT_CMPINT32 (section_len, ==, 25); ASSERT_CMPSTR (mcd_rpc_op_msg_section_get_identifier (rpc, 1u), "first"); - const void *const sequence = - mcd_rpc_op_msg_section_get_document_sequence (rpc, 1u); + const void *const sequence = mcd_rpc_op_msg_section_get_document_sequence (rpc, 1u); ASSERT (sequence); const int32_t bson_len = _int32_from_le (sequence); @@ -638,8 +591,7 @@ _test_rpc_message_from_data_op_msg_valid_kind_1_multiple (const uint8_t *data, const int32_t section_len = mcd_rpc_op_msg_section_get_length (rpc, 2u); ASSERT_CMPINT32 (section_len, ==, 43); ASSERT_CMPSTR (mcd_rpc_op_msg_section_get_identifier (rpc, 2u), "second"); - const uint8_t *const sequence = - mcd_rpc_op_msg_section_get_document_sequence (rpc, 2u); + const uint8_t *const sequence = mcd_rpc_op_msg_section_get_document_sequence (rpc, 2u); ASSERT (sequence); // BSON objects, index 0. @@ -684,9 +636,7 @@ test_rpc_message_from_data_op_msg_valid_kind_1_multiple (void) uint8_t data[] = {TEST_DATA_OP_MSG_KIND_1_MULTIPLE}; _test_rpc_message_from_data_op_msg_valid ( - data, - sizeof (data), - _test_rpc_message_from_data_op_msg_valid_kind_1_multiple); + data, sizeof (data), _test_rpc_message_from_data_op_msg_valid_kind_1_multiple); } static void @@ -705,24 +655,18 @@ test_rpc_message_from_data_op_reply_valid (void) { const void *data_end = NULL; - mcd_rpc_message *const rpc = - mcd_rpc_message_from_data (data, data_len, &data_end); + mcd_rpc_message *const rpc = mcd_rpc_message_from_data (data, data_len, &data_end); ASSERT_RPC_MESSAGE_RESULT (rpc, data, data_end, data_len); ASSERT (bson_in_range_unsigned (int32_t, data_len)); - ASSERT_CMPINT32 ( - mcd_rpc_header_get_message_length (rpc), ==, (int32_t) data_len); + ASSERT_CMPINT32 (mcd_rpc_header_get_message_length (rpc), ==, (int32_t) data_len); ASSERT_CMPINT32 (mcd_rpc_header_get_request_id (rpc), ==, 16909060); ASSERT_CMPINT32 (mcd_rpc_header_get_response_to (rpc), ==, 84281096); - ASSERT_CMPINT32 ( - mcd_rpc_header_get_op_code (rpc), ==, MONGOC_OP_CODE_REPLY); + ASSERT_CMPINT32 (mcd_rpc_header_get_op_code (rpc), ==, MONGOC_OP_CODE_REPLY); - ASSERT_CMPINT32 (mcd_rpc_op_reply_get_response_flags (rpc), - ==, - MONGOC_OP_REPLY_RESPONSE_FLAG_NONE); + ASSERT_CMPINT32 (mcd_rpc_op_reply_get_response_flags (rpc), ==, MONGOC_OP_REPLY_RESPONSE_FLAG_NONE); - ASSERT_CMPINT64 ( - mcd_rpc_op_reply_get_cursor_id (rpc), ==, 1234605616436508552); + ASSERT_CMPINT64 (mcd_rpc_op_reply_get_cursor_id (rpc), ==, 1234605616436508552); ASSERT_CMPINT32 (mcd_rpc_op_reply_get_starting_from (rpc), ==, 0); @@ -764,12 +708,9 @@ test_rpc_message_from_data_op_reply_valid (void) { data[16] = MONGOC_OP_REPLY_RESPONSE_FLAG_CURSOR_NOT_FOUND; - mcd_rpc_message *const rpc = - mcd_rpc_message_from_data (data, data_len, NULL); + mcd_rpc_message *const rpc = mcd_rpc_message_from_data (data, data_len, NULL); ASSERT (rpc); - ASSERT_CMPINT32 (mcd_rpc_op_reply_get_response_flags (rpc), - ==, - MONGOC_OP_REPLY_RESPONSE_FLAG_CURSOR_NOT_FOUND); + ASSERT_CMPINT32 (mcd_rpc_op_reply_get_response_flags (rpc), ==, MONGOC_OP_REPLY_RESPONSE_FLAG_CURSOR_NOT_FOUND); mcd_rpc_message_destroy (rpc); data[16] = MONGOC_OP_REPLY_RESPONSE_FLAG_NONE; @@ -779,8 +720,7 @@ test_rpc_message_from_data_op_reply_valid (void) { data[28] = 1u; - mcd_rpc_message *const rpc = - mcd_rpc_message_from_data (data, data_len, NULL); + mcd_rpc_message *const rpc = mcd_rpc_message_from_data (data, data_len, NULL); ASSERT (rpc); ASSERT_CMPINT32 (mcd_rpc_op_reply_get_starting_from (rpc), ==, 1); mcd_rpc_message_destroy (rpc); @@ -794,8 +734,7 @@ test_rpc_message_from_data_op_reply_valid (void) data[32] = 0x00u; // Set numberReturned to 0. { - mcd_rpc_message *const rpc = - mcd_rpc_message_from_data (data, data_len, NULL); + mcd_rpc_message *const rpc = mcd_rpc_message_from_data (data, data_len, NULL); ASSERT (rpc); ASSERT_CMPINT32 (mcd_rpc_op_reply_get_number_returned (rpc), ==, 0); ASSERT_CMPSIZE_T (mcd_rpc_op_reply_get_documents_len (rpc), ==, 0u); @@ -816,23 +755,18 @@ test_rpc_message_from_data_op_update_valid (void) { const void *data_end = NULL; - mcd_rpc_message *const rpc = - mcd_rpc_message_from_data (data, data_len, &data_end); + mcd_rpc_message *const rpc = mcd_rpc_message_from_data (data, data_len, &data_end); ASSERT_RPC_MESSAGE_RESULT (rpc, data, data_end, data_len); ASSERT (bson_in_range_unsigned (int32_t, data_len)); - ASSERT_CMPINT32 ( - mcd_rpc_header_get_message_length (rpc), ==, (int32_t) data_len); + ASSERT_CMPINT32 (mcd_rpc_header_get_message_length (rpc), ==, (int32_t) data_len); ASSERT_CMPINT32 (mcd_rpc_header_get_request_id (rpc), ==, 16909060); ASSERT_CMPINT32 (mcd_rpc_header_get_response_to (rpc), ==, 84281096); - ASSERT_CMPINT32 ( - mcd_rpc_header_get_op_code (rpc), ==, MONGOC_OP_CODE_UPDATE); + ASSERT_CMPINT32 (mcd_rpc_header_get_op_code (rpc), ==, MONGOC_OP_CODE_UPDATE); - ASSERT_CMPSTR (mcd_rpc_op_update_get_full_collection_name (rpc), - "db.coll"); + ASSERT_CMPSTR (mcd_rpc_op_update_get_full_collection_name (rpc), "db.coll"); - ASSERT_CMPINT32 ( - mcd_rpc_op_update_get_flags (rpc), ==, MONGOC_OP_UPDATE_FLAG_NONE); + ASSERT_CMPINT32 (mcd_rpc_op_update_get_flags (rpc), ==, MONGOC_OP_UPDATE_FLAG_NONE); { const uint8_t *const selector = mcd_rpc_op_update_get_selector (rpc); @@ -867,11 +801,9 @@ test_rpc_message_from_data_op_update_valid (void) { data[28] = MONGOC_OP_UPDATE_FLAG_UPSERT; - mcd_rpc_message *const rpc = - mcd_rpc_message_from_data (data, data_len, NULL); + mcd_rpc_message *const rpc = mcd_rpc_message_from_data (data, data_len, NULL); ASSERT (rpc); - ASSERT_CMPINT32 ( - mcd_rpc_op_update_get_flags (rpc), ==, MONGOC_OP_UPDATE_FLAG_UPSERT); + ASSERT_CMPINT32 (mcd_rpc_op_update_get_flags (rpc), ==, MONGOC_OP_UPDATE_FLAG_UPSERT); mcd_rpc_message_destroy (rpc); data[28] = MONGOC_OP_UPDATE_FLAG_NONE; @@ -886,23 +818,18 @@ test_rpc_message_from_data_op_insert_valid (void) { const void *data_end = NULL; - mcd_rpc_message *const rpc = - mcd_rpc_message_from_data (data, data_len, &data_end); + mcd_rpc_message *const rpc = mcd_rpc_message_from_data (data, data_len, &data_end); ASSERT_RPC_MESSAGE_RESULT (rpc, data, data_end, data_len); ASSERT (bson_in_range_unsigned (int32_t, data_len)); - ASSERT_CMPINT32 ( - mcd_rpc_header_get_message_length (rpc), ==, (int32_t) data_len); + ASSERT_CMPINT32 (mcd_rpc_header_get_message_length (rpc), ==, (int32_t) data_len); ASSERT_CMPINT32 (mcd_rpc_header_get_request_id (rpc), ==, 16909060); ASSERT_CMPINT32 (mcd_rpc_header_get_response_to (rpc), ==, 84281096); - ASSERT_CMPINT32 ( - mcd_rpc_header_get_op_code (rpc), ==, MONGOC_OP_CODE_INSERT); + ASSERT_CMPINT32 (mcd_rpc_header_get_op_code (rpc), ==, MONGOC_OP_CODE_INSERT); - ASSERT_CMPINT32 ( - mcd_rpc_op_insert_get_flags (rpc), ==, MONGOC_OP_INSERT_FLAG_NONE); + ASSERT_CMPINT32 (mcd_rpc_op_insert_get_flags (rpc), ==, MONGOC_OP_INSERT_FLAG_NONE); - ASSERT_CMPSTR (mcd_rpc_op_insert_get_full_collection_name (rpc), - "db.coll"); + ASSERT_CMPSTR (mcd_rpc_op_insert_get_full_collection_name (rpc), "db.coll"); const uint8_t *const documents = mcd_rpc_op_insert_get_documents (rpc); ASSERT (documents); @@ -939,12 +866,9 @@ test_rpc_message_from_data_op_insert_valid (void) { data[16] = MONGOC_OP_INSERT_FLAG_CONTINUE_ON_ERROR; - mcd_rpc_message *const rpc = - mcd_rpc_message_from_data (data, data_len, NULL); + mcd_rpc_message *const rpc = mcd_rpc_message_from_data (data, data_len, NULL); ASSERT (rpc); - ASSERT_CMPINT32 (mcd_rpc_op_insert_get_flags (rpc), - ==, - MONGOC_OP_INSERT_FLAG_CONTINUE_ON_ERROR); + ASSERT_CMPINT32 (mcd_rpc_op_insert_get_flags (rpc), ==, MONGOC_OP_INSERT_FLAG_CONTINUE_ON_ERROR); mcd_rpc_message_destroy (rpc); data[16] = MONGOC_OP_INSERT_FLAG_NONE; @@ -955,8 +879,7 @@ test_rpc_message_from_data_op_insert_valid (void) data[0] = (uint8_t) (data[0] - 16u); // Exclude document 1. { - mcd_rpc_message *const rpc = - mcd_rpc_message_from_data (data, data_len, NULL); + mcd_rpc_message *const rpc = mcd_rpc_message_from_data (data, data_len, NULL); ASSERT (rpc); ASSERT_CMPSIZE_T (mcd_rpc_op_insert_get_documents_len (rpc), ==, 16u); mcd_rpc_message_destroy (rpc); @@ -974,23 +897,18 @@ test_rpc_message_from_data_op_query_valid (void) { const void *data_end = NULL; - mcd_rpc_message *const rpc = - mcd_rpc_message_from_data (data, data_len, &data_end); + mcd_rpc_message *const rpc = mcd_rpc_message_from_data (data, data_len, &data_end); ASSERT_RPC_MESSAGE_RESULT (rpc, data, data_end, data_len); ASSERT (bson_in_range_unsigned (int32_t, data_len)); - ASSERT_CMPINT32 ( - mcd_rpc_header_get_message_length (rpc), ==, (int32_t) data_len); + ASSERT_CMPINT32 (mcd_rpc_header_get_message_length (rpc), ==, (int32_t) data_len); ASSERT_CMPINT32 (mcd_rpc_header_get_request_id (rpc), ==, 16909060); ASSERT_CMPINT32 (mcd_rpc_header_get_response_to (rpc), ==, 84281096); - ASSERT_CMPINT32 ( - mcd_rpc_header_get_op_code (rpc), ==, MONGOC_OP_CODE_QUERY); + ASSERT_CMPINT32 (mcd_rpc_header_get_op_code (rpc), ==, MONGOC_OP_CODE_QUERY); - ASSERT_CMPINT32 ( - mcd_rpc_op_query_get_flags (rpc), ==, MONGOC_OP_QUERY_FLAG_NONE); + ASSERT_CMPINT32 (mcd_rpc_op_query_get_flags (rpc), ==, MONGOC_OP_QUERY_FLAG_NONE); - ASSERT_CMPSTR (mcd_rpc_op_query_get_full_collection_name (rpc), - "db.coll"); + ASSERT_CMPSTR (mcd_rpc_op_query_get_full_collection_name (rpc), "db.coll"); ASSERT_CMPINT32 (mcd_rpc_op_query_get_number_to_skip (rpc), ==, 0); @@ -1010,8 +928,7 @@ test_rpc_message_from_data_op_query_valid (void) } { - const uint8_t *const selector = - mcd_rpc_op_query_get_return_fields_selector (rpc); + const uint8_t *const selector = mcd_rpc_op_query_get_return_fields_selector (rpc); ASSERT_CMPSIZE_T ((size_t) (selector - data), ==, 49u); const int32_t selector_len = _int32_from_le (selector); @@ -1030,12 +947,9 @@ test_rpc_message_from_data_op_query_valid (void) { data[16] = MONGOC_OP_QUERY_FLAG_TAILABLE_CURSOR; - mcd_rpc_message *const rpc = - mcd_rpc_message_from_data (data, data_len, NULL); + mcd_rpc_message *const rpc = mcd_rpc_message_from_data (data, data_len, NULL); ASSERT (rpc); - ASSERT_CMPINT32 (mcd_rpc_op_query_get_flags (rpc), - ==, - MONGOC_OP_QUERY_FLAG_TAILABLE_CURSOR); + ASSERT_CMPINT32 (mcd_rpc_op_query_get_flags (rpc), ==, MONGOC_OP_QUERY_FLAG_TAILABLE_CURSOR); mcd_rpc_message_destroy (rpc); data[16] = MONGOC_OP_QUERY_FLAG_NONE; @@ -1045,8 +959,7 @@ test_rpc_message_from_data_op_query_valid (void) { data[28] = 1; // Set numberToSkip to 1. - mcd_rpc_message *const rpc = - mcd_rpc_message_from_data (data, data_len, NULL); + mcd_rpc_message *const rpc = mcd_rpc_message_from_data (data, data_len, NULL); ASSERT (rpc); ASSERT_CMPINT32 (mcd_rpc_op_query_get_number_to_skip (rpc), ==, 1); mcd_rpc_message_destroy (rpc); @@ -1058,8 +971,7 @@ test_rpc_message_from_data_op_query_valid (void) { data[32] = 1; // Set numberToReturn to 1. - mcd_rpc_message *const rpc = - mcd_rpc_message_from_data (data, data_len, NULL); + mcd_rpc_message *const rpc = mcd_rpc_message_from_data (data, data_len, NULL); ASSERT (rpc); ASSERT_CMPINT32 (mcd_rpc_op_query_get_number_to_return (rpc), ==, 1); mcd_rpc_message_destroy (rpc); @@ -1071,8 +983,7 @@ test_rpc_message_from_data_op_query_valid (void) { data[0] = (uint8_t) (data[0] - 16u); // Omit returnFieldSelector. - mcd_rpc_message *const rpc = - mcd_rpc_message_from_data (data, data_len, NULL); + mcd_rpc_message *const rpc = mcd_rpc_message_from_data (data, data_len, NULL); ASSERT (rpc); ASSERT (!mcd_rpc_op_query_get_return_fields_selector (rpc)); mcd_rpc_message_destroy (rpc); @@ -1090,25 +1001,20 @@ test_rpc_message_from_data_op_get_more_valid (void) // Valid test input data. { const void *data_end = NULL; - mcd_rpc_message *const rpc = - mcd_rpc_message_from_data (data, data_len, &data_end); + mcd_rpc_message *const rpc = mcd_rpc_message_from_data (data, data_len, &data_end); ASSERT_RPC_MESSAGE_RESULT (rpc, data, data_end, data_len); ASSERT (bson_in_range_unsigned (int32_t, data_len)); - ASSERT_CMPINT32 ( - mcd_rpc_header_get_message_length (rpc), ==, (int32_t) data_len); + ASSERT_CMPINT32 (mcd_rpc_header_get_message_length (rpc), ==, (int32_t) data_len); ASSERT_CMPINT32 (mcd_rpc_header_get_request_id (rpc), ==, 16909060); ASSERT_CMPINT32 (mcd_rpc_header_get_response_to (rpc), ==, 84281096); - ASSERT_CMPINT32 ( - mcd_rpc_header_get_op_code (rpc), ==, MONGOC_OP_CODE_GET_MORE); + ASSERT_CMPINT32 (mcd_rpc_header_get_op_code (rpc), ==, MONGOC_OP_CODE_GET_MORE); - ASSERT_CMPSTR (mcd_rpc_op_get_more_get_full_collection_name (rpc), - "db.coll"); + ASSERT_CMPSTR (mcd_rpc_op_get_more_get_full_collection_name (rpc), "db.coll"); ASSERT_CMPINT32 (mcd_rpc_op_get_more_get_number_to_return (rpc), ==, 0); - ASSERT_CMPINT64 ( - mcd_rpc_op_get_more_get_cursor_id (rpc), ==, 1234605616436508552); + ASSERT_CMPINT64 (mcd_rpc_op_get_more_get_cursor_id (rpc), ==, 1234605616436508552); mcd_rpc_message_destroy (rpc); } @@ -1123,23 +1029,18 @@ test_rpc_message_from_data_op_delete_valid (void) // Valid test input data. { const void *data_end = NULL; - mcd_rpc_message *const rpc = - mcd_rpc_message_from_data (data, data_len, &data_end); + mcd_rpc_message *const rpc = mcd_rpc_message_from_data (data, data_len, &data_end); ASSERT_RPC_MESSAGE_RESULT (rpc, data, data_end, data_len); ASSERT (bson_in_range_unsigned (int32_t, data_len)); - ASSERT_CMPINT32 ( - mcd_rpc_header_get_message_length (rpc), ==, (int32_t) data_len); + ASSERT_CMPINT32 (mcd_rpc_header_get_message_length (rpc), ==, (int32_t) data_len); ASSERT_CMPINT32 (mcd_rpc_header_get_request_id (rpc), ==, 16909060); ASSERT_CMPINT32 (mcd_rpc_header_get_response_to (rpc), ==, 84281096); - ASSERT_CMPINT32 ( - mcd_rpc_header_get_op_code (rpc), ==, MONGOC_OP_CODE_DELETE); + ASSERT_CMPINT32 (mcd_rpc_header_get_op_code (rpc), ==, MONGOC_OP_CODE_DELETE); - ASSERT_CMPSTR (mcd_rpc_op_delete_get_full_collection_name (rpc), - "db.coll"); + ASSERT_CMPSTR (mcd_rpc_op_delete_get_full_collection_name (rpc), "db.coll"); - ASSERT_CMPINT32 ( - mcd_rpc_op_delete_get_flags (rpc), ==, MONGOC_OP_DELETE_FLAG_NONE); + ASSERT_CMPINT32 (mcd_rpc_op_delete_get_flags (rpc), ==, MONGOC_OP_DELETE_FLAG_NONE); { const uint8_t *const selector = mcd_rpc_op_delete_get_selector (rpc); @@ -1167,23 +1068,18 @@ test_rpc_message_from_data_op_kill_cursors_valid (void) // Valid test input data. { const void *data_end = NULL; - mcd_rpc_message *const rpc = - mcd_rpc_message_from_data (data, data_len, &data_end); + mcd_rpc_message *const rpc = mcd_rpc_message_from_data (data, data_len, &data_end); ASSERT_RPC_MESSAGE_RESULT (rpc, data, data_end, data_len); ASSERT (bson_in_range_unsigned (int32_t, data_len)); - ASSERT_CMPINT32 ( - mcd_rpc_header_get_message_length (rpc), ==, (int32_t) data_len); + ASSERT_CMPINT32 (mcd_rpc_header_get_message_length (rpc), ==, (int32_t) data_len); ASSERT_CMPINT32 (mcd_rpc_header_get_request_id (rpc), ==, 16909060); ASSERT_CMPINT32 (mcd_rpc_header_get_response_to (rpc), ==, 84281096); - ASSERT_CMPINT32 ( - mcd_rpc_header_get_op_code (rpc), ==, MONGOC_OP_CODE_KILL_CURSORS); + ASSERT_CMPINT32 (mcd_rpc_header_get_op_code (rpc), ==, MONGOC_OP_CODE_KILL_CURSORS); - ASSERT_CMPINT32 ( - mcd_rpc_op_kill_cursors_get_number_of_cursor_ids (rpc), ==, 2); + ASSERT_CMPINT32 (mcd_rpc_op_kill_cursors_get_number_of_cursor_ids (rpc), ==, 2); - const int64_t *const cursor_ids = - mcd_rpc_op_kill_cursors_get_cursor_ids (rpc); + const int64_t *const cursor_ids = mcd_rpc_op_kill_cursors_get_cursor_ids (rpc); ASSERT_CMPINT64 (cursor_ids[0], ==, 1230066625199609624); ASSERT_CMPINT64 (cursor_ids[1], ==, 2387509390608836392); @@ -1196,14 +1092,10 @@ test_rpc_message_from_data_op_kill_cursors_valid (void) data[0] = (uint8_t) (data[0] - 8u); // Truncate cursorID 1. data[20] = (uint8_t) (data[20] - 1u); // Set numberOfCursorIds to 1. - mcd_rpc_message *const rpc = - mcd_rpc_message_from_data (data, data_len, NULL); + mcd_rpc_message *const rpc = mcd_rpc_message_from_data (data, data_len, NULL); ASSERT (rpc); - ASSERT_CMPINT32 ( - mcd_rpc_op_kill_cursors_get_number_of_cursor_ids (rpc), ==, 1); - ASSERT_CMPINT64 (mcd_rpc_op_kill_cursors_get_cursor_ids (rpc)[0], - ==, - 1230066625199609624); + ASSERT_CMPINT32 (mcd_rpc_op_kill_cursors_get_number_of_cursor_ids (rpc), ==, 1); + ASSERT_CMPINT64 (mcd_rpc_op_kill_cursors_get_cursor_ids (rpc)[0], ==, 1230066625199609624); mcd_rpc_message_destroy (rpc); data[20] = (uint8_t) (data[20] + 1u); // Restore numberOfCursorIds. @@ -1215,11 +1107,9 @@ test_rpc_message_from_data_op_kill_cursors_valid (void) data[0] = (uint8_t) (data[0] - 16u); // Exclude cursorIDs. data[20] = (uint8_t) (data[20] - 2u); // Set numberOfCursorIds to 0. - mcd_rpc_message *const rpc = - mcd_rpc_message_from_data (data, data_len, NULL); + mcd_rpc_message *const rpc = mcd_rpc_message_from_data (data, data_len, NULL); ASSERT (rpc); - ASSERT_CMPINT32 ( - mcd_rpc_op_kill_cursors_get_number_of_cursor_ids (rpc), ==, 0); + ASSERT_CMPINT32 (mcd_rpc_op_kill_cursors_get_number_of_cursor_ids (rpc), ==, 0); ASSERT (mcd_rpc_op_kill_cursors_get_cursor_ids (rpc) == NULL); mcd_rpc_message_destroy (rpc); @@ -1239,46 +1129,23 @@ _test_from_data_invalid_decr (const char *file, size_t max, size_t bytes_parsed_expected) { - ASSERT_WITH_MSG ( - min <= max, - "%s:%d: min (%zu) should be less than or equal to max (%zu)", - file, - line, - min, - max); - ASSERT_WITH_MSG (max < data_len, - "%s:%d: max byte %zu exceeds input data length %zu", - file, - line, - max, - data_len); + ASSERT_WITH_MSG (min <= max, "%s:%d: min (%zu) should be less than or equal to max (%zu)", file, line, min, max); + ASSERT_WITH_MSG (max < data_len, "%s:%d: max byte %zu exceeds input data length %zu", file, line, max, data_len); for (size_t i = min; i <= max; ++i) { data[i] = (uint8_t) (data[i] - 1u); // Set to original value - 1. { const void *data_end = NULL; - mcd_rpc_message *rpc = - mcd_rpc_message_from_data (data, data_len, &data_end); + mcd_rpc_message *rpc = mcd_rpc_message_from_data (data, data_len, &data_end); if (expect_success) { - ASSERT_WITH_MSG ( - rpc, - "%s:%d: byte %zu: expected decrement to still succeed", - file, - line, - i); + ASSERT_WITH_MSG (rpc, "%s:%d: byte %zu: expected decrement to still succeed", file, line, i); } else { - ASSERT_WITH_MSG ( - !rpc, - "%s:%d: byte %zu: expected decrement to trigger failure", - file, - line, - i); + ASSERT_WITH_MSG (!rpc, "%s:%d: byte %zu: expected decrement to trigger failure", file, line, i); } - const size_t bytes_parsed_actual = - (size_t) ((const uint8_t *) data_end - data); + const size_t bytes_parsed_actual = (size_t) ((const uint8_t *) data_end - data); ASSERT_WITH_MSG (bytes_parsed_expected == bytes_parsed_actual, "%s:%d: byte %zu: expected decrement to cause " @@ -1306,39 +1173,22 @@ _test_from_data_invalid_incr (const char *file, size_t max, size_t bytes_parsed_expected) { - ASSERT_WITH_MSG (max < data_len, - "%s:%d: max byte %zu exceeds input data length %zu", - file, - line, - max, - data_len); + ASSERT_WITH_MSG (max < data_len, "%s:%d: max byte %zu exceeds input data length %zu", file, line, max, data_len); for (size_t i = min; i <= max; ++i) { data[i] = (uint8_t) (data[i] + 1u); // Set to original value + 1. { const void *data_end = NULL; - mcd_rpc_message *rpc = - mcd_rpc_message_from_data (data, data_len, &data_end); + mcd_rpc_message *rpc = mcd_rpc_message_from_data (data, data_len, &data_end); if (expect_success) { - ASSERT_WITH_MSG ( - rpc, - "%s:%d: byte %zu: expected increment to still succeed", - file, - line, - i); + ASSERT_WITH_MSG (rpc, "%s:%d: byte %zu: expected increment to still succeed", file, line, i); } else { - ASSERT_WITH_MSG ( - !rpc, - "%s:%d: byte %zu: expected increment to trigger failure", - file, - line, - i); + ASSERT_WITH_MSG (!rpc, "%s:%d: byte %zu: expected increment to trigger failure", file, line, i); } - const size_t bytes_parsed_actual = - (size_t) ((const uint8_t *) data_end - data); + const size_t bytes_parsed_actual = (size_t) ((const uint8_t *) data_end - data); ASSERT_WITH_MSG (bytes_parsed_expected == bytes_parsed_actual, "%s:%d: byte %zu: expected increment to cause " @@ -1377,10 +1227,8 @@ _test_from_data_input_bounds (const uint8_t *data, size_t data_len) // It is NOT an error for data length to be greater than messageLength. { const void *data_end = NULL; - mcd_rpc_message *rpc = - mcd_rpc_message_from_data (data, data_len + 1u, &data_end); - ASSERT_CMPSIZE_T ( - (size_t) ((const uint8_t *) data_end - data), ==, data_len); + mcd_rpc_message *rpc = mcd_rpc_message_from_data (data, data_len + 1u, &data_end); + ASSERT_CMPSIZE_T ((size_t) ((const uint8_t *) data_end - data), ==, data_len); ASSERT_WITH_MSG (rpc, "expected extra bytes to remain unparsed"); ASSERT_CMPUINT (*(const uint8_t *) data_end, ==, 0xFF); mcd_rpc_message_destroy (rpc); @@ -1389,17 +1237,13 @@ _test_from_data_input_bounds (const uint8_t *data, size_t data_len) #define EXPECT_DECR_FAILURE(min, max, end) \ - _test_from_data_invalid_decr ( \ - __FILE__, __LINE__, data, data_len, false, min, max, end) + _test_from_data_invalid_decr (__FILE__, __LINE__, data, data_len, false, min, max, end) #define EXPECT_DECR_SUCCESS(min, max, end) \ - _test_from_data_invalid_decr ( \ - __FILE__, __LINE__, data, data_len, true, min, max, end) + _test_from_data_invalid_decr (__FILE__, __LINE__, data, data_len, true, min, max, end) #define EXPECT_INCR_FAILURE(min, max, end) \ - _test_from_data_invalid_incr ( \ - __FILE__, __LINE__, data, data_len, false, min, max, end) + _test_from_data_invalid_incr (__FILE__, __LINE__, data, data_len, false, min, max, end) #define EXPECT_INCR_SUCCESS(min, max, end) \ - _test_from_data_invalid_incr ( \ - __FILE__, __LINE__, data, data_len, true, min, max, end) + _test_from_data_invalid_incr (__FILE__, __LINE__, data, data_len, true, min, max, end) #define EXPECT_DECR_IGNORED(min, max, end) #define EXPECT_INCR_IGNORED(min, max, end) @@ -1731,17 +1575,15 @@ test_rpc_message_from_data_op_insert_invalid (void) data[0] = (uint8_t) (data[0] - 32u); // Exclude both documents. const void *data_end = NULL; - mcd_rpc_message *const rpc = - mcd_rpc_message_from_data (data, data_len, &data_end); + mcd_rpc_message *const rpc = mcd_rpc_message_from_data (data, data_len, &data_end); const size_t parsed_len = (size_t) ((const uint8_t *) data_end - data); const size_t expected_len = 28u; ASSERT_WITH_MSG (!rpc, "OP_INSERT requires at least one document"); - ASSERT_WITH_MSG ( - parsed_len == expected_len, - "expected %zu bytes to be parsed before error, but parsed %zu bytes", - expected_len, - parsed_len); + ASSERT_WITH_MSG (parsed_len == expected_len, + "expected %zu bytes to be parsed before error, but parsed %zu bytes", + expected_len, + parsed_len); mcd_rpc_message_destroy (rpc); @@ -1796,17 +1638,15 @@ test_rpc_message_from_data_op_query_invalid (void) // returnFieldsSelector documents. const void *data_end = NULL; - mcd_rpc_message *const rpc = - mcd_rpc_message_from_data (data, data_len, &data_end); + mcd_rpc_message *const rpc = mcd_rpc_message_from_data (data, data_len, &data_end); const size_t parsed_len = (size_t) ((const uint8_t *) data_end - data); const size_t expected_len = 36u; ASSERT_WITH_MSG (!rpc, "OP_QUERY requires a query document"); - ASSERT_WITH_MSG ( - parsed_len == expected_len, - "expected %zu bytes to be parsed before error, but parsed %zu bytes", - expected_len, - parsed_len); + ASSERT_WITH_MSG (parsed_len == expected_len, + "expected %zu bytes to be parsed before error, but parsed %zu bytes", + expected_len, + parsed_len); mcd_rpc_message_destroy (rpc); @@ -1916,56 +1756,47 @@ test_rpc_message_from_data_op_kill_cursors_invalid (void) } -#define ASSERT_IOVEC_VALUE(index, expected, type, raw_type, from_le, spec) \ - if (1) { \ - const type _expected = expected; \ - const mongoc_iovec_t iovec = iovecs[index]; \ - const size_t len = sizeof (type); \ - ASSERT_WITH_MSG (iovec.iov_len == sizeof (type), \ - "expected iov_len to be %zu, but got %zu", \ - len, \ - iovec.iov_len); \ - raw_type storage; \ - memcpy (&storage, iovec.iov_base, sizeof (type)); \ - storage = from_le (storage); \ - type value; \ - memcpy (&value, &storage, sizeof (type)); \ - ASSERT_WITH_MSG (value == _expected, \ - "expected iov_base to point to %s with value %" spec \ - ", but got %" spec, \ - #type, \ - _expected, \ - value); \ - } else \ +#define ASSERT_IOVEC_VALUE(index, expected, type, raw_type, from_le, spec) \ + if (1) { \ + const type _expected = expected; \ + const mongoc_iovec_t iovec = iovecs[index]; \ + const size_t len = sizeof (type); \ + ASSERT_WITH_MSG (iovec.iov_len == sizeof (type), "expected iov_len to be %zu, but got %zu", len, iovec.iov_len); \ + raw_type storage; \ + memcpy (&storage, iovec.iov_base, sizeof (type)); \ + storage = from_le (storage); \ + type value; \ + memcpy (&value, &storage, sizeof (type)); \ + ASSERT_WITH_MSG (value == _expected, \ + "expected iov_base to point to %s with value %" spec ", but got %" spec, \ + #type, \ + _expected, \ + value); \ + } else \ (void) 0 -#define ASSERT_IOVEC_UINT8(index, expected) \ - ASSERT_IOVEC_VALUE (index, expected, uint8_t, uint8_t, (uint8_t), PRIu8) +#define ASSERT_IOVEC_UINT8(index, expected) ASSERT_IOVEC_VALUE (index, expected, uint8_t, uint8_t, (uint8_t), PRIu8) #define ASSERT_IOVEC_INT32(index, expected) \ - ASSERT_IOVEC_VALUE ( \ - index, expected, int32_t, uint32_t, BSON_UINT32_FROM_LE, PRId32) + ASSERT_IOVEC_VALUE (index, expected, int32_t, uint32_t, BSON_UINT32_FROM_LE, PRId32) #define ASSERT_IOVEC_UINT32(index, expected) \ - ASSERT_IOVEC_VALUE ( \ - index, expected, uint32_t, uint32_t, BSON_UINT32_FROM_LE, PRIu32) + ASSERT_IOVEC_VALUE (index, expected, uint32_t, uint32_t, BSON_UINT32_FROM_LE, PRIu32) #define ASSERT_IOVEC_INT64(index, expected) \ - ASSERT_IOVEC_VALUE ( \ - index, expected, int64_t, uint64_t, BSON_UINT64_FROM_LE, PRId64) - -#define ASSERT_IOVEC_BYTES(index, expected_base_index, expected_len) \ - if (1) { \ - const mongoc_iovec_t iovec = iovecs[index]; \ - ASSERT_WITH_MSG (iovec.iov_len == expected_len, \ - "expected iov_len to be %zu, but got %zu", \ - (size_t) expected_len, \ - iovec.iov_len); \ - ASSERT_WITH_MSG ( \ - (const uint8_t *) iovec.iov_base == (data + expected_base_index), \ - "expected iov_base to point to byte %zu (%p), but got byte %zu (%p)", \ - (size_t) (expected_base_index), \ - (void *) (data + expected_base_index), \ - (size_t) ((const uint8_t *) iovec.iov_base - data), \ - iovec.iov_base); \ - } else \ + ASSERT_IOVEC_VALUE (index, expected, int64_t, uint64_t, BSON_UINT64_FROM_LE, PRId64) + +#define ASSERT_IOVEC_BYTES(index, expected_base_index, expected_len) \ + if (1) { \ + const mongoc_iovec_t iovec = iovecs[index]; \ + ASSERT_WITH_MSG (iovec.iov_len == expected_len, \ + "expected iov_len to be %zu, but got %zu", \ + (size_t) expected_len, \ + iovec.iov_len); \ + ASSERT_WITH_MSG ((const uint8_t *) iovec.iov_base == (data + expected_base_index), \ + "expected iov_base to point to byte %zu (%p), but got byte %zu (%p)", \ + (size_t) (expected_base_index), \ + (void *) (data + expected_base_index), \ + (size_t) ((const uint8_t *) iovec.iov_base - data), \ + iovec.iov_base); \ + } else \ (void) 0 @@ -1974,8 +1805,7 @@ test_rpc_message_to_iovecs_op_compressed (void) { const uint8_t data[] = {TEST_DATA_OP_COMPRESSED}; - mcd_rpc_message *const rpc = - mcd_rpc_message_from_data (data, sizeof (data), NULL); + mcd_rpc_message *const rpc = mcd_rpc_message_from_data (data, sizeof (data), NULL); size_t num_iovecs; mongoc_iovec_t *const iovecs = mcd_rpc_message_to_iovecs (rpc, &num_iovecs); @@ -2000,8 +1830,7 @@ test_rpc_message_to_iovecs_op_msg_kind_0 (void) { const uint8_t data[] = {TEST_DATA_OP_MSG_KIND_0}; - mcd_rpc_message *const rpc = - mcd_rpc_message_from_data (data, sizeof (data), NULL); + mcd_rpc_message *const rpc = mcd_rpc_message_from_data (data, sizeof (data), NULL); size_t num_iovecs; mongoc_iovec_t *const iovecs = mcd_rpc_message_to_iovecs (rpc, &num_iovecs); @@ -2026,8 +1855,7 @@ test_rpc_message_to_iovecs_op_msg_kind_1_single (void) { const uint8_t data[] = {TEST_DATA_OP_MSG_KIND_1_SINGLE}; - mcd_rpc_message *const rpc = - mcd_rpc_message_from_data (data, sizeof (data), NULL); + mcd_rpc_message *const rpc = mcd_rpc_message_from_data (data, sizeof (data), NULL); size_t num_iovecs; mongoc_iovec_t *const iovecs = mcd_rpc_message_to_iovecs (rpc, &num_iovecs); @@ -2056,8 +1884,7 @@ test_rpc_message_to_iovecs_op_msg_kind_1_multiple (void) { const uint8_t data[] = {TEST_DATA_OP_MSG_KIND_1_MULTIPLE}; - mcd_rpc_message *const rpc = - mcd_rpc_message_from_data (data, sizeof (data), NULL); + mcd_rpc_message *const rpc = mcd_rpc_message_from_data (data, sizeof (data), NULL); size_t num_iovecs; mongoc_iovec_t *const iovecs = mcd_rpc_message_to_iovecs (rpc, &num_iovecs); @@ -2098,8 +1925,7 @@ test_rpc_message_to_iovecs_op_reply (void) { const uint8_t data[] = {TEST_DATA_OP_REPLY}; - mcd_rpc_message *const rpc = - mcd_rpc_message_from_data (data, sizeof (data), NULL); + mcd_rpc_message *const rpc = mcd_rpc_message_from_data (data, sizeof (data), NULL); size_t num_iovecs; mongoc_iovec_t *const iovecs = mcd_rpc_message_to_iovecs (rpc, &num_iovecs); @@ -2125,8 +1951,7 @@ test_rpc_message_to_iovecs_op_update (void) { const uint8_t data[] = {TEST_DATA_OP_UPDATE}; - mcd_rpc_message *const rpc = - mcd_rpc_message_from_data (data, sizeof (data), NULL); + mcd_rpc_message *const rpc = mcd_rpc_message_from_data (data, sizeof (data), NULL); size_t num_iovecs; mongoc_iovec_t *const iovecs = mcd_rpc_message_to_iovecs (rpc, &num_iovecs); @@ -2152,8 +1977,7 @@ test_rpc_message_to_iovecs_op_insert (void) { const uint8_t data[] = {TEST_DATA_OP_INSERT}; - mcd_rpc_message *const rpc = - mcd_rpc_message_from_data (data, sizeof (data), NULL); + mcd_rpc_message *const rpc = mcd_rpc_message_from_data (data, sizeof (data), NULL); size_t num_iovecs; mongoc_iovec_t *const iovecs = mcd_rpc_message_to_iovecs (rpc, &num_iovecs); @@ -2177,8 +2001,7 @@ test_rpc_message_to_iovecs_op_query (void) { const uint8_t data[] = {TEST_DATA_OP_QUERY}; - mcd_rpc_message *const rpc = - mcd_rpc_message_from_data (data, sizeof (data), NULL); + mcd_rpc_message *const rpc = mcd_rpc_message_from_data (data, sizeof (data), NULL); size_t num_iovecs; mongoc_iovec_t *const iovecs = mcd_rpc_message_to_iovecs (rpc, &num_iovecs); @@ -2205,8 +2028,7 @@ test_rpc_message_to_iovecs_op_get_more (void) { const uint8_t data[] = {TEST_DATA_OP_GET_MORE}; - mcd_rpc_message *const rpc = - mcd_rpc_message_from_data (data, sizeof (data), NULL); + mcd_rpc_message *const rpc = mcd_rpc_message_from_data (data, sizeof (data), NULL); size_t num_iovecs; mongoc_iovec_t *const iovecs = mcd_rpc_message_to_iovecs (rpc, &num_iovecs); @@ -2231,8 +2053,7 @@ test_rpc_message_to_iovecs_op_delete (void) { const uint8_t data[] = {TEST_DATA_OP_DELETE}; - mcd_rpc_message *const rpc = - mcd_rpc_message_from_data (data, sizeof (data), NULL); + mcd_rpc_message *const rpc = mcd_rpc_message_from_data (data, sizeof (data), NULL); size_t num_iovecs; mongoc_iovec_t *const iovecs = mcd_rpc_message_to_iovecs (rpc, &num_iovecs); @@ -2257,8 +2078,7 @@ test_rpc_message_to_iovecs_op_kill_cursors (void) { const uint8_t data[] = {TEST_DATA_OP_KILL_CURSORS}; - mcd_rpc_message *const rpc = - mcd_rpc_message_from_data (data, sizeof (data), NULL); + mcd_rpc_message *const rpc = mcd_rpc_message_from_data (data, sizeof (data), NULL); size_t num_iovecs; mongoc_iovec_t *const iovecs = mcd_rpc_message_to_iovecs (rpc, &num_iovecs); @@ -2293,61 +2113,52 @@ test_rpc_message_to_iovecs_op_kill_cursors (void) } -#define ASSERT_CMPIOVEC_VALUE(index, type, raw_type, from_le, spec) \ - if (1) { \ - const mongoc_iovec_t _actual = iovecs[index]; \ - const mongoc_iovec_t _expected = expected_iovecs[index]; \ - ASSERT_WITH_MSG ( \ - _expected.iov_len == sizeof (type), \ - "expected iov_len does not match expected type length"); \ - ASSERT_WITH_MSG (_actual.iov_len == _expected.iov_len, \ - "expected iov_len to be %zu, but got %zu", \ - _expected.iov_len, \ - _actual.iov_len); \ - raw_type storage; \ - type actual_value; \ - type expected_value; \ - memcpy (&storage, _actual.iov_base, sizeof (type)); \ - storage = from_le (storage); \ - memcpy (&actual_value, &storage, sizeof (type)); \ - memcpy (&storage, _expected.iov_base, sizeof (type)); \ - storage = from_le (storage); \ - memcpy (&expected_value, &storage, sizeof (type)); \ - ASSERT_WITH_MSG (actual_value == expected_value, \ - "expected iov_base to point to %s with value %" spec \ - ", but got %" spec, \ - #type, \ - expected_value, \ - actual_value); \ - } else \ +#define ASSERT_CMPIOVEC_VALUE(index, type, raw_type, from_le, spec) \ + if (1) { \ + const mongoc_iovec_t _actual = iovecs[index]; \ + const mongoc_iovec_t _expected = expected_iovecs[index]; \ + ASSERT_WITH_MSG (_expected.iov_len == sizeof (type), "expected iov_len does not match expected type length"); \ + ASSERT_WITH_MSG (_actual.iov_len == _expected.iov_len, \ + "expected iov_len to be %zu, but got %zu", \ + _expected.iov_len, \ + _actual.iov_len); \ + raw_type storage; \ + type actual_value; \ + type expected_value; \ + memcpy (&storage, _actual.iov_base, sizeof (type)); \ + storage = from_le (storage); \ + memcpy (&actual_value, &storage, sizeof (type)); \ + memcpy (&storage, _expected.iov_base, sizeof (type)); \ + storage = from_le (storage); \ + memcpy (&expected_value, &storage, sizeof (type)); \ + ASSERT_WITH_MSG (actual_value == expected_value, \ + "expected iov_base to point to %s with value %" spec ", but got %" spec, \ + #type, \ + expected_value, \ + actual_value); \ + } else \ (void) 0 -#define ASSERT_CMPIOVEC_UINT8(index) \ - ASSERT_CMPIOVEC_VALUE (index, uint8_t, uint8_t, (uint8_t), PRIu8) -#define ASSERT_CMPIOVEC_INT32(index) \ - ASSERT_CMPIOVEC_VALUE (index, int32_t, uint32_t, BSON_UINT32_FROM_LE, PRId32) -#define ASSERT_CMPIOVEC_UINT32(index) \ - ASSERT_CMPIOVEC_VALUE ( \ - index, uint32_t, uint32_t, BSON_UINT32_FROM_LE, PRIu32) -#define ASSERT_CMPIOVEC_INT64(index) \ - ASSERT_CMPIOVEC_VALUE (index, int64_t, uint64_t, BSON_UINT64_FROM_LE, PRId64) - -#define ASSERT_CMPIOVEC_BYTES(index) \ - if (1) { \ - const mongoc_iovec_t _actual = iovecs[index]; \ - const mongoc_iovec_t _expected = expected_iovecs[index]; \ - ASSERT_WITH_MSG (_actual.iov_len == _expected.iov_len, \ - "expected iov_len to be %zu, but got %zu", \ - _expected.iov_len, \ - _actual.iov_len); \ - ASSERT_WITH_MSG ( \ - _actual.iov_base == _expected.iov_base, \ - "expected iov_base to point to byte %zu (%p), but got byte %zu (%p)", \ - (size_t) ((const uint8_t *) _expected.iov_base - data), \ - _expected.iov_base, \ - (size_t) ((const uint8_t *) _actual.iov_base - data), \ - _actual.iov_base); \ - } else \ +#define ASSERT_CMPIOVEC_UINT8(index) ASSERT_CMPIOVEC_VALUE (index, uint8_t, uint8_t, (uint8_t), PRIu8) +#define ASSERT_CMPIOVEC_INT32(index) ASSERT_CMPIOVEC_VALUE (index, int32_t, uint32_t, BSON_UINT32_FROM_LE, PRId32) +#define ASSERT_CMPIOVEC_UINT32(index) ASSERT_CMPIOVEC_VALUE (index, uint32_t, uint32_t, BSON_UINT32_FROM_LE, PRIu32) +#define ASSERT_CMPIOVEC_INT64(index) ASSERT_CMPIOVEC_VALUE (index, int64_t, uint64_t, BSON_UINT64_FROM_LE, PRId64) + +#define ASSERT_CMPIOVEC_BYTES(index) \ + if (1) { \ + const mongoc_iovec_t _actual = iovecs[index]; \ + const mongoc_iovec_t _expected = expected_iovecs[index]; \ + ASSERT_WITH_MSG (_actual.iov_len == _expected.iov_len, \ + "expected iov_len to be %zu, but got %zu", \ + _expected.iov_len, \ + _actual.iov_len); \ + ASSERT_WITH_MSG (_actual.iov_base == _expected.iov_base, \ + "expected iov_base to point to byte %zu (%p), but got byte %zu (%p)", \ + (size_t) ((const uint8_t *) _expected.iov_base - data), \ + _expected.iov_base, \ + (size_t) ((const uint8_t *) _actual.iov_base - data), \ + _actual.iov_base); \ + } else \ (void) 0 @@ -2356,13 +2167,11 @@ test_rpc_message_setters_op_compressed (void) { const uint8_t data[] = {TEST_DATA_OP_COMPRESSED}; - mcd_rpc_message *const expected_rpc = - mcd_rpc_message_from_data (data, sizeof (data), NULL); + mcd_rpc_message *const expected_rpc = mcd_rpc_message_from_data (data, sizeof (data), NULL); ASSERT (expected_rpc); size_t expected_num_iovecs; - mongoc_iovec_t *const expected_iovecs = - mcd_rpc_message_to_iovecs (expected_rpc, &expected_num_iovecs); + mongoc_iovec_t *const expected_iovecs = mcd_rpc_message_to_iovecs (expected_rpc, &expected_num_iovecs); ASSERT (expected_iovecs); mcd_rpc_message *const rpc = mcd_rpc_message_new (); @@ -2405,13 +2214,11 @@ test_rpc_message_setters_op_msg_kind_0 (void) { const uint8_t data[] = {TEST_DATA_OP_MSG_KIND_0}; - mcd_rpc_message *const expected_rpc = - mcd_rpc_message_from_data (data, sizeof (data), NULL); + mcd_rpc_message *const expected_rpc = mcd_rpc_message_from_data (data, sizeof (data), NULL); ASSERT (expected_rpc); size_t expected_num_iovecs; - mongoc_iovec_t *const expected_iovecs = - mcd_rpc_message_to_iovecs (expected_rpc, &expected_num_iovecs); + mongoc_iovec_t *const expected_iovecs = mcd_rpc_message_to_iovecs (expected_rpc, &expected_num_iovecs); ASSERT (expected_iovecs); mcd_rpc_message *const rpc = mcd_rpc_message_new (); @@ -2455,13 +2262,11 @@ test_rpc_message_setters_op_msg_kind_1_single (void) { const uint8_t data[] = {TEST_DATA_OP_MSG_KIND_1_SINGLE}; - mcd_rpc_message *const expected_rpc = - mcd_rpc_message_from_data (data, sizeof (data), NULL); + mcd_rpc_message *const expected_rpc = mcd_rpc_message_from_data (data, sizeof (data), NULL); ASSERT (expected_rpc); size_t expected_num_iovecs; - mongoc_iovec_t *const expected_iovecs = - mcd_rpc_message_to_iovecs (expected_rpc, &expected_num_iovecs); + mongoc_iovec_t *const expected_iovecs = mcd_rpc_message_to_iovecs (expected_rpc, &expected_num_iovecs); ASSERT (expected_iovecs); mcd_rpc_message *const rpc = mcd_rpc_message_new (); @@ -2513,13 +2318,11 @@ test_rpc_message_setters_op_msg_kind_1_multiple (void) { const uint8_t data[] = {TEST_DATA_OP_MSG_KIND_1_MULTIPLE}; - mcd_rpc_message *const expected_rpc = - mcd_rpc_message_from_data (data, sizeof (data), NULL); + mcd_rpc_message *const expected_rpc = mcd_rpc_message_from_data (data, sizeof (data), NULL); ASSERT (expected_rpc); size_t expected_num_iovecs; - mongoc_iovec_t *const expected_iovecs = - mcd_rpc_message_to_iovecs (expected_rpc, &expected_num_iovecs); + mongoc_iovec_t *const expected_iovecs = mcd_rpc_message_to_iovecs (expected_rpc, &expected_num_iovecs); ASSERT (expected_iovecs); mcd_rpc_message *const rpc = mcd_rpc_message_new (); @@ -2587,13 +2390,11 @@ test_rpc_message_setters_op_reply (void) { const uint8_t data[] = {TEST_DATA_OP_REPLY}; - mcd_rpc_message *const expected_rpc = - mcd_rpc_message_from_data (data, sizeof (data), NULL); + mcd_rpc_message *const expected_rpc = mcd_rpc_message_from_data (data, sizeof (data), NULL); ASSERT (expected_rpc); size_t expected_num_iovecs; - mongoc_iovec_t *const expected_iovecs = - mcd_rpc_message_to_iovecs (expected_rpc, &expected_num_iovecs); + mongoc_iovec_t *const expected_iovecs = mcd_rpc_message_to_iovecs (expected_rpc, &expected_num_iovecs); ASSERT (expected_iovecs); mcd_rpc_message *const rpc = mcd_rpc_message_new (); @@ -2638,13 +2439,11 @@ test_rpc_message_setters_op_update (void) { const uint8_t data[] = {TEST_DATA_OP_UPDATE}; - mcd_rpc_message *const expected_rpc = - mcd_rpc_message_from_data (data, sizeof (data), NULL); + mcd_rpc_message *const expected_rpc = mcd_rpc_message_from_data (data, sizeof (data), NULL); ASSERT (expected_rpc); size_t expected_num_iovecs; - mongoc_iovec_t *const expected_iovecs = - mcd_rpc_message_to_iovecs (expected_rpc, &expected_num_iovecs); + mongoc_iovec_t *const expected_iovecs = mcd_rpc_message_to_iovecs (expected_rpc, &expected_num_iovecs); ASSERT (expected_iovecs); mcd_rpc_message *const rpc = mcd_rpc_message_new (); @@ -2688,13 +2487,11 @@ test_rpc_message_setters_op_insert (void) { const uint8_t data[] = {TEST_DATA_OP_INSERT}; - mcd_rpc_message *const expected_rpc = - mcd_rpc_message_from_data (data, sizeof (data), NULL); + mcd_rpc_message *const expected_rpc = mcd_rpc_message_from_data (data, sizeof (data), NULL); ASSERT (expected_rpc); size_t expected_num_iovecs; - mongoc_iovec_t *const expected_iovecs = - mcd_rpc_message_to_iovecs (expected_rpc, &expected_num_iovecs); + mongoc_iovec_t *const expected_iovecs = mcd_rpc_message_to_iovecs (expected_rpc, &expected_num_iovecs); ASSERT (expected_iovecs); mcd_rpc_message *const rpc = mcd_rpc_message_new (); @@ -2735,13 +2532,11 @@ test_rpc_message_setters_op_query (void) { const uint8_t data[] = {TEST_DATA_OP_QUERY}; - mcd_rpc_message *const expected_rpc = - mcd_rpc_message_from_data (data, sizeof (data), NULL); + mcd_rpc_message *const expected_rpc = mcd_rpc_message_from_data (data, sizeof (data), NULL); ASSERT (expected_rpc); size_t expected_num_iovecs; - mongoc_iovec_t *const expected_iovecs = - mcd_rpc_message_to_iovecs (expected_rpc, &expected_num_iovecs); + mongoc_iovec_t *const expected_iovecs = mcd_rpc_message_to_iovecs (expected_rpc, &expected_num_iovecs); ASSERT (expected_iovecs); mcd_rpc_message *const rpc = mcd_rpc_message_new (); @@ -2788,13 +2583,11 @@ test_rpc_message_setters_op_get_more (void) { const uint8_t data[] = {TEST_DATA_OP_GET_MORE}; - mcd_rpc_message *const expected_rpc = - mcd_rpc_message_from_data (data, sizeof (data), NULL); + mcd_rpc_message *const expected_rpc = mcd_rpc_message_from_data (data, sizeof (data), NULL); ASSERT (expected_rpc); size_t expected_num_iovecs; - mongoc_iovec_t *const expected_iovecs = - mcd_rpc_message_to_iovecs (expected_rpc, &expected_num_iovecs); + mongoc_iovec_t *const expected_iovecs = mcd_rpc_message_to_iovecs (expected_rpc, &expected_num_iovecs); ASSERT (expected_iovecs); mcd_rpc_message *const rpc = mcd_rpc_message_new (); @@ -2836,13 +2629,11 @@ test_rpc_message_setters_op_delete (void) { const uint8_t data[] = {TEST_DATA_OP_DELETE}; - mcd_rpc_message *const expected_rpc = - mcd_rpc_message_from_data (data, sizeof (data), NULL); + mcd_rpc_message *const expected_rpc = mcd_rpc_message_from_data (data, sizeof (data), NULL); ASSERT (expected_rpc); size_t expected_num_iovecs; - mongoc_iovec_t *const expected_iovecs = - mcd_rpc_message_to_iovecs (expected_rpc, &expected_num_iovecs); + mongoc_iovec_t *const expected_iovecs = mcd_rpc_message_to_iovecs (expected_rpc, &expected_num_iovecs); ASSERT (expected_iovecs); mcd_rpc_message *const rpc = mcd_rpc_message_new (); @@ -2884,13 +2675,11 @@ test_rpc_message_setters_op_kill_cursors (void) { const uint8_t data[] = {TEST_DATA_OP_KILL_CURSORS}; - mcd_rpc_message *const expected_rpc = - mcd_rpc_message_from_data (data, sizeof (data), NULL); + mcd_rpc_message *const expected_rpc = mcd_rpc_message_from_data (data, sizeof (data), NULL); ASSERT (expected_rpc); size_t expected_num_iovecs; - mongoc_iovec_t *const expected_iovecs = - mcd_rpc_message_to_iovecs (expected_rpc, &expected_num_iovecs); + mongoc_iovec_t *const expected_iovecs = mcd_rpc_message_to_iovecs (expected_rpc, &expected_num_iovecs); ASSERT (expected_iovecs); const int64_t cursor_ids[] = {1230066625199609624, 2387509390608836392}; @@ -2925,9 +2714,7 @@ test_rpc_message_setters_op_kill_cursors (void) const mongoc_iovec_t *const expected_iovec = expected_iovecs + 6; ASSERT_CMPSIZE_T (iovec->iov_len, ==, expected_iovec->iov_len); - ASSERT (memcmp (iovec->iov_base, - expected_iovec->iov_base, - expected_iovec->iov_len) == 0); + ASSERT (memcmp (iovec->iov_base, expected_iovec->iov_base, expected_iovec->iov_len) == 0); } bson_free (iovecs); @@ -2944,8 +2731,7 @@ test_rpc_message_from_data_in_place (void) const uint8_t data_op_compressed[] = {TEST_DATA_OP_COMPRESSED}; const uint8_t data_op_msg_kind_0[] = {TEST_DATA_OP_MSG_KIND_0}; const uint8_t data_op_msg_kind_1_single[] = {TEST_DATA_OP_MSG_KIND_1_SINGLE}; - const uint8_t data_op_msg_kind_1_multiple[] = { - TEST_DATA_OP_MSG_KIND_1_MULTIPLE}; + const uint8_t data_op_msg_kind_1_multiple[] = {TEST_DATA_OP_MSG_KIND_1_MULTIPLE}; const uint8_t data_op_reply[] = {TEST_DATA_OP_REPLY}; const uint8_t data_op_update[] = {TEST_DATA_OP_UPDATE}; const uint8_t data_op_insert[] = {TEST_DATA_OP_INSERT}; @@ -3014,8 +2800,7 @@ test_rpc_message_from_data_in_place (void) ASSERT_RPC_MESSAGE_RESULT (res, data, data_end, data_len); size_t num_iovecs; - mongoc_iovec_t *const iovecs = - mcd_rpc_message_to_iovecs (rpc, &num_iovecs); + mongoc_iovec_t *const iovecs = mcd_rpc_message_to_iovecs (rpc, &num_iovecs); ASSERT (iovecs && num_iovecs > 0u); bson_free (iovecs); @@ -3032,8 +2817,7 @@ test_rpc_message_from_data_in_place (void) ASSERT_RPC_MESSAGE_RESULT (res, data, data_end, data_len); size_t num_iovecs; - mongoc_iovec_t *const iovecs = - mcd_rpc_message_to_iovecs (rpc, &num_iovecs); + mongoc_iovec_t *const iovecs = mcd_rpc_message_to_iovecs (rpc, &num_iovecs); ASSERT (iovecs && num_iovecs > 0u); bson_free (iovecs); @@ -3047,119 +2831,49 @@ test_rpc_message_from_data_in_place (void) void test_mcd_rpc_install (TestSuite *suite) { - TestSuite_Add (suite, - "/rpc_message/from_data/op_compressed/valid", - test_rpc_message_from_data_op_compressed_valid); - TestSuite_Add (suite, - "/rpc_message/from_data/op_msg/valid", - test_rpc_message_from_data_op_msg_valid); - TestSuite_Add (suite, - "/rpc_message/from_data/op_reply/valid", - test_rpc_message_from_data_op_reply_valid); - TestSuite_Add (suite, - "/rpc_message/from_data/op_update/valid", - test_rpc_message_from_data_op_update_valid); - TestSuite_Add (suite, - "/rpc_message/from_data/op_insert/valid", - test_rpc_message_from_data_op_insert_valid); - TestSuite_Add (suite, - "/rpc_message/from_data/op_query/valid", - test_rpc_message_from_data_op_query_valid); - TestSuite_Add (suite, - "/rpc_message/from_data/op_get_more/valid", - test_rpc_message_from_data_op_get_more_valid); - TestSuite_Add (suite, - "/rpc_message/from_data/op_delete/valid", - test_rpc_message_from_data_op_delete_valid); - TestSuite_Add (suite, - "/rpc_message/from_data/op_kill_cursors/valid", - test_rpc_message_from_data_op_kill_cursors_valid); - - TestSuite_Add (suite, - "/rpc_message/from_data/op_compressed/invalid", - test_rpc_message_from_data_op_compressed_invalid); - TestSuite_Add (suite, - "/rpc_message/from_data/op_msg/invalid", - test_rpc_message_from_data_op_msg_invalid); - TestSuite_Add (suite, - "/rpc_message/from_data/op_reply/invalid", - test_rpc_message_from_data_op_reply_invalid); - TestSuite_Add (suite, - "/rpc_message/from_data/op_update/invalid", - test_rpc_message_from_data_op_update_invalid); - TestSuite_Add (suite, - "/rpc_message/from_data/op_insert/invalid", - test_rpc_message_from_data_op_insert_invalid); - TestSuite_Add (suite, - "/rpc_message/from_data/op_query/invalid", - test_rpc_message_from_data_op_query_invalid); - TestSuite_Add (suite, - "/rpc_message/from_data/op_get_more/invalid", - test_rpc_message_from_data_op_get_more_invalid); - TestSuite_Add (suite, - "/rpc_message/from_data/op_delete/invalid", - test_rpc_message_from_data_op_delete_invalid); - TestSuite_Add (suite, - "/rpc_message/from_data/op_kill_cursors/invalid", - test_rpc_message_from_data_op_kill_cursors_invalid); - - TestSuite_Add (suite, - "/rpc_message/to_iovecs/op_compressed", - test_rpc_message_to_iovecs_op_compressed); - TestSuite_Add (suite, - "/rpc_message/to_iovecs/op_msg", - test_rpc_message_to_iovecs_op_msg); - TestSuite_Add (suite, - "/rpc_message/to_iovecs/op_reply", - test_rpc_message_to_iovecs_op_reply); - TestSuite_Add (suite, - "/rpc_message/to_iovecs/op_update", - test_rpc_message_to_iovecs_op_update); - TestSuite_Add (suite, - "/rpc_message/to_iovecs/op_insert", - test_rpc_message_to_iovecs_op_insert); - TestSuite_Add (suite, - "/rpc_message/to_iovecs/op_query", - test_rpc_message_to_iovecs_op_query); - TestSuite_Add (suite, - "/rpc_message/to_iovecs/op_get_more", - test_rpc_message_to_iovecs_op_get_more); - TestSuite_Add (suite, - "/rpc_message/to_iovecs/op_delete", - test_rpc_message_to_iovecs_op_delete); - TestSuite_Add (suite, - "/rpc_message/to_iovecs/op_kill_cursors", - test_rpc_message_to_iovecs_op_kill_cursors); - - TestSuite_Add (suite, - "/rpc_message/setters/op_compressed", - test_rpc_message_setters_op_compressed); + TestSuite_Add (suite, "/rpc_message/from_data/op_compressed/valid", test_rpc_message_from_data_op_compressed_valid); + TestSuite_Add (suite, "/rpc_message/from_data/op_msg/valid", test_rpc_message_from_data_op_msg_valid); + TestSuite_Add (suite, "/rpc_message/from_data/op_reply/valid", test_rpc_message_from_data_op_reply_valid); + TestSuite_Add (suite, "/rpc_message/from_data/op_update/valid", test_rpc_message_from_data_op_update_valid); + TestSuite_Add (suite, "/rpc_message/from_data/op_insert/valid", test_rpc_message_from_data_op_insert_valid); + TestSuite_Add (suite, "/rpc_message/from_data/op_query/valid", test_rpc_message_from_data_op_query_valid); + TestSuite_Add (suite, "/rpc_message/from_data/op_get_more/valid", test_rpc_message_from_data_op_get_more_valid); + TestSuite_Add (suite, "/rpc_message/from_data/op_delete/valid", test_rpc_message_from_data_op_delete_valid); + TestSuite_Add ( + suite, "/rpc_message/from_data/op_kill_cursors/valid", test_rpc_message_from_data_op_kill_cursors_valid); + + TestSuite_Add ( + suite, "/rpc_message/from_data/op_compressed/invalid", test_rpc_message_from_data_op_compressed_invalid); + TestSuite_Add (suite, "/rpc_message/from_data/op_msg/invalid", test_rpc_message_from_data_op_msg_invalid); + TestSuite_Add (suite, "/rpc_message/from_data/op_reply/invalid", test_rpc_message_from_data_op_reply_invalid); + TestSuite_Add (suite, "/rpc_message/from_data/op_update/invalid", test_rpc_message_from_data_op_update_invalid); + TestSuite_Add (suite, "/rpc_message/from_data/op_insert/invalid", test_rpc_message_from_data_op_insert_invalid); + TestSuite_Add (suite, "/rpc_message/from_data/op_query/invalid", test_rpc_message_from_data_op_query_invalid); + TestSuite_Add (suite, "/rpc_message/from_data/op_get_more/invalid", test_rpc_message_from_data_op_get_more_invalid); + TestSuite_Add (suite, "/rpc_message/from_data/op_delete/invalid", test_rpc_message_from_data_op_delete_invalid); TestSuite_Add ( - suite, "/rpc_message/setters/op_msg", test_rpc_message_setters_op_msg); - TestSuite_Add (suite, - "/rpc_message/setters/op_reply", - test_rpc_message_setters_op_reply); - TestSuite_Add (suite, - "/rpc_message/setters/op_update", - test_rpc_message_setters_op_update); - TestSuite_Add (suite, - "/rpc_message/setters/op_insert", - test_rpc_message_setters_op_insert); - TestSuite_Add (suite, - "/rpc_message/setters/op_query", - test_rpc_message_setters_op_query); - TestSuite_Add (suite, - "/rpc_message/setters/op_get_more", - test_rpc_message_setters_op_get_more); - TestSuite_Add (suite, - "/rpc_message/setters/op_delete", - test_rpc_message_setters_op_delete); - TestSuite_Add (suite, - "/rpc_message/setters/op_kill_cursors", - test_rpc_message_setters_op_kill_cursors); - - - TestSuite_Add (suite, - "/rpc_message/from_data/in_place", - test_rpc_message_from_data_in_place); + suite, "/rpc_message/from_data/op_kill_cursors/invalid", test_rpc_message_from_data_op_kill_cursors_invalid); + + TestSuite_Add (suite, "/rpc_message/to_iovecs/op_compressed", test_rpc_message_to_iovecs_op_compressed); + TestSuite_Add (suite, "/rpc_message/to_iovecs/op_msg", test_rpc_message_to_iovecs_op_msg); + TestSuite_Add (suite, "/rpc_message/to_iovecs/op_reply", test_rpc_message_to_iovecs_op_reply); + TestSuite_Add (suite, "/rpc_message/to_iovecs/op_update", test_rpc_message_to_iovecs_op_update); + TestSuite_Add (suite, "/rpc_message/to_iovecs/op_insert", test_rpc_message_to_iovecs_op_insert); + TestSuite_Add (suite, "/rpc_message/to_iovecs/op_query", test_rpc_message_to_iovecs_op_query); + TestSuite_Add (suite, "/rpc_message/to_iovecs/op_get_more", test_rpc_message_to_iovecs_op_get_more); + TestSuite_Add (suite, "/rpc_message/to_iovecs/op_delete", test_rpc_message_to_iovecs_op_delete); + TestSuite_Add (suite, "/rpc_message/to_iovecs/op_kill_cursors", test_rpc_message_to_iovecs_op_kill_cursors); + + TestSuite_Add (suite, "/rpc_message/setters/op_compressed", test_rpc_message_setters_op_compressed); + TestSuite_Add (suite, "/rpc_message/setters/op_msg", test_rpc_message_setters_op_msg); + TestSuite_Add (suite, "/rpc_message/setters/op_reply", test_rpc_message_setters_op_reply); + TestSuite_Add (suite, "/rpc_message/setters/op_update", test_rpc_message_setters_op_update); + TestSuite_Add (suite, "/rpc_message/setters/op_insert", test_rpc_message_setters_op_insert); + TestSuite_Add (suite, "/rpc_message/setters/op_query", test_rpc_message_setters_op_query); + TestSuite_Add (suite, "/rpc_message/setters/op_get_more", test_rpc_message_setters_op_get_more); + TestSuite_Add (suite, "/rpc_message/setters/op_delete", test_rpc_message_setters_op_delete); + TestSuite_Add (suite, "/rpc_message/setters/op_kill_cursors", test_rpc_message_setters_op_kill_cursors); + + + TestSuite_Add (suite, "/rpc_message/from_data/in_place", test_rpc_message_from_data_in_place); } diff --git a/src/libmongoc/tests/test-mongoc-aggregate.c b/src/libmongoc/tests/test-mongoc-aggregate.c index fc97ace3ba..c20355a2c4 100644 --- a/src/libmongoc/tests/test-mongoc-aggregate.c +++ b/src/libmongoc/tests/test-mongoc-aggregate.c @@ -22,22 +22,19 @@ _test_query_flag (mongoc_query_flags_t flag, bson_t *opt) server = mock_server_with_auto_hello (WIRE_VERSION_MAX); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); collection = mongoc_client_get_collection (client, "db", "collection"); - cursor = mongoc_collection_aggregate ( - collection, flag, tmp_bson ("{'pipeline': []}"), opt, NULL); + cursor = mongoc_collection_aggregate (collection, flag, tmp_bson ("{'pipeline': []}"), opt, NULL); ASSERT_OR_PRINT (!mongoc_cursor_error (cursor, &error), error); /* "aggregate" command */ future = future_cursor_next (cursor, &doc); - request = - mock_server_receives_msg (server, - MONGOC_QUERY_NONE, - tmp_bson ("{'aggregate': 'collection'," - " 'pipeline': [ ]," - " 'tailable': {'$exists': false}}")); + request = mock_server_receives_msg (server, + MONGOC_QUERY_NONE, + tmp_bson ("{'aggregate': 'collection'," + " 'pipeline': [ ]," + " 'tailable': {'$exists': false}}")); ASSERT (request); reply_to_request_simple (request, "{'ok': 1," @@ -51,12 +48,11 @@ _test_query_flag (mongoc_query_flags_t flag, bson_t *opt) /* "getMore" command */ future = future_cursor_next (cursor, &doc); - request = - mock_server_receives_msg (server, - MONGOC_QUERY_NONE, - tmp_bson ("{'getMore': {'$numberLong': '123'}," - " 'collection': 'collection'," - " 'tailable': {'$exists': false}}")); + request = mock_server_receives_msg (server, + MONGOC_QUERY_NONE, + tmp_bson ("{'getMore': {'$numberLong': '123'}," + " 'collection': 'collection'," + " 'tailable': {'$exists': false}}")); ASSERT (request); reply_to_request_simple (request, "{'ok': 1," @@ -87,8 +83,7 @@ test_query_flags (void) flag_and_opt_t flags_and_opts[] = { {MONGOC_QUERY_TAILABLE_CURSOR, tmp_bson ("{'tailable': true}")}, - {MONGOC_QUERY_TAILABLE_CURSOR | MONGOC_QUERY_AWAIT_DATA, - tmp_bson ("{'tailable': true, 'awaitData': true}")}}; + {MONGOC_QUERY_TAILABLE_CURSOR | MONGOC_QUERY_AWAIT_DATA, tmp_bson ("{'tailable': true, 'awaitData': true}")}}; /* test with both flag and opt */ for (i = 0; i < (sizeof flags_and_opts) / (sizeof (flag_and_opt_t)); i++) { @@ -100,6 +95,5 @@ test_query_flags (void) void test_aggregate_install (TestSuite *suite) { - TestSuite_AddMockServerTest ( - suite, "/Aggregate/query_flags", test_query_flags); + TestSuite_AddMockServerTest (suite, "/Aggregate/query_flags", test_query_flags); } diff --git a/src/libmongoc/tests/test-mongoc-async.c b/src/libmongoc/tests/test-mongoc-async.c index 3a96467deb..38810ce28e 100644 --- a/src/libmongoc/tests/test-mongoc-async.c +++ b/src/libmongoc/tests/test-mongoc-async.c @@ -34,13 +34,11 @@ get_localhost_stream (uint16_t port) server_addr.sin_family = AF_INET; server_addr.sin_port = htons (port); server_addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK); - r = mongoc_socket_connect ( - conn_sock, (struct sockaddr *) &server_addr, sizeof (server_addr), 0); + r = mongoc_socket_connect (conn_sock, (struct sockaddr *) &server_addr, sizeof (server_addr), 0); errcode = mongoc_socket_errno (conn_sock); if (!(r == 0 || MONGOC_ERRNO_IS_AGAIN (errcode))) { - test_error ( - "mongoc_socket_connect unexpected return: %d (errno: %d)", r, errcode); + test_error ("mongoc_socket_connect unexpected return: %d (errno: %d)", r, errcode); } return mongoc_stream_socket_new (conn_sock); @@ -131,8 +129,7 @@ test_hello_impl (bool with_ssl) copt.ca_file = CERT_CA; copt.weak_cert_validation = 1; - sock_streams[i] = mongoc_stream_tls_new_with_hostname ( - sock_streams[i], NULL, &copt, 1); + sock_streams[i] = mongoc_stream_tls_new_with_hostname (sock_streams[i], NULL, &copt, 1); setup = mongoc_async_cmd_tls_setup; setup_ctx = (void *) "127.0.0.1"; } @@ -162,19 +159,17 @@ test_hello_impl (bool with_ssl) offset = NSERVERS / 2; for (i = 0; i < NSERVERS; i++) { server_id = (i + offset) % NSERVERS; - request = mock_server_receives_command ( - servers[server_id], "admin", MONGOC_QUERY_SECONDARY_OK, NULL); + request = mock_server_receives_command (servers[server_id], "admin", MONGOC_QUERY_SECONDARY_OK, NULL); /* use "serverId" field to distinguish among responses */ - reply = - bson_strdup_printf ("{'ok': 1," - " '" HANDSHAKE_RESPONSE_LEGACY_HELLO "': true," - " 'minWireVersion': %d," - " 'maxWireVersion': %d," - " 'serverId': %d}", - WIRE_VERSION_MIN, - WIRE_VERSION_MAX, - server_id); + reply = bson_strdup_printf ("{'ok': 1," + " '" HANDSHAKE_RESPONSE_LEGACY_HELLO "': true," + " 'minWireVersion': %d," + " 'maxWireVersion': %d," + " 'serverId': %d}", + WIRE_VERSION_MIN, + WIRE_VERSION_MAX, + server_id); reply_to_request_simple (request, reply); bson_free (reply); @@ -236,8 +231,7 @@ test_large_hello_helper (mongoc_async_cmd_t *acmd, ASSERT_CMPINT (result, ==, MONGOC_ASYNC_CMD_SUCCESS); ASSERT_HAS_FIELD (bson, HANDSHAKE_RESPONSE_LEGACY_HELLO); - BSON_ASSERT ( - bson_iter_init_find (&iter, bson, HANDSHAKE_RESPONSE_LEGACY_HELLO)); + BSON_ASSERT (bson_iter_init_find (&iter, bson, HANDSHAKE_RESPONSE_LEGACY_HELLO)); BSON_ASSERT (BSON_ITER_HOLDS_BOOL (&iter) && bson_iter_bool (&iter)); } @@ -268,8 +262,7 @@ test_large_hello (void *ctx) #ifdef MONGOC_ENABLE_SSL if (test_framework_get_ssl ()) { ssl_opts = *test_framework_get_ssl_opts (); - sock_stream = - mongoc_stream_tls_new_with_hostname (sock_stream, NULL, &ssl_opts, 1); + sock_stream = mongoc_stream_tls_new_with_hostname (sock_stream, NULL, &ssl_opts, 1); } #endif @@ -287,8 +280,7 @@ test_large_hello (void *ctx) NULL, /* initiator. */ 0, /* initiate delay. */ #ifdef MONGOC_ENABLE_SSL - test_framework_get_ssl () ? mongoc_async_cmd_tls_setup - : NULL, + test_framework_get_ssl () ? mongoc_async_cmd_tls_setup : NULL, #else NULL, #endif @@ -343,8 +335,7 @@ test_hello_delay (void) mock_server_run (server); - stream_with_result.stream = - get_localhost_stream (mock_server_get_port (server)); + stream_with_result.stream = get_localhost_stream (mock_server_get_port (server)); stream_with_result.finished = false; BSON_ASSERT (BSON_APPEND_INT32 (&hello_cmd, HANDSHAKE_CMD_LEGACY_HELLO, 1)); @@ -366,8 +357,7 @@ test_hello_delay (void) mongoc_async_run (async); /* it should have taken at least 100ms to finish. */ - ASSERT_CMPINT64 ( - bson_get_monotonic_time () - start, >, (int64_t) (100 * 1000)); + ASSERT_CMPINT64 (bson_get_monotonic_time () - start, >, (int64_t) (100 * 1000)); BSON_ASSERT (stream_with_result.finished); bson_destroy (&hello_cmd); diff --git a/src/libmongoc/tests/test-mongoc-aws.c b/src/libmongoc/tests/test-mongoc-aws.c index 74a58bff6a..cfbe6a056e 100644 --- a/src/libmongoc/tests/test-mongoc-aws.c +++ b/src/libmongoc/tests/test-mongoc-aws.c @@ -41,28 +41,24 @@ test_obtain_credentials (void *unused) mongoc_uri_destroy (uri); /* A username specified with no password is an error. */ - uri = mongoc_uri_new ( - "mongodb://access_key_id:@localhost/?authMechanism=MONGODB-AWS"); + uri = mongoc_uri_new ("mongodb://access_key_id:@localhost/?authMechanism=MONGODB-AWS"); ret = _mongoc_aws_credentials_obtain (uri, &creds, &error); BSON_ASSERT (!ret); - ASSERT_ERROR_CONTAINS ( - error, - MONGOC_ERROR_CLIENT, - MONGOC_ERROR_CLIENT_AUTHENTICATE, - "ACCESS_KEY_ID is set, but SECRET_ACCESS_KEY is missing"); + ASSERT_ERROR_CONTAINS (error, + MONGOC_ERROR_CLIENT, + MONGOC_ERROR_CLIENT_AUTHENTICATE, + "ACCESS_KEY_ID is set, but SECRET_ACCESS_KEY is missing"); _mongoc_aws_credentials_cleanup (&creds); mongoc_uri_destroy (uri); /* Password not set at all (not empty string) */ - uri = mongoc_uri_new ( - "mongodb://access_key_id@localhost/?authMechanism=MONGODB-AWS"); + uri = mongoc_uri_new ("mongodb://access_key_id@localhost/?authMechanism=MONGODB-AWS"); ret = _mongoc_aws_credentials_obtain (uri, &creds, &error); BSON_ASSERT (!ret); - ASSERT_ERROR_CONTAINS ( - error, - MONGOC_ERROR_CLIENT, - MONGOC_ERROR_CLIENT_AUTHENTICATE, - "ACCESS_KEY_ID is set, but SECRET_ACCESS_KEY is missing"); + ASSERT_ERROR_CONTAINS (error, + MONGOC_ERROR_CLIENT, + MONGOC_ERROR_CLIENT_AUTHENTICATE, + "ACCESS_KEY_ID is set, but SECRET_ACCESS_KEY is missing"); _mongoc_aws_credentials_cleanup (&creds); mongoc_uri_destroy (uri); @@ -128,11 +124,10 @@ test_obtain_credentials_from_env (void *unused) uri = mongoc_uri_new ("mongodb://localhost/?authMechanism=MONGODB-AWS"); ret = _mongoc_aws_credentials_obtain (uri, &creds, &error); BSON_ASSERT (!ret); - ASSERT_ERROR_CONTAINS ( - error, - MONGOC_ERROR_CLIENT, - MONGOC_ERROR_CLIENT_AUTHENTICATE, - "ACCESS_KEY_ID is set, but SECRET_ACCESS_KEY is missing"); + ASSERT_ERROR_CONTAINS (error, + MONGOC_ERROR_CLIENT, + MONGOC_ERROR_CLIENT_AUTHENTICATE, + "ACCESS_KEY_ID is set, but SECRET_ACCESS_KEY is missing"); _mongoc_aws_credentials_cleanup (&creds); mongoc_uri_destroy (uri); @@ -142,11 +137,10 @@ test_obtain_credentials_from_env (void *unused) uri = mongoc_uri_new ("mongodb://localhost/?authMechanism=MONGODB-AWS"); ret = _mongoc_aws_credentials_obtain (uri, &creds, &error); BSON_ASSERT (!ret); - ASSERT_ERROR_CONTAINS ( - error, - MONGOC_ERROR_CLIENT, - MONGOC_ERROR_CLIENT_AUTHENTICATE, - "SECRET_ACCESS_KEY is set, but ACCESS_KEY_ID is missing"); + ASSERT_ERROR_CONTAINS (error, + MONGOC_ERROR_CLIENT, + MONGOC_ERROR_CLIENT_AUTHENTICATE, + "SECRET_ACCESS_KEY is set, but ACCESS_KEY_ID is missing"); _mongoc_aws_credentials_cleanup (&creds); mongoc_uri_destroy (uri); @@ -196,76 +190,52 @@ test_derive_region (void *unused) #define WITH_LEN(s) s, strlen (s) - ret = _mongoc_validate_and_derive_region ( - WITH_LEN ("abc..def"), ®ion, &error); + ret = _mongoc_validate_and_derive_region (WITH_LEN ("abc..def"), ®ion, &error); BSON_ASSERT (!ret); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_CLIENT, - MONGOC_ERROR_CLIENT_AUTHENTICATE, - "Invalid STS host: empty part"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_AUTHENTICATE, "Invalid STS host: empty part"); bson_free (region); ret = _mongoc_validate_and_derive_region (WITH_LEN ("."), ®ion, &error); BSON_ASSERT (!ret); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_CLIENT, - MONGOC_ERROR_CLIENT_AUTHENTICATE, - "Invalid STS host: empty part"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_AUTHENTICATE, "Invalid STS host: empty part"); bson_free (region); ret = _mongoc_validate_and_derive_region (WITH_LEN ("..."), ®ion, &error); BSON_ASSERT (!ret); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_CLIENT, - MONGOC_ERROR_CLIENT_AUTHENTICATE, - "Invalid STS host: empty part"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_AUTHENTICATE, "Invalid STS host: empty part"); bson_free (region); - ret = - _mongoc_validate_and_derive_region (WITH_LEN ("first."), ®ion, &error); + ret = _mongoc_validate_and_derive_region (WITH_LEN ("first."), ®ion, &error); BSON_ASSERT (!ret); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_CLIENT, - MONGOC_ERROR_CLIENT_AUTHENTICATE, - "Invalid STS host: empty part"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_AUTHENTICATE, "Invalid STS host: empty part"); bson_free (region); - ret = _mongoc_validate_and_derive_region ( - WITH_LEN ("sts.amazonaws.com"), ®ion, &error); + ret = _mongoc_validate_and_derive_region (WITH_LEN ("sts.amazonaws.com"), ®ion, &error); BSON_ASSERT (ret); ASSERT_CMPSTR ("us-east-1", region); bson_free (region); - ret = _mongoc_validate_and_derive_region ( - WITH_LEN ("first.second"), ®ion, &error); + ret = _mongoc_validate_and_derive_region (WITH_LEN ("first.second"), ®ion, &error); BSON_ASSERT (ret); ASSERT_CMPSTR ("second", region); bson_free (region); - ret = - _mongoc_validate_and_derive_region (WITH_LEN ("first"), ®ion, &error); + ret = _mongoc_validate_and_derive_region (WITH_LEN ("first"), ®ion, &error); BSON_ASSERT (ret); ASSERT_CMPSTR ("us-east-1", region); bson_free (region); ret = _mongoc_validate_and_derive_region (WITH_LEN (""), ®ion, &error); BSON_ASSERT (!ret); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_CLIENT, - MONGOC_ERROR_CLIENT_AUTHENTICATE, - "Invalid STS host: empty"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_AUTHENTICATE, "Invalid STS host: empty"); bson_free (region); large = bson_malloc0 (257); memset (large, 'a', 256); - ret = _mongoc_validate_and_derive_region ( - large, strlen (large), ®ion, &error); + ret = _mongoc_validate_and_derive_region (large, strlen (large), ®ion, &error); BSON_ASSERT (!ret); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_CLIENT, - MONGOC_ERROR_CLIENT_AUTHENTICATE, - "Invalid STS host: too large"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_AUTHENTICATE, "Invalid STS host: too large"); bson_free (region); bson_free (large); @@ -284,8 +254,7 @@ test_aws_cache (void *unused) valid_creds.session_token = bson_strdup ("session_token"); // Set expiration to one minute from now. valid_creds.expiration.set = true; - valid_creds.expiration.value = - mcd_timer_expire_after (mcd_milliseconds (60 * 1000)); + valid_creds.expiration.value = mcd_timer_expire_after (mcd_milliseconds (60 * 1000)); _mongoc_aws_credentials_t expired_creds = MONGOC_AWS_CREDENTIALS_INIT; expired_creds.access_key_id = bson_strdup ("access_key_id"); @@ -293,8 +262,7 @@ test_aws_cache (void *unused) expired_creds.session_token = bson_strdup ("session_token"); // Set expiration to one minute before. expired_creds.expiration.set = true; - expired_creds.expiration.value = - mcd_timer_expire_after (mcd_milliseconds (-60 * 1000)); + expired_creds.expiration.value = mcd_timer_expire_after (mcd_milliseconds (-60 * 1000)); _mongoc_aws_credentials_cache_t *cache = &mongoc_aws_credentials_cache; _mongoc_aws_credentials_cache_clear (); @@ -370,16 +338,8 @@ test_aws_install (TestSuite *suite) NULL /* ctx */, test_framework_skip_if_no_aws, test_framework_skip_if_no_setenv); - TestSuite_AddFull (suite, - "/aws/derive_region", - test_derive_region, - NULL /* dtor */, - NULL /* ctx */, - test_framework_skip_if_no_aws); - TestSuite_AddFull (suite, - "/aws/cache", - test_aws_cache, - NULL /* dtor */, - NULL /* ctx */, - test_framework_skip_if_no_aws); + TestSuite_AddFull ( + suite, "/aws/derive_region", test_derive_region, NULL /* dtor */, NULL /* ctx */, test_framework_skip_if_no_aws); + TestSuite_AddFull ( + suite, "/aws/cache", test_aws_cache, NULL /* dtor */, NULL /* ctx */, test_framework_skip_if_no_aws); } diff --git a/src/libmongoc/tests/test-mongoc-background-monitoring.c b/src/libmongoc/tests/test-mongoc-background-monitoring.c index f8b7b629ad..8972e0715a 100644 --- a/src/libmongoc/tests/test-mongoc-background-monitoring.c +++ b/src/libmongoc/tests/test-mongoc-background-monitoring.c @@ -43,9 +43,8 @@ typedef enum { TF_FAST_HEARTBEAT = 1 << 0, TF_FAST_MIN_HEARTBEAT = 1 << 1, TF_AUTO_RESPOND_POLLING_HELLO = 1 << 2, - TF_NO_MONGODB_API_VERSION = - 1 << 3, /* if set, do not pick up the MONGODB_API_VERSION environment - variable */ + TF_NO_MONGODB_API_VERSION = 1 << 3, /* if set, do not pick up the MONGODB_API_VERSION environment + variable */ } tf_flags_t; typedef struct { @@ -65,8 +64,7 @@ tf_dump (test_fixture_t *tf) printf ("== Begin dump ==\n"); printf ("-- Current observations --\n"); printf ("n_heartbeat_started=%d\n", tf->observations->n_heartbeat_started); - printf ("n_heartbeat_succeeded=%d\n", - tf->observations->n_heartbeat_succeeded); + printf ("n_heartbeat_succeeded=%d\n", tf->observations->n_heartbeat_succeeded); printf ("n_heartbeat_failed=%d\n", tf->observations->n_heartbeat_failed); printf ("n_server_changed=%d\n", tf->observations->n_server_changed); printf ("sd_type=%d\n", tf->observations->sd_type); @@ -76,8 +74,7 @@ tf_dump (test_fixture_t *tf) printf ("== End dump ==\n"); } -void BSON_GNUC_PRINTF (2, 3) - tf_log (test_fixture_t *tf, const char *format, ...) +void BSON_GNUC_PRINTF (2, 3) tf_log (test_fixture_t *tf, const char *format, ...) { va_list ap; char *str; @@ -117,15 +114,11 @@ _heartbeat_started (const mongoc_apm_server_heartbeat_started_t *event) { test_fixture_t *tf; - tf = (test_fixture_t *) mongoc_apm_server_heartbeat_started_get_context ( - event); + tf = (test_fixture_t *) mongoc_apm_server_heartbeat_started_get_context (event); bson_mutex_lock (&tf->mutex); tf->observations->n_heartbeat_started++; - tf->observations->awaited = - mongoc_apm_server_heartbeat_started_get_awaited (event); - TF_LOG (tf, - "%s heartbeat started", - tf->observations->awaited ? "awaitable" : "polling"); + tf->observations->awaited = mongoc_apm_server_heartbeat_started_get_awaited (event); + TF_LOG (tf, "%s heartbeat started", tf->observations->awaited ? "awaitable" : "polling"); mongoc_cond_broadcast (&tf->cond); bson_mutex_unlock (&tf->mutex); } @@ -135,15 +128,11 @@ _heartbeat_succeeded (const mongoc_apm_server_heartbeat_succeeded_t *event) { test_fixture_t *tf; - tf = (test_fixture_t *) mongoc_apm_server_heartbeat_succeeded_get_context ( - event); + tf = (test_fixture_t *) mongoc_apm_server_heartbeat_succeeded_get_context (event); bson_mutex_lock (&tf->mutex); tf->observations->n_heartbeat_succeeded++; - tf->observations->awaited = - mongoc_apm_server_heartbeat_succeeded_get_awaited (event); - TF_LOG (tf, - "%s heartbeat succeeded", - tf->observations->awaited ? "awaitable" : "polling"); + tf->observations->awaited = mongoc_apm_server_heartbeat_succeeded_get_awaited (event); + TF_LOG (tf, "%s heartbeat succeeded", tf->observations->awaited ? "awaitable" : "polling"); mongoc_cond_broadcast (&tf->cond); bson_mutex_unlock (&tf->mutex); } @@ -153,15 +142,11 @@ _heartbeat_failed (const mongoc_apm_server_heartbeat_failed_t *event) { test_fixture_t *tf; - tf = - (test_fixture_t *) mongoc_apm_server_heartbeat_failed_get_context (event); + tf = (test_fixture_t *) mongoc_apm_server_heartbeat_failed_get_context (event); bson_mutex_lock (&tf->mutex); tf->observations->n_heartbeat_failed++; - tf->observations->awaited = - mongoc_apm_server_heartbeat_failed_get_awaited (event); - TF_LOG (tf, - "%s heartbeat failed", - tf->observations->awaited ? "awaitable" : "polling"); + tf->observations->awaited = mongoc_apm_server_heartbeat_failed_get_awaited (event); + TF_LOG (tf, "%s heartbeat failed", tf->observations->awaited ? "awaitable" : "polling"); mongoc_cond_broadcast (&tf->cond); bson_mutex_unlock (&tf->mutex); } @@ -177,18 +162,15 @@ _server_changed (const mongoc_apm_server_changed_t *event) old_sd = mongoc_apm_server_changed_get_previous_description (event); new_sd = mongoc_apm_server_changed_get_new_description (event); bson_mutex_lock (&tf->mutex); - TF_LOG (tf, - "server changed %s => %s", - mongoc_server_description_type (old_sd), - mongoc_server_description_type (new_sd)); + TF_LOG ( + tf, "server changed %s => %s", mongoc_server_description_type (old_sd), mongoc_server_description_type (new_sd)); tf->observations->sd_type = new_sd->type; tf->observations->n_server_changed++; mongoc_cond_broadcast (&tf->cond); bson_mutex_unlock (&tf->mutex); } -#define TV \ - "{ 'processId': { '$oid': 'AABBAABBAABBAABBAABBAABB' }, 'counter': 1 }" +#define TV "{ 'processId': { '$oid': 'AABBAABBAABBAABBAABBAABB' }, 'counter': 1 }" bool auto_respond_polling_hello (request_t *request, void *ctx) @@ -201,8 +183,7 @@ auto_respond_polling_hello (request_t *request, void *ctx) doc = request_get_doc ((request), 0); if (!bson_has_field (doc, "topologyVersion")) { - reply_to_request_simple (request, - "{'ok': 1, 'topologyVersion': " TV " }"); + reply_to_request_simple (request, "{'ok': 1, 'topologyVersion': " TV " }"); request_destroy (request); return true; } @@ -229,23 +210,20 @@ tf_new (tf_flags_t flags) mongoc_apm_set_server_heartbeat_started_cb (callbacks, _heartbeat_started); mongoc_apm_set_server_changed_cb (callbacks, _server_changed); - mongoc_apm_set_server_heartbeat_succeeded_cb (callbacks, - _heartbeat_succeeded); + mongoc_apm_set_server_heartbeat_succeeded_cb (callbacks, _heartbeat_succeeded); mongoc_apm_set_server_heartbeat_failed_cb (callbacks, _heartbeat_failed); if (flags & TF_NO_MONGODB_API_VERSION) { tf->pool = mongoc_client_pool_new (mock_server_get_uri (tf->server)); } else { - tf->pool = test_framework_client_pool_new_from_uri ( - mock_server_get_uri (tf->server), NULL); + tf->pool = test_framework_client_pool_new_from_uri (mock_server_get_uri (tf->server), NULL); } mongoc_client_pool_set_apm_callbacks (tf->pool, callbacks, tf); mongoc_apm_callbacks_destroy (callbacks); if (flags & TF_FAST_HEARTBEAT) { - mc_tpld_modification tdmod = - mc_tpld_modify_begin (_mongoc_client_pool_get_topology (tf->pool)); + mc_tpld_modification tdmod = mc_tpld_modify_begin (_mongoc_client_pool_get_topology (tf->pool)); tdmod.new_td->heartbeat_msec = FAST_HEARTBEAT_MS; mc_tpld_modify_commit (tdmod); /* A fast heartbeat implies a fast min heartbeat. */ @@ -253,13 +231,11 @@ tf_new (tf_flags_t flags) } if (flags & TF_FAST_MIN_HEARTBEAT) { - _mongoc_client_pool_get_topology (tf->pool) - ->min_heartbeat_frequency_msec = FAST_HEARTBEAT_MS; + _mongoc_client_pool_get_topology (tf->pool)->min_heartbeat_frequency_msec = FAST_HEARTBEAT_MS; } if (flags & TF_AUTO_RESPOND_POLLING_HELLO) { - mock_server_autoresponds ( - tf->server, auto_respond_polling_hello, NULL, NULL); + mock_server_autoresponds (tf->server, auto_respond_polling_hello, NULL, NULL); } tf->flags = flags; tf->logs = bson_string_new (""); @@ -284,21 +260,20 @@ tf_destroy (test_fixture_t *tf) * _predicate is only tested when observations change. * Upon failure, dumps logs and observations. */ -#define OBSERVE_SOON(_tf, _predicate) \ - do { \ - int64_t _start_ms = bson_get_monotonic_time () / 1000; \ - int64_t _expires_ms = _start_ms + 5000; \ - bson_mutex_lock (&_tf->mutex); \ - while (!(_predicate)) { \ - if (bson_get_monotonic_time () / 1000 > _expires_ms) { \ - bson_mutex_unlock (&_tf->mutex); \ - tf_dump (_tf); \ - test_error ("Predicate expired: %s", #_predicate); \ - } \ - mongoc_cond_timedwait ( \ - &_tf->cond, &_tf->mutex, _expires_ms - _start_ms); \ - } \ - bson_mutex_unlock (&_tf->mutex); \ +#define OBSERVE_SOON(_tf, _predicate) \ + do { \ + int64_t _start_ms = bson_get_monotonic_time () / 1000; \ + int64_t _expires_ms = _start_ms + 5000; \ + bson_mutex_lock (&_tf->mutex); \ + while (!(_predicate)) { \ + if (bson_get_monotonic_time () / 1000 > _expires_ms) { \ + bson_mutex_unlock (&_tf->mutex); \ + tf_dump (_tf); \ + test_error ("Predicate expired: %s", #_predicate); \ + } \ + mongoc_cond_timedwait (&_tf->cond, &_tf->mutex, _expires_ms - _start_ms); \ + } \ + bson_mutex_unlock (&_tf->mutex); \ } while (0) /* Check that _predicate is true immediately. Upon failure, @@ -330,8 +305,7 @@ _signal_shutdown (test_fixture_t *tf) mongoc_topology_description_reconcile (tdmod.new_td, NULL); capture_logs (false); /* remove the server monitor from the set of server monitors. */ - _mongoc_topology_background_monitoring_reconcile (tf->client->topology, - tdmod.new_td); + _mongoc_topology_background_monitoring_reconcile (tf->client->topology, tdmod.new_td); mc_tpld_modify_commit (tdmod); } @@ -344,11 +318,9 @@ _add_server_monitor (test_fixture_t *tf) uri = mock_server_get_uri (tf->server); /* remove the server description from the topology description. */ - mongoc_topology_description_add_server ( - tdmod.new_td, mongoc_uri_get_hosts (uri)->host_and_port, &id); + mongoc_topology_description_add_server (tdmod.new_td, mongoc_uri_get_hosts (uri)->host_and_port, &id); /* add the server monitor from the set of server monitors. */ - _mongoc_topology_background_monitoring_reconcile (tf->client->topology, - tdmod.new_td); + _mongoc_topology_background_monitoring_reconcile (tf->client->topology, tdmod.new_td); mc_tpld_modify_commit (tdmod); } @@ -365,8 +337,7 @@ _request_cancel (test_fixture_t *tf) { bson_mutex_lock (&tf->client->topology->tpld_modification_mtx); /* Assume server id is 1. */ - _mongoc_topology_background_monitoring_cancel_check (tf->client->topology, - 1); + _mongoc_topology_background_monitoring_cancel_check (tf->client->topology, 1); bson_mutex_unlock (&tf->client->topology->tpld_modification_mtx); } @@ -765,9 +736,7 @@ test_streaming_succeeds (void) tf = tf_new (TF_AUTO_RESPOND_POLLING_HELLO); request = mock_server_receives_msg ( - tf->server, - MONGOC_MSG_EXHAUST_ALLOWED, - tmp_bson ("{'topologyVersion': { '$exists': true}}")); + tf->server, MONGOC_MSG_EXHAUST_ALLOWED, tmp_bson ("{'topologyVersion': { '$exists': true}}")); OBSERVE (tf, request); OBSERVE (tf, tf->observations->n_heartbeat_started == 2); OBSERVE (tf, tf->observations->awaited); @@ -790,9 +759,7 @@ test_streaming_hangup (void) tf = tf_new (TF_AUTO_RESPOND_POLLING_HELLO); request = mock_server_receives_msg ( - tf->server, - MONGOC_MSG_EXHAUST_ALLOWED, - tmp_bson ("{'topologyVersion': { '$exists': true}}")); + tf->server, MONGOC_MSG_EXHAUST_ALLOWED, tmp_bson ("{'topologyVersion': { '$exists': true}}")); OBSERVE (tf, request); OBSERVE (tf, tf->observations->n_heartbeat_started == 2); OBSERVE (tf, tf->observations->awaited); @@ -818,9 +785,7 @@ test_streaming_badreply (void) tf = tf_new (TF_AUTO_RESPOND_POLLING_HELLO); request = mock_server_receives_msg ( - tf->server, - MONGOC_MSG_EXHAUST_ALLOWED, - tmp_bson ("{'topologyVersion': { '$exists': true}}")); + tf->server, MONGOC_MSG_EXHAUST_ALLOWED, tmp_bson ("{'topologyVersion': { '$exists': true}}")); OBSERVE (tf, request); OBSERVE (tf, tf->observations->n_heartbeat_started == 2); reply_to_request_simple (request, "{'ok': 0}"); @@ -850,9 +815,7 @@ test_streaming_shutdown (void) tf = tf_new (TF_AUTO_RESPOND_POLLING_HELLO | TF_FAST_HEARTBEAT); request = mock_server_receives_msg ( - tf->server, - MONGOC_MSG_EXHAUST_ALLOWED, - tmp_bson ("{'topologyVersion': { '$exists': true}}")); + tf->server, MONGOC_MSG_EXHAUST_ALLOWED, tmp_bson ("{'topologyVersion': { '$exists': true}}")); OBSERVE (tf, request); OBSERVE (tf, tf->observations->n_heartbeat_started == 2); _signal_shutdown (tf); @@ -872,9 +835,7 @@ test_streaming_cancel (void) tf = tf_new (TF_AUTO_RESPOND_POLLING_HELLO); request = mock_server_receives_msg ( - tf->server, - MONGOC_MSG_EXHAUST_ALLOWED, - tmp_bson ("{'topologyVersion': { '$exists': true}}")); + tf->server, MONGOC_MSG_EXHAUST_ALLOWED, tmp_bson ("{'topologyVersion': { '$exists': true}}")); OBSERVE (tf, request); OBSERVE (tf, tf->observations->n_heartbeat_started == 2); _request_cancel (tf); @@ -892,9 +853,7 @@ test_streaming_cancel (void) /* The handshake will be handled by the auto responder. */ request = mock_server_receives_msg ( - tf->server, - MONGOC_MSG_EXHAUST_ALLOWED, - tmp_bson ("{'topologyVersion': { '$exists': true}}")); + tf->server, MONGOC_MSG_EXHAUST_ALLOWED, tmp_bson ("{'topologyVersion': { '$exists': true}}")); OBSERVE (tf, request); OBSERVE (tf, tf->observations->n_heartbeat_started == 4); reply_to_request_with_ok_and_destroy (request); @@ -912,15 +871,11 @@ test_moretocome_succeeds (void) tf = tf_new (TF_AUTO_RESPOND_POLLING_HELLO); request = mock_server_receives_msg ( - tf->server, - MONGOC_MSG_EXHAUST_ALLOWED, - tmp_bson ("{'topologyVersion': { '$exists': true}}")); + tf->server, MONGOC_MSG_EXHAUST_ALLOWED, tmp_bson ("{'topologyVersion': { '$exists': true}}")); OBSERVE (tf, request); OBSERVE (tf, tf->observations->n_heartbeat_started == 2); OBSERVE (tf, tf->observations->awaited); - reply_to_op_msg_request (request, - MONGOC_MSG_MORE_TO_COME, - tmp_bson ("{'ok': 1, 'topologyVersion': " TV "}")); + reply_to_op_msg_request (request, MONGOC_MSG_MORE_TO_COME, tmp_bson ("{'ok': 1, 'topologyVersion': " TV "}")); OBSERVE_SOON (tf, tf->observations->n_heartbeat_succeeded == 2); OBSERVE_SOON (tf, tf->observations->n_heartbeat_failed == 0); @@ -929,23 +884,17 @@ test_moretocome_succeeds (void) OBSERVE (tf, tf->observations->awaited); /* Server monitor is still streaming replies. */ - reply_to_op_msg_request (request, - MONGOC_MSG_MORE_TO_COME, - tmp_bson ("{'ok': 1, 'topologyVersion': " TV "}")); + reply_to_op_msg_request (request, MONGOC_MSG_MORE_TO_COME, tmp_bson ("{'ok': 1, 'topologyVersion': " TV "}")); OBSERVE_SOON (tf, tf->observations->n_heartbeat_succeeded == 3); OBSERVE (tf, tf->observations->awaited); /* Reply with no moretocome flag. */ - reply_to_op_msg_request (request, - MONGOC_MSG_NONE, - tmp_bson ("{'ok': 1, 'topologyVersion': " TV "}")); + reply_to_op_msg_request (request, MONGOC_MSG_NONE, tmp_bson ("{'ok': 1, 'topologyVersion': " TV "}")); OBSERVE_SOON (tf, tf->observations->n_heartbeat_succeeded == 4); OBSERVE (tf, tf->observations->awaited); request_destroy (request); /* Server monitor immediately sends awaitable hello. */ request = mock_server_receives_msg ( - tf->server, - MONGOC_MSG_EXHAUST_ALLOWED, - tmp_bson ("{'topologyVersion': { '$exists': true}}")); + tf->server, MONGOC_MSG_EXHAUST_ALLOWED, tmp_bson ("{'topologyVersion': { '$exists': true}}")); OBSERVE (tf, request); OBSERVE_SOON (tf, tf->observations->n_heartbeat_started == 5); OBSERVE_SOON (tf, tf->observations->n_heartbeat_failed == 0); @@ -965,15 +914,11 @@ test_moretocome_hangup (void) tf = tf_new (TF_AUTO_RESPOND_POLLING_HELLO); request = mock_server_receives_msg ( - tf->server, - MONGOC_MSG_EXHAUST_ALLOWED, - tmp_bson ("{'topologyVersion': { '$exists': true}}")); + tf->server, MONGOC_MSG_EXHAUST_ALLOWED, tmp_bson ("{'topologyVersion': { '$exists': true}}")); OBSERVE (tf, request); OBSERVE (tf, tf->observations->n_heartbeat_started == 2); OBSERVE (tf, tf->observations->awaited); - reply_to_op_msg_request (request, - MONGOC_MSG_MORE_TO_COME, - tmp_bson ("{'ok': 1, 'topologyVersion': " TV "}")); + reply_to_op_msg_request (request, MONGOC_MSG_MORE_TO_COME, tmp_bson ("{'ok': 1, 'topologyVersion': " TV "}")); OBSERVE_SOON (tf, tf->observations->n_heartbeat_succeeded == 2); OBSERVE_SOON (tf, tf->observations->n_heartbeat_failed == 0); @@ -1003,14 +948,10 @@ test_moretocome_badreply (void) tf = tf_new (TF_AUTO_RESPOND_POLLING_HELLO); request = mock_server_receives_msg ( - tf->server, - MONGOC_MSG_EXHAUST_ALLOWED, - tmp_bson ("{'topologyVersion': { '$exists': true}}")); + tf->server, MONGOC_MSG_EXHAUST_ALLOWED, tmp_bson ("{'topologyVersion': { '$exists': true}}")); OBSERVE (tf, request); OBSERVE (tf, tf->observations->n_heartbeat_started == 2); - reply_to_op_msg_request (request, - MONGOC_MSG_MORE_TO_COME, - tmp_bson ("{'ok': 1, 'topologyVersion': " TV "}")); + reply_to_op_msg_request (request, MONGOC_MSG_MORE_TO_COME, tmp_bson ("{'ok': 1, 'topologyVersion': " TV "}")); OBSERVE_SOON (tf, tf->observations->n_heartbeat_succeeded == 2); OBSERVE_SOON (tf, tf->observations->n_heartbeat_failed == 0); @@ -1042,14 +983,10 @@ test_moretocome_shutdown (void) tf = tf_new (TF_AUTO_RESPOND_POLLING_HELLO | TF_FAST_HEARTBEAT); request = mock_server_receives_msg ( - tf->server, - MONGOC_MSG_EXHAUST_ALLOWED, - tmp_bson ("{'topologyVersion': { '$exists': true}}")); + tf->server, MONGOC_MSG_EXHAUST_ALLOWED, tmp_bson ("{'topologyVersion': { '$exists': true}}")); OBSERVE (tf, request); OBSERVE (tf, tf->observations->n_heartbeat_started == 2); - reply_to_op_msg_request (request, - MONGOC_MSG_MORE_TO_COME, - tmp_bson ("{'ok': 1, 'topologyVersion': " TV "}")); + reply_to_op_msg_request (request, MONGOC_MSG_MORE_TO_COME, tmp_bson ("{'ok': 1, 'topologyVersion': " TV "}")); OBSERVE_SOON (tf, tf->observations->n_heartbeat_succeeded == 2); OBSERVE_SOON (tf, tf->observations->n_heartbeat_failed == 0); @@ -1076,14 +1013,10 @@ test_moretocome_cancel (void) tf = tf_new (TF_AUTO_RESPOND_POLLING_HELLO); request = mock_server_receives_msg ( - tf->server, - MONGOC_MSG_EXHAUST_ALLOWED, - tmp_bson ("{'topologyVersion': { '$exists': true}}")); + tf->server, MONGOC_MSG_EXHAUST_ALLOWED, tmp_bson ("{'topologyVersion': { '$exists': true}}")); OBSERVE (tf, request); OBSERVE (tf, tf->observations->n_heartbeat_started == 2); - reply_to_op_msg_request (request, - MONGOC_MSG_MORE_TO_COME, - tmp_bson ("{'ok': 1, 'topologyVersion': " TV "}")); + reply_to_op_msg_request (request, MONGOC_MSG_MORE_TO_COME, tmp_bson ("{'ok': 1, 'topologyVersion': " TV "}")); OBSERVE_SOON (tf, tf->observations->n_heartbeat_succeeded == 2); OBSERVE_SOON (tf, tf->observations->n_heartbeat_failed == 0); @@ -1114,14 +1047,10 @@ test_moretocome_cancel (void) /* Server monitor sends a fresh awaitable hello. */ request = mock_server_receives_msg ( - tf->server, - MONGOC_MSG_EXHAUST_ALLOWED, - tmp_bson ("{'topologyVersion': { '$exists': true}}")); + tf->server, MONGOC_MSG_EXHAUST_ALLOWED, tmp_bson ("{'topologyVersion': { '$exists': true}}")); OBSERVE (tf, request); OBSERVE (tf, tf->observations->n_heartbeat_started == 5); - reply_to_op_msg_request (request, - MONGOC_MSG_NONE, - tmp_bson ("{'ok': 1, 'topologyVersion': " TV "}")); + reply_to_op_msg_request (request, MONGOC_MSG_NONE, tmp_bson ("{'ok': 1, 'topologyVersion': " TV "}")); OBSERVE_SOON (tf, tf->observations->n_heartbeat_succeeded == 4); OBSERVE_SOON (tf, tf->observations->n_heartbeat_failed == 1); OBSERVE_SOON (tf, tf->observations->n_server_changed == 1); @@ -1131,14 +1060,10 @@ test_moretocome_cancel (void) /* Since the reply did not include moretocome, server monitor sends another. */ request = mock_server_receives_msg ( - tf->server, - MONGOC_MSG_EXHAUST_ALLOWED, - tmp_bson ("{'topologyVersion': { '$exists': true}}")); + tf->server, MONGOC_MSG_EXHAUST_ALLOWED, tmp_bson ("{'topologyVersion': { '$exists': true}}")); OBSERVE (tf, request); OBSERVE (tf, tf->observations->n_heartbeat_started == 6); - reply_to_op_msg_request (request, - MONGOC_MSG_NONE, - tmp_bson ("{'ok': 1, 'topologyVersion': " TV "}")); + reply_to_op_msg_request (request, MONGOC_MSG_NONE, tmp_bson ("{'ok': 1, 'topologyVersion': " TV "}")); OBSERVE_SOON (tf, tf->observations->n_heartbeat_succeeded == 5); OBSERVE_SOON (tf, tf->observations->n_heartbeat_failed == 1); OBSERVE_SOON (tf, tf->observations->n_server_changed == 1); @@ -1152,73 +1077,39 @@ void test_monitoring_install (TestSuite *suite) { /* Tests for initial connection. */ + TestSuite_AddMockServerTest (suite, "/server_monitor_thread/connect/succeeds", test_connect_succeeds); TestSuite_AddMockServerTest ( - suite, "/server_monitor_thread/connect/succeeds", test_connect_succeeds); - TestSuite_AddMockServerTest ( - suite, - "/server_monitor_thread/connect/faas_use_polling", - test_connect_faas_use_polling); - TestSuite_AddMockServerTest ( - suite, "/server_monitor_thread/connect/hangup", test_connect_hangup); - TestSuite_AddMockServerTest ( - suite, "/server_monitor_thread/connect/badreply", test_connect_badreply); - TestSuite_AddMockServerTest ( - suite, "/server_monitor_thread/connect/shutdown", test_connect_shutdown); - TestSuite_AddMockServerTest (suite, - "/server_monitor_thread/connect/requestscan", - test_connect_requestscan); + suite, "/server_monitor_thread/connect/faas_use_polling", test_connect_faas_use_polling); + TestSuite_AddMockServerTest (suite, "/server_monitor_thread/connect/hangup", test_connect_hangup); + TestSuite_AddMockServerTest (suite, "/server_monitor_thread/connect/badreply", test_connect_badreply); + TestSuite_AddMockServerTest (suite, "/server_monitor_thread/connect/shutdown", test_connect_shutdown); + TestSuite_AddMockServerTest (suite, "/server_monitor_thread/connect/requestscan", test_connect_requestscan); /* Tests for retry. */ - TestSuite_AddMockServerTest ( - suite, "/server_monitor_thread/retry/succeeds", test_retry_succeeds); - TestSuite_AddMockServerTest ( - suite, "/server_monitor_thread/retry/hangup", test_retry_hangup); - TestSuite_AddMockServerTest ( - suite, "/server_monitor_thread/retry/badreply", test_retry_badreply); - TestSuite_AddMockServerTest ( - suite, "/server_monitor_thread/retry/shutdown", test_retry_shutdown); + TestSuite_AddMockServerTest (suite, "/server_monitor_thread/retry/succeeds", test_retry_succeeds); + TestSuite_AddMockServerTest (suite, "/server_monitor_thread/retry/hangup", test_retry_hangup); + TestSuite_AddMockServerTest (suite, "/server_monitor_thread/retry/badreply", test_retry_badreply); + TestSuite_AddMockServerTest (suite, "/server_monitor_thread/retry/shutdown", test_retry_shutdown); /* Tests for streaming. */ - TestSuite_AddMockServerTest (suite, - "/server_monitor_thread/streaming/succeeds", - test_streaming_succeeds); - TestSuite_AddMockServerTest ( - suite, "/server_monitor_thread/streaming/hangup", test_streaming_hangup); - TestSuite_AddMockServerTest (suite, - "/server_monitor_thread/streaming/badreply", - test_streaming_badreply); - TestSuite_AddMockServerTest (suite, - "/server_monitor_thread/streaming/shutdown", - test_streaming_shutdown); - TestSuite_AddMockServerTest ( - suite, "/server_monitor_thread/streaming/cancel", test_streaming_cancel); + TestSuite_AddMockServerTest (suite, "/server_monitor_thread/streaming/succeeds", test_streaming_succeeds); + TestSuite_AddMockServerTest (suite, "/server_monitor_thread/streaming/hangup", test_streaming_hangup); + TestSuite_AddMockServerTest (suite, "/server_monitor_thread/streaming/badreply", test_streaming_badreply); + TestSuite_AddMockServerTest (suite, "/server_monitor_thread/streaming/shutdown", test_streaming_shutdown); + TestSuite_AddMockServerTest (suite, "/server_monitor_thread/streaming/cancel", test_streaming_cancel); /* Tests for moretocome. */ - TestSuite_AddMockServerTest (suite, - "/server_monitor_thread/moretocome/succeeds", - test_moretocome_succeeds); - TestSuite_AddMockServerTest (suite, - "/server_monitor_thread/moretocome/hangup", - test_moretocome_hangup); - TestSuite_AddMockServerTest (suite, - "/server_monitor_thread/moretocome/badreply", - test_moretocome_badreply); - TestSuite_AddMockServerTest (suite, - "/server_monitor_thread/moretocome/shutdown", - test_moretocome_shutdown); - TestSuite_AddMockServerTest (suite, - "/server_monitor_thread/moretocome/cancel", - test_moretocome_cancel); + TestSuite_AddMockServerTest (suite, "/server_monitor_thread/moretocome/succeeds", test_moretocome_succeeds); + TestSuite_AddMockServerTest (suite, "/server_monitor_thread/moretocome/hangup", test_moretocome_hangup); + TestSuite_AddMockServerTest (suite, "/server_monitor_thread/moretocome/badreply", test_moretocome_badreply); + TestSuite_AddMockServerTest (suite, "/server_monitor_thread/moretocome/shutdown", test_moretocome_shutdown); + TestSuite_AddMockServerTest (suite, "/server_monitor_thread/moretocome/cancel", test_moretocome_cancel); /* Test flip flopping. */ - TestSuite_AddMockServerTest ( - suite, "/server_monitor_thread/flip_flop", test_flip_flop); + TestSuite_AddMockServerTest (suite, "/server_monitor_thread/flip_flop", test_flip_flop); /* Test repeated scan requests. */ - TestSuite_AddMockServerTest (suite, - "/server_monitor_thread/repeated_requestscan", - test_repeated_requestscan); + TestSuite_AddMockServerTest (suite, "/server_monitor_thread/repeated_requestscan", test_repeated_requestscan); - TestSuite_AddMockServerTest ( - suite, "/server_monitor_thread/sleep_after_scan", test_sleep_after_scan); + TestSuite_AddMockServerTest (suite, "/server_monitor_thread/sleep_after_scan", test_sleep_after_scan); } diff --git a/src/libmongoc/tests/test-mongoc-buffer.c b/src/libmongoc/tests/test-mongoc-buffer.c index 3874b76997..58c0dce87b 100644 --- a/src/libmongoc/tests/test-mongoc-buffer.c +++ b/src/libmongoc/tests/test-mongoc-buffer.c @@ -14,8 +14,7 @@ test_mongoc_buffer_basic (void) uint8_t *data = (uint8_t *) bson_malloc0 (1024); ssize_t r; - stream = - mongoc_stream_file_new_for_path (BINARY_DIR "/reply1.dat", O_RDONLY, 0); + stream = mongoc_stream_file_new_for_path (BINARY_DIR "/reply1.dat", O_RDONLY, 0); ASSERT (stream); _mongoc_buffer_init (&buf, data, 1024, NULL, NULL); diff --git a/src/libmongoc/tests/test-mongoc-bulk.c b/src/libmongoc/tests/test-mongoc-bulk.c index 6942776094..bac609a324 100644 --- a/src/libmongoc/tests/test-mongoc-bulk.c +++ b/src/libmongoc/tests/test-mongoc-bulk.c @@ -14,10 +14,7 @@ #include "mock_server/mock-rs.h" -typedef void (*update_fn) (mongoc_bulk_operation_t *bulk, - const bson_t *selector, - const bson_t *document, - bool upsert); +typedef void (*update_fn) (mongoc_bulk_operation_t *bulk, const bson_t *selector, const bson_t *document, bool upsert); typedef bool (*update_with_opts_fn) (mongoc_bulk_operation_t *bulk, const bson_t *selector, @@ -137,9 +134,7 @@ create_unique_index (mongoc_collection_t *collection) opt.unique = true; BEGIN_IGNORE_DEPRECATIONS - ASSERT_OR_PRINT (mongoc_collection_create_index ( - collection, tmp_bson ("{'a': 1}"), &opt, &error), - error); + ASSERT_OR_PRINT (mongoc_collection_create_index (collection, tmp_bson ("{'a': 1}"), &opt, &error), error); END_IGNORE_DEPRECATIONS } @@ -183,8 +178,7 @@ test_bulk (void) mongoc_bulk_operation_remove (bulk, &del); bson_destroy (&del); - ASSERT_OR_PRINT (mongoc_bulk_operation_execute (bulk, &reply, &error), - error); + ASSERT_OR_PRINT (mongoc_bulk_operation_execute (bulk, &reply, &error), error); ASSERT_MATCH (&reply, "{'nInserted': 4," @@ -221,14 +215,11 @@ _test_opt (const char *opts_json, const char *msg) collection = get_test_collection (client, "test_bulk"); BSON_ASSERT (collection); - bulk = mongoc_collection_create_bulk_operation_with_opts ( - collection, tmp_bson (opts_json)); + bulk = mongoc_collection_create_bulk_operation_with_opts (collection, tmp_bson (opts_json)); BSON_ASSERT (bulk); - BSON_ASSERT (!mongoc_bulk_operation_insert_with_opts ( - bulk, tmp_bson ("{}"), NULL, &error)); - ASSERT_ERROR_CONTAINS ( - error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, msg); + BSON_ASSERT (!mongoc_bulk_operation_insert_with_opts (bulk, tmp_bson ("{}"), NULL, &error)); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, msg); mongoc_bulk_operation_destroy (bulk); mongoc_collection_destroy (collection); @@ -244,8 +235,7 @@ test_opts (void) _test_opt ("{'writeConcern': {'w': 0, 'j': 1}}", "Invalid writeConcern"); _test_opt ("{'sessionId': 'hi'}", "Invalid sessionId"); _test_opt ("{'sessionId': 101}", "Invalid sessionId"); - _test_opt ("{'ordered': 'yes'}", - "Invalid field \"ordered\" in opts, should contain bool"); + _test_opt ("{'ordered': 'yes'}", "Invalid field \"ordered\" in opts, should contain bool"); } @@ -260,8 +250,7 @@ test_bulk_error (void) mock_server = mock_server_with_auto_hello (WIRE_VERSION_MIN); mock_server_run (mock_server); - client = test_framework_client_new_from_uri ( - mock_server_get_uri (mock_server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (mock_server), NULL); bulk = mongoc_bulk_operation_new (true); mongoc_bulk_operation_set_client (bulk, client); @@ -306,42 +295,36 @@ test_bulk_error_unordered (void) bulk = mongoc_collection_create_bulk_operation_with_opts (collection, &opts); for (i = 0; i <= 2048; i++) { mongoc_bulk_operation_update_many_with_opts ( - bulk, - tmp_bson ("{'hello': 'earth'}"), - tmp_bson ("{'$set': {'hello': 'world'}}"), - NULL, - &error); + bulk, tmp_bson ("{'hello': 'earth'}"), tmp_bson ("{'$set': {'hello': 'world'}}"), NULL, &error); } future = future_bulk_operation_execute (bulk, &reply, &error); - request = mock_server_receives_bulk_msg ( - mock_server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'test'," - " 'update': 'test'," - " 'writeConcern': {'$exists': false}," - " 'ordered': false}"), - tmp_bson ("{'q': {'hello': 'earth'}," - " 'u': {'$set': {'hello': 'world'}}," - " 'upsert': false," - " 'multi': true}"), - 1001); + request = mock_server_receives_bulk_msg (mock_server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'test'," + " 'update': 'test'," + " 'writeConcern': {'$exists': false}," + " 'ordered': false}"), + tmp_bson ("{'q': {'hello': 'earth'}," + " 'u': {'$set': {'hello': 'world'}}," + " 'upsert': false," + " 'multi': true}"), + 1001); reply_to_request_simple (request, "{ 'ok' : 1, 'n' : 5 }"); request_destroy (request); - request = mock_server_receives_bulk_msg ( - mock_server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'test'," - " 'update': 'test'," - " 'writeConcern': {'$exists': false}," - " 'ordered': false}"), - tmp_bson ("{'q': {'hello': 'earth'}," - " 'u': {'$set': {'hello': 'world'}}," - " 'upsert': false," - " 'multi': true}"), - 1001); + request = mock_server_receives_bulk_msg (mock_server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'test'," + " 'update': 'test'," + " 'writeConcern': {'$exists': false}," + " 'ordered': false}"), + tmp_bson ("{'q': {'hello': 'earth'}," + " 'u': {'$set': {'hello': 'world'}}," + " 'upsert': false," + " 'multi': true}"), + 1001); request_destroy (request); mock_server_destroy (mock_server); @@ -349,10 +332,7 @@ test_bulk_error_unordered (void) future_wait_max (future, 100); ASSERT (!future_value_get_uint32_t (&future->return_value)); future_destroy (future); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_SOCKET, - "socket error or timeout"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "socket error or timeout"); ASSERT_MATCH (&reply, "{'nInserted': 0," @@ -395,8 +375,7 @@ test_insert (bool ordered) mongoc_bulk_operation_insert (bulk, &doc); mongoc_bulk_operation_insert (bulk, &doc); - ASSERT_OR_PRINT (mongoc_bulk_operation_execute (bulk, &reply, &error), - error); + ASSERT_OR_PRINT (mongoc_bulk_operation_execute (bulk, &reply, &error), error); ASSERT_MATCH (&reply, "{'nInserted': 2," @@ -465,10 +444,7 @@ test_insert_check_keys (void) mongoc_bulk_operation_insert (bulk, tmp_bson ("{'': 1}")); r = (bool) mongoc_bulk_operation_execute (bulk, &reply, &error); BSON_ASSERT (!r); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "empty key"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "empty key"); BSON_ASSERT (bson_empty (&reply)); @@ -483,10 +459,7 @@ test_insert_check_keys (void) mongoc_bulk_operation_insert (bulk, tmp_bson ("{'': 1}")); r = (bool) mongoc_bulk_operation_execute (bulk, &reply, &error); BSON_ASSERT (!r); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "empty key"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "empty key"); BSON_ASSERT (bson_empty (&reply)); @@ -525,8 +498,7 @@ test_upsert (bool ordered) mongoc_bulk_operation_update (bulk, sel, doc, true); - ASSERT_OR_PRINT (mongoc_bulk_operation_execute (bulk, &reply, &error), - error); + ASSERT_OR_PRINT (mongoc_bulk_operation_execute (bulk, &reply, &error), error); ASSERT_MATCH (&reply, "{'nInserted': 0," @@ -550,8 +522,7 @@ test_upsert (bool ordered) doc = tmp_bson ("{'$set': {'hello': 'there'}}"); mongoc_bulk_operation_update (bulk, sel, doc, false); - ASSERT_OR_PRINT (mongoc_bulk_operation_execute (bulk, &reply, &error), - error); + ASSERT_OR_PRINT (mongoc_bulk_operation_execute (bulk, &reply, &error), error); ASSERT_MATCH (&reply, "{'nInserted': 0," @@ -608,20 +579,14 @@ test_upsert_unordered_oversized (void *ctx) bulk = mongoc_collection_create_bulk_operation_with_opts (collection, &opts); /* much too large */ - u = tmp_bson ("{'$set': {'x': '%s', 'y': '%s'}}", - huge_string (client), - huge_string (client)); + u = tmp_bson ("{'$set': {'x': '%s', 'y': '%s'}}", huge_string (client), huge_string (client)); - r = mongoc_bulk_operation_update_one_with_opts ( - bulk, tmp_bson (NULL), u, tmp_bson ("{'upsert': true}"), &error); + r = mongoc_bulk_operation_update_one_with_opts (bulk, tmp_bson (NULL), u, tmp_bson ("{'upsert': true}"), &error); ASSERT_OR_PRINT (r, error); r = (bool) mongoc_bulk_operation_execute (bulk, &reply, &error); ASSERT (!r); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_BSON, - MONGOC_ERROR_BSON_INVALID, - "Document 0 is too large"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "Document 0 is too large"); ASSERT_MATCH (&reply, "{'nInserted': 0," @@ -798,8 +763,7 @@ test_update_one (bool ordered) sel = tmp_bson ("{}"); doc = tmp_bson ("{'$set': {'hello': 'there'}}"); mongoc_bulk_operation_update_one (bulk, sel, doc, true); - ASSERT_OR_PRINT ((bool) mongoc_bulk_operation_execute (bulk, &reply, &error), - error); + ASSERT_OR_PRINT ((bool) mongoc_bulk_operation_execute (bulk, &reply, &error), error); ASSERT_MATCH (&reply, "{'nInserted': 0," @@ -856,45 +820,32 @@ test_update_with_opts_validate (void) update_with_opts_fn update_function; update_function = fns[i]; - bulk = - mongoc_collection_create_bulk_operation_with_opts (collection, NULL); - BSON_ASSERT (!update_function ( - bulk, tmp_bson ("{}"), tmp_bson ("{'a.a': 1}"), NULL, &error)); + bulk = mongoc_collection_create_bulk_operation_with_opts (collection, NULL); + BSON_ASSERT (!update_function (bulk, tmp_bson ("{}"), tmp_bson ("{'a.a': 1}"), NULL, &error)); + ASSERT_ERROR_CONTAINS ( + error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "update only works with $ operators"); + + BSON_ASSERT (update_function ( + bulk, tmp_bson ("{}"), tmp_bson ("{'a.a': 1}"), tmp_bson ("{'validate': %d}", BSON_VALIDATE_NONE), &error)); + BSON_ASSERT (!update_function (bulk, + tmp_bson ("{}"), + tmp_bson ("{'a.a': 1}"), + tmp_bson ("{'validate': %d}", BSON_VALIDATE_DOT_KEYS), + &error)); ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, - "update only works with $ operators"); - - BSON_ASSERT ( - update_function (bulk, - tmp_bson ("{}"), - tmp_bson ("{'a.a': 1}"), - tmp_bson ("{'validate': %d}", BSON_VALIDATE_NONE), - &error)); - BSON_ASSERT (!update_function ( - bulk, - tmp_bson ("{}"), - tmp_bson ("{'a.a': 1}"), - tmp_bson ("{'validate': %d}", BSON_VALIDATE_DOT_KEYS), - &error)); - ASSERT_ERROR_CONTAINS ( - error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "invalid argument for update: keys cannot contain \".\": \"a.a\""); + "invalid argument for update: keys cannot contain \".\": \"a.a\""); mongoc_bulk_operation_destroy (bulk); /* Test a valid update_one with explicit validation on the server. */ - bulk = - mongoc_collection_create_bulk_operation_with_opts (collection, NULL); - BSON_ASSERT ( - update_function (bulk, - tmp_bson ("{}"), - tmp_bson ("{'$set': {'a': 1}}"), - tmp_bson ("{'validate': %d}", BSON_VALIDATE_DOT_KEYS), - &error)); - ASSERT_OR_PRINT (mongoc_bulk_operation_execute (bulk, NULL, &error), - error); + bulk = mongoc_collection_create_bulk_operation_with_opts (collection, NULL); + BSON_ASSERT (update_function (bulk, + tmp_bson ("{}"), + tmp_bson ("{'$set': {'a': 1}}"), + tmp_bson ("{'validate': %d}", BSON_VALIDATE_DOT_KEYS), + &error)); + ASSERT_OR_PRINT (mongoc_bulk_operation_execute (bulk, NULL, &error), error); mongoc_bulk_operation_destroy (bulk); } @@ -905,14 +856,10 @@ test_update_with_opts_validate (void) /* Tests that documents in `coll` found with `selector` all match `match` */ static void -_test_docs_in_coll_matches (mongoc_collection_t *coll, - bson_t *selector, - const char *match, - uint32_t expected_count) +_test_docs_in_coll_matches (mongoc_collection_t *coll, bson_t *selector, const char *match, uint32_t expected_count) { const bson_t *next_doc; - mongoc_cursor_t *cursor = - mongoc_collection_find_with_opts (coll, selector, NULL, NULL); + mongoc_cursor_t *cursor = mongoc_collection_find_with_opts (coll, selector, NULL, NULL); while (expected_count > 0) { ASSERT (mongoc_cursor_next (cursor, &next_doc)); if (match) { @@ -954,31 +901,25 @@ test_update_arrayfilters (void *ctx) for (i = 1; i < 4; i++) { ret = mongoc_bulk_operation_insert_with_opts ( - bulk, - tmp_bson ("{'_id': %d, 'a': [{'x':1}, {'x':2}]}", i), - NULL, - &err); + bulk, tmp_bson ("{'_id': %d, 'a': [{'x':1}, {'x':2}]}", i), NULL, &err); ASSERT_OR_PRINT (ret, err); } - ret = mongoc_bulk_operation_update_one_with_opts ( - bulk, - tmp_bson ("{'_id': 1}"), - tmp_bson ("{'$set': {'a.$[i].x': 3}}"), - tmp_bson ("{'arrayFilters': [{'i.x': {'$gt': 1}}]}"), - &err); + ret = mongoc_bulk_operation_update_one_with_opts (bulk, + tmp_bson ("{'_id': 1}"), + tmp_bson ("{'$set': {'a.$[i].x': 3}}"), + tmp_bson ("{'arrayFilters': [{'i.x': {'$gt': 1}}]}"), + &err); ASSERT_OR_PRINT (ret, err); - ret = mongoc_bulk_operation_update_many_with_opts ( - bulk, - tmp_bson ("{'_id': {'$gt': 1}}"), - tmp_bson ("{'$set': {'a.$[i].x': 4}}"), - tmp_bson ("{'arrayFilters': [{'i.x': {'$gt': 1}}]}"), - &err); + ret = mongoc_bulk_operation_update_many_with_opts (bulk, + tmp_bson ("{'_id': {'$gt': 1}}"), + tmp_bson ("{'$set': {'a.$[i].x': 4}}"), + tmp_bson ("{'arrayFilters': [{'i.x': {'$gt': 1}}]}"), + &err); ASSERT_OR_PRINT (ret, err); - ASSERT_OR_PRINT ((bool) mongoc_bulk_operation_execute (bulk, &reply, &err), - err); + ASSERT_OR_PRINT ((bool) mongoc_bulk_operation_execute (bulk, &reply, &err), err); ASSERT_MATCH (&reply, "{'nInserted': 3," @@ -992,14 +933,11 @@ test_update_arrayfilters (void *ctx) ASSERT_COUNT (3, collection); - _test_docs_in_coll_matches ( - collection, tmp_bson ("{'_id':1}"), "{'a': [{'x':1}, {'x':3}]}", 1); + _test_docs_in_coll_matches (collection, tmp_bson ("{'_id':1}"), "{'a': [{'x':1}, {'x':3}]}", 1); - _test_docs_in_coll_matches ( - collection, tmp_bson ("{'_id':2}"), "{'a': [{'x':1}, {'x':4}]}", 1); + _test_docs_in_coll_matches (collection, tmp_bson ("{'_id':2}"), "{'a': [{'x':1}, {'x':4}]}", 1); - _test_docs_in_coll_matches ( - collection, tmp_bson ("{'_id':3}"), "{'a': [{'x':1}, {'x':4}]}", 1); + _test_docs_in_coll_matches (collection, tmp_bson ("{'_id':3}"), "{'a': [{'x':1}, {'x':4}]}", 1); ASSERT_OR_PRINT (mongoc_collection_drop (collection, &err), err); @@ -1040,15 +978,12 @@ test_update_hint_validate (void) opts = tmp_bson ("{'hint': []}"); } - bulk = - mongoc_collection_create_bulk_operation_with_opts (collection, NULL); + bulk = mongoc_collection_create_bulk_operation_with_opts (collection, NULL); ret = fns[i](bulk, tmp_bson ("{'_id': 1}"), document, opts, &err); BSON_ASSERT (!ret); - ASSERT_ERROR_CONTAINS (err, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "The hint option must be a string or document"); + ASSERT_ERROR_CONTAINS ( + err, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "The hint option must be a string or document"); mongoc_bulk_operation_destroy (bulk); } @@ -1081,15 +1016,12 @@ test_delete_hint_validate (void) opts = tmp_bson ("{'hint': []}"); - bulk = - mongoc_collection_create_bulk_operation_with_opts (collection, NULL); + bulk = mongoc_collection_create_bulk_operation_with_opts (collection, NULL); ret = fns[i](bulk, tmp_bson ("{'_id': 1}"), opts, &err); BSON_ASSERT (!ret); - ASSERT_ERROR_CONTAINS (err, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "The hint option must be a string or document"); + ASSERT_ERROR_CONTAINS ( + err, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "The hint option must be a string or document"); mongoc_bulk_operation_destroy (bulk); } @@ -1133,8 +1065,7 @@ test_replace_one (bool ordered) sel = tmp_bson ("{}"); doc = tmp_bson ("{'hello': 'there'}"); mongoc_bulk_operation_replace_one (bulk, sel, doc, true); - ASSERT_OR_PRINT ((bool) mongoc_bulk_operation_execute (bulk, &reply, &error), - error); + ASSERT_OR_PRINT ((bool) mongoc_bulk_operation_execute (bulk, &reply, &error), error); ASSERT_MATCH (&reply, "{'nInserted': 0," @@ -1174,8 +1105,7 @@ _test_replace_one_check_keys (bool with_opts) if (with_opts) { /* rejected immediately */ - r = mongoc_bulk_operation_replace_one_with_opts ( - bulk, tmp_bson ("{}"), tmp_bson ("{'$a': 1}"), NULL, &error); + r = mongoc_bulk_operation_replace_one_with_opts (bulk, tmp_bson ("{}"), tmp_bson ("{'$a': 1}"), NULL, &error); ASSERT (!r); ASSERT_ERROR_CONTAINS (error, @@ -1185,15 +1115,11 @@ _test_replace_one_check_keys (bool with_opts) r = (bool) mongoc_bulk_operation_execute (bulk, &reply, &error); ASSERT (!r); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "empty bulk write"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "empty bulk write"); } else { /* rejected during execute() */ capture_logs (true); - mongoc_bulk_operation_replace_one ( - bulk, tmp_bson ("{}"), tmp_bson ("{'$a': 1}"), true); + mongoc_bulk_operation_replace_one (bulk, tmp_bson ("{}"), tmp_bson ("{'$a': 1}"), true); r = (bool) mongoc_bulk_operation_execute (bulk, &reply, &error); ASSERT (!r); @@ -1238,35 +1164,24 @@ test_replace_one_with_opts_validate (void) collection = get_test_collection (client, "test_replace_with_opts_validate"); bulk = mongoc_collection_create_bulk_operation_with_opts (collection, NULL); + BSON_ASSERT ( + !mongoc_bulk_operation_replace_one_with_opts (bulk, tmp_bson ("{}"), tmp_bson ("{'$a': 1}"), NULL, &error)); + ASSERT_ERROR_CONTAINS ( + error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid key '$a': replace prohibits $ operators"); + BSON_ASSERT (!mongoc_bulk_operation_replace_one_with_opts ( - bulk, tmp_bson ("{}"), tmp_bson ("{'$a': 1}"), NULL, &error)); + bulk, tmp_bson ("{}"), tmp_bson ("{'a.a': 1}"), tmp_bson ("{'validate': %d}", BSON_VALIDATE_DOT_KEYS), &error)); ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, - "Invalid key '$a': replace prohibits $ operators"); - - BSON_ASSERT (!mongoc_bulk_operation_replace_one_with_opts ( - bulk, - tmp_bson ("{}"), - tmp_bson ("{'a.a': 1}"), - tmp_bson ("{'validate': %d}", BSON_VALIDATE_DOT_KEYS), - &error)); - ASSERT_ERROR_CONTAINS ( - error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "invalid argument for replace: keys cannot contain \".\": \"a.a\""); + "invalid argument for replace: keys cannot contain \".\": \"a.a\""); mongoc_bulk_operation_destroy (bulk); /* Test a valid replace_one with explicit validation on the server. */ bulk = mongoc_collection_create_bulk_operation_with_opts (collection, NULL); BSON_ASSERT (mongoc_bulk_operation_replace_one_with_opts ( - bulk, - tmp_bson ("{}"), - tmp_bson ("{'a': 1}"), - tmp_bson ("{'validate': %d}", BSON_VALIDATE_DOT_KEYS), - &error)); + bulk, tmp_bson ("{}"), tmp_bson ("{'a': 1}"), tmp_bson ("{'validate': %d}", BSON_VALIDATE_DOT_KEYS), &error)); ASSERT_OR_PRINT (mongoc_bulk_operation_execute (bulk, NULL, &error), error); mongoc_bulk_operation_destroy (bulk); @@ -1311,8 +1226,7 @@ test_upsert_large (void *ctx) mongoc_bulk_operation_update (bulk, selector, &update, true); } - ASSERT_OR_PRINT ((bool) mongoc_bulk_operation_execute (bulk, &reply, &error), - error); + ASSERT_OR_PRINT ((bool) mongoc_bulk_operation_execute (bulk, &reply, &error), error); ASSERT_MATCH (&reply, "{'nInserted': 0," @@ -1362,16 +1276,11 @@ test_upsert_huge (void *ctx) BSON_ASSERT (bulk); bson_append_document_begin (&doc, "$set", -1, &child); - BSON_ASSERT (bson_append_utf8 (&child, - "x", - -1, - huge_string (client), - (int) huge_string_length (client))); + BSON_ASSERT (bson_append_utf8 (&child, "x", -1, huge_string (client), (int) huge_string_length (client))); bson_append_document_end (&doc, &child); mongoc_bulk_operation_update (bulk, sel, &doc, true); - ASSERT_OR_PRINT ((bool) mongoc_bulk_operation_execute (bulk, &reply, &error), - error); + ASSERT_OR_PRINT ((bool) mongoc_bulk_operation_execute (bulk, &reply, &error), error); ASSERT_MATCH (&reply, "{'nInserted': 0," @@ -1439,8 +1348,7 @@ test_update (bool ordered) BSON_ASSERT (collection); for (i = 0; i < sizeof docs_inserted / sizeof (bson_t *); i++) { - BSON_ASSERT (mongoc_collection_insert_one ( - collection, docs_inserted[i], NULL, NULL, NULL)); + BSON_ASSERT (mongoc_collection_insert_one (collection, docs_inserted[i], NULL, NULL, NULL)); } bson_append_bool (&opts, "ordered", 7, ordered); @@ -1453,11 +1361,10 @@ test_update (bool ordered) mongoc_bulk_operation_update (bulk, sel, bad_update_doc, false); BSON_ASSERT (!mongoc_bulk_operation_execute (bulk, &reply, &error)); - ASSERT_ERROR_CONTAINS ( - error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Invalid key 'foo': update only works with $ operators"); + ASSERT_ERROR_CONTAINS (error, + MONGOC_ERROR_COMMAND, + MONGOC_ERROR_COMMAND_INVALID_ARG, + "Invalid key 'foo': update only works with $ operators"); BSON_ASSERT (bson_empty (&reply)); mongoc_bulk_operation_destroy (bulk); @@ -1466,8 +1373,7 @@ test_update (bool ordered) bulk = mongoc_collection_create_bulk_operation_with_opts (collection, &opts); update_doc = tmp_bson ("{'$set': {'foo': 'bar'}}"); mongoc_bulk_operation_update (bulk, sel, update_doc, false); - ASSERT_OR_PRINT (mongoc_bulk_operation_execute (bulk, &reply, &error), - error); + ASSERT_OR_PRINT (mongoc_bulk_operation_execute (bulk, &reply, &error), error); ASSERT_MATCH (&reply, "{'nInserted': 0," @@ -1531,25 +1437,19 @@ _test_update_check_keys (bool many, bool with_opts) if (with_opts) { /* document is rejected immediately */ if (many) { - r = mongoc_bulk_operation_update_many_with_opts ( - bulk, q, u, NULL, &error); + r = mongoc_bulk_operation_update_many_with_opts (bulk, q, u, NULL, &error); } else { - r = mongoc_bulk_operation_update_one_with_opts ( - bulk, q, u, NULL, &error); + r = mongoc_bulk_operation_update_one_with_opts (bulk, q, u, NULL, &error); } BSON_ASSERT (!r); - ASSERT_ERROR_CONTAINS ( - error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Invalid key 'a': update only works with $ operators"); - - r = (bool) mongoc_bulk_operation_execute (bulk, &reply, &error); - BSON_ASSERT (!r); ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, - "empty bulk"); + "Invalid key 'a': update only works with $ operators"); + + r = (bool) mongoc_bulk_operation_execute (bulk, &reply, &error); + BSON_ASSERT (!r); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "empty bulk"); } else { /* document rejected when bulk op is executed */ if (many) { @@ -1559,11 +1459,10 @@ _test_update_check_keys (bool many, bool with_opts) } r = (bool) mongoc_bulk_operation_execute (bulk, &reply, &error); BSON_ASSERT (!r); - ASSERT_ERROR_CONTAINS ( - error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Invalid key 'a': update only works with $ operators"); + ASSERT_ERROR_CONTAINS (error, + MONGOC_ERROR_COMMAND, + MONGOC_ERROR_COMMAND_INVALID_ARG, + "Invalid key 'a': update only works with $ operators"); } BSON_ASSERT (bson_empty (&reply)); @@ -1641,10 +1540,7 @@ _test_update_validate (update_validate_test_t *test) /* document is rejected immediately */ r = test->update_with_opts (bulk, q, bad_update, NULL, &error); BSON_ASSERT (!r); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - test->error_message); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, test->error_message); /* now a valid document */ r = test->update_with_opts (bulk, q, good_update, NULL, &error); @@ -1661,10 +1557,7 @@ _test_update_validate (update_validate_test_t *test) /* invalid document is rejected without invalidating batch */ r = test->update_with_opts (bulk, q, bad_update, NULL, &error); BSON_ASSERT (!r); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - test->error_message); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, test->error_message); ASSERT_CMPSIZE_T ((size_t) 1, ==, bulk->commands.len); r = (bool) mongoc_bulk_operation_execute (bulk, &reply, &error); @@ -1684,10 +1577,7 @@ _test_update_validate (update_validate_test_t *test) r = (bool) mongoc_bulk_operation_execute (bulk, &reply, &error); BSON_ASSERT (!r); BSON_ASSERT (bson_empty (&reply)); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - test->error_message); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, test->error_message); } else { /* valid, then invalid */ test->update (bulk, q, good_update, false); @@ -1699,10 +1589,7 @@ _test_update_validate (update_validate_test_t *test) r = (bool) mongoc_bulk_operation_execute (bulk, &reply, &error); BSON_ASSERT (!r); BSON_ASSERT (bson_empty (&reply)); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - test->error_message); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, test->error_message); } } @@ -1903,24 +1790,20 @@ _test_insert_invalid (bool with_opts, bool invalid_first) client = test_framework_new_default_client (); collection = get_test_collection (client, "test_insert_validate"); bulk = mongoc_collection_create_bulk_operation_with_opts (collection, NULL); - BSON_ASSERT (mongoc_collection_delete_many ( - collection, tmp_bson (NULL), NULL, NULL, NULL)); + BSON_ASSERT (mongoc_collection_delete_many (collection, tmp_bson (NULL), NULL, NULL, NULL)); capture_logs (true); if (with_opts) { if (invalid_first) { /* document is rejected immediately */ - r = mongoc_bulk_operation_insert_with_opts ( - bulk, bad_insert, NULL, &error); + r = mongoc_bulk_operation_insert_with_opts (bulk, bad_insert, NULL, &error); BSON_ASSERT (!r); - ASSERT_ERROR_CONTAINS ( - error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, err); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, err); /* now a valid document */ - r = mongoc_bulk_operation_insert_with_opts ( - bulk, good_insert, NULL, &error); + r = mongoc_bulk_operation_insert_with_opts (bulk, good_insert, NULL, &error); ASSERT_OR_PRINT (r, error); ASSERT_CMPSIZE_T ((size_t) 1, ==, bulk->commands.len); r = (bool) mongoc_bulk_operation_execute (bulk, &reply, &error); @@ -1928,16 +1811,13 @@ _test_insert_invalid (bool with_opts, bool invalid_first) BSON_ASSERT (!bson_empty (&reply)); } else { /* first a valid document */ - r = mongoc_bulk_operation_insert_with_opts ( - bulk, good_insert, NULL, &error); + r = mongoc_bulk_operation_insert_with_opts (bulk, good_insert, NULL, &error); ASSERT_OR_PRINT (r, error); /* invalid document is rejected without invalidating batch */ - r = mongoc_bulk_operation_insert_with_opts ( - bulk, bad_insert, NULL, &error); + r = mongoc_bulk_operation_insert_with_opts (bulk, bad_insert, NULL, &error); BSON_ASSERT (!r); - ASSERT_ERROR_CONTAINS ( - error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, err); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, err); ASSERT_CMPSIZE_T ((size_t) 1, ==, bulk->commands.len); r = (bool) mongoc_bulk_operation_execute (bulk, &reply, &error); @@ -1957,8 +1837,7 @@ _test_insert_invalid (bool with_opts, bool invalid_first) r = (bool) mongoc_bulk_operation_execute (bulk, &reply, &error); BSON_ASSERT (!r); BSON_ASSERT (bson_empty (&reply)); - ASSERT_ERROR_CONTAINS ( - error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, err); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, err); } else { /* valid, then invalid */ mongoc_bulk_operation_insert (bulk, good_insert); @@ -1970,8 +1849,7 @@ _test_insert_invalid (bool with_opts, bool invalid_first) r = (bool) mongoc_bulk_operation_execute (bulk, &reply, &error); BSON_ASSERT (!r); BSON_ASSERT (bson_empty (&reply)); - ASSERT_ERROR_CONTAINS ( - error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, err); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, err); } } @@ -2022,46 +1900,29 @@ test_insert_with_opts_validate (void) collection = get_test_collection (client, "test_insert_with_opts_validate"); bulk = mongoc_collection_create_bulk_operation_with_opts (collection, NULL); - BSON_ASSERT (!mongoc_bulk_operation_insert_with_opts ( - bulk, tmp_bson ("{'': 1}"), NULL, &error)); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "empty key"); + BSON_ASSERT (!mongoc_bulk_operation_insert_with_opts (bulk, tmp_bson ("{'': 1}"), NULL, &error)); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "empty key"); ASSERT_OR_PRINT (mongoc_bulk_operation_insert_with_opts ( - bulk, - tmp_bson ("{'': 1}"), - tmp_bson ("{'validate': %d}", BSON_VALIDATE_NONE), - &error), + bulk, tmp_bson ("{'': 1}"), tmp_bson ("{'validate': %d}", BSON_VALIDATE_NONE), &error), error); ASSERT_OR_PRINT (mongoc_bulk_operation_insert_with_opts ( - bulk, - tmp_bson ("{'': 1}"), - tmp_bson ("{'validate': %d}", BSON_VALIDATE_UTF8), - &error), + bulk, tmp_bson ("{'': 1}"), tmp_bson ("{'validate': %d}", BSON_VALIDATE_UTF8), &error), error); ASSERT_OR_PRINT (!mongoc_bulk_operation_insert_with_opts ( - bulk, - tmp_bson ("{'a.a': 1}"), - tmp_bson ("{'validate': %d}", BSON_VALIDATE_DOT_KEYS), - &error), + bulk, tmp_bson ("{'a.a': 1}"), tmp_bson ("{'validate': %d}", BSON_VALIDATE_DOT_KEYS), &error), error); - ASSERT_ERROR_CONTAINS ( - error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "invalid document for insert: keys cannot contain \".\": \"a.a\""); + ASSERT_ERROR_CONTAINS (error, + MONGOC_ERROR_COMMAND, + MONGOC_ERROR_COMMAND_INVALID_ARG, + "invalid document for insert: keys cannot contain \".\": \"a.a\""); mongoc_bulk_operation_destroy (bulk); /* Test a valid insert with explicit validation on the server. */ bulk = mongoc_collection_create_bulk_operation_with_opts (collection, NULL); BSON_ASSERT (mongoc_bulk_operation_insert_with_opts ( - bulk, - tmp_bson ("{'a': 1}"), - tmp_bson ("{'validate': %d}", BSON_VALIDATE_DOT_KEYS), - &error)); + bulk, tmp_bson ("{'a': 1}"), tmp_bson ("{'validate': %d}", BSON_VALIDATE_DOT_KEYS), &error)); ASSERT_OR_PRINT (mongoc_bulk_operation_execute (bulk, NULL, &error), error); mongoc_bulk_operation_destroy (bulk); @@ -2070,8 +1931,7 @@ test_insert_with_opts_validate (void) } -typedef void (*remove_fn) (mongoc_bulk_operation_t *bulk, - const bson_t *selector); +typedef void (*remove_fn) (mongoc_bulk_operation_t *bulk, const bson_t *selector); typedef struct { remove_fn remove; @@ -2121,10 +1981,8 @@ _test_remove_validate (remove_validate_test_t *test) r = (bool) mongoc_bulk_operation_execute (bulk, &reply, &error); BSON_ASSERT (!r); BSON_ASSERT (bson_empty (&reply)); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "invalid document for insert: empty key"); + ASSERT_ERROR_CONTAINS ( + error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "invalid document for insert: empty key"); bson_destroy (&reply); mongoc_bulk_operation_destroy (bulk); @@ -2198,8 +2056,7 @@ test_index_offset (void) mongoc_bulk_operation_remove_one (bulk, sel); mongoc_bulk_operation_update (bulk, sel, doc, true); - ASSERT_OR_PRINT (mongoc_bulk_operation_execute (bulk, &reply, &error), - error); + ASSERT_OR_PRINT (mongoc_bulk_operation_execute (bulk, &reply, &error), error); ASSERT_MATCH (&reply, "{'nInserted': 0," @@ -2241,14 +2098,11 @@ test_single_ordered_bulk (void) BSON_ASSERT (bulk); mongoc_bulk_operation_insert (bulk, tmp_bson ("{'a': 1}")); - mongoc_bulk_operation_update ( - bulk, tmp_bson ("{'a': 1}"), tmp_bson ("{'$set': {'b': 1}}"), false); - mongoc_bulk_operation_update ( - bulk, tmp_bson ("{'a': 2}"), tmp_bson ("{'$set': {'b': 2}}"), true); + mongoc_bulk_operation_update (bulk, tmp_bson ("{'a': 1}"), tmp_bson ("{'$set': {'b': 1}}"), false); + mongoc_bulk_operation_update (bulk, tmp_bson ("{'a': 2}"), tmp_bson ("{'$set': {'b': 2}}"), true); mongoc_bulk_operation_insert (bulk, tmp_bson ("{'a': 3}")); mongoc_bulk_operation_remove (bulk, tmp_bson ("{'a': 3}")); - ASSERT_OR_PRINT ((bool) mongoc_bulk_operation_execute (bulk, &reply, &error), - error); + ASSERT_OR_PRINT ((bool) mongoc_bulk_operation_execute (bulk, &reply, &error), error); ASSERT_MATCH (&reply, "{'nInserted': 2," @@ -2343,14 +2197,11 @@ test_update_continue_on_error (void) bson_append_bool (&opts, "ordered", 7, false); bulk = mongoc_collection_create_bulk_operation_with_opts (collection, &opts); /* succeeds */ - mongoc_bulk_operation_update ( - bulk, doc0, tmp_bson ("{'$inc': {'b': 1}}"), false); + mongoc_bulk_operation_update (bulk, doc0, tmp_bson ("{'$inc': {'b': 1}}"), false); /* fails */ - mongoc_bulk_operation_update ( - bulk, doc0, tmp_bson ("{'$set': {'a': 2}}"), false); + mongoc_bulk_operation_update (bulk, doc0, tmp_bson ("{'$set': {'a': 2}}"), false); /* succeeds */ - mongoc_bulk_operation_update ( - bulk, doc1, tmp_bson ("{'$set': {'b': 2}}"), false); + mongoc_bulk_operation_update (bulk, doc1, tmp_bson ("{'$set': {'b': 2}}"), false); r = (bool) mongoc_bulk_operation_execute (bulk, &reply, &error); BSON_ASSERT (!r); @@ -2366,10 +2217,7 @@ test_update_continue_on_error (void) assert_write_error_count (1, &reply); ASSERT_COUNT (2, collection); ASSERT_CMPINT ( - 1, - ==, - (int) mongoc_collection_count_documents ( - collection, tmp_bson ("{'b': 2}"), NULL, NULL, NULL, NULL)); + 1, ==, (int) mongoc_collection_count_documents (collection, tmp_bson ("{'b': 2}"), NULL, NULL, NULL, NULL)); bson_destroy (&reply); mongoc_bulk_operation_destroy (bulk); @@ -2455,8 +2303,7 @@ test_single_error_ordered_bulk (void) bulk = mongoc_collection_create_bulk_operation_with_opts (collection, NULL); BSON_ASSERT (bulk); mongoc_bulk_operation_insert (bulk, tmp_bson ("{'b': 1, 'a': 1}")); - mongoc_bulk_operation_update ( - bulk, tmp_bson ("{'b': 2}"), tmp_bson ("{'$set': {'a': 1}}"), true); + mongoc_bulk_operation_update (bulk, tmp_bson ("{'b': 2}"), tmp_bson ("{'$set': {'a': 1}}"), true); mongoc_bulk_operation_insert (bulk, tmp_bson ("{'b': 3, 'a': 2}")); r = (bool) mongoc_bulk_operation_execute (bulk, &reply, &error); @@ -2501,8 +2348,7 @@ test_multiple_error_ordered_bulk (void) client = test_framework_new_default_client (); BSON_ASSERT (client); - collection = - get_test_collection (client, "test_multiple_error_ordered_bulk"); + collection = get_test_collection (client, "test_multiple_error_ordered_bulk"); BSON_ASSERT (collection); create_unique_index (collection); @@ -2513,11 +2359,9 @@ test_multiple_error_ordered_bulk (void) /* 0 succeeds */ mongoc_bulk_operation_insert (bulk, tmp_bson ("{'b': 1, 'a': 1}")); /* 1 succeeds */ - mongoc_bulk_operation_update ( - bulk, tmp_bson ("{'b': 3}"), tmp_bson ("{'$set': {'a': 2}}"), true); + mongoc_bulk_operation_update (bulk, tmp_bson ("{'b': 3}"), tmp_bson ("{'$set': {'a': 2}}"), true); /* 2 fails, duplicate value for 'a' */ - mongoc_bulk_operation_update ( - bulk, tmp_bson ("{'b': 2}"), tmp_bson ("{'$set': {'a': 1}}"), true); + mongoc_bulk_operation_update (bulk, tmp_bson ("{'b': 2}"), tmp_bson ("{'$set': {'a': 1}}"), true); /* 3 not attempted, bulk is already aborted */ mongoc_bulk_operation_insert (bulk, tmp_bson ("{'b': 4, 'a': 3}")); @@ -2570,14 +2414,11 @@ test_single_unordered_bulk (void) bson_append_bool (&opts, "ordered", 7, false); bulk = mongoc_collection_create_bulk_operation_with_opts (collection, &opts); mongoc_bulk_operation_insert (bulk, tmp_bson ("{'a': 1}")); - mongoc_bulk_operation_update ( - bulk, tmp_bson ("{'a': 1}"), tmp_bson ("{'$set': {'b': 1}}"), false); - mongoc_bulk_operation_update ( - bulk, tmp_bson ("{'a': 2}"), tmp_bson ("{'$set': {'b': 2}}"), true); + mongoc_bulk_operation_update (bulk, tmp_bson ("{'a': 1}"), tmp_bson ("{'$set': {'b': 1}}"), false); + mongoc_bulk_operation_update (bulk, tmp_bson ("{'a': 2}"), tmp_bson ("{'$set': {'b': 2}}"), true); mongoc_bulk_operation_insert (bulk, tmp_bson ("{'a': 3}")); mongoc_bulk_operation_remove (bulk, tmp_bson ("{'a': 3}")); - ASSERT_OR_PRINT ((bool) mongoc_bulk_operation_execute (bulk, &reply, &error), - error); + ASSERT_OR_PRINT ((bool) mongoc_bulk_operation_execute (bulk, &reply, &error), error); ASSERT_MATCH (&reply, "{'nInserted': 2," @@ -2612,8 +2453,7 @@ test_single_error_unordered_bulk (void) client = test_framework_new_default_client (); BSON_ASSERT (client); - collection = - get_test_collection (client, "test_single_error_unordered_bulk"); + collection = get_test_collection (client, "test_single_error_unordered_bulk"); BSON_ASSERT (collection); create_unique_index (collection); @@ -2624,8 +2464,7 @@ test_single_error_unordered_bulk (void) /* 0 succeeds */ mongoc_bulk_operation_insert (bulk, tmp_bson ("{'b': 1, 'a': 1}")); /* 1 fails */ - mongoc_bulk_operation_update ( - bulk, tmp_bson ("{'b': 2}"), tmp_bson ("{'$set': {'a': 1}}"), true); + mongoc_bulk_operation_update (bulk, tmp_bson ("{'b': 2}"), tmp_bson ("{'$set': {'a': 1}}"), true); /* 2 succeeds */ mongoc_bulk_operation_insert (bulk, tmp_bson ("{'b': 3, 'a': 2}")); r = (bool) mongoc_bulk_operation_execute (bulk, &reply, &error); @@ -2679,16 +2518,8 @@ _test_oversized_bulk_op (bool ordered) /* this fails, aborting bulk, even if it's unordered */ huge_doc = BCON_NEW ("a", BCON_INT32 (1)); - bson_append_utf8 (huge_doc, - "b", - -1, - huge_string (client), - (int) huge_string_length (client)); - bson_append_utf8 (huge_doc, - "c", - -1, - huge_string (client), - (int) huge_string_length (client)); + bson_append_utf8 (huge_doc, "b", -1, huge_string (client), (int) huge_string_length (client)); + bson_append_utf8 (huge_doc, "c", -1, huge_string (client), (int) huge_string_length (client)); mongoc_bulk_operation_insert (bulk, huge_doc); /* would succeed if it ran */ @@ -2696,10 +2527,7 @@ _test_oversized_bulk_op (bool ordered) r = (bool) mongoc_bulk_operation_execute (bulk, &reply, &error); BSON_ASSERT (!r); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_BSON, - MONGOC_ERROR_BSON_INVALID, - "Document 0 is too large"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "Document 0 is too large"); ASSERT_MATCH (&reply, "{'nInserted': 0," @@ -2756,8 +2584,7 @@ _test_write_concern (bool ordered, bool multi_err) mock_server = mock_server_with_auto_hello (WIRE_VERSION_MIN); mock_server_run (mock_server); - client = test_framework_client_new_from_uri ( - mock_server_get_uri (mock_server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (mock_server), NULL); collection = mongoc_client_get_collection (client, "test", "test"); wc = mongoc_write_concern_new (); mongoc_write_concern_set_w (wc, 2); @@ -2770,38 +2597,34 @@ _test_write_concern (bool ordered, bool multi_err) future = future_bulk_operation_execute (bulk, &reply, &error); - request = mock_server_receives_msg ( - mock_server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'test'," - " 'insert': 'test'," - " 'writeConcern': {'w': 2, 'wtimeout': {'$numberLong': '100'}}," - " 'ordered': %s}", - ordered ? "true" : "false"), - tmp_bson ("{'_id': 1}")); + request = mock_server_receives_msg (mock_server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'test'," + " 'insert': 'test'," + " 'writeConcern': {'w': 2, 'wtimeout': {'$numberLong': '100'}}," + " 'ordered': %s}", + ordered ? "true" : "false"), + tmp_bson ("{'_id': 1}")); BSON_ASSERT (request); - reply_to_request_simple ( - request, - "{'ok': 1.0, 'n': 1, " - " 'writeConcernError': {'code': 17, 'errmsg': 'foo'}}"); + reply_to_request_simple (request, + "{'ok': 1.0, 'n': 1, " + " 'writeConcernError': {'code': 17, 'errmsg': 'foo'}}"); request_destroy (request); - request = mock_server_receives_msg ( - mock_server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'test'," - " 'delete': 'test'," - " 'writeConcern': {'w': 2, 'wtimeout': {'$numberLong': '100'}}," - " 'ordered': %s}", - ordered ? "true" : "false"), - tmp_bson ("{'q': {'_id': 2}, 'limit': 0}")); + request = mock_server_receives_msg (mock_server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'test'," + " 'delete': 'test'," + " 'writeConcern': {'w': 2, 'wtimeout': {'$numberLong': '100'}}," + " 'ordered': %s}", + ordered ? "true" : "false"), + tmp_bson ("{'q': {'_id': 2}, 'limit': 0}")); if (multi_err) { - reply_to_request_simple ( - request, - "{'ok': 1.0, 'n': 1, " - " 'writeConcernError': {'code': 42, 'errmsg': 'bar'}}"); + reply_to_request_simple (request, + "{'ok': 1.0, 'n': 1, " + " 'writeConcernError': {'code': 42, 'errmsg': 'bar'}}"); } else { reply_to_request_simple (request, "{'ok': 1.0, 'n': 1}"); } @@ -2828,8 +2651,7 @@ _test_write_concern (bool ordered, bool multi_err) first_err, second_err); - ASSERT_CMPSTR ("Multiple write concern errors: \"foo\", \"bar\"", - error.message); + ASSERT_CMPSTR ("Multiple write concern errors: \"foo\", \"bar\"", error.message); } else { ASSERT_MATCH (&reply, "{'nInserted': 1," @@ -2922,12 +2744,10 @@ test_unordered_bulk_writes_with_error (void) collection = mongoc_client_get_collection (client, "db", "test"); /* use an unordered bulk write; we expect to continue on error */ - bulk = mongoc_collection_create_bulk_operation_with_opts ( - collection, tmp_bson ("{'ordered': false}")); + bulk = mongoc_collection_create_bulk_operation_with_opts (collection, tmp_bson ("{'ordered': false}")); /* maxWriteBatchSize is set to 1; with 2 inserts we get a batch split */ for (i = 0; i < 2; i++) { - mongoc_bulk_operation_insert_with_opts ( - bulk, tmp_bson ("{'_id': %d}", i), NULL, &error); + mongoc_bulk_operation_insert_with_opts (bulk, tmp_bson ("{'_id': %d}", i), NULL, &error); } future = future_bulk_operation_execute (bulk, &reply, &error); @@ -2969,8 +2789,7 @@ _test_write_concern_err_api (int32_t error_api_version) mock_server = mock_server_with_auto_hello (WIRE_VERSION_MIN); mock_server_run (mock_server); - client = test_framework_client_new_from_uri ( - mock_server_get_uri (mock_server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (mock_server), NULL); ASSERT (mongoc_client_set_error_api (client, error_api_version)); collection = mongoc_client_get_collection (client, "test", "test"); bulk = mongoc_collection_create_bulk_operation_with_opts (collection, NULL); @@ -2978,22 +2797,17 @@ _test_write_concern_err_api (int32_t error_api_version) future = future_bulk_operation_execute (bulk, &reply, &error); - request = - mock_server_receives_msg (mock_server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'test', 'insert': 'test'}"), - tmp_bson ("{'_id': 1}")); + request = mock_server_receives_msg ( + mock_server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'test', 'insert': 'test'}"), tmp_bson ("{'_id': 1}")); - reply_to_request_simple ( - request, - "{'ok': 1.0, 'n': 1, " - " 'writeConcernError': {'code': 42, 'errmsg': 'foo'}}"); + reply_to_request_simple (request, + "{'ok': 1.0, 'n': 1, " + " 'writeConcernError': {'code': 42, 'errmsg': 'foo'}}"); BSON_ASSERT (!future_get_uint32_t (future)); /* legacy write concern errs have no code from server, driver uses 64 */ expected_code = 42; - ASSERT_ERROR_CONTAINS ( - error, MONGOC_ERROR_WRITE_CONCERN, expected_code, "foo"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_WRITE_CONCERN, expected_code, "foo"); request_destroy (request); future_destroy (future); @@ -3033,8 +2847,7 @@ test_multiple_error_unordered_bulk (void) client = test_framework_new_default_client (); BSON_ASSERT (client); - collection = - get_test_collection (client, "test_multiple_error_unordered_bulk"); + collection = get_test_collection (client, "test_multiple_error_unordered_bulk"); BSON_ASSERT (collection); create_unique_index (collection); @@ -3042,12 +2855,9 @@ test_multiple_error_unordered_bulk (void) bson_append_bool (&opts, "ordered", 7, false); bulk = mongoc_collection_create_bulk_operation_with_opts (collection, &opts); mongoc_bulk_operation_insert (bulk, tmp_bson ("{'b': 1, 'a': 1}")); - mongoc_bulk_operation_update ( - bulk, tmp_bson ("{'b': 2}"), tmp_bson ("{'$set': {'a': 3}}"), true); - mongoc_bulk_operation_update ( - bulk, tmp_bson ("{'b': 3}"), tmp_bson ("{'$set': {'a': 4}}"), true); - mongoc_bulk_operation_update ( - bulk, tmp_bson ("{'b': 4}"), tmp_bson ("{'$set': {'a': 3}}"), true); + mongoc_bulk_operation_update (bulk, tmp_bson ("{'b': 2}"), tmp_bson ("{'$set': {'a': 3}}"), true); + mongoc_bulk_operation_update (bulk, tmp_bson ("{'b': 3}"), tmp_bson ("{'$set': {'a': 4}}"), true); + mongoc_bulk_operation_update (bulk, tmp_bson ("{'b': 4}"), tmp_bson ("{'$set': {'a': 3}}"), true); mongoc_bulk_operation_insert (bulk, tmp_bson ("{'b': 5, 'a': 2}")); mongoc_bulk_operation_insert (bulk, tmp_bson ("{'b': 6, 'a': 1}")); r = (bool) mongoc_bulk_operation_execute (bulk, &reply, &error); @@ -3105,8 +2915,7 @@ _test_wtimeout_plus_duplicate_key_err (void) mock_server = mock_server_with_auto_hello (WIRE_VERSION_MIN); mock_server_run (mock_server); - client = test_framework_client_new_from_uri ( - mock_server_get_uri (mock_server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (mock_server), NULL); collection = mongoc_client_get_collection (client, "test", "test"); /* unordered bulk */ @@ -3117,36 +2926,33 @@ _test_wtimeout_plus_duplicate_key_err (void) mongoc_bulk_operation_remove (bulk, tmp_bson ("{'_id': 3}")); future = future_bulk_operation_execute (bulk, &reply, &error); - request = - mock_server_receives_msg (mock_server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'test'," - " 'insert': 'test'," - " 'writeConcern': {'$exists': false}," - " 'ordered': false}"), - tmp_bson ("{'_id': 1}"), - tmp_bson ("{'_id': 2}")); + request = mock_server_receives_msg (mock_server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'test'," + " 'insert': 'test'," + " 'writeConcern': {'$exists': false}," + " 'ordered': false}"), + tmp_bson ("{'_id': 1}"), + tmp_bson ("{'_id': 2}")); BSON_ASSERT (request); - reply_to_request ( - request, - 0, - 0, - 0, - 1, - "{'ok': 1.0, 'n': 1," - " 'writeErrors': [{'index': 0, 'code': 11000, 'errmsg': 'dupe'}]," - " 'writeConcernError': {'code': 17, 'errmsg': 'foo'}}"); + reply_to_request (request, + 0, + 0, + 0, + 1, + "{'ok': 1.0, 'n': 1," + " 'writeErrors': [{'index': 0, 'code': 11000, 'errmsg': 'dupe'}]," + " 'writeConcernError': {'code': 17, 'errmsg': 'foo'}}"); request_destroy (request); - request = - mock_server_receives_msg (mock_server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'test'," - " 'delete': 'test'," - " 'writeConcern': {'$exists': false}," - " 'ordered': false}"), - tmp_bson ("{'q': {'_id': 3}, 'limit': 0}")); + request = mock_server_receives_msg (mock_server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'test'," + " 'delete': 'test'," + " 'writeConcern': {'$exists': false}," + " 'ordered': false}"), + tmp_bson ("{'q': {'_id': 3}, 'limit': 0}")); BSON_ASSERT (request); reply_to_request (request, @@ -3216,11 +3022,8 @@ test_large_inserts_ordered (void *ctx) BSON_ASSERT (client); huge_doc = BCON_NEW ("a", BCON_INT32 (1)); - bson_append_utf8 (huge_doc, - "long-key-to-make-this-fail", - -1, - huge_string (client), - (int) huge_string_length (client)); + bson_append_utf8 ( + huge_doc, "long-key-to-make-this-fail", -1, huge_string (client), (int) huge_string_length (client)); collection = get_test_collection (client, "test_large_inserts_ordered"); BSON_ASSERT (collection); @@ -3249,8 +3052,7 @@ test_large_inserts_ordered (void *ctx) ASSERT_CURSOR_DONE (cursor); bson_destroy (&query); - mongoc_collection_delete_many ( - collection, tmp_bson ("{}"), NULL, NULL, NULL); + mongoc_collection_delete_many (collection, tmp_bson ("{}"), NULL, NULL, NULL); bson_destroy (&reply); mongoc_bulk_operation_destroy (bulk); @@ -3266,8 +3068,7 @@ test_large_inserts_ordered (void *ctx) mongoc_bulk_operation_insert (bulk, big_doc); } - ASSERT_OR_PRINT ((bool) mongoc_bulk_operation_execute (bulk, &reply, &error), - error); + ASSERT_OR_PRINT ((bool) mongoc_bulk_operation_execute (bulk, &reply, &error), error); assert_n_inserted (6, &reply); ASSERT_COUNT (6, collection); @@ -3304,11 +3105,8 @@ test_large_inserts_unordered (void *ctx) BSON_ASSERT (client); huge_doc = BCON_NEW ("a", BCON_INT32 (1)); - bson_append_utf8 (huge_doc, - "long-key-to-make-this-fail", - -1, - huge_string (client), - (int) huge_string_length (client)); + bson_append_utf8 ( + huge_doc, "long-key-to-make-this-fail", -1, huge_string (client), (int) huge_string_length (client)); collection = get_test_collection (client, "test_large_inserts_unordered"); BSON_ASSERT (collection); @@ -3344,8 +3142,7 @@ test_large_inserts_unordered (void *ctx) ASSERT_CURSOR_DONE (cursor); bson_destroy (&query); - mongoc_collection_delete_many ( - collection, tmp_bson ("{}"), NULL, NULL, NULL); + mongoc_collection_delete_many (collection, tmp_bson ("{}"), NULL, NULL, NULL); bson_destroy (&reply); mongoc_bulk_operation_destroy (bulk); @@ -3361,8 +3158,7 @@ test_large_inserts_unordered (void *ctx) mongoc_bulk_operation_insert (bulk, big_doc); } - ASSERT_OR_PRINT ((bool) mongoc_bulk_operation_execute (bulk, &reply, &error), - error); + ASSERT_OR_PRINT ((bool) mongoc_bulk_operation_execute (bulk, &reply, &error), error); assert_n_inserted (6, &reply); ASSERT_COUNT (6, collection); @@ -3377,9 +3173,7 @@ test_large_inserts_unordered (void *ctx) static void -execute_numerous_bulk_op (mock_server_t *server, - mongoc_bulk_operation_t *bulk, - const char *doc_json) +execute_numerous_bulk_op (mock_server_t *server, mongoc_bulk_operation_t *bulk, const char *doc_json) { bson_error_t error; future_t *future; @@ -3432,32 +3226,26 @@ _test_numerous (bool ordered) mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); collection = mongoc_client_get_collection (client, "db", "collection"); -#define TEST_NUMEROUS(_one_write, _doc_format) \ - do { \ - bulk = \ - mongoc_collection_create_bulk_operation_with_opts (collection, opts); \ - for (i = 0; i < 7; i++) { \ - mongoc_bulk_operation_##_one_write; \ - } \ - execute_numerous_bulk_op (server, bulk, _doc_format); \ - mongoc_bulk_operation_destroy (bulk); \ +#define TEST_NUMEROUS(_one_write, _doc_format) \ + do { \ + bulk = mongoc_collection_create_bulk_operation_with_opts (collection, opts); \ + for (i = 0; i < 7; i++) { \ + mongoc_bulk_operation_##_one_write; \ + } \ + execute_numerous_bulk_op (server, bulk, _doc_format); \ + mongoc_bulk_operation_destroy (bulk); \ } while (0) TEST_NUMEROUS (insert (bulk, doc), "{'_id': 1}"); - TEST_NUMEROUS (remove_many_with_opts (bulk, doc, NULL, NULL), - "{'q': {'_id': 1}, 'limit': 0}"); + TEST_NUMEROUS (remove_many_with_opts (bulk, doc, NULL, NULL), "{'q': {'_id': 1}, 'limit': 0}"); TEST_NUMEROUS (remove_one (bulk, doc), "{'q': {'_id': 1}, 'limit': 1}"); - TEST_NUMEROUS (replace_one (bulk, doc, tmp_bson ("{}"), false), - "{'q': {'_id': 1}, 'u': {}}"); - TEST_NUMEROUS ( - update_one (bulk, doc, tmp_bson ("{'$set': {'x': 1}}"), false), - "{'q': {'_id': 1}, 'u': {'$set': {'x': 1}}}"); - TEST_NUMEROUS (update_many_with_opts ( - bulk, doc, tmp_bson ("{'$set': {'x': 1}}"), NULL, NULL), + TEST_NUMEROUS (replace_one (bulk, doc, tmp_bson ("{}"), false), "{'q': {'_id': 1}, 'u': {}}"); + TEST_NUMEROUS (update_one (bulk, doc, tmp_bson ("{'$set': {'x': 1}}"), false), + "{'q': {'_id': 1}, 'u': {'$set': {'x': 1}}}"); + TEST_NUMEROUS (update_many_with_opts (bulk, doc, tmp_bson ("{'$set': {'x': 1}}"), NULL, NULL), "{'q': {'_id': 1}, 'u': {'$set': {'x': 1}}}"); mongoc_collection_destroy (collection); @@ -3537,10 +3325,8 @@ test_bulk_split (void *ctx) bson_append_bool (&opts, "ordered", 7, false); - ASSERT_OR_PRINT (mongoc_client_session_append (session, &opts, &error), - error); - bulk_op = - mongoc_collection_create_bulk_operation_with_opts (collection, &opts); + ASSERT_OR_PRINT (mongoc_client_session_append (session, &opts, &error), error); + bulk_op = mongoc_collection_create_bulk_operation_with_opts (collection, &opts); /* if n_docs is 100,010 insert 3337 docs with _ids 0, 3, 6, ..., 100,008 */ for (i = 0; i < n_docs; i += 3) { @@ -3558,8 +3344,7 @@ test_bulk_split (void *ctx) mongoc_bulk_operation_destroy (bulk_op); /* ordered false so we continue on error */ - bulk_op = - mongoc_collection_create_bulk_operation_with_opts (collection, &opts); + bulk_op = mongoc_collection_create_bulk_operation_with_opts (collection, &opts); /* insert n_docs documents with _ids 0, 1, 2, 3, ..., 100,008 */ for (i = 0; i < n_docs; i++) { bson_init (&doc); @@ -3577,14 +3362,9 @@ test_bulk_split (void *ctx) /* all 100,010 docs were inserted, either by the first or second bulk op */ { bson_t count_opts = BSON_INITIALIZER; - ASSERT_OR_PRINT ( - mongoc_client_session_append (session, &count_opts, &error), error); - int64_t count = mongoc_collection_count_documents (collection, - tmp_bson ("{}"), - &count_opts, - NULL /* read_prefs */, - NULL /* reply */, - &error); + ASSERT_OR_PRINT (mongoc_client_session_append (session, &count_opts, &error), error); + int64_t count = mongoc_collection_count_documents ( + collection, tmp_bson ("{}"), &count_opts, NULL /* read_prefs */, NULL /* reply */, &error); ASSERT_OR_PRINT (count != -1, error); ASSERT_CMPINT64 (count, ==, 100010); bson_destroy (&count_opts); @@ -3601,10 +3381,7 @@ test_bulk_split (void *ctx) BSON_ASSERT (bson_iter_recurse (&error_iter, &indexnum)); BSON_ASSERT (bson_iter_find (&indexnum, "index")); if (bson_iter_int32 (&indexnum) != i) { - fprintf (stderr, - "index should be %d, but is %d\n", - i, - bson_iter_int32 (&indexnum)); + fprintf (stderr, "index should be %d, but is %d\n", i, bson_iter_int32 (&indexnum)); } BSON_ASSERT (bson_iter_int32 (&indexnum) == i); bson_iter_next (&error_iter); @@ -3657,8 +3434,7 @@ test_bulk_edge_case_372 (bool ordered) update = tmp_bson ("{'_id': 2}"); mongoc_bulk_operation_replace_one (bulk, selector, update, true); - ASSERT_OR_PRINT (mongoc_bulk_operation_execute (bulk, &reply, &error), - error); + ASSERT_OR_PRINT (mongoc_bulk_operation_execute (bulk, &reply, &error), error); ASSERT_MATCH (&reply, "{'nInserted': 0," @@ -3673,8 +3449,7 @@ test_bulk_edge_case_372 (bool ordered) " ]," " 'writeErrors': []}"); - BSON_ASSERT (bson_iter_init_find (&iter, &reply, "upserted") && - BSON_ITER_HOLDS_ARRAY (&iter) && + BSON_ASSERT (bson_iter_init_find (&iter, &reply, "upserted") && BSON_ITER_HOLDS_ARRAY (&iter) && bson_iter_recurse (&iter, &citer)); bson_destroy (&reply); @@ -3715,8 +3490,7 @@ command_succeeded (const mongoc_apm_command_succeeded_t *event) const char *cmd_name = mongoc_apm_command_succeeded_get_command_name (event); if (!strcasecmp (cmd_name, "insert")) { - ((stats_t *) mongoc_apm_command_succeeded_get_context (event)) - ->succeeded++; + ((stats_t *) mongoc_apm_command_succeeded_get_context (event))->succeeded++; } } @@ -3756,22 +3530,19 @@ test_bulk_max_msg_size (void) /* Cluster time document argument is injected sometimes */ if (!bson_empty (&client->topology->_shared_descr_.ptr->cluster_time)) { - filler_string -= client->topology->_shared_descr_.ptr->cluster_time.len + - strlen ("$clusterTime") + 2u; + filler_string -= client->topology->_shared_descr_.ptr->cluster_time.len + strlen ("$clusterTime") + 2u; } /* API version may be appended */ if (client->api) { filler_string -= strlen ("apiVersion") + 7u + - strlen (mongoc_server_api_version_to_string ( - mongoc_server_api_get_version (client->api))); + strlen (mongoc_server_api_version_to_string (mongoc_server_api_get_version (client->api))); } cs = mongoc_client_start_session (client, NULL, NULL); if (cs) { /* sessions are supported */ - filler_string -= - mongoc_client_session_get_lsid (cs)->len + strlen ("lsid") + 2u; + filler_string -= mongoc_client_session_get_lsid (cs)->len + strlen ("lsid") + 2u; /* TODO: this check can be removed once CDRIVER-3070 is resolved */ if (test_framework_is_mongos () || test_framework_is_replset ()) { @@ -4086,12 +3857,10 @@ test_bulk_write_concern_split (void *unused) ASSERT_OR_PRINT (success, error); /* wait for bulk insert to complete on this connection */ - r = mongoc_client_command_simple ( - client, "test", tmp_bson ("{'getlasterror': 1}"), NULL, &reply, &error); + r = mongoc_client_command_simple (client, "test", tmp_bson ("{'getlasterror': 1}"), NULL, &reply, &error); ASSERT_OR_PRINT (r, error); - if (bson_iter_init_find (&iter, &reply, "err") && - BSON_ITER_HOLDS_UTF8 (&iter)) { + if (bson_iter_init_find (&iter, &reply, "err") && BSON_ITER_HOLDS_UTF8 (&iter)) { test_error ("%s", bson_iter_utf8 (&iter, NULL)); } @@ -4114,8 +3883,7 @@ server_id_for_read_mode (mongoc_client_t *client, mongoc_read_mode_t read_mode) ASSERT (client); prefs = mongoc_read_prefs_new (read_mode); - sd = mongoc_topology_select ( - client->topology, MONGOC_SS_READ, prefs, NULL, &error); + sd = mongoc_topology_select (client->topology, MONGOC_SS_READ, prefs, NULL, &error); ASSERT_OR_PRINT (sd, error); server_id = sd->id; @@ -4147,8 +3915,7 @@ _test_bulk_hint (bool pooled, bool use_primary) mock_rs_run (rs); if (pooled) { - pool = - test_framework_client_pool_new_from_uri (mock_rs_get_uri (rs), NULL); + pool = test_framework_client_pool_new_from_uri (mock_rs_get_uri (rs), NULL); client = mongoc_client_pool_pop (pool); } else { client = test_framework_client_new_from_uri (mock_rs_get_uri (rs), NULL); @@ -4156,12 +3923,7 @@ _test_bulk_hint (bool pooled, bool use_primary) /* warm up the client so its server_id is valid */ ret = mongoc_client_command_simple ( - client, - "admin", - tmp_bson ("{'" HANDSHAKE_CMD_LEGACY_HELLO "': 1}"), - NULL, - NULL, - &error); + client, "admin", tmp_bson ("{'" HANDSHAKE_CMD_LEGACY_HELLO "': 1}"), NULL, NULL, &error); ASSERT_OR_PRINT (ret, error); collection = mongoc_client_get_collection (client, "test", "test"); @@ -4178,11 +3940,8 @@ _test_bulk_hint (bool pooled, bool use_primary) mongoc_bulk_operation_insert (bulk, tmp_bson ("{'_id': 1}")); future = future_bulk_operation_execute (bulk, &reply, &error); - request = - mock_rs_receives_msg (rs, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'test', 'insert': 'test'}"), - tmp_bson ("{'_id': 1}")); + request = mock_rs_receives_msg ( + rs, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'test', 'insert': 'test'}"), tmp_bson ("{'_id': 1}")); BSON_ASSERT (request); reply_to_request_simple (request, "{'ok': 1.0, 'n': 1}"); @@ -4241,13 +4000,8 @@ static bool test_bulk_reply_w0_finished (mongoc_collection_t *coll) { bson_error_t error; - int64_t count = - mongoc_collection_count_documents (coll, - tmp_bson ("{'finished': true}"), - NULL /* opts */, - NULL /* read_prefs */, - NULL /* reply */, - &error); + int64_t count = mongoc_collection_count_documents ( + coll, tmp_bson ("{'finished': true}"), NULL /* opts */, NULL /* read_prefs */, NULL /* reply */, &error); ASSERT_OR_PRINT (-1 != count, error); return count == 1; } @@ -4270,13 +4024,11 @@ test_bulk_reply_w0 (void) mongoc_write_concern_append (wc, &opts); bulk = mongoc_collection_create_bulk_operation_with_opts (collection, &opts); mongoc_bulk_operation_insert (bulk, tmp_bson ("{}")); - mongoc_bulk_operation_update ( - bulk, tmp_bson ("{}"), tmp_bson ("{'$set': {'x': 1}}"), false); + mongoc_bulk_operation_update (bulk, tmp_bson ("{}"), tmp_bson ("{'$set': {'x': 1}}"), false); mongoc_bulk_operation_remove (bulk, tmp_bson ("{}")); mongoc_bulk_operation_insert (bulk, tmp_bson ("{'finished': true}")); - ASSERT_OR_PRINT (mongoc_bulk_operation_execute (bulk, &reply, &error), - error); + ASSERT_OR_PRINT (mongoc_bulk_operation_execute (bulk, &reply, &error), error); ASSERT (bson_empty (&reply)); @@ -4304,21 +4056,15 @@ test_bulk_invalid_write_concern (void) client = test_framework_new_default_client (); collection = get_test_collection (client, "test_bulk_invalid_write_concern"); - bulk = mongoc_collection_create_bulk_operation_with_opts ( - collection, tmp_bson ("{'writeConcern': {'w': 0, 'j': true}}")); - BSON_ASSERT (!mongoc_bulk_operation_insert_with_opts ( - bulk, tmp_bson ("{}"), NULL, &error)); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Bulk operation is invalid from prior error"); + bulk = mongoc_collection_create_bulk_operation_with_opts (collection, + tmp_bson ("{'writeConcern': {'w': 0, 'j': true}}")); + BSON_ASSERT (!mongoc_bulk_operation_insert_with_opts (bulk, tmp_bson ("{}"), NULL, &error)); + ASSERT_ERROR_CONTAINS ( + error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Bulk operation is invalid from prior error"); memset (&error, 0, sizeof (bson_error_t)); BSON_ASSERT (!mongoc_bulk_operation_execute (bulk, &reply, &error)); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Invalid writeConcern"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid writeConcern"); ASSERT (bson_empty (&reply)); @@ -4328,13 +4074,7 @@ test_bulk_invalid_write_concern (void) mongoc_client_destroy (client); } -typedef enum { - BULK_REMOVE, - BULK_REMOVE_ONE, - BULK_REPLACE_ONE, - BULK_UPDATE, - BULK_UPDATE_ONE -} bulkop; +typedef enum { BULK_REMOVE, BULK_REMOVE_ONE, BULK_REPLACE_ONE, BULK_UPDATE, BULK_UPDATE_ONE } bulkop; static void _test_bulk_collation (bool w, bulkop op) @@ -4355,26 +4095,17 @@ _test_bulk_collation (bool w, bulkop op) mock_server = mock_server_with_auto_hello (WIRE_VERSION_MIN); mock_server_run (mock_server); - client = test_framework_client_new_from_uri ( - mock_server_get_uri (mock_server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (mock_server), NULL); collection = mongoc_client_get_collection (client, "test", "test"); bulk = mongoc_collection_create_bulk_operation_with_opts ( - collection, - tmp_bson ("{'writeConcern': {'w': %d, 'wtimeout': 100}}", w ? 1 : 0)); + collection, tmp_bson ("{'writeConcern': {'w': %d, 'wtimeout': 100}}", w ? 1 : 0)); - opts = BCON_NEW ("collation", - "{", - "locale", - BCON_UTF8 ("en_US"), - "caseFirst", - BCON_UTF8 ("lower"), - "}"); + opts = BCON_NEW ("collation", "{", "locale", BCON_UTF8 ("en_US"), "caseFirst", BCON_UTF8 ("lower"), "}"); switch (op) { case BULK_REMOVE: - r = mongoc_bulk_operation_remove_many_with_opts ( - bulk, tmp_bson ("{'_id': 1}"), opts, &error); + r = mongoc_bulk_operation_remove_many_with_opts (bulk, tmp_bson ("{'_id': 1}"), opts, &error); expect_msg = "{'$db': 'test'," " 'delete': 'test'," " 'writeConcern': {" @@ -4385,8 +4116,7 @@ _test_bulk_collation (bool w, bulkop op) " 'collation': {'locale': 'en_US', 'caseFirst': 'lower'}}"; break; case BULK_REMOVE_ONE: - r = mongoc_bulk_operation_remove_one_with_opts ( - bulk, tmp_bson ("{'_id': 2}"), opts, &error); + r = mongoc_bulk_operation_remove_one_with_opts (bulk, tmp_bson ("{'_id': 2}"), opts, &error); expect_msg = "{'$db': 'test'," " 'delete': 'test'," " 'writeConcern': {" @@ -4411,11 +4141,7 @@ _test_bulk_collation (bool w, bulkop op) break; case BULK_UPDATE: r = mongoc_bulk_operation_update_many_with_opts ( - bulk, - tmp_bson ("{'_id': 5}"), - tmp_bson ("{'$set': {'_id': 6}}"), - opts, - &error); + bulk, tmp_bson ("{'_id': 5}"), tmp_bson ("{'$set': {'_id': 6}}"), opts, &error); expect_msg = "{'$db': 'test'," " 'update': 'test'," " 'writeConcern': {" @@ -4428,11 +4154,7 @@ _test_bulk_collation (bool w, bulkop op) break; case BULK_UPDATE_ONE: r = mongoc_bulk_operation_update_one_with_opts ( - bulk, - tmp_bson ("{'_id': 7}"), - tmp_bson ("{'$set': {'_id': 8}}"), - opts, - &error); + bulk, tmp_bson ("{'_id': 7}"), tmp_bson ("{'$set': {'_id': 8}}"), opts, &error); expect_msg = "{'$db': 'test'," " 'update': 'test'," " 'writeConcern': {" @@ -4451,10 +4173,8 @@ _test_bulk_collation (bool w, bulkop op) future = future_bulk_operation_execute (bulk, &reply, &error); if (w) { - request = mock_server_receives_msg (mock_server, - MONGOC_MSG_NONE, - tmp_bson (expect_msg, w ? 1 : 0), - tmp_bson (expect_doc)); + request = mock_server_receives_msg ( + mock_server, MONGOC_MSG_NONE, tmp_bson (expect_msg, w ? 1 : 0), tmp_bson (expect_doc)); reply_to_request_simple (request, "{'ok': 1.0, 'n': 1}"); request_destroy (request); @@ -4493,34 +4213,27 @@ _test_bulk_collation_multi (bool w) mock_server = mock_server_with_auto_hello (WIRE_VERSION_MIN); mock_server_run (mock_server); - client = test_framework_client_new_from_uri ( - mock_server_get_uri (mock_server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (mock_server), NULL); collection = mongoc_client_get_collection (client, "test", "test"); bulk = mongoc_collection_create_bulk_operation_with_opts ( - collection, - tmp_bson ("{'writeConcern': {'w': %d, 'wtimeout': 100}}", w ? 1 : 0)); + collection, tmp_bson ("{'writeConcern': {'w': %d, 'wtimeout': 100}}", w ? 1 : 0)); - mongoc_bulk_operation_remove_many_with_opts ( - bulk, tmp_bson ("{'_id': 1}"), NULL, &error); + mongoc_bulk_operation_remove_many_with_opts (bulk, tmp_bson ("{'_id': 1}"), NULL, &error); mongoc_bulk_operation_remove_many_with_opts ( - bulk, - tmp_bson ("{'_id': 2}"), - tmp_bson ("{'collation': {'locale': 'en_US', 'caseFirst': 'lower'}}"), - &error); + bulk, tmp_bson ("{'_id': 2}"), tmp_bson ("{'collation': {'locale': 'en_US', 'caseFirst': 'lower'}}"), &error); future = future_bulk_operation_execute (bulk, &reply, &error); if (w) { - request = mock_server_receives_msg ( - mock_server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'test'," - " 'delete': 'test'," - " 'ordered': true}"), - tmp_bson ("{'q': {'_id': 1}}"), - tmp_bson ("{'q': {'_id': 2}," - " 'collation': {'locale': 'en_US', 'caseFirst': 'lower'}}")); + request = mock_server_receives_msg (mock_server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'test'," + " 'delete': 'test'," + " 'ordered': true}"), + tmp_bson ("{'q': {'_id': 1}}"), + tmp_bson ("{'q': {'_id': 2}," + " 'collation': {'locale': 'en_US', 'caseFirst': 'lower'}}")); reply_to_request_simple (request, "{'ok': 1.0, 'n': 1}"); request_destroy (request); ASSERT (future_get_uint32_t (future)); @@ -4586,17 +4299,12 @@ test_bulk_update_one_error_message (void) bulk = mongoc_collection_create_bulk_operation_with_opts (collection, NULL); mongoc_bulk_operation_update_many_with_opts ( - bulk, - tmp_bson ("{'_id': 5}"), - tmp_bson ("{'set': {'_id': 6}}"), - NULL, - &error); + bulk, tmp_bson ("{'_id': 5}"), tmp_bson ("{'set': {'_id': 6}}"), NULL, &error); - ASSERT_ERROR_CONTAINS ( - error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Invalid key 'set': update only works with $ operators"); + ASSERT_ERROR_CONTAINS (error, + MONGOC_ERROR_COMMAND, + MONGOC_ERROR_COMMAND_INVALID_ARG, + "Invalid key 'set': update only works with $ operators"); mongoc_bulk_operation_destroy (bulk); mongoc_collection_destroy (collection); @@ -4624,28 +4332,17 @@ test_bulk_opts_parse (void) #define RM_ERR(_msg, _fn, ...) \ r = mongoc_bulk_operation_##_fn##_with_opts (bulk, q, __VA_ARGS__, &error); \ BSON_ASSERT (!r); \ - ASSERT_ERROR_CONTAINS (error, \ - MONGOC_ERROR_COMMAND, \ - MONGOC_ERROR_COMMAND_INVALID_ARG, \ - "Invalid " _msg) - -#define UPDATE_ERR(_msg, _fn, ...) \ - r = mongoc_bulk_operation_update_##_fn##_with_opts ( \ - bulk, q, u, __VA_ARGS__, &error); \ - BSON_ASSERT (!r); \ - ASSERT_ERROR_CONTAINS (error, \ - MONGOC_ERROR_COMMAND, \ - MONGOC_ERROR_COMMAND_INVALID_ARG, \ - "Invalid " _msg) - -#define REPLACE_ERR(_msg, ...) \ - r = mongoc_bulk_operation_replace_one_with_opts ( \ - bulk, q, repl, __VA_ARGS__, &error); \ - BSON_ASSERT (!r); \ - ASSERT_ERROR_CONTAINS (error, \ - MONGOC_ERROR_COMMAND, \ - MONGOC_ERROR_COMMAND_INVALID_ARG, \ - "Invalid " _msg) + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid " _msg) + +#define UPDATE_ERR(_msg, _fn, ...) \ + r = mongoc_bulk_operation_update_##_fn##_with_opts (bulk, q, u, __VA_ARGS__, &error); \ + BSON_ASSERT (!r); \ + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid " _msg) + +#define REPLACE_ERR(_msg, ...) \ + r = mongoc_bulk_operation_replace_one_with_opts (bulk, q, repl, __VA_ARGS__, &error); \ + BSON_ASSERT (!r); \ + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid " _msg) RM_ERR ("option 'foo'", remove_one, tmp_bson ("{'foo': 1}")); RM_ERR ("option 'foo'", remove_many, tmp_bson ("{'foo': 1}")); @@ -4662,10 +4359,7 @@ test_bulk_opts_parse (void) REPLACE_ERR ("option 'foo'", tmp_bson ("{'foo': 1}")); REPLACE_ERR ("\"multi\": true in opts", tmp_bson ("{'multi': true}")); -#define NO_ERR(_fn, ...) \ - ASSERT_OR_PRINT ( \ - mongoc_bulk_operation_##_fn##_with_opts (bulk, __VA_ARGS__, &error), \ - error) +#define NO_ERR(_fn, ...) ASSERT_OR_PRINT (mongoc_bulk_operation_##_fn##_with_opts (bulk, __VA_ARGS__, &error), error) /* for some reason we allow "multi" and "limit", if they equal the default */ NO_ERR (remove_one, q, tmp_bson ("{'limit': 1}")); @@ -4689,10 +4383,7 @@ test_bulk_no_client (void) bulk = mongoc_bulk_operation_new (true /* ordered */); BSON_ASSERT (!mongoc_bulk_operation_execute (bulk, &reply, &error)); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "requires a client"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "requires a client"); /* reply was initialized */ BSON_ASSERT (bson_empty (&reply)); @@ -4716,30 +4407,23 @@ test_bulk_bypass_document_validation (void) collection = get_test_collection (client, "bypass_validation"); /* bypassDocumentValidation can't be passed in opts */ - bulk = mongoc_collection_create_bulk_operation_with_opts ( - collection, tmp_bson ("{'bypassDocumentValidation': true}")); + bulk = + mongoc_collection_create_bulk_operation_with_opts (collection, tmp_bson ("{'bypassDocumentValidation': true}")); i = mongoc_bulk_operation_execute (bulk, NULL, &error); ASSERT_CMPUINT32 (i, ==, (uint32_t) 0); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Invalid option 'bypassDocumentValidation'"); + ASSERT_ERROR_CONTAINS ( + error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid option 'bypassDocumentValidation'"); mongoc_bulk_operation_destroy (bulk); /* not allowed in insert opts either */ bulk = mongoc_collection_create_bulk_operation_with_opts (collection, NULL); r = mongoc_bulk_operation_insert_with_opts ( - bulk, - tmp_bson ("{}"), - tmp_bson ("{'bypassDocumentValidation': true}"), - &error); + bulk, tmp_bson ("{}"), tmp_bson ("{'bypassDocumentValidation': true}"), &error); BSON_ASSERT (!r); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Invalid option 'bypassDocumentValidation'"); + ASSERT_ERROR_CONTAINS ( + error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid option 'bypassDocumentValidation'"); mongoc_bulk_operation_destroy (bulk); mongoc_collection_destroy (collection); @@ -4765,12 +4449,10 @@ _test_bulk_let (bulkop op) mock_server = mock_server_with_auto_hello (WIRE_VERSION_MIN); mock_server_run (mock_server); - client = test_framework_client_new_from_uri ( - mock_server_get_uri (mock_server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (mock_server), NULL); collection = mongoc_client_get_collection (client, "test", "test"); - bulk = mongoc_collection_create_bulk_operation_with_opts ( - collection, tmp_bson ("{'let': {'id': 1}}")); + bulk = mongoc_collection_create_bulk_operation_with_opts (collection, tmp_bson ("{'let': {'id': 1}}")); switch (op) { case BULK_REMOVE: @@ -4793,11 +4475,7 @@ _test_bulk_let (bulkop op) break; case BULK_REPLACE_ONE: r = mongoc_bulk_operation_replace_one_with_opts ( - bulk, - tmp_bson ("{'$expr': {'$eq': ['$_id', '$$id']}}"), - tmp_bson ("{'x': 'foo'}"), - NULL, - &error); + bulk, tmp_bson ("{'$expr': {'$eq': ['$_id', '$$id']}}"), tmp_bson ("{'x': 'foo'}"), NULL, &error); expect_msg = "{'$db': 'test'," " 'update': 'test'," " 'let': {'id': 1}," @@ -4808,11 +4486,7 @@ _test_bulk_let (bulkop op) break; case BULK_UPDATE: r = mongoc_bulk_operation_update_many_with_opts ( - bulk, - tmp_bson ("{'$expr': {'$eq': ['$_id', '$$id']}}"), - tmp_bson ("{'$set': {'x': 'foo'}}"), - NULL, - &error); + bulk, tmp_bson ("{'$expr': {'$eq': ['$_id', '$$id']}}"), tmp_bson ("{'$set': {'x': 'foo'}}"), NULL, &error); expect_msg = "{'$db': 'test'," " 'update': 'test'," " 'let': {'id': 1}," @@ -4823,11 +4497,7 @@ _test_bulk_let (bulkop op) break; case BULK_UPDATE_ONE: r = mongoc_bulk_operation_update_one_with_opts ( - bulk, - tmp_bson ("{'$expr': {'$eq': ['$_id', '$$id']}}"), - tmp_bson ("{'$set': {'x': 'foo'}}"), - NULL, - &error); + bulk, tmp_bson ("{'$expr': {'$eq': ['$_id', '$$id']}}"), tmp_bson ("{'$set': {'x': 'foo'}}"), NULL, &error); expect_msg = "{'$db': 'test'," " 'update': 'test'," " 'let': {'id': 1}," @@ -4843,10 +4513,7 @@ _test_bulk_let (bulkop op) ASSERT_OR_PRINT (r, error); future = future_bulk_operation_execute (bulk, &reply, &error); - request = mock_server_receives_msg (mock_server, - MONGOC_MSG_NONE, - tmp_bson (expect_msg), - tmp_bson (expect_doc)); + request = mock_server_receives_msg (mock_server, MONGOC_MSG_NONE, tmp_bson (expect_msg), tmp_bson (expect_doc)); reply_to_request_simple (request, "{'ok': 1.0, 'n': 1}"); request_destroy (request); @@ -4887,42 +4554,25 @@ test_bulk_let_multi (void) mock_server = mock_server_with_auto_hello (WIRE_VERSION_MIN); mock_server_run (mock_server); - client = test_framework_client_new_from_uri ( - mock_server_get_uri (mock_server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (mock_server), NULL); collection = mongoc_client_get_collection (client, "test", "test"); - bulk = mongoc_collection_create_bulk_operation_with_opts ( - collection, tmp_bson ("{'let': {'id': 1}}")); + bulk = mongoc_collection_create_bulk_operation_with_opts (collection, tmp_bson ("{'let': {'id': 1}}")); - mongoc_bulk_operation_insert_with_opts ( - bulk, tmp_bson ("{'_id': 1}"), NULL, &error); + mongoc_bulk_operation_insert_with_opts (bulk, tmp_bson ("{'_id': 1}"), NULL, &error); - mongoc_bulk_operation_remove_many_with_opts ( - bulk, tmp_bson ("{'$expr': {'$eq': ['$_id', '$$id']}}"), NULL, &error); + mongoc_bulk_operation_remove_many_with_opts (bulk, tmp_bson ("{'$expr': {'$eq': ['$_id', '$$id']}}"), NULL, &error); - mongoc_bulk_operation_remove_many_with_opts ( - bulk, tmp_bson ("{'_id': 2}"), NULL, &error); + mongoc_bulk_operation_remove_many_with_opts (bulk, tmp_bson ("{'_id': 2}"), NULL, &error); mongoc_bulk_operation_replace_one_with_opts ( - bulk, - tmp_bson ("{'$expr': {'$eq': ['$_id', '$$id']}}"), - tmp_bson ("{'x': 'foo'}"), - NULL, - &error); + bulk, tmp_bson ("{'$expr': {'$eq': ['$_id', '$$id']}}"), tmp_bson ("{'x': 'foo'}"), NULL, &error); mongoc_bulk_operation_update_many_with_opts ( - bulk, - tmp_bson ("{'$expr': {'$eq': ['$_id', '$$id']}}"), - tmp_bson ("{'$set': {'x': 'foo'}}"), - NULL, - &error); + bulk, tmp_bson ("{'$expr': {'$eq': ['$_id', '$$id']}}"), tmp_bson ("{'$set': {'x': 'foo'}}"), NULL, &error); mongoc_bulk_operation_update_one_with_opts ( - bulk, - tmp_bson ("{'$expr': {'$eq': ['$_id', '$$id']}}"), - tmp_bson ("{'$set': {'x': 'foo'}}"), - NULL, - &error); + bulk, tmp_bson ("{'$expr': {'$eq': ['$_id', '$$id']}}"), tmp_bson ("{'$set': {'x': 'foo'}}"), NULL, &error); future = future_bulk_operation_execute (bulk, &reply, &error); @@ -4936,34 +4586,32 @@ test_bulk_let_multi (void) reply_to_request_simple (request, "{'ok': 1.0, 'n': 1}"); request_destroy (request); - request = mock_server_receives_msg ( - mock_server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'test'," - " 'delete': 'test'," - " 'let': {'id': 1}," - " 'ordered': true}"), - tmp_bson ("{'q': {'$expr': {'$eq': ['$_id', '$$id']}}, 'limit': 0}"), - tmp_bson ("{'q': {'_id': 2}, 'limit': 0}")); + request = mock_server_receives_msg (mock_server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'test'," + " 'delete': 'test'," + " 'let': {'id': 1}," + " 'ordered': true}"), + tmp_bson ("{'q': {'$expr': {'$eq': ['$_id', '$$id']}}, 'limit': 0}"), + tmp_bson ("{'q': {'_id': 2}, 'limit': 0}")); reply_to_request_simple (request, "{'ok': 1.0, 'n': 1}"); request_destroy (request); - request = mock_server_receives_msg ( - mock_server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'test'," - " 'update': 'test'," - " 'let': {'id': 1}," - " 'ordered': true}"), - tmp_bson ("{'q': {'$expr': {'$eq': ['$_id', '$$id']}}," - " 'u': {'x': 'foo'}," - " 'multi': false}"), - tmp_bson ("{'q': {'$expr': {'$eq': ['$_id', '$$id']}}," - " 'u': {'$set': {'x': 'foo'}}," - " 'multi': true}"), - tmp_bson ("{'q': {'$expr': {'$eq': ['$_id', '$$id']}}," - " 'u': {'$set': {'x': 'foo'}}," - " 'multi': false}")); + request = mock_server_receives_msg (mock_server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'test'," + " 'update': 'test'," + " 'let': {'id': 1}," + " 'ordered': true}"), + tmp_bson ("{'q': {'$expr': {'$eq': ['$_id', '$$id']}}," + " 'u': {'x': 'foo'}," + " 'multi': false}"), + tmp_bson ("{'q': {'$expr': {'$eq': ['$_id', '$$id']}}," + " 'u': {'$set': {'x': 'foo'}}," + " 'multi': true}"), + tmp_bson ("{'q': {'$expr': {'$eq': ['$_id', '$$id']}}," + " 'u': {'$set': {'x': 'foo'}}," + " 'multi': false}")); reply_to_request_simple (request, "{'ok': 1.0, 'n': 1}"); request_destroy (request); @@ -5003,15 +4651,14 @@ test_bulk_write_multiple_errors (void *unused) bson_append_bool (&opts, "ordered", 7, false); bulk = mongoc_collection_create_bulk_operation_with_opts (collection, &opts); // Use appName to isolate the failpoint to this test. - bool ret = mongoc_client_command_simple ( - client, - "admin", - tmp_bson ("{'configureFailPoint': 'failCommand', 'mode': {'times': 2}, " - "'data': {'failCommands': ['insert', 'delete'], 'errorCode': " - "8, 'appName': 'test_bulk_write_multiple_errors'}}"), - NULL, - NULL, - &error); + bool ret = mongoc_client_command_simple (client, + "admin", + tmp_bson ("{'configureFailPoint': 'failCommand', 'mode': {'times': 2}, " + "'data': {'failCommands': ['insert', 'delete'], 'errorCode': " + "8, 'appName': 'test_bulk_write_multiple_errors'}}"), + NULL, + NULL, + &error); ASSERT_OR_PRINT (ret, error); mongoc_bulk_operation_insert (bulk, @@ -5024,8 +4671,7 @@ test_bulk_write_multiple_errors (void *unused) mongoc_bulk_operation_delete (bulk, tmp_bson ("{'_id': 4}")); // suceed mongoc_bulk_operation_insert (bulk, tmp_bson ("{'_id': 5}")); // suceed - mongoc_bulk_operation_insert ( - bulk, tmp_bson ("{'_id': 5}")); // duplicate key error + mongoc_bulk_operation_insert (bulk, tmp_bson ("{'_id': 5}")); // duplicate key error r = (bool) mongoc_bulk_operation_execute (bulk, &reply, &error); @@ -5065,8 +4711,7 @@ test_bulk_write_set_client_after_operation (void) BSON_ASSERT (client); mongoc_client_set_appname (client, "test_bulk_write_client_after_operation"); bulk = mongoc_bulk_operation_new (false /* ordered */); - ok = mongoc_bulk_operation_insert_with_opts ( - bulk, tmp_bson ("{'x': 1}"), tmp_bson ("{}"), &error); + ok = mongoc_bulk_operation_insert_with_opts (bulk, tmp_bson ("{'x': 1}"), tmp_bson ("{}"), &error); ASSERT_OR_PRINT (ok, error); mongoc_bulk_operation_set_client (bulk, client); mongoc_bulk_operation_set_database (bulk, "db"); @@ -5086,171 +4731,80 @@ test_bulk_install (TestSuite *suite) TestSuite_AddLive (suite, "/BulkOperation/basic", test_bulk); TestSuite_AddLive (suite, "/BulkOperation/opts", test_opts); TestSuite_AddMockServerTest (suite, "/BulkOperation/error", test_bulk_error); - TestSuite_AddMockServerTest ( - suite, "/BulkOperation/error/unordered", test_bulk_error_unordered); - TestSuite_AddLive ( - suite, "/BulkOperation/insert_ordered", test_insert_ordered); + TestSuite_AddMockServerTest (suite, "/BulkOperation/error/unordered", test_bulk_error_unordered); + TestSuite_AddLive (suite, "/BulkOperation/insert_ordered", test_insert_ordered); + TestSuite_AddLive (suite, "/BulkOperation/insert_unordered", test_insert_unordered); + TestSuite_AddLive (suite, "/BulkOperation/insert_check_keys", test_insert_check_keys); + TestSuite_AddLive (suite, "/BulkOperation/update_ordered", test_update_ordered); + TestSuite_AddLive (suite, "/BulkOperation/update_unordered", test_update_unordered); + TestSuite_AddLive (suite, "/BulkOperation/update_one_check_keys", test_update_one_check_keys); + TestSuite_AddLive (suite, "/BulkOperation/update_check_keys", test_update_check_keys); + TestSuite_AddLive (suite, "/BulkOperation/update_one_with_opts_check_keys", test_update_one_with_opts_check_keys); + TestSuite_AddLive (suite, "/BulkOperation/update_many_with_opts_check_keys", test_update_many_with_opts_check_keys); + TestSuite_AddLive (suite, "/BulkOperation/update_one_invalid_first", test_update_one_invalid_first); + TestSuite_AddLive (suite, "/BulkOperation/update_invalid_first", test_update_invalid_first); TestSuite_AddLive ( - suite, "/BulkOperation/insert_unordered", test_insert_unordered); + suite, "/BulkOperation/update_one_with_opts_invalid_first", test_update_one_with_opts_invalid_first); TestSuite_AddLive ( - suite, "/BulkOperation/insert_check_keys", test_insert_check_keys); + suite, "/BulkOperation/update_many_with_opts_invalid_first", test_update_many_with_opts_invalid_first); + TestSuite_AddLive (suite, "/BulkOperation/replace_one_invalid_first", test_replace_one_invalid_first); TestSuite_AddLive ( - suite, "/BulkOperation/update_ordered", test_update_ordered); + suite, "/BulkOperation/replace_one_with_opts_invalid_first", test_replace_one_with_opts_invalid_first); + TestSuite_AddLive (suite, "/BulkOperation/update_one_invalid_second", test_update_one_invalid_second); + TestSuite_AddLive (suite, "/BulkOperation/update_invalid_second", test_update_invalid_second); TestSuite_AddLive ( - suite, "/BulkOperation/update_unordered", test_update_unordered); - TestSuite_AddLive (suite, - "/BulkOperation/update_one_check_keys", - test_update_one_check_keys); + suite, "/BulkOperation/update_one_with_opts_invalid_second", test_update_one_with_opts_invalid_second); TestSuite_AddLive ( - suite, "/BulkOperation/update_check_keys", test_update_check_keys); - TestSuite_AddLive (suite, - "/BulkOperation/update_one_with_opts_check_keys", - test_update_one_with_opts_check_keys); - TestSuite_AddLive (suite, - "/BulkOperation/update_many_with_opts_check_keys", - test_update_many_with_opts_check_keys); - TestSuite_AddLive (suite, - "/BulkOperation/update_one_invalid_first", - test_update_one_invalid_first); + suite, "/BulkOperation/update_many_with_opts_invalid_second", test_update_many_with_opts_invalid_second); + TestSuite_AddLive (suite, "/BulkOperation/replace_one_invalid_second", test_replace_one_invalid_second); TestSuite_AddLive ( - suite, "/BulkOperation/update_invalid_first", test_update_invalid_first); - TestSuite_AddLive (suite, - "/BulkOperation/update_one_with_opts_invalid_first", - test_update_one_with_opts_invalid_first); - TestSuite_AddLive (suite, - "/BulkOperation/update_many_with_opts_invalid_first", - test_update_many_with_opts_invalid_first); - TestSuite_AddLive (suite, - "/BulkOperation/replace_one_invalid_first", - test_replace_one_invalid_first); - TestSuite_AddLive (suite, - "/BulkOperation/replace_one_with_opts_invalid_first", - test_replace_one_with_opts_invalid_first); - TestSuite_AddLive (suite, - "/BulkOperation/update_one_invalid_second", - test_update_one_invalid_second); - TestSuite_AddLive (suite, - "/BulkOperation/update_invalid_second", - test_update_invalid_second); - TestSuite_AddLive (suite, - "/BulkOperation/update_one_with_opts_invalid_second", - test_update_one_with_opts_invalid_second); - TestSuite_AddLive (suite, - "/BulkOperation/update_many_with_opts_invalid_second", - test_update_many_with_opts_invalid_second); - TestSuite_AddLive (suite, - "/BulkOperation/replace_one_invalid_second", - test_replace_one_invalid_second); - TestSuite_AddLive (suite, - "/BulkOperation/replace_one_with_opts_invalid_second", - test_replace_one_with_opts_invalid_second); + suite, "/BulkOperation/replace_one_with_opts_invalid_second", test_replace_one_with_opts_invalid_second); + TestSuite_AddLive (suite, "/BulkOperation/insert_invalid_first", test_insert_invalid_first); + TestSuite_AddLive (suite, "/BulkOperation/insert_invalid_second", test_insert_invalid_second); + TestSuite_AddLive (suite, "/BulkOperation/insert_with_opts_invalid_first", test_insert_with_opts_invalid_first); + TestSuite_AddLive (suite, "/BulkOperation/insert_with_opts_invalid_second", test_insert_with_opts_invalid_second); + TestSuite_AddLive (suite, "/BulkOperation/insert_with_opts_validate", test_insert_with_opts_validate); + TestSuite_AddLive (suite, "/BulkOperation/remove_one_after_invalid", test_remove_one_after_invalid); + TestSuite_AddLive (suite, "/BulkOperation/remove_after_invalid", test_remove_after_invalid); TestSuite_AddLive ( - suite, "/BulkOperation/insert_invalid_first", test_insert_invalid_first); - TestSuite_AddLive (suite, - "/BulkOperation/insert_invalid_second", - test_insert_invalid_second); - TestSuite_AddLive (suite, - "/BulkOperation/insert_with_opts_invalid_first", - test_insert_with_opts_invalid_first); - TestSuite_AddLive (suite, - "/BulkOperation/insert_with_opts_invalid_second", - test_insert_with_opts_invalid_second); - TestSuite_AddLive (suite, - "/BulkOperation/insert_with_opts_validate", - test_insert_with_opts_validate); - TestSuite_AddLive (suite, - "/BulkOperation/remove_one_after_invalid", - test_remove_one_after_invalid); + suite, "/BulkOperation/remove_one_with_opts_after_invalid", test_remove_one_with_opts_after_invalid); TestSuite_AddLive ( - suite, "/BulkOperation/remove_after_invalid", test_remove_after_invalid); - TestSuite_AddLive (suite, - "/BulkOperation/remove_one_with_opts_after_invalid", - test_remove_one_with_opts_after_invalid); - TestSuite_AddLive (suite, - "/BulkOperation/remove_many_with_opts_after_invalid", - test_remove_many_with_opts_after_invalid); - TestSuite_AddLive ( - suite, "/BulkOperation/upsert_ordered", test_upsert_ordered); - TestSuite_AddLive ( - suite, "/BulkOperation/upsert_unordered", test_upsert_unordered); + suite, "/BulkOperation/remove_many_with_opts_after_invalid", test_remove_many_with_opts_after_invalid); + TestSuite_AddLive (suite, "/BulkOperation/upsert_ordered", test_upsert_ordered); + TestSuite_AddLive (suite, "/BulkOperation/upsert_unordered", test_upsert_unordered); TestSuite_AddFull (suite, "/BulkOperation/upsert_unordered_oversized", test_upsert_unordered_oversized, NULL, NULL, test_framework_skip_if_slow_or_live); - TestSuite_AddFull (suite, - "/BulkOperation/upsert_large", - test_upsert_large, - NULL, - NULL, - test_framework_skip_if_slow_or_live); - TestSuite_AddFull (suite, - "/BulkOperation/upsert_huge", - test_upsert_huge, - NULL, - NULL, - test_framework_skip_if_slow_or_live); - TestSuite_AddLive (suite, - "/BulkOperation/upserted_index_ordered", - test_upserted_index_ordered); - TestSuite_AddLive (suite, - "/BulkOperation/upserted_index_unordered", - test_upserted_index_unordered); - TestSuite_AddLive ( - suite, "/BulkOperation/update_one_ordered", test_update_one_ordered); - TestSuite_AddLive ( - suite, "/BulkOperation/update_one_unordered", test_update_one_unordered); - TestSuite_AddLive (suite, - "/BulkOperation/update_with_opts_validate", - test_update_with_opts_validate); - TestSuite_AddFull (suite, - "/BulkOperation/update_arrayfilters", - test_update_arrayfilters, - NULL, - NULL, - TestSuite_CheckLive); - TestSuite_AddLive ( - suite, "/BulkOperation/update/hint/validate", test_update_hint_validate); - TestSuite_AddLive ( - suite, "/BulkOperation/delete/hint/validate", test_delete_hint_validate); - TestSuite_AddLive ( - suite, "/BulkOperation/replace_one_ordered", test_replace_one_ordered); - TestSuite_AddLive (suite, - "/BulkOperation/replace_one_unordered", - test_replace_one_unordered); - TestSuite_AddLive ( - suite, "/BulkOperation/replace_one/keys", test_replace_one_check_keys); - TestSuite_AddLive (suite, - "/BulkOperation/replace_one_with_opts/keys", - test_replace_one_with_opts_check_keys); - TestSuite_AddLive (suite, - "/BulkOperation/replace_one_with_opts_validate", - test_replace_one_with_opts_validate); + TestSuite_AddFull ( + suite, "/BulkOperation/upsert_large", test_upsert_large, NULL, NULL, test_framework_skip_if_slow_or_live); + TestSuite_AddFull ( + suite, "/BulkOperation/upsert_huge", test_upsert_huge, NULL, NULL, test_framework_skip_if_slow_or_live); + TestSuite_AddLive (suite, "/BulkOperation/upserted_index_ordered", test_upserted_index_ordered); + TestSuite_AddLive (suite, "/BulkOperation/upserted_index_unordered", test_upserted_index_unordered); + TestSuite_AddLive (suite, "/BulkOperation/update_one_ordered", test_update_one_ordered); + TestSuite_AddLive (suite, "/BulkOperation/update_one_unordered", test_update_one_unordered); + TestSuite_AddLive (suite, "/BulkOperation/update_with_opts_validate", test_update_with_opts_validate); + TestSuite_AddFull ( + suite, "/BulkOperation/update_arrayfilters", test_update_arrayfilters, NULL, NULL, TestSuite_CheckLive); + TestSuite_AddLive (suite, "/BulkOperation/update/hint/validate", test_update_hint_validate); + TestSuite_AddLive (suite, "/BulkOperation/delete/hint/validate", test_delete_hint_validate); + TestSuite_AddLive (suite, "/BulkOperation/replace_one_ordered", test_replace_one_ordered); + TestSuite_AddLive (suite, "/BulkOperation/replace_one_unordered", test_replace_one_unordered); + TestSuite_AddLive (suite, "/BulkOperation/replace_one/keys", test_replace_one_check_keys); + TestSuite_AddLive (suite, "/BulkOperation/replace_one_with_opts/keys", test_replace_one_with_opts_check_keys); + TestSuite_AddLive (suite, "/BulkOperation/replace_one_with_opts_validate", test_replace_one_with_opts_validate); TestSuite_AddLive (suite, "/BulkOperation/index_offset", test_index_offset); - TestSuite_AddLive ( - suite, "/BulkOperation/single_ordered_bulk", test_single_ordered_bulk); - TestSuite_AddLive (suite, - "/BulkOperation/insert_continue_on_error", - test_insert_continue_on_error); - TestSuite_AddLive (suite, - "/BulkOperation/update_continue_on_error", - test_update_continue_on_error); - TestSuite_AddLive (suite, - "/BulkOperation/remove_continue_on_error", - test_remove_continue_on_error); - TestSuite_AddLive (suite, - "/BulkOperation/single_error_ordered_bulk", - test_single_error_ordered_bulk); - TestSuite_AddLive (suite, - "/BulkOperation/multiple_error_ordered_bulk", - test_multiple_error_ordered_bulk); - TestSuite_AddLive (suite, - "/BulkOperation/single_unordered_bulk", - test_single_unordered_bulk); - TestSuite_AddLive (suite, - "/BulkOperation/single_error_unordered_bulk", - test_single_error_unordered_bulk); + TestSuite_AddLive (suite, "/BulkOperation/single_ordered_bulk", test_single_ordered_bulk); + TestSuite_AddLive (suite, "/BulkOperation/insert_continue_on_error", test_insert_continue_on_error); + TestSuite_AddLive (suite, "/BulkOperation/update_continue_on_error", test_update_continue_on_error); + TestSuite_AddLive (suite, "/BulkOperation/remove_continue_on_error", test_remove_continue_on_error); + TestSuite_AddLive (suite, "/BulkOperation/single_error_ordered_bulk", test_single_error_ordered_bulk); + TestSuite_AddLive (suite, "/BulkOperation/multiple_error_ordered_bulk", test_multiple_error_ordered_bulk); + TestSuite_AddLive (suite, "/BulkOperation/single_unordered_bulk", test_single_unordered_bulk); + TestSuite_AddLive (suite, "/BulkOperation/single_error_unordered_bulk", test_single_error_unordered_bulk); TestSuite_AddFull (suite, "/BulkOperation/oversized/ordered", test_oversized_bulk_op_ordered, @@ -5264,39 +4818,24 @@ test_bulk_install (TestSuite *suite) NULL, test_framework_skip_if_slow_or_live); TestSuite_AddMockServerTest ( - suite, - "/BulkOperation/write_concern/write_command/ordered", - test_write_concern_write_command_ordered); - TestSuite_AddMockServerTest ( - suite, - "/BulkOperation/write_concern/write_command/ordered/multi_err", - test_write_concern_write_command_ordered_multi_err); - TestSuite_AddMockServerTest ( - suite, - "/BulkOperation/write_concern/write_command/unordered", - test_write_concern_write_command_unordered); - TestSuite_AddMockServerTest ( - suite, - "/BulkOperation/write_concern/write_command/unordered/multi_err", - test_write_concern_write_command_unordered_multi_err); + suite, "/BulkOperation/write_concern/write_command/ordered", test_write_concern_write_command_ordered); TestSuite_AddMockServerTest (suite, - "/BulkOperation/writes/unordered/error", - test_unordered_bulk_writes_with_error); + "/BulkOperation/write_concern/write_command/ordered/multi_err", + test_write_concern_write_command_ordered_multi_err); TestSuite_AddMockServerTest ( - suite, - "/BulkOperation/write_concern/error/write_command/v1", - test_write_concern_error_write_command_v1); + suite, "/BulkOperation/write_concern/write_command/unordered", test_write_concern_write_command_unordered); + TestSuite_AddMockServerTest (suite, + "/BulkOperation/write_concern/write_command/unordered/multi_err", + test_write_concern_write_command_unordered_multi_err); + TestSuite_AddMockServerTest (suite, "/BulkOperation/writes/unordered/error", test_unordered_bulk_writes_with_error); TestSuite_AddMockServerTest ( - suite, - "/BulkOperation/write_concern/error/write_command/v2", - test_write_concern_error_write_command_v2); - TestSuite_AddLive (suite, - "/BulkOperation/multiple_error_unordered_bulk", - test_multiple_error_unordered_bulk); + suite, "/BulkOperation/write_concern/error/write_command/v1", test_write_concern_error_write_command_v1); TestSuite_AddMockServerTest ( - suite, - "/BulkOperation/wtimeout_duplicate_key/write_commands", - test_wtimeout_plus_duplicate_key_err_write_commands); + suite, "/BulkOperation/write_concern/error/write_command/v2", test_write_concern_error_write_command_v2); + TestSuite_AddLive (suite, "/BulkOperation/multiple_error_unordered_bulk", test_multiple_error_unordered_bulk); + TestSuite_AddMockServerTest (suite, + "/BulkOperation/wtimeout_duplicate_key/write_commands", + test_wtimeout_plus_duplicate_key_err_write_commands); TestSuite_AddFull (suite, "/BulkOperation/large_inserts_ordered", test_large_inserts_ordered, @@ -5309,29 +4848,19 @@ test_bulk_install (TestSuite *suite) NULL, NULL, test_framework_skip_if_slow_or_live); - TestSuite_AddFull (suite, - "/BulkOperation/numerous_ordered", - test_numerous_ordered, - NULL, - NULL, - test_framework_skip_if_slow_or_live); + TestSuite_AddFull ( + suite, "/BulkOperation/numerous_ordered", test_numerous_ordered, NULL, NULL, test_framework_skip_if_slow_or_live); TestSuite_AddFull (suite, "/BulkOperation/numerous_unordered", test_numerous_unordered, NULL, NULL, test_framework_skip_if_slow_or_live); - TestSuite_AddLive (suite, - "/BulkOperation/CDRIVER-372_ordered", - test_bulk_edge_case_372_ordered); - TestSuite_AddLive (suite, - "/BulkOperation/CDRIVER-372_unordered", - test_bulk_edge_case_372_unordered); + TestSuite_AddLive (suite, "/BulkOperation/CDRIVER-372_ordered", test_bulk_edge_case_372_ordered); + TestSuite_AddLive (suite, "/BulkOperation/CDRIVER-372_unordered", test_bulk_edge_case_372_unordered); TestSuite_AddLive (suite, "/BulkOperation/new", test_bulk_new); - TestSuite_AddLive ( - suite, "/BulkOperation/OP_MSG/max_batch_size", test_bulk_max_batch_size); - TestSuite_AddLive ( - suite, "/BulkOperation/OP_MSG/max_msg_size", test_bulk_max_msg_size); + TestSuite_AddLive (suite, "/BulkOperation/OP_MSG/max_batch_size", test_bulk_max_batch_size); + TestSuite_AddLive (suite, "/BulkOperation/OP_MSG/max_msg_size", test_bulk_max_msg_size); TestSuite_AddFull (suite, "/BulkOperation/split", test_bulk_split, @@ -5344,43 +4873,24 @@ test_bulk_install (TestSuite *suite) NULL /* dtor */, NULL /* ctx */, test_framework_skip_if_no_getlasterror); - TestSuite_AddMockServerTest (suite, - "/BulkOperation/hint/single/command/secondary", - test_hint_single_command_secondary); - TestSuite_AddMockServerTest (suite, - "/BulkOperation/hint/single/command/primary", - test_hint_single_command_primary); - TestSuite_AddMockServerTest (suite, - "/BulkOperation/hint/pooled/command/secondary", - test_hint_pooled_command_secondary); - TestSuite_AddMockServerTest (suite, - "/BulkOperation/hint/pooled/command/primary", - test_hint_pooled_command_primary); - TestSuite_AddLive (suite, "/BulkOperation/reply_w0", test_bulk_reply_w0); - TestSuite_AddLive (suite, - "/BulkOperation/invalid_write_concern", - test_bulk_invalid_write_concern); TestSuite_AddMockServerTest ( - suite, "/BulkOperation/opts/collation/w0", test_bulk_collation_w0); + suite, "/BulkOperation/hint/single/command/secondary", test_hint_single_command_secondary); + TestSuite_AddMockServerTest (suite, "/BulkOperation/hint/single/command/primary", test_hint_single_command_primary); TestSuite_AddMockServerTest ( - suite, "/BulkOperation/opts/collation/w1", test_bulk_collation_w1); - TestSuite_AddMockServerTest (suite, - "/BulkOperation/opts/collation/multi/w0", - test_bulk_collation_multi_w0); - TestSuite_AddMockServerTest (suite, - "/BulkOperation/opts/collation/multi/w1", - test_bulk_collation_multi_w1); - TestSuite_Add (suite, - "/BulkOperation/update_one/error_message", - test_bulk_update_one_error_message); + suite, "/BulkOperation/hint/pooled/command/secondary", test_hint_pooled_command_secondary); + TestSuite_AddMockServerTest (suite, "/BulkOperation/hint/pooled/command/primary", test_hint_pooled_command_primary); + TestSuite_AddLive (suite, "/BulkOperation/reply_w0", test_bulk_reply_w0); + TestSuite_AddLive (suite, "/BulkOperation/invalid_write_concern", test_bulk_invalid_write_concern); + TestSuite_AddMockServerTest (suite, "/BulkOperation/opts/collation/w0", test_bulk_collation_w0); + TestSuite_AddMockServerTest (suite, "/BulkOperation/opts/collation/w1", test_bulk_collation_w1); + TestSuite_AddMockServerTest (suite, "/BulkOperation/opts/collation/multi/w0", test_bulk_collation_multi_w0); + TestSuite_AddMockServerTest (suite, "/BulkOperation/opts/collation/multi/w1", test_bulk_collation_multi_w1); + TestSuite_Add (suite, "/BulkOperation/update_one/error_message", test_bulk_update_one_error_message); TestSuite_Add (suite, "/BulkOperation/opts/parse", test_bulk_opts_parse); TestSuite_Add (suite, "/BulkOperation/no_client", test_bulk_no_client); - TestSuite_AddLive ( - suite, "/BulkOperation/bypass", test_bulk_bypass_document_validation); - TestSuite_AddMockServerTest ( - suite, "/BulkOperation/opts/let", test_bulk_let); - TestSuite_AddMockServerTest ( - suite, "/BulkOperation/opts/let/multi", test_bulk_let_multi); + TestSuite_AddLive (suite, "/BulkOperation/bypass", test_bulk_bypass_document_validation); + TestSuite_AddMockServerTest (suite, "/BulkOperation/opts/let", test_bulk_let); + TestSuite_AddMockServerTest (suite, "/BulkOperation/opts/let/multi", test_bulk_let_multi); TestSuite_AddFull (suite, "/BulkOperation/multiple_errors", test_bulk_write_multiple_errors, @@ -5389,7 +4899,5 @@ test_bulk_install (TestSuite *suite) test_framework_skip_if_no_failpoint, /* Require server 4.2 for failCommand appName */ test_framework_skip_if_max_wire_version_less_than_8); - TestSuite_AddLive (suite, - "/BulkOperation/set_client_after_operation", - test_bulk_write_set_client_after_operation); + TestSuite_AddLive (suite, "/BulkOperation/set_client_after_operation", test_bulk_write_set_client_after_operation); } diff --git a/src/libmongoc/tests/test-mongoc-cache.c b/src/libmongoc/tests/test-mongoc-cache.c index c6cd162ac3..e044a33b1b 100644 --- a/src/libmongoc/tests/test-mongoc-cache.c +++ b/src/libmongoc/tests/test-mongoc-cache.c @@ -39,24 +39,20 @@ ping (void) char *uri; int ret = EXIT_FAILURE; - uri = bson_strdup_printf ("mongodb://localhost/?tls=true&tlsCAFile=%s", - ca_file); + uri = bson_strdup_printf ("mongodb://localhost/?tls=true&tlsCAFile=%s", ca_file); ASSERT ((client = mongoc_client_new (uri))); bson_init (&ping); bson_append_int32 (&ping, "ping", 4, 1); database = mongoc_client_get_database (client, "cache"); - if (mongoc_database_command_with_opts ( - database, &ping, NULL, NULL, &reply, &error)) { + if (mongoc_database_command_with_opts (database, &ping, NULL, NULL, &reply, &error)) { MONGOC_DEBUG ("Ping success\n"); ret = EXIT_SUCCESS; } else { MONGOC_DEBUG ("Ping failure: %s\n", error.message); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_SERVER_SELECTION, - MONGOC_ERROR_SERVER_SELECTION_FAILURE, - "TLS handshake failed"); + ASSERT_ERROR_CONTAINS ( + error, MONGOC_ERROR_SERVER_SELECTION, MONGOC_ERROR_SERVER_SELECTION_FAILURE, "TLS handshake failed"); } bson_free (uri); diff --git a/src/libmongoc/tests/test-mongoc-change-stream.c b/src/libmongoc/tests/test-mongoc-change-stream.c index 82b6d659b9..3042fa34db 100644 --- a/src/libmongoc/tests/test-mongoc-change-stream.c +++ b/src/libmongoc/tests/test-mongoc-change-stream.c @@ -27,20 +27,18 @@ #include "json-test.h" #include "json-test-operations.h" -#define DESTROY_CHANGE_STREAM(cursor_id) \ - do { \ - future_t *_future = future_change_stream_destroy (stream); \ - request_t *_request = mock_server_receives_msg ( \ - server, \ - MONGOC_MSG_NONE, \ - tmp_bson ("{'$db': 'db'," \ - " 'killCursors': 'coll'," \ - " 'cursors': [{'$numberLong': '" #cursor_id "'}]}")); \ - reply_to_request_simple (_request, \ - "{ 'cursorsKilled': [ " #cursor_id " ] }"); \ - future_wait (_future); \ - future_destroy (_future); \ - request_destroy (_request); \ +#define DESTROY_CHANGE_STREAM(cursor_id) \ + do { \ + future_t *_future = future_change_stream_destroy (stream); \ + request_t *_request = mock_server_receives_msg (server, \ + MONGOC_MSG_NONE, \ + tmp_bson ("{'$db': 'db'," \ + " 'killCursors': 'coll'," \ + " 'cursors': [{'$numberLong': '" #cursor_id "'}]}")); \ + reply_to_request_simple (_request, "{ 'cursorsKilled': [ " #cursor_id " ] }"); \ + future_wait (_future); \ + future_destroy (_future); \ + request_destroy (_request); \ } while (0) @@ -65,13 +63,8 @@ _setup_for_resume (mongoc_change_stream_t *stream) cmd = "{'configureFailPoint': 'failCommand', 'mode': { 'times': 1 }, " "'data': { 'failCommands': ['getMore'], 'errorCode': 6 }}"; } - ret = mongoc_client_command_simple_with_server_id (client, - "admin", - tmp_bson (cmd), - NULL /* read prefs */, - stream->cursor->server_id, - NULL /* reply */, - &error); + ret = mongoc_client_command_simple_with_server_id ( + client, "admin", tmp_bson (cmd), NULL /* read prefs */, stream->cursor->server_id, NULL /* reply */, &error); ASSERT_OR_PRINT (ret, error); } @@ -82,19 +75,15 @@ test_framework_skip_if_not_single_version_5 (void) if (!TestSuite_CheckLive ()) { return 0; } - return (!test_framework_is_replset () && !test_framework_is_mongos ()) ? 1 - : 0; + return (!test_framework_is_replset () && !test_framework_is_mongos ()) ? 1 : 0; } static mongoc_collection_t * -drop_and_get_coll (mongoc_client_t *client, - const char *db_name, - const char *coll_name) +drop_and_get_coll (mongoc_client_t *client, const char *db_name, const char *coll_name) { ASSERT (client); - mongoc_collection_t *coll = - mongoc_client_get_collection (client, db_name, coll_name); + mongoc_collection_t *coll = mongoc_client_get_collection (client, db_name, coll_name); mongoc_collection_drop (coll, NULL); return coll; } @@ -112,14 +101,12 @@ test_change_stream_pipeline (void) mongoc_collection_t *coll; mongoc_change_stream_t *stream; const bson_t *next_doc = NULL; - bson_t *nonempty_pipeline = - tmp_bson ("{ 'pipeline' : [ { '$project' : { 'ns': false } } ] }"); + bson_t *nonempty_pipeline = tmp_bson ("{ 'pipeline' : [ { '$project' : { 'ns': false } } ] }"); server = mock_server_with_auto_hello (WIRE_VERSION_MIN); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); ASSERT (client); coll = mongoc_client_get_collection (client, "db", "coll"); @@ -127,17 +114,14 @@ test_change_stream_pipeline (void) future = future_collection_watch (coll, tmp_bson ("{}"), NULL); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db'," - " 'aggregate': 'coll'," - " 'pipeline': [{'$changeStream': {}}]," - " 'cursor': {}}")); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'db'," + " 'aggregate': 'coll'," + " 'pipeline': [{'$changeStream': {}}]," + " 'cursor': {}}")); - reply_to_request_simple ( - request, - "{'cursor' : {'id': 123, 'ns': 'db.coll', 'firstBatch': []}, 'ok': 1 }"); + reply_to_request_simple (request, "{'cursor' : {'id': 123, 'ns': 'db.coll', 'firstBatch': []}, 'ok': 1 }"); stream = future_get_mongoc_change_stream_ptr (future); ASSERT (stream); @@ -147,14 +131,12 @@ test_change_stream_pipeline (void) future = future_change_stream_next (stream, &next_doc); - request = - mock_server_receives_msg (server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db'," - " 'getMore': {'$numberLong': '123'}," - " 'collection': 'coll'}")); - reply_to_request_simple (request, - "{'cursor' : { 'nextBatch' : [] }, 'ok': 1}"); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'db'," + " 'getMore': {'$numberLong': '123'}," + " 'collection': 'coll'}")); + reply_to_request_simple (request, "{'cursor' : { 'nextBatch' : [] }, 'ok': 1}"); ASSERT (!future_get_bool (future)); ASSERT (!mongoc_change_stream_error_document (stream, NULL, NULL)); ASSERT (next_doc == NULL); @@ -163,14 +145,12 @@ test_change_stream_pipeline (void) /* Another call to next should produce another getMore */ future = future_change_stream_next (stream, &next_doc); - request = - mock_server_receives_msg (server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db'," - " 'getMore': {'$numberLong': '123'}," - " 'collection': 'coll'}")); - reply_to_request_simple (request, - "{ 'cursor': { 'nextBatch': [] }, 'ok': 1 }"); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'db'," + " 'getMore': {'$numberLong': '123'}," + " 'collection': 'coll'}")); + reply_to_request_simple (request, "{ 'cursor': { 'nextBatch': [] }, 'ok': 1 }"); ASSERT (!future_get_bool (future)); ASSERT (!mongoc_change_stream_error_document (stream, NULL, NULL)); ASSERT (next_doc == NULL); @@ -182,18 +162,15 @@ test_change_stream_pipeline (void) /* Test non-empty pipeline */ future = future_collection_watch (coll, nonempty_pipeline, NULL); - request = - mock_server_receives_msg (server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db'," - " 'aggregate': 'coll'," - " 'pipeline': [" - " {'$changeStream': {}}," - " {'$project': {'ns': false}}]," - " 'cursor': {}}")); - reply_to_request_simple ( - request, - "{'cursor': {'id': 123, 'ns': 'db.coll','firstBatch': []},'ok': 1}"); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'db'," + " 'aggregate': 'coll'," + " 'pipeline': [" + " {'$changeStream': {}}," + " {'$project': {'ns': false}}]," + " 'cursor': {}}")); + reply_to_request_simple (request, "{'cursor': {'id': 123, 'ns': 'db.coll','firstBatch': []},'ok': 1}"); stream = future_get_mongoc_change_stream_ptr (future); ASSERT (stream); @@ -203,14 +180,12 @@ test_change_stream_pipeline (void) future = future_change_stream_next (stream, &next_doc); - request = - mock_server_receives_msg (server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db'," - " 'getMore': {'$numberLong': '123'}," - " 'collection': 'coll'}")); - reply_to_request_simple (request, - "{ 'cursor': { 'nextBatch': [] }, 'ok': 1 }"); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'db'," + " 'getMore': {'$numberLong': '123'}," + " 'collection': 'coll'}")); + reply_to_request_simple (request, "{ 'cursor': { 'nextBatch': [] }, 'ok': 1 }"); ASSERT (!future_get_bool (future)); ASSERT (!mongoc_change_stream_error_document (stream, NULL, NULL)); ASSERT (next_doc == NULL); @@ -251,23 +226,19 @@ test_change_stream_live_single_server (void *test_ctx) coll = mongoc_client_get_collection (client, "db", "coll"); ASSERT (coll); - ASSERT_OR_PRINT ( - mongoc_collection_insert_one (coll, tmp_bson (NULL), NULL, NULL, &error), - error); + ASSERT_OR_PRINT (mongoc_collection_insert_one (coll, tmp_bson (NULL), NULL, NULL, &error), error); stream = mongoc_collection_watch (coll, tmp_bson ("{}"), NULL); ASSERT (stream); - ASSERT ( - mongoc_change_stream_error_document (stream, NULL, &reported_err_doc)); + ASSERT (mongoc_change_stream_error_document (stream, NULL, &reported_err_doc)); ASSERT (next_doc == NULL); if (test_framework_max_wire_version_at_least (6)) { ASSERT_MATCH (reported_err_doc, not_replset_doc); } else { ASSERT_MATCH (reported_err_doc, not_supported_doc); - ASSERT_CONTAINS (bson_lookup_utf8 (reported_err_doc, "errmsg"), - "Unrecognized pipeline stage"); + ASSERT_CONTAINS (bson_lookup_utf8 (reported_err_doc, "errmsg"), "Unrecognized pipeline stage"); } mongoc_change_stream_destroy (stream); @@ -287,18 +258,14 @@ test_resume_token_command_start (const mongoc_apm_command_started_t *event) const bson_t *cmd = mongoc_apm_command_started_get_command (event); const char *cmd_name = mongoc_apm_command_started_get_command_name (event); - test_resume_token_ctx_t *ctx = - (test_resume_token_ctx_t *) mongoc_apm_command_started_get_context ( - event); + test_resume_token_ctx_t *ctx = (test_resume_token_ctx_t *) mongoc_apm_command_started_get_context (event); if (strcmp (cmd_name, "aggregate") == 0) { if (ctx->expecting_resume_token) { - char *rt_pattern = bson_as_canonical_extended_json ( - ctx->expected_resume_token_bson, NULL); - char *pattern = - bson_strdup_printf ("{'aggregate': 'coll_resume', 'pipeline': " - "[{'$changeStream': { 'resumeAfter': %s }}]}", - rt_pattern); + char *rt_pattern = bson_as_canonical_extended_json (ctx->expected_resume_token_bson, NULL); + char *pattern = bson_strdup_printf ("{'aggregate': 'coll_resume', 'pipeline': " + "[{'$changeStream': { 'resumeAfter': %s }}]}", + rt_pattern); ASSERT_MATCH (cmd, pattern); bson_free (pattern); bson_free (rt_pattern); @@ -336,38 +303,27 @@ test_change_stream_live_track_resume_token (void *test_ctx) ASSERT (client); callbacks = mongoc_apm_callbacks_new (); - mongoc_apm_set_command_started_cb (callbacks, - test_resume_token_command_start); + mongoc_apm_set_command_started_cb (callbacks, test_resume_token_command_start); mongoc_client_set_apm_callbacks (client, callbacks, &ctx); coll = drop_and_get_coll (client, "db", "coll_resume"); ASSERT (coll); - ASSERT_OR_PRINT ( - mongoc_collection_insert_one (coll, tmp_bson (NULL), NULL, NULL, &error), - error); + ASSERT_OR_PRINT (mongoc_collection_insert_one (coll, tmp_bson (NULL), NULL, NULL, &error), error); /* Set the batch size to 1 so we only get one document per call to next. */ - stream = mongoc_collection_watch ( - coll, tmp_bson ("{}"), tmp_bson ("{'batchSize': 1}")); + stream = mongoc_collection_watch (coll, tmp_bson ("{}"), tmp_bson ("{'batchSize': 1}")); ASSERT (stream); - ASSERT_OR_PRINT (!mongoc_change_stream_error_document (stream, &error, NULL), - error); + ASSERT_OR_PRINT (!mongoc_change_stream_error_document (stream, &error, NULL), error); /* Insert a few docs to listen for. Use write concern majority, so subsequent * call to watch will be guaranteed to retrieve them. */ mongoc_write_concern_set_wmajority (wc, 30000); mongoc_write_concern_append (wc, &opts); - ASSERT_OR_PRINT (mongoc_collection_insert_one ( - coll, tmp_bson ("{'_id': 0}"), &opts, NULL, &error), - error); + ASSERT_OR_PRINT (mongoc_collection_insert_one (coll, tmp_bson ("{'_id': 0}"), &opts, NULL, &error), error); - ASSERT_OR_PRINT (mongoc_collection_insert_one ( - coll, tmp_bson ("{'_id': 1}"), &opts, NULL, &error), - error); + ASSERT_OR_PRINT (mongoc_collection_insert_one (coll, tmp_bson ("{'_id': 1}"), &opts, NULL, &error), error); - ASSERT_OR_PRINT (mongoc_collection_insert_one ( - coll, tmp_bson ("{'_id': 2}"), &opts, NULL, &error), - error); + ASSERT_OR_PRINT (mongoc_collection_insert_one (coll, tmp_bson ("{'_id': 2}"), &opts, NULL, &error), error); /* The resume token should be updated to the most recently iterated doc */ ASSERT (mongoc_change_stream_next (stream, &next_doc)); @@ -400,8 +356,7 @@ test_change_stream_live_track_resume_token (void *test_ctx) /* There are no docs left. But the next call should still keep the same * resume token */ ASSERT (!mongoc_change_stream_next (stream, &next_doc)); - ASSERT_OR_PRINT (!mongoc_change_stream_error_document (stream, &error, NULL), - error); + ASSERT_OR_PRINT (!mongoc_change_stream_error_document (stream, &error, NULL), error); ASSERT (!next_doc); resume_token = mongoc_change_stream_get_resume_token (stream); ASSERT (!bson_empty0 (resume_token)); @@ -430,16 +385,13 @@ test_batch_size_command_succeeded (const mongoc_apm_command_succeeded_t *event) const bson_t *reply = mongoc_apm_command_succeeded_get_reply (event); const char *cmd_name = mongoc_apm_command_succeeded_get_command_name (event); - test_batch_size_ctx_t *ctx = - (test_batch_size_ctx_t *) mongoc_apm_command_succeeded_get_context ( - event); + test_batch_size_ctx_t *ctx = (test_batch_size_ctx_t *) mongoc_apm_command_succeeded_get_context (event); if (strcmp (cmd_name, "getMore") == 0) { bson_t next_batch; ++ctx->num_get_mores; bson_lookup_doc (reply, "cursor.nextBatch", &next_batch); - ASSERT (bson_count_keys (&next_batch) == - ctx->expected_getmore_batch_size); + ASSERT (bson_count_keys (&next_batch) == ctx->expected_getmore_batch_size); } else if (strcmp (cmd_name, "aggregate") == 0) { bson_t first_batch; bson_lookup_doc (reply, "cursor.firstBatch", &first_batch); @@ -469,18 +421,14 @@ test_change_stream_live_batch_size (void *test_ctx) ASSERT (client); callbacks = mongoc_apm_callbacks_new (); - mongoc_apm_set_command_succeeded_cb (callbacks, - test_batch_size_command_succeeded); + mongoc_apm_set_command_succeeded_cb (callbacks, test_batch_size_command_succeeded); mongoc_client_set_apm_callbacks (client, callbacks, &ctx); coll = drop_and_get_coll (client, "db", "coll_batch"); ASSERT (coll); - ASSERT_OR_PRINT ( - mongoc_collection_insert_one (coll, tmp_bson (NULL), NULL, NULL, &err), - err); + ASSERT_OR_PRINT (mongoc_collection_insert_one (coll, tmp_bson (NULL), NULL, NULL, &err), err); - stream = mongoc_collection_watch ( - coll, tmp_bson ("{}"), tmp_bson ("{'batchSize': 1}")); + stream = mongoc_collection_watch (coll, tmp_bson ("{}"), tmp_bson ("{'batchSize': 1}")); ASSERT (stream); ctx.expected_agg_batch_size = 0; @@ -496,8 +444,7 @@ test_change_stream_live_batch_size (void *test_ctx) mongoc_write_concern_append (wc, &opts); for (i = 0; i < 10; i++) { bson_t *doc = BCON_NEW ("_id", BCON_INT32 (i)); - ASSERT_OR_PRINT ( - mongoc_collection_insert_one (coll, doc, &opts, NULL, &err), err); + ASSERT_OR_PRINT (mongoc_collection_insert_one (coll, doc, &opts, NULL, &err), err); bson_destroy (doc); } @@ -508,8 +455,7 @@ test_change_stream_live_batch_size (void *test_ctx) ctx.expected_getmore_batch_size = 0; ASSERT (!mongoc_change_stream_next (stream, &next_doc)); - ASSERT_OR_PRINT (!mongoc_change_stream_error_document (stream, &err, NULL), - err); + ASSERT_OR_PRINT (!mongoc_change_stream_error_document (stream, &err, NULL), err); ASSERT (next_doc == NULL); /* 10 getMores for results, 1 for initial next, 1 for last empty next */ @@ -545,34 +491,25 @@ _test_resume_token_error (const char *id_projection) coll = drop_and_get_coll (client, "db", "coll_missing_resume"); ASSERT (coll); - ASSERT_OR_PRINT ( - mongoc_collection_insert_one (coll, tmp_bson (NULL), NULL, NULL, &err), - err); + ASSERT_OR_PRINT (mongoc_collection_insert_one (coll, tmp_bson (NULL), NULL, NULL, &err), err); - stream = mongoc_collection_watch ( - coll, - tmp_bson ("{'pipeline': [{'$project': {'_id': %s }}]}", id_projection), - NULL); + stream = + mongoc_collection_watch (coll, tmp_bson ("{'pipeline': [{'$project': {'_id': %s }}]}", id_projection), NULL); ASSERT (stream); - ASSERT_OR_PRINT (!mongoc_change_stream_error_document (stream, &err, NULL), - err); + ASSERT_OR_PRINT (!mongoc_change_stream_error_document (stream, &err, NULL), err); mongoc_write_concern_set_wmajority (wc, 30000); mongoc_write_concern_append (wc, &opts); - ASSERT_OR_PRINT (mongoc_collection_insert_one ( - coll, tmp_bson ("{'_id': 2}"), &opts, NULL, &err), - err); + ASSERT_OR_PRINT (mongoc_collection_insert_one (coll, tmp_bson ("{'_id': 2}"), &opts, NULL, &err), err); ASSERT (!mongoc_change_stream_next (stream, &next_doc)); ASSERT (mongoc_change_stream_error_document (stream, &err, NULL)); /* Newer server versions emit different errors. */ if (!test_framework_max_wire_version_at_least (8)) { - ASSERT_ERROR_CONTAINS (err, - MONGOC_ERROR_CURSOR, - MONGOC_ERROR_CHANGE_STREAM_NO_RESUME_TOKEN, - "Cannot provide resume functionality"); + ASSERT_ERROR_CONTAINS ( + err, MONGOC_ERROR_CURSOR, MONGOC_ERROR_CHANGE_STREAM_NO_RESUME_TOKEN, "Cannot provide resume functionality"); } else { ASSERT_ERROR_CONTAINS (err, MONGOC_ERROR_SERVER, @@ -609,9 +546,7 @@ test_change_stream_live_invalid_resume_token (void *test_ctx) } static void -_test_getmore_error (const char *server_reply, - bool should_resume, - bool resume_kills_cursor) +_test_getmore_error (const char *server_reply, bool should_resume, bool resume_kills_cursor) { mock_server_t *server; request_t *request; @@ -623,15 +558,11 @@ _test_getmore_error (const char *server_reply, server = mock_server_with_auto_hello (WIRE_VERSION_MIN); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); coll = mongoc_client_get_collection (client, "db", "coll"); future = future_collection_watch (coll, tmp_bson ("{}"), NULL); - request = mock_server_receives_msg ( - server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', 'aggregate': 'coll'}")); - reply_to_request_simple ( - request, - "{'cursor': {'id': 123, 'ns': 'db.coll','firstBatch': []},'ok': 1 }"); + request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', 'aggregate': 'coll'}")); + reply_to_request_simple (request, "{'cursor': {'id': 123, 'ns': 'db.coll','firstBatch': []},'ok': 1 }"); stream = future_get_mongoc_change_stream_ptr (future); BSON_ASSERT (stream); future_destroy (future); @@ -639,12 +570,11 @@ _test_getmore_error (const char *server_reply, /* the first getMore receives an error. */ future = future_change_stream_next (stream, &next_doc); - request = - mock_server_receives_msg (server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db'," - " 'getMore': {'$numberLong': '123'}," - " 'collection': 'coll'}")); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'db'," + " 'getMore': {'$numberLong': '123'}," + " 'collection': 'coll'}")); reply_to_request_simple (request, server_reply); request_destroy (request); if (should_resume) { @@ -653,17 +583,12 @@ _test_getmore_error (const char *server_reply, /* errors that are considered "not primary" or "node is recovering" * errors by SDAM will mark the connected server as UNKNOWN, and no * killCursors will be executed. */ - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db', 'killCursors': 'coll'}")); + request = + mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', 'killCursors': 'coll'}")); reply_to_request_simple (request, "{'cursorsKilled': [123]}"); request_destroy (request); } - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db', 'aggregate': 'coll'}")); + request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', 'aggregate': 'coll'}")); reply_to_request_simple (request, "{'cursor':" " {'id': 124," @@ -691,41 +616,30 @@ _test_getmore_error (const char *server_reply, static void test_getmore_errors (void) { - _test_getmore_error ("{'ok': 0, 'code': 1, 'errmsg': 'internal error'}", - false /* should_resume */, - false /* ignored */); - _test_getmore_error ("{'ok': 0, 'code': 6, 'errmsg': 'host unreachable'}", - true /* should_resume */, - true /* resume_kills_cursor */); - _test_getmore_error ("{'ok': 0, 'code': 12345, 'errmsg': 'random error'}", - false /* should_resume */, - false /* ignored */); + _test_getmore_error ( + "{'ok': 0, 'code': 1, 'errmsg': 'internal error'}", false /* should_resume */, false /* ignored */); + _test_getmore_error ( + "{'ok': 0, 'code': 6, 'errmsg': 'host unreachable'}", true /* should_resume */, true /* resume_kills_cursor */); + _test_getmore_error ( + "{'ok': 0, 'code': 12345, 'errmsg': 'random error'}", false /* should_resume */, false /* ignored */); /* most error codes are resumable, excluding a few deny listed ones. */ - _test_getmore_error ("{'ok': 0, 'code': 11601, 'errmsg': 'interrupted'}", - false /* should_resume */, - false /* ignored */); _test_getmore_error ( - "{'ok': 0, 'code': 136, 'errmsg': 'capped position lost'}", - false /* should_resume */, - false /* ignored */); - _test_getmore_error ("{'ok': 0, 'code': 237, 'errmsg': 'cursor killed'}", - false /* should_resume */, - false /* ignored */); - _test_getmore_error ("{'ok': 0, 'errmsg': 'random error'}", - false /* should_resume */, - false /* ignored */); - /* Even an error with a 'NonResumableChangeStreamError' label will resume if - * it is on the allow list. */ + "{'ok': 0, 'code': 11601, 'errmsg': 'interrupted'}", false /* should_resume */, false /* ignored */); _test_getmore_error ( - "{'ok': 0, 'code': 6, 'errorLabels': " - "['NonResumableChangeStreamError'], 'errmsg': 'host unreachable'}", - true /* should_resume */, - true /* resume_kills_cursor */); + "{'ok': 0, 'code': 136, 'errmsg': 'capped position lost'}", false /* should_resume */, false /* ignored */); _test_getmore_error ( - "{'ok': 0, 'code': 6, 'errorLabels': " - "['NonRetryableChangeStreamError'], 'errmsg': 'host unreachable'}", - true /* should_resume */, - true /* resume_kills_cursor */); + "{'ok': 0, 'code': 237, 'errmsg': 'cursor killed'}", false /* should_resume */, false /* ignored */); + _test_getmore_error ("{'ok': 0, 'errmsg': 'random error'}", false /* should_resume */, false /* ignored */); + /* Even an error with a 'NonResumableChangeStreamError' label will resume if + * it is on the allow list. */ + _test_getmore_error ("{'ok': 0, 'code': 6, 'errorLabels': " + "['NonResumableChangeStreamError'], 'errmsg': 'host unreachable'}", + true /* should_resume */, + true /* resume_kills_cursor */); + _test_getmore_error ("{'ok': 0, 'code': 6, 'errorLabels': " + "['NonRetryableChangeStreamError'], 'errmsg': 'host unreachable'}", + true /* should_resume */, + true /* resume_kills_cursor */); } /* From Change Streams Spec tests: * "ChangeStream will automatically resume one time on a resumable error @@ -747,16 +661,13 @@ test_change_stream_resumable_error (void) bson_error_t err; const bson_t *err_doc = NULL; const bson_t *next_doc = NULL; - const char *not_primary_err = - "{ 'code': 10107, 'errmsg': 'not primary', 'ok': 0 }"; - const char *interrupted_err = - "{ 'code': 11601, 'errmsg': 'interrupted', 'ok': 0 }"; + const char *not_primary_err = "{ 'code': 10107, 'errmsg': 'not primary', 'ok': 0 }"; + const char *interrupted_err = "{ 'code': 11601, 'errmsg': 'interrupted', 'ok': 0 }"; const bson_t *watch_cmd = tmp_bson ("{'$db': 'db'," " 'aggregate': 'coll'," " 'pipeline': [{'$changeStream': {}}]," " 'cursor': {}}"); - const char *expected_msg = - "{'$db': 'db', 'getMore': {'$numberLong': '%d'}, 'collection': 'coll' }"; + const char *expected_msg = "{'$db': 'db', 'getMore': {'$numberLong': '%d'}, 'collection': 'coll' }"; server = mock_server_with_auto_hello (WIRE_VERSION_MIN); mock_server_run (server); @@ -784,8 +695,7 @@ test_change_stream_resumable_error (void) /* Test that a network hangup results in a resumable error */ future = future_change_stream_next (stream, &next_doc); - request = mock_server_receives_msg ( - server, MONGOC_MSG_NONE, tmp_bson (expected_msg, 123)); + request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson (expected_msg, 123)); BSON_ASSERT (request); reply_to_request_with_hang_up (request); request_destroy (request); @@ -793,37 +703,28 @@ test_change_stream_resumable_error (void) /* Retry command */ request = mock_server_receives_msg (server, MONGOC_MSG_NONE, watch_cmd); BSON_ASSERT (request); - reply_to_request_simple ( - request, - "{'cursor': {'id': 124,'ns': 'db.coll','firstBatch': []},'ok': 1 }"); + reply_to_request_simple (request, "{'cursor': {'id': 124,'ns': 'db.coll','firstBatch': []},'ok': 1 }"); request_destroy (request); - request = mock_server_receives_msg ( - server, MONGOC_MSG_NONE, tmp_bson (expected_msg, 124)); - reply_to_request_simple (request, - "{ 'cursor': { 'nextBatch': [] }, 'ok': 1 }"); + request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson (expected_msg, 124)); + reply_to_request_simple (request, "{ 'cursor': { 'nextBatch': [] }, 'ok': 1 }"); request_destroy (request); ASSERT (!future_get_bool (future)); - ASSERT_OR_PRINT (!mongoc_change_stream_error_document (stream, &err, NULL), - err); + ASSERT_OR_PRINT (!mongoc_change_stream_error_document (stream, &err, NULL), err); ASSERT (next_doc == NULL); future_destroy (future); /* Test the "not_primary" resumable error occurring twice in a row */ future = future_change_stream_next (stream, &next_doc); - request = mock_server_receives_msg ( - server, MONGOC_MSG_NONE, tmp_bson (expected_msg, 124)); + request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson (expected_msg, 124)); reply_to_request_simple (request, not_primary_err); request_destroy (request); /* Retry command */ request = mock_server_receives_msg (server, MONGOC_MSG_NONE, watch_cmd); - reply_to_request_simple ( - request, - "{'cursor': {'id': 125, 'ns': 'db.coll','firstBatch': []},'ok': 1}"); + reply_to_request_simple (request, "{'cursor': {'id': 125, 'ns': 'db.coll','firstBatch': []},'ok': 1}"); request_destroy (request); - request = mock_server_receives_msg ( - server, MONGOC_MSG_NONE, tmp_bson (expected_msg, 125)); + request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson (expected_msg, 125)); reply_to_request_simple (request, not_primary_err); request_destroy (request); @@ -835,8 +736,7 @@ test_change_stream_resumable_error (void) "}"); request_destroy (request); - request = mock_server_receives_msg ( - server, MONGOC_MSG_NONE, tmp_bson (expected_msg, 126)); + request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson (expected_msg, 126)); reply_to_request_simple (request, interrupted_err); request_destroy (request); @@ -862,16 +762,13 @@ test_change_stream_resumable_error (void) future_destroy (future); future = future_change_stream_next (stream, &next_doc); - request = mock_server_receives_msg ( - server, MONGOC_MSG_NONE, tmp_bson (expected_msg, 123)); - reply_to_request_simple ( - request, "{ 'code': 10107, 'errmsg': 'not primary', 'ok': 0 }"); + request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson (expected_msg, 123)); + reply_to_request_simple (request, "{ 'code': 10107, 'errmsg': 'not primary', 'ok': 0 }"); request_destroy (request); /* Retry command */ request = mock_server_receives_msg (server, MONGOC_MSG_NONE, watch_cmd); - reply_to_request_simple (request, - "{'code': 123, 'errmsg': 'bad cmd', 'ok': 0}"); + reply_to_request_simple (request, "{'code': 123, 'errmsg': 'bad cmd', 'ok': 0}"); request_destroy (request); /* Check that error is returned */ @@ -906,8 +803,7 @@ test_change_stream_options (void) server = mock_server_with_auto_hello (WIRE_VERSION_MIN); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); ASSERT (client); coll = mongoc_client_get_collection (client, "db", "coll"); @@ -925,34 +821,29 @@ test_change_stream_options (void) */ /* fullDocument */ - future = future_collection_watch ( - coll, - tmp_bson ("{}"), - tmp_bson ("{ 'fullDocument': 'updateLookup', " - "'resumeAfter': {'resume': 'after'}, " - "'startAfter': {'start': 'after'}, " - "'startAtOperationTime': { '$timestamp': { 't': 1, 'i': 1 }}, " - "'maxAwaitTimeMS': 5000, 'batchSize': " - "5, 'collation': { 'locale': 'en' }}")); - - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ( - "{'$db': 'db'," - " 'aggregate': 'coll'," - " 'pipeline': [" - " {'$changeStream': {" - " 'fullDocument': 'updateLookup'," - " 'resumeAfter': {'resume': 'after'}," - " 'startAfter': {'start': 'after'}," - " 'startAtOperationTime': {'$timestamp': { 't': 1, 'i': 1 }}}}]," - " 'cursor': {'batchSize': 5}," - " 'collation': {'locale': 'en'}}")); - - reply_to_request_simple ( - request, - "{'cursor': {'id': 123,'ns': 'db.coll','firstBatch': []},'ok': 1 }"); + future = future_collection_watch (coll, + tmp_bson ("{}"), + tmp_bson ("{ 'fullDocument': 'updateLookup', " + "'resumeAfter': {'resume': 'after'}, " + "'startAfter': {'start': 'after'}, " + "'startAtOperationTime': { '$timestamp': { 't': 1, 'i': 1 }}, " + "'maxAwaitTimeMS': 5000, 'batchSize': " + "5, 'collation': { 'locale': 'en' }}")); + + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'db'," + " 'aggregate': 'coll'," + " 'pipeline': [" + " {'$changeStream': {" + " 'fullDocument': 'updateLookup'," + " 'resumeAfter': {'resume': 'after'}," + " 'startAfter': {'start': 'after'}," + " 'startAtOperationTime': {'$timestamp': { 't': 1, 'i': 1 }}}}]," + " 'cursor': {'batchSize': 5}," + " 'collation': {'locale': 'en'}}")); + + reply_to_request_simple (request, "{'cursor': {'id': 123,'ns': 'db.coll','firstBatch': []},'ok': 1 }"); stream = future_get_mongoc_change_stream_ptr (future); ASSERT (stream); @@ -960,20 +851,17 @@ test_change_stream_options (void) request_destroy (request); future = future_change_stream_next (stream, &next_doc); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db'," - " 'getMore': {'$numberLong': '123'}," - " 'collection': 'coll'," - " 'maxTimeMS': {'$numberLong': '5000'}," - " 'batchSize': {'$numberLong': '5'}}")); - reply_to_request_simple (request, - "{ 'cursor': { 'nextBatch': [] }, 'ok': 1 }"); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'db'," + " 'getMore': {'$numberLong': '123'}," + " 'collection': 'coll'," + " 'maxTimeMS': {'$numberLong': '5000'}," + " 'batchSize': {'$numberLong': '5'}}")); + reply_to_request_simple (request, "{ 'cursor': { 'nextBatch': [] }, 'ok': 1 }"); request_destroy (request); ASSERT (!future_get_bool (future)); - ASSERT_OR_PRINT (!mongoc_change_stream_error_document (stream, &err, NULL), - err); + ASSERT_OR_PRINT (!mongoc_change_stream_error_document (stream, &err, NULL), err); ASSERT (next_doc == NULL); future_destroy (future); @@ -1003,20 +891,15 @@ test_change_stream_live_watch (void *test_ctx) coll = drop_and_get_coll (client, "db", "coll_watch"); ASSERT (coll); - ASSERT_OR_PRINT ( - mongoc_collection_insert_one (coll, tmp_bson (NULL), NULL, NULL, &err), - err); + ASSERT_OR_PRINT (mongoc_collection_insert_one (coll, tmp_bson (NULL), NULL, NULL, &err), err); stream = mongoc_collection_watch (coll, tmp_bson ("{}"), NULL); ASSERT (stream); - ASSERT_OR_PRINT (!mongoc_change_stream_error_document (stream, &err, NULL), - err); + ASSERT_OR_PRINT (!mongoc_change_stream_error_document (stream, &err, NULL), err); /* Test that inserting a doc produces the expected change stream doc */ mongoc_write_concern_append (wc, &opts); - ASSERT_OR_PRINT ( - mongoc_collection_insert_one (coll, inserted_doc, &opts, NULL, &err), - err); + ASSERT_OR_PRINT (mongoc_collection_insert_one (coll, inserted_doc, &opts, NULL, &err), err); ASSERT (mongoc_change_stream_next (stream, &next_doc)); @@ -1028,31 +911,23 @@ test_change_stream_live_watch (void *test_ctx) ASSERT_HAS_FIELD (next_doc, "_id"); ASSERT (!strcmp (bson_lookup_utf8 (next_doc, "operationType"), "insert")); - ASSERT_MATCH ( - next_doc, - "{ '_id': { '$exists': true },'operationType': 'insert', 'ns': " - "{ 'db': 'db', 'coll': 'coll_watch' },'documentKey': { " - "'$exists': true }, 'updateDescription': { '$exists': false }, " - "'fullDocument': { '_id': { '$exists': true }, 'x': 'y' }}"); + ASSERT_MATCH (next_doc, + "{ '_id': { '$exists': true },'operationType': 'insert', 'ns': " + "{ 'db': 'db', 'coll': 'coll_watch' },'documentKey': { " + "'$exists': true }, 'updateDescription': { '$exists': false }, " + "'fullDocument': { '_id': { '$exists': true }, 'x': 'y' }}"); /* Test updating a doc */ ASSERT_OR_PRINT ( - mongoc_collection_update_one (coll, - tmp_bson ("{}"), - tmp_bson ("{'$set': {'x': 'z'} }"), - &opts, - NULL, - &err), - err); + mongoc_collection_update_one (coll, tmp_bson ("{}"), tmp_bson ("{'$set': {'x': 'z'} }"), &opts, NULL, &err), err); ASSERT (mongoc_change_stream_next (stream, &next_doc)); - ASSERT_MATCH ( - next_doc, - "{ '_id': { '$exists': true },'operationType': 'update', 'ns': { 'db': " - "'db', 'coll': 'coll_watch' },'documentKey': { '$exists': " - "true }, 'updateDescription': { 'updatedFields': { 'x': 'z' } " - "}, 'fullDocument': { '$exists': false }}"); + ASSERT_MATCH (next_doc, + "{ '_id': { '$exists': true },'operationType': 'update', 'ns': { 'db': " + "'db', 'coll': 'coll_watch' },'documentKey': { '$exists': " + "true }, 'updateDescription': { 'updatedFields': { 'x': 'z' } " + "}, 'fullDocument': { '$exists': false }}"); bson_destroy (&opts); mongoc_write_concern_destroy (wc); @@ -1090,14 +965,13 @@ test_change_stream_live_read_prefs (void *test_ctx) coll = drop_and_get_coll (client, "db", "coll_read_prefs"); ASSERT (coll); - ASSERT_OR_PRINT (mongoc_collection_insert_one ( - coll, - tmp_bson (NULL), - tmp_bson ("{'writeConcern': {'w': %d}}", - test_framework_data_nodes_count ()), - NULL, - &err), - err); + ASSERT_OR_PRINT ( + mongoc_collection_insert_one (coll, + tmp_bson (NULL), + tmp_bson ("{'writeConcern': {'w': %d}}", test_framework_data_nodes_count ()), + NULL, + &err), + err); prefs = mongoc_read_prefs_copy (mongoc_collection_get_read_prefs (coll)); mongoc_read_prefs_set_mode (prefs, MONGOC_READ_SECONDARY); @@ -1115,8 +989,7 @@ test_change_stream_live_read_prefs (void *test_ctx) /* Call next to create the cursor, should return no documents. */ ASSERT (!mongoc_change_stream_next (stream, &next_doc)); - ASSERT_OR_PRINT (!mongoc_change_stream_error_document (stream, &err, NULL), - err); + ASSERT_OR_PRINT (!mongoc_change_stream_error_document (stream, &err, NULL), err); _setup_for_resume (stream); @@ -1124,8 +997,7 @@ test_change_stream_live_read_prefs (void *test_ctx) /* depending on the server version, this may or may not receive another * document on resume */ (void) mongoc_change_stream_next (stream, &next_doc); - ASSERT_OR_PRINT ( - !mongoc_change_stream_error_document (stream, &err, &next_doc), err); + ASSERT_OR_PRINT (!mongoc_change_stream_error_document (stream, &err, &next_doc), err); raw_cursor = stream->cursor; ASSERT (first_cursor_id != mongoc_cursor_get_id (raw_cursor)); @@ -1144,19 +1016,14 @@ test_change_stream_server_selection_fails (void) { const bson_t *bson; bson_error_t err; - mongoc_client_t *client = - test_framework_client_new ("mongodb://localhost:12345/", NULL); - mongoc_collection_t *coll = - mongoc_client_get_collection (client, "test", "test"); - mongoc_change_stream_t *cs = - mongoc_collection_watch (coll, tmp_bson ("{}"), NULL); + mongoc_client_t *client = test_framework_client_new ("mongodb://localhost:12345/", NULL); + mongoc_collection_t *coll = mongoc_client_get_collection (client, "test", "test"); + mongoc_change_stream_t *cs = mongoc_collection_watch (coll, tmp_bson ("{}"), NULL); mongoc_change_stream_next (cs, &bson); BSON_ASSERT (mongoc_change_stream_error_document (cs, &err, &bson)); - ASSERT_ERROR_CONTAINS (err, - MONGOC_ERROR_SERVER_SELECTION, - MONGOC_ERROR_SERVER_SELECTION_FAILURE, - "No servers yet eligible for rescan"); + ASSERT_ERROR_CONTAINS ( + err, MONGOC_ERROR_SERVER_SELECTION, MONGOC_ERROR_SERVER_SELECTION_FAILURE, "No servers yet eligible for rescan"); mongoc_change_stream_destroy (cs); mongoc_collection_destroy (coll); mongoc_client_destroy (client); @@ -1177,11 +1044,8 @@ test_change_stream_next_after_error (void *test_ctx) mongoc_client_set_error_api (client, MONGOC_ERROR_API_VERSION_2); coll = mongoc_client_get_collection (client, "db", "coll"); - ASSERT_OR_PRINT ( - mongoc_collection_insert_one (coll, tmp_bson (NULL), NULL, NULL, &err), - err); - stream = mongoc_collection_watch ( - coll, tmp_bson ("{'pipeline': ['invalid_stage']}"), NULL); + ASSERT_OR_PRINT (mongoc_collection_insert_one (coll, tmp_bson (NULL), NULL, NULL, &err), err); + stream = mongoc_collection_watch (coll, tmp_bson ("{'pipeline': ['invalid_stage']}"), NULL); BSON_ASSERT (!mongoc_change_stream_next (stream, &bson)); BSON_ASSERT (mongoc_change_stream_error_document (stream, &err, &bson)); BSON_ASSERT (err.domain == MONGOC_ERROR_SERVER); @@ -1200,8 +1064,7 @@ _accepts_array_started (const mongoc_apm_command_started_t *event) { const bson_t *cmd = mongoc_apm_command_started_get_command (event); const char *cmd_name = mongoc_apm_command_started_get_command_name (event); - array_started_ctx_t *ctx = - (array_started_ctx_t *) mongoc_apm_command_started_get_context (event); + array_started_ctx_t *ctx = (array_started_ctx_t *) mongoc_apm_command_started_get_context (event); if (strcmp (cmd_name, "aggregate") != 0) { return; } @@ -1221,66 +1084,45 @@ test_change_stream_accepts_array (void *test_ctx) mongoc_change_stream_t *stream; const bson_t *bson; bson_error_t err; - bson_t *opts = - tmp_bson ("{'maxAwaitTimeMS': 1}"); /* to speed up the test. */ + bson_t *opts = tmp_bson ("{'maxAwaitTimeMS': 1}"); /* to speed up the test. */ BSON_UNUSED (test_ctx); mongoc_client_set_error_api (client, MONGOC_ERROR_API_VERSION_2); /* set up apm callbacks to listen for the agg commands. */ - ctx.pattern = - bson_strdup ("{'aggregate': 'coll', 'pipeline': [ {'$changeStream': {}}, " - "{'$match': {'x': 1}}, {'$project': {'x': 1}}]}"); + ctx.pattern = bson_strdup ("{'aggregate': 'coll', 'pipeline': [ {'$changeStream': {}}, " + "{'$match': {'x': 1}}, {'$project': {'x': 1}}]}"); mongoc_apm_set_command_started_cb (callbacks, _accepts_array_started); mongoc_client_set_apm_callbacks (client, callbacks, &ctx); coll = mongoc_client_get_collection (client, "db", "coll"); - ASSERT_OR_PRINT ( - mongoc_collection_insert_one (coll, tmp_bson (NULL), NULL, NULL, &err), - err); + ASSERT_OR_PRINT (mongoc_collection_insert_one (coll, tmp_bson (NULL), NULL, NULL, &err), err); /* try starting a change stream with a { "pipeline": [...] } argument */ - stream = mongoc_collection_watch ( - coll, - tmp_bson ("{'pipeline': [{'$match': {'x': 1}}, {'$project': {'x': 1}}]}"), - opts); + stream = + mongoc_collection_watch (coll, tmp_bson ("{'pipeline': [{'$match': {'x': 1}}, {'$project': {'x': 1}}]}"), opts); (void) mongoc_change_stream_next (stream, &bson); - ASSERT_OR_PRINT (!mongoc_change_stream_error_document (stream, &err, &bson), - err); + ASSERT_OR_PRINT (!mongoc_change_stream_error_document (stream, &err, &bson), err); ASSERT_CMPINT32 (ctx.agg_count, ==, 1); mongoc_change_stream_destroy (stream); /* try with an array like document. */ - stream = mongoc_collection_watch ( - coll, - tmp_bson ("{'0': {'$match': {'x': 1}}, '1': {'$project': {'x': 1}}}"), - opts); + stream = mongoc_collection_watch (coll, tmp_bson ("{'0': {'$match': {'x': 1}}, '1': {'$project': {'x': 1}}}"), opts); (void) mongoc_change_stream_next (stream, &bson); - ASSERT_OR_PRINT (!mongoc_change_stream_error_document (stream, &err, &bson), - err); + ASSERT_OR_PRINT (!mongoc_change_stream_error_document (stream, &err, &bson), err); ASSERT_CMPINT32 (ctx.agg_count, ==, 2); mongoc_change_stream_destroy (stream); /* try with malformed { "pipeline": [...] } argument. */ bson_free (ctx.pattern); - ctx.pattern = bson_strdup ( - "{'aggregate': 'coll', 'pipeline': [ {'$changeStream': {}}, 42 ]}"); - stream = - mongoc_collection_watch (coll, tmp_bson ("{'pipeline': [42] }"), NULL); + ctx.pattern = bson_strdup ("{'aggregate': 'coll', 'pipeline': [ {'$changeStream': {}}, 42 ]}"); + stream = mongoc_collection_watch (coll, tmp_bson ("{'pipeline': [42] }"), NULL); (void) mongoc_change_stream_next (stream, &bson); BSON_ASSERT (mongoc_change_stream_error_document (stream, &err, &bson)); - ASSERT_ERROR_CONTAINS ( - err, - MONGOC_ERROR_SERVER, - 14, - "Each element of the 'pipeline' array must be an object"); + ASSERT_ERROR_CONTAINS (err, MONGOC_ERROR_SERVER, 14, "Each element of the 'pipeline' array must be an object"); ASSERT_CMPINT32 (ctx.agg_count, ==, 3); mongoc_change_stream_destroy (stream); /* try with malformed array doc argument. */ stream = mongoc_collection_watch (coll, tmp_bson ("{'0': 42 }"), NULL); (void) mongoc_change_stream_next (stream, &bson); BSON_ASSERT (mongoc_change_stream_error_document (stream, &err, &bson)); - ASSERT_ERROR_CONTAINS ( - err, - MONGOC_ERROR_SERVER, - 14, - "Each element of the 'pipeline' array must be an object"); + ASSERT_ERROR_CONTAINS (err, MONGOC_ERROR_SERVER, 14, "Each element of the 'pipeline' array must be an object"); ASSERT_CMPINT32 (ctx.agg_count, ==, 4); mongoc_change_stream_destroy (stream); bson_free (ctx.pattern); @@ -1306,21 +1148,13 @@ test_change_stream_start_at_operation_time (void *test_ctx) session = mongoc_client_start_session (client, NULL, &error); coll = mongoc_client_get_collection (client, "db", "coll"); bson_init (&opts); - ASSERT_OR_PRINT (mongoc_client_session_append (session, &opts, &error), - error); - ASSERT_OR_PRINT ( - mongoc_collection_insert_one (coll, tmp_bson (NULL), &opts, NULL, &error), - error); - BSON_APPEND_TIMESTAMP (&opts, - "startAtOperationTime", - session->operation_timestamp, - session->operation_increment); - stream = - mongoc_collection_watch (coll, tmp_bson ("{'pipeline': []}"), &opts); + ASSERT_OR_PRINT (mongoc_client_session_append (session, &opts, &error), error); + ASSERT_OR_PRINT (mongoc_collection_insert_one (coll, tmp_bson (NULL), &opts, NULL, &error), error); + BSON_APPEND_TIMESTAMP (&opts, "startAtOperationTime", session->operation_timestamp, session->operation_increment); + stream = mongoc_collection_watch (coll, tmp_bson ("{'pipeline': []}"), &opts); (void) mongoc_change_stream_next (stream, &doc); - ASSERT_OR_PRINT (!mongoc_change_stream_error_document (stream, &error, NULL), - error); + ASSERT_OR_PRINT (!mongoc_change_stream_error_document (stream, &error, NULL), error); bson_destroy (&opts); mongoc_change_stream_destroy (stream); @@ -1346,8 +1180,7 @@ _resume_at_optime_started (const mongoc_apm_command_started_t *event) resume_ctx_t *ctx; ctx = (resume_ctx_t *) mongoc_apm_command_started_get_context (event); - if (0 != strcmp (mongoc_apm_command_started_get_command_name (event), - "aggregate")) { + if (0 != strcmp (mongoc_apm_command_started_get_command_name (event), "aggregate")) { return; } @@ -1367,12 +1200,10 @@ _resume_at_optime_started (const mongoc_apm_command_started_t *event) /* it should re-use the same optime on resume. */ bson_lookup_value (&ctx->agg_reply, "operationTime", &replied_optime); - bson_lookup_value (mongoc_apm_command_started_get_command (event), - "pipeline.0.$changeStream.startAtOperationTime", - &sent_optime); + bson_lookup_value ( + mongoc_apm_command_started_get_command (event), "pipeline.0.$changeStream.startAtOperationTime", &sent_optime); BSON_ASSERT (replied_optime.value_type == BSON_TYPE_TIMESTAMP); - BSON_ASSERT ( - match_bson_value (&sent_optime, &replied_optime, &match_ctx)); + BSON_ASSERT (match_bson_value (&sent_optime, &replied_optime, &match_ctx)); bson_value_destroy (&sent_optime); bson_value_destroy (&replied_optime); } @@ -1384,11 +1215,9 @@ _resume_at_optime_succeeded (const mongoc_apm_command_succeeded_t *event) resume_ctx_t *ctx; ctx = (resume_ctx_t *) mongoc_apm_command_succeeded_get_context (event); - if (!strcmp (mongoc_apm_command_succeeded_get_command_name (event), - "aggregate")) { + if (!strcmp (mongoc_apm_command_succeeded_get_command_name (event), "aggregate")) { bson_destroy (&ctx->agg_reply); - bson_copy_to (mongoc_apm_command_succeeded_get_reply (event), - &ctx->agg_reply); + bson_copy_to (mongoc_apm_command_succeeded_get_reply (event), &ctx->agg_reply); } } @@ -1415,8 +1244,7 @@ test_change_stream_resume_at_optime (void *test_ctx) _setup_for_resume (stream); (void) mongoc_change_stream_next (stream, &doc); - ASSERT_OR_PRINT (!mongoc_change_stream_error_document (stream, &error, NULL), - error); + ASSERT_OR_PRINT (!mongoc_change_stream_error_document (stream, &error, NULL), error); BSON_ASSERT (ctx.has_initiated); BSON_ASSERT (ctx.has_resumed); @@ -1428,14 +1256,12 @@ test_change_stream_resume_at_optime (void *test_ctx) } static void -_resume_with_post_batch_resume_token_started ( - const mongoc_apm_command_started_t *event) +_resume_with_post_batch_resume_token_started (const mongoc_apm_command_started_t *event) { resume_ctx_t *ctx; ctx = (resume_ctx_t *) mongoc_apm_command_started_get_context (event); - if (0 != strcmp (mongoc_apm_command_started_get_command_name (event), - "aggregate")) { + if (0 != strcmp (mongoc_apm_command_started_get_command_name (event), "aggregate")) { return; } @@ -1454,11 +1280,9 @@ _resume_with_post_batch_resume_token_started ( match_ctx_t match_ctx = {{0}}; /* it should re-use the same postBatchResumeToken on resume. */ + bson_lookup_value (&ctx->agg_reply, "cursor.postBatchResumeToken", &replied_pbrt); bson_lookup_value ( - &ctx->agg_reply, "cursor.postBatchResumeToken", &replied_pbrt); - bson_lookup_value (mongoc_apm_command_started_get_command (event), - "pipeline.0.$changeStream.resumeAfter", - &sent_pbrt); + mongoc_apm_command_started_get_command (event), "pipeline.0.$changeStream.resumeAfter", &sent_pbrt); BSON_ASSERT (replied_pbrt.value_type == BSON_TYPE_DOCUMENT); BSON_ASSERT (match_bson_value (&sent_pbrt, &replied_pbrt, &match_ctx)); bson_value_destroy (&sent_pbrt); @@ -1467,17 +1291,14 @@ _resume_with_post_batch_resume_token_started ( } static void -_resume_with_post_batch_resume_token_succeeded ( - const mongoc_apm_command_succeeded_t *event) +_resume_with_post_batch_resume_token_succeeded (const mongoc_apm_command_succeeded_t *event) { resume_ctx_t *ctx; ctx = (resume_ctx_t *) mongoc_apm_command_succeeded_get_context (event); - if (!strcmp (mongoc_apm_command_succeeded_get_command_name (event), - "aggregate")) { + if (!strcmp (mongoc_apm_command_succeeded_get_command_name (event), "aggregate")) { bson_destroy (&ctx->agg_reply); - bson_copy_to (mongoc_apm_command_succeeded_get_reply (event), - &ctx->agg_reply); + bson_copy_to (mongoc_apm_command_succeeded_get_reply (event), &ctx->agg_reply); } } @@ -1496,18 +1317,15 @@ test_change_stream_resume_with_post_batch_resume_token (void *test_ctx) BSON_UNUSED (test_ctx); callbacks = mongoc_apm_callbacks_new (); - mongoc_apm_set_command_started_cb ( - callbacks, _resume_with_post_batch_resume_token_started); - mongoc_apm_set_command_succeeded_cb ( - callbacks, _resume_with_post_batch_resume_token_succeeded); + mongoc_apm_set_command_started_cb (callbacks, _resume_with_post_batch_resume_token_started); + mongoc_apm_set_command_succeeded_cb (callbacks, _resume_with_post_batch_resume_token_succeeded); mongoc_client_set_apm_callbacks (client, callbacks, &ctx); coll = mongoc_client_get_collection (client, "db", "coll"); stream = mongoc_collection_watch (coll, tmp_bson ("{'pipeline': []}"), NULL); _setup_for_resume (stream); (void) mongoc_change_stream_next (stream, &doc); - ASSERT_OR_PRINT (!mongoc_change_stream_error_document (stream, &error, NULL), - error); + ASSERT_OR_PRINT (!mongoc_change_stream_error_document (stream, &error, NULL), error); BSON_ASSERT (ctx.has_initiated); BSON_ASSERT (ctx.has_resumed); @@ -1538,13 +1356,10 @@ test_change_stream_database_watch (void *test_ctx) stream = mongoc_database_watch (db, tmp_bson ("{}"), NULL); coll = mongoc_database_get_collection (db, "coll"); - ASSERT_OR_PRINT ( - mongoc_collection_insert_one (coll, tmp_bson (NULL), &opts, NULL, &error), - error); + ASSERT_OR_PRINT (mongoc_collection_insert_one (coll, tmp_bson (NULL), &opts, NULL, &error), error); (void) mongoc_change_stream_next (stream, &doc); - ASSERT_OR_PRINT (!mongoc_change_stream_error_document (stream, &error, NULL), - error); + ASSERT_OR_PRINT (!mongoc_change_stream_error_document (stream, &error, NULL), error); bson_destroy (&opts); mongoc_change_stream_destroy (stream); @@ -1571,13 +1386,10 @@ test_change_stream_client_watch (void *test_ctx) stream = mongoc_client_watch (client, tmp_bson ("{}"), NULL); coll = mongoc_client_get_collection (client, "db", "coll"); - ASSERT_OR_PRINT ( - mongoc_collection_insert_one (coll, tmp_bson (NULL), &opts, NULL, &error), - error); + ASSERT_OR_PRINT (mongoc_collection_insert_one (coll, tmp_bson (NULL), &opts, NULL, &error), error); (void) mongoc_change_stream_next (stream, &doc); - ASSERT_OR_PRINT (!mongoc_change_stream_error_document (stream, &error, NULL), - error); + ASSERT_OR_PRINT (!mongoc_change_stream_error_document (stream, &error, NULL), error); bson_destroy (&opts); mongoc_change_stream_destroy (stream); @@ -1595,8 +1407,7 @@ _skip_if_rs_version_less_than (const char *version) if (!test_framework_skip_if_not_replset ()) { return 0; } - if (test_framework_get_server_version () >= - test_framework_str_to_version (version)) { + if (test_framework_get_server_version () >= test_framework_str_to_version (version)) { return 1; } return 0; @@ -1625,17 +1436,13 @@ typedef struct { } change_stream_spec_ctx_t; static bool -change_stream_spec_operation_cb (json_test_ctx_t *ctx, - const bson_t *test, - const bson_t *operation) +change_stream_spec_operation_cb (json_test_ctx_t *ctx, const bson_t *test, const bson_t *operation) { bson_t reply; bool res; - mongoc_collection_t *coll = - mongoc_client_get_collection (ctx->client, - bson_lookup_utf8 (operation, "database"), - bson_lookup_utf8 (operation, "collection")); + mongoc_collection_t *coll = mongoc_client_get_collection ( + ctx->client, bson_lookup_utf8 (operation, "database"), bson_lookup_utf8 (operation, "collection")); res = json_test_operation (ctx, test, operation, coll, NULL, &reply); mongoc_collection_destroy (coll); bson_destroy (&reply); @@ -1644,11 +1451,9 @@ change_stream_spec_operation_cb (json_test_ctx_t *ctx, } static void -change_stream_spec_before_test_cb (json_test_ctx_t *test_ctx, - const bson_t *test) +change_stream_spec_before_test_cb (json_test_ctx_t *test_ctx, const bson_t *test) { - change_stream_spec_ctx_t *ctx = - (change_stream_spec_ctx_t *) test_ctx->config->ctx; + change_stream_spec_ctx_t *ctx = (change_stream_spec_ctx_t *) test_ctx->config->ctx; bson_t opts; bson_t pipeline; bson_t tmp; @@ -1663,19 +1468,13 @@ change_stream_spec_before_test_cb (json_test_ctx_t *test_ctx, } bson_lookup_doc (test, "changeStreamPipeline", &pipeline); if (!strcmp (target, "collection")) { - ctx->change_stream = - mongoc_collection_watch (test_ctx->collection, &pipeline, &opts); + ctx->change_stream = mongoc_collection_watch (test_ctx->collection, &pipeline, &opts); } else if (!strcmp (target, "database")) { - ctx->change_stream = - mongoc_database_watch (test_ctx->db, &pipeline, &opts); + ctx->change_stream = mongoc_database_watch (test_ctx->db, &pipeline, &opts); } else if (!strcmp (target, "client")) { - ctx->change_stream = - mongoc_client_watch (test_ctx->client, &pipeline, &opts); + ctx->change_stream = mongoc_client_watch (test_ctx->client, &pipeline, &opts); } else { - ASSERT_WITH_MSG (false, - "target unknown: \"%s\" in test: %s", - target, - bson_as_json (test, NULL)); + ASSERT_WITH_MSG (false, "target unknown: \"%s\" in test: %s", target, bson_as_json (test, NULL)); } bson_destroy (&opts); } @@ -1699,8 +1498,7 @@ _iterate_until_error_or_event (mongoc_change_stream_t *stream, do { has_document = mongoc_change_stream_next (stream, event); - has_error = - mongoc_change_stream_error_document (stream, error, error_reply); + has_error = mongoc_change_stream_error_document (stream, error, error_reply); /* in case the test was set-up incorrectly, and there really are no events * coming, exit early. */ max_retry--; @@ -1711,8 +1509,7 @@ _iterate_until_error_or_event (mongoc_change_stream_t *stream, static void change_stream_spec_after_test_cb (json_test_ctx_t *test_ctx, const bson_t *test) { - change_stream_spec_ctx_t *ctx = - (change_stream_spec_ctx_t *) test_ctx->config->ctx; + change_stream_spec_ctx_t *ctx = (change_stream_spec_ctx_t *) test_ctx->config->ctx; bson_error_t error; const bson_t *reply; const bson_t *doc; @@ -1722,11 +1519,9 @@ change_stream_spec_after_test_cb (json_test_ctx_t *test_ctx, const bson_t *test) int32_t expected_err_code; /* iterate change stream once. */ - ret = _iterate_until_error_or_event ( - ctx->change_stream, &doc, &error, &reply); + ret = _iterate_until_error_or_event (ctx->change_stream, &doc, &error, &reply); if (ret) { - test_error ( - "Expected error, but change stream did not return an error"); + test_error ("Expected error, but change stream did not return an error"); } expected_err_code = bson_lookup_int32 (test, "result.error.code"); @@ -1772,13 +1567,9 @@ change_stream_spec_after_test_cb (json_test_ctx_t *test_ctx, const bson_t *test) */ for (i = 0; i < num_iterations; i++) { char *key = bson_strdup_printf ("%d", i); - ret = _iterate_until_error_or_event ( - ctx->change_stream, &doc, &error, &reply); + ret = _iterate_until_error_or_event (ctx->change_stream, &doc, &error, &reply); if (!ret) { - test_error ("unexpected error at iteration %d/%d: %s\n", - i + 1, - num_iterations, - error.message); + test_error ("unexpected error at iteration %d/%d: %s\n", i + 1, num_iterations, error.message); } bson_append_document (&all_changes, key, -1, doc); bson_free (key); @@ -1798,8 +1589,7 @@ change_stream_spec_after_test_cb (json_test_ctx_t *test_ctx, const bson_t *test) } bson_destroy (&all_changes); - if (mongoc_change_stream_error_document ( - ctx->change_stream, &error, NULL)) { + if (mongoc_change_stream_error_document (ctx->change_stream, &error, NULL)) { test_error ("Expected success, but error occurred: %s", error.message); } } else { @@ -1845,17 +1635,15 @@ _test_resume (const char *opts, server = mock_server_with_auto_hello (WIRE_VERSION_4_0); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); mongoc_client_set_error_api (client, MONGOC_ERROR_API_VERSION_2); coll = mongoc_client_get_collection (client, "db", "coll"); future = future_collection_watch (coll, tmp_bson ("{}"), tmp_bson (opts)); - request = mock_server_receives_msg ( - server, - MONGOC_QUERY_NONE, - tmp_bson ("{ 'aggregate': 'coll', 'pipeline' : [ { '$changeStream': { %s " - " 'fullDocument': null } } ], 'cursor': { } }", - expected_change_stream_opts)); + request = mock_server_receives_msg (server, + MONGOC_QUERY_NONE, + tmp_bson ("{ 'aggregate': 'coll', 'pipeline' : [ { '$changeStream': { %s " + " 'fullDocument': null } } ], 'cursor': { } }", + expected_change_stream_opts)); msg = bson_strdup_printf ("{'cursor': {'id': 123, 'ns': 'db.coll'," "'firstBatch': [%s]%s }, 'operationTime': " "{ '$timestamp': {'t': 1, 'i': 2} }, 'ok': 1 }", @@ -1874,26 +1662,20 @@ _test_resume (const char *opts, } future = future_change_stream_next (stream, &doc); request = mock_server_receives_msg ( - server, - MONGOC_QUERY_NONE, - tmp_bson ("{ 'getMore': {'$numberLong': '123'}, 'collection': 'coll' }")); + server, MONGOC_QUERY_NONE, tmp_bson ("{ 'getMore': {'$numberLong': '123'}, 'collection': 'coll' }")); reply_to_request_with_hang_up (request); request_destroy (request); /* since the server closed the connection, a resume is attempted. */ - request = mock_server_receives_msg ( - server, - MONGOC_QUERY_NONE, - tmp_bson ("{ 'aggregate': 'coll', 'pipeline' : [ { '$changeStream': { %s " - " 'fullDocument': null }} ], 'cursor': { } }", - expected_resume_change_stream_opts)); - reply_to_request_simple ( - request, - "{'cursor': {'id': 0,'ns': 'db.coll','firstBatch': []},'ok': 1 }"); + request = mock_server_receives_msg (server, + MONGOC_QUERY_NONE, + tmp_bson ("{ 'aggregate': 'coll', 'pipeline' : [ { '$changeStream': { %s " + " 'fullDocument': null }} ], 'cursor': { } }", + expected_resume_change_stream_opts)); + reply_to_request_simple (request, "{'cursor': {'id': 0,'ns': 'db.coll','firstBatch': []},'ok': 1 }"); request_destroy (request); BSON_ASSERT (!future_get_bool (future)); - ASSERT_OR_PRINT (!mongoc_change_stream_error_document (stream, &err, NULL), - err); + ASSERT_OR_PRINT (!mongoc_change_stream_error_document (stream, &err, NULL), err); BSON_ASSERT (doc == NULL); future_destroy (future); @@ -1926,60 +1708,34 @@ test_resume_cases (void) /* no options specified. */ /* - if no doc recv'ed, use the operationTime returned by aggregate. */ - _test_resume ("{}", - NO_OPT_OP "," NO_OPT_RA "," NO_OPT_SA ",", - "", - AGG_OP "," NO_OPT_RA "," NO_OPT_SA ",", - ""); + _test_resume ("{}", NO_OPT_OP "," NO_OPT_RA "," NO_OPT_SA ",", "", AGG_OP "," NO_OPT_RA "," NO_OPT_SA ",", ""); /* - if doc recv'ed and iterated, use the doc's resume token. */ - _test_resume ("{}", - NO_OPT_OP "," NO_OPT_RA "," NO_OPT_SA ",", - DOC, - DOC_RA "," NO_OPT_OP "," NO_OPT_SA ",", - ""); + _test_resume ("{}", NO_OPT_OP "," NO_OPT_RA "," NO_OPT_SA ",", DOC, DOC_RA "," NO_OPT_OP "," NO_OPT_SA ",", ""); /* only 'startAtOperationTime' specified. */ /* - if no doc recv'ed, use the startAtOperationTime option. */ - _test_resume ("{" OPT_OP "}", - OPT_OP "," NO_OPT_RA "," NO_OPT_SA ",", - "", - OPT_OP "," NO_OPT_RA "," NO_OPT_SA ",", - ""); + _test_resume ( + "{" OPT_OP "}", OPT_OP "," NO_OPT_RA "," NO_OPT_SA ",", "", OPT_OP "," NO_OPT_RA "," NO_OPT_SA ",", ""); /* - if doc recv'ed and iterated, use the doc's resume token. */ - _test_resume ("{" OPT_OP "}", - OPT_OP "," NO_OPT_RA "," NO_OPT_SA ",", - DOC, - DOC_RA "," NO_OPT_OP "," NO_OPT_SA ",", - ""); + _test_resume ( + "{" OPT_OP "}", OPT_OP "," NO_OPT_RA "," NO_OPT_SA ",", DOC, DOC_RA "," NO_OPT_OP "," NO_OPT_SA ",", ""); /* only 'resumeAfter' specified. */ /* - if no doc recv'ed, use the resumeAfter option. */ - _test_resume ("{" OPT_RA "}", - OPT_RA "," NO_OPT_OP "," NO_OPT_SA ",", - "", - OPT_RA "," NO_OPT_OP "," NO_OPT_SA ",", - ""); + _test_resume ( + "{" OPT_RA "}", OPT_RA "," NO_OPT_OP "," NO_OPT_SA ",", "", OPT_RA "," NO_OPT_OP "," NO_OPT_SA ",", ""); /* - if doc recv'ed and iterated, use the doc's resume token. */ - _test_resume ("{" OPT_RA "}", - OPT_RA "," NO_OPT_OP "," NO_OPT_SA ",", - DOC, - DOC_RA "," NO_OPT_OP "," NO_OPT_SA ",", - ""); + _test_resume ( + "{" OPT_RA "}", OPT_RA "," NO_OPT_OP "," NO_OPT_SA ",", DOC, DOC_RA "," NO_OPT_OP "," NO_OPT_SA ",", ""); /* only 'startAfter' specified. */ /* - if no doc recv'ed, use the startAfter option for the original aggregate * whether or not we are resuming. */ - _test_resume ("{" OPT_SA "}", - OPT_SA "," NO_OPT_OP "," NO_OPT_RA ",", - "", - OPT_SA "," NO_OPT_OP "," NO_OPT_RA ",", - ""); + _test_resume ( + "{" OPT_SA "}", OPT_SA "," NO_OPT_OP "," NO_OPT_RA ",", "", OPT_SA "," NO_OPT_OP "," NO_OPT_RA ",", ""); /* - if doc recv'ed and iterated, use the doc's resume token. */ - _test_resume ("{" OPT_SA "}", - OPT_SA "," NO_OPT_OP "," NO_OPT_RA ",", - DOC, - DOC_RA "," NO_OPT_OP "," NO_OPT_SA ",", - ""); + _test_resume ( + "{" OPT_SA "}", OPT_SA "," NO_OPT_OP "," NO_OPT_RA ",", DOC, DOC_RA "," NO_OPT_OP "," NO_OPT_SA ",", ""); /* 'resumeAfter', 'startAfter', and 'startAtOperationTime' are all specified. * All should be passed (although the server currently returns an error). */ @@ -2021,18 +1777,12 @@ test_resume_cases_with_post_batch_resume_token (void) /* no options specified. */ /* - if no doc recv'ed, use resumeAfter with postBatchResumeToken. */ - _test_resume ("{}", - NO_OPT_OP "," NO_OPT_RA "," NO_OPT_SA ",", - "", - PBR_RA "," NO_OPT_OP "," NO_OPT_SA ",", - "," CURSOR_PBR); + _test_resume ( + "{}", NO_OPT_OP "," NO_OPT_RA "," NO_OPT_SA ",", "", PBR_RA "," NO_OPT_OP "," NO_OPT_SA ",", "," CURSOR_PBR); /* - if one doc recv'ed and iterated, use resumeAfter with * postBatchResumeToken. */ - _test_resume ("{}", - NO_OPT_OP "," NO_OPT_RA "," NO_OPT_SA ",", - DOC, - PBR_RA "," NO_OPT_OP "," NO_OPT_SA ",", - "," CURSOR_PBR); + _test_resume ( + "{}", NO_OPT_OP "," NO_OPT_RA "," NO_OPT_SA ",", DOC, PBR_RA "," NO_OPT_OP "," NO_OPT_SA ",", "," CURSOR_PBR); /* only 'startAtOperationTime' specified. */ /* - if no doc recv'ed, use resumeAfter with postBatchResumeToken. */ @@ -2103,8 +1853,7 @@ test_error_null_doc (void *ctx) mongoc_client_t *client; mongoc_change_stream_t *stream; bson_error_t err; - const bson_t *error_doc = - tmp_bson ("{}"); /* assign to a non-zero address. */ + const bson_t *error_doc = tmp_bson ("{}"); /* assign to a non-zero address. */ BSON_UNUSED (ctx); @@ -2112,8 +1861,7 @@ test_error_null_doc (void *ctx) stream = mongoc_client_watch (client, tmp_bson ("{}"), NULL); /* error_doc starts as non-NULL. */ BSON_ASSERT (error_doc); - BSON_ASSERT ( - !mongoc_change_stream_error_document (stream, &err, &error_doc)); + BSON_ASSERT (!mongoc_change_stream_error_document (stream, &err, &error_doc)); /* error_doc is set to NULL no error occurred. */ BSON_ASSERT (!error_doc); mongoc_change_stream_destroy (stream); @@ -2155,11 +1903,9 @@ prose_test_11 (void *ctx) ASSERT (coll); /* Set the batch size to 1 so we only get one document per call to next. */ - stream = mongoc_collection_watch ( - coll, tmp_bson ("{}"), tmp_bson ("{'batchSize': 1}")); + stream = mongoc_collection_watch (coll, tmp_bson ("{}"), tmp_bson ("{'batchSize': 1}")); ASSERT (stream); - ASSERT_OR_PRINT (!mongoc_change_stream_error_document (stream, &error, NULL), - error); + ASSERT_OR_PRINT (!mongoc_change_stream_error_document (stream, &error, NULL), error); /* The resume token should be updated to the post batch resume token */ ASSERT (!mongoc_change_stream_next (stream, &next_doc)); @@ -2170,22 +1916,18 @@ prose_test_11 (void *ctx) /* Look into the struct and get the actual post batch resume token, assert it * is equal to our resume token */ post_batch_expected = (_data_change_stream_t *) stream->cursor->impl.data; - ASSERT (bson_compare (resume_token, - &post_batch_expected->post_batch_resume_token) == 0); + ASSERT (bson_compare (resume_token, &post_batch_expected->post_batch_resume_token) == 0); mongoc_write_concern_set_wmajority (wc, 30000); mongoc_write_concern_append (wc, &opts); - ASSERT_OR_PRINT (mongoc_collection_insert_one ( - coll, tmp_bson ("{'_id': 0}"), &opts, NULL, &error), - error); + ASSERT_OR_PRINT (mongoc_collection_insert_one (coll, tmp_bson ("{'_id': 0}"), &opts, NULL, &error), error); /* Checking that a resume token is returned */ ASSERT (mongoc_change_stream_next (stream, &next_doc)); ASSERT (next_doc); resume_token = mongoc_change_stream_get_resume_token (stream); ASSERT (!bson_empty0 (resume_token)); - ASSERT (bson_compare (resume_token, - &post_batch_expected->post_batch_resume_token) == 0); + ASSERT (bson_compare (resume_token, &post_batch_expected->post_batch_resume_token) == 0); bson_destroy (&opts); mongoc_write_concern_destroy (wc); @@ -2219,17 +1961,13 @@ prose_test_12 (void *ctx) ASSERT (coll); /* Set the batch size to 1 so we only get one document per call to next. */ - stream = mongoc_collection_watch ( - coll, tmp_bson ("{}"), tmp_bson ("{'batchSize': 1}")); + stream = mongoc_collection_watch (coll, tmp_bson ("{}"), tmp_bson ("{'batchSize': 1}")); ASSERT (stream); - ASSERT_OR_PRINT (!mongoc_change_stream_error_document (stream, &error, NULL), - error); + ASSERT_OR_PRINT (!mongoc_change_stream_error_document (stream, &error, NULL), error); mongoc_write_concern_set_wmajority (wc, 30000); mongoc_write_concern_append (wc, &opts); - ASSERT_OR_PRINT (mongoc_collection_insert_one ( - coll, tmp_bson ("{'_id': 0}"), &opts, NULL, &error), - error); + ASSERT_OR_PRINT (mongoc_collection_insert_one (coll, tmp_bson ("{'_id': 0}"), &opts, NULL, &error), error); /* Checking that a resume token is returned */ ASSERT (mongoc_change_stream_next (stream, &next_doc)); @@ -2288,34 +2026,25 @@ prose_test_13 (void *ctx) ASSERT (client); callbacks = mongoc_apm_callbacks_new (); - mongoc_apm_set_command_started_cb (callbacks, - test_resume_token_command_start); + mongoc_apm_set_command_started_cb (callbacks, test_resume_token_command_start); mongoc_client_set_apm_callbacks (client, callbacks, &ctx); coll = drop_and_get_coll (client, "db", "coll_resume"); ASSERT (coll); - ASSERT_OR_PRINT ( - mongoc_collection_insert_one (coll, tmp_bson (NULL), NULL, NULL, &error), - error); + ASSERT_OR_PRINT (mongoc_collection_insert_one (coll, tmp_bson (NULL), NULL, NULL, &error), error); /* Set the batch size to 1 so we only get one document per call to next. */ - stream = mongoc_collection_watch ( - coll, tmp_bson ("{}"), tmp_bson ("{'batchSize': 1}")); + stream = mongoc_collection_watch (coll, tmp_bson ("{}"), tmp_bson ("{'batchSize': 1}")); ASSERT (stream); - ASSERT_OR_PRINT (!mongoc_change_stream_error_document (stream, &error, NULL), - error); + ASSERT_OR_PRINT (!mongoc_change_stream_error_document (stream, &error, NULL), error); /* Insert a few docs to listen for. Use write concern majority, so subsequent * call to watch will be guaranteed to retrieve them. */ mongoc_write_concern_set_wmajority (wc, 30000); mongoc_write_concern_append (wc, &opts); - ASSERT_OR_PRINT (mongoc_collection_insert_one ( - coll, tmp_bson ("{'_id': 0}"), &opts, NULL, &error), - error); + ASSERT_OR_PRINT (mongoc_collection_insert_one (coll, tmp_bson ("{'_id': 0}"), &opts, NULL, &error), error); - ASSERT_OR_PRINT (mongoc_collection_insert_one ( - coll, tmp_bson ("{'_id': 1}"), &opts, NULL, &error), - error); + ASSERT_OR_PRINT (mongoc_collection_insert_one (coll, tmp_bson ("{'_id': 1}"), &opts, NULL, &error), error); /* The resume token should be updated to the most recently iterated doc */ ASSERT (mongoc_change_stream_next (stream, &next_doc)); @@ -2345,8 +2074,7 @@ prose_test_13 (void *ctx) static void _save_operation_time_from_agg (const mongoc_apm_command_succeeded_t *event) { - if (0 == strcmp ("aggregate", - mongoc_apm_command_succeeded_get_command_name (event))) { + if (0 == strcmp ("aggregate", mongoc_apm_command_succeeded_get_command_name (event))) { mongoc_timestamp_t *timestamp; bson_iter_t iter; const bson_t *cmd; @@ -2378,8 +2106,7 @@ prose_test_14 (void *test_ctx) BSON_UNUSED (test_ctx); callbacks = mongoc_apm_callbacks_new (); - mongoc_apm_set_command_succeeded_cb (callbacks, - _save_operation_time_from_agg); + mongoc_apm_set_command_succeeded_cb (callbacks, _save_operation_time_from_agg); mongoc_client_set_apm_callbacks (client, callbacks, &optime); mongoc_apm_callbacks_destroy (callbacks); @@ -2390,18 +2117,10 @@ prose_test_14 (void *test_ctx) * time. */ BSON_ASSERT (optime.timestamp != 0); - ASSERT_OR_PRINT (mongoc_collection_insert_one ( - coll, tmp_bson ("{'_id': 0}"), &opts, NULL, &error), - error); - ASSERT_OR_PRINT (mongoc_collection_insert_one ( - coll, tmp_bson ("{'_id': 1}"), &opts, NULL, &error), - error); - ASSERT_OR_PRINT (mongoc_collection_insert_one ( - coll, tmp_bson ("{'_id': 2}"), &opts, NULL, &error), - error); - ASSERT_OR_PRINT (mongoc_collection_insert_one ( - coll, tmp_bson ("{'_id': 3}"), &opts, NULL, &error), - error); + ASSERT_OR_PRINT (mongoc_collection_insert_one (coll, tmp_bson ("{'_id': 0}"), &opts, NULL, &error), error); + ASSERT_OR_PRINT (mongoc_collection_insert_one (coll, tmp_bson ("{'_id': 1}"), &opts, NULL, &error), error); + ASSERT_OR_PRINT (mongoc_collection_insert_one (coll, tmp_bson ("{'_id': 2}"), &opts, NULL, &error), error); + ASSERT_OR_PRINT (mongoc_collection_insert_one (coll, tmp_bson ("{'_id': 3}"), &opts, NULL, &error), error); ASSERT (mongoc_change_stream_next (stream, &doc)); resume_token = mongoc_change_stream_get_resume_token (stream); @@ -2433,8 +2152,7 @@ prose_test_14 (void *test_ctx) /* Finally, with neither. */ bson_destroy (&opts); bson_init (&opts); - BSON_APPEND_TIMESTAMP ( - &opts, "startAtOperationTime", optime.timestamp, optime.increment); + BSON_APPEND_TIMESTAMP (&opts, "startAtOperationTime", optime.timestamp, optime.increment); stream = mongoc_collection_watch (coll, tmp_bson ("{}"), &opts); resume_token = mongoc_change_stream_get_resume_token (stream); @@ -2461,24 +2179,19 @@ prose_test_17 (void) server = mock_server_with_auto_hello (WIRE_VERSION_MAX); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); coll = mongoc_client_get_collection (client, "db", "coll"); /* Pass an arbitrary document as the resume token, like {'x': 1} */ - future = future_collection_watch ( - coll, tmp_bson ("{}"), tmp_bson ("{'startAfter': {'x': 1}}")); + future = future_collection_watch (coll, tmp_bson ("{}"), tmp_bson ("{'startAfter': {'x': 1}}")); - request = mock_server_receives_msg ( - server, - MONGOC_QUERY_NONE, - tmp_bson ("{ 'aggregate': 'coll', 'pipeline' : [ { '$changeStream': { " - "'startAfter': {'x': 1} , 'resumeAfter': { '$exists': false }, " - "'startAtOperationTime': { '$exists': false } } } ]}")); + request = mock_server_receives_msg (server, + MONGOC_QUERY_NONE, + tmp_bson ("{ 'aggregate': 'coll', 'pipeline' : [ { '$changeStream': { " + "'startAfter': {'x': 1} , 'resumeAfter': { '$exists': false }, " + "'startAtOperationTime': { '$exists': false } } } ]}")); - reply_to_request_simple ( - request, - "{'cursor': {'id': 123, 'ns': 'db.coll', 'firstBatch': []}, 'ok': 1 }"); + reply_to_request_simple (request, "{'cursor': {'id': 123, 'ns': 'db.coll', 'firstBatch': []}, 'ok': 1 }"); request_destroy (request); @@ -2489,38 +2202,29 @@ prose_test_17 (void) future = future_change_stream_next (stream, &next_doc); request = mock_server_receives_msg ( - server, - MONGOC_QUERY_NONE, - tmp_bson ("{ 'getMore': {'$numberLong': '123'}, 'collection': 'coll' }")); + server, MONGOC_QUERY_NONE, tmp_bson ("{ 'getMore': {'$numberLong': '123'}, 'collection': 'coll' }")); - reply_to_request_simple ( - request, - "{ 'code': 10107, 'errmsg': 'not primary', 'errorLabels': " - "['ResumableChangeStreamError'], 'ok': 0 }"); + reply_to_request_simple (request, + "{ 'code': 10107, 'errmsg': 'not primary', 'errorLabels': " + "['ResumableChangeStreamError'], 'ok': 0 }"); request_destroy (request); /* Resume occurs. */ request = mock_server_receives_msg ( - server, - MONGOC_QUERY_NONE, - tmp_bson ( - "{ 'killCursors': 'coll', 'cursors': [{ '$numberLong': '123'}]}")); + server, MONGOC_QUERY_NONE, tmp_bson ("{ 'killCursors': 'coll', 'cursors': [{ '$numberLong': '123'}]}")); reply_to_request_with_ok_and_destroy (request); - request = mock_server_receives_msg ( - server, - MONGOC_QUERY_NONE, - tmp_bson ("{ 'aggregate': 'coll', 'pipeline': [ { " - "'$changeStream': { 'startAfter': {'x': 1}, 'resumeAfter': { " - "'$exists': false }, 'startAtOperationTime': { '$exists': " - "false } } " - "}]}")); + request = mock_server_receives_msg (server, + MONGOC_QUERY_NONE, + tmp_bson ("{ 'aggregate': 'coll', 'pipeline': [ { " + "'$changeStream': { 'startAfter': {'x': 1}, 'resumeAfter': { " + "'$exists': false }, 'startAtOperationTime': { '$exists': " + "false } } " + "}]}")); /* Reply with a 0 cursor ID to prevent a killCursors command. */ - reply_to_request_simple ( - request, - "{'cursor': {'id': 0, 'ns': 'db.coll', 'firstBatch': []}, 'ok': 1 }"); + reply_to_request_simple (request, "{'cursor': {'id': 0, 'ns': 'db.coll', 'firstBatch': []}, 'ok': 1 }"); request_destroy (request); BSON_ASSERT (!future_get_bool (future)); future_destroy (future); @@ -2545,20 +2249,17 @@ prose_test_18 (void) server = mock_server_with_auto_hello (WIRE_VERSION_MAX); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); coll = mongoc_client_get_collection (client, "db", "coll"); /* Pass an arbitrary document as the resume token, like {'x': 1} */ - future = future_collection_watch ( - coll, tmp_bson ("{}"), tmp_bson ("{'startAfter': {'x': 1}}")); + future = future_collection_watch (coll, tmp_bson ("{}"), tmp_bson ("{'startAfter': {'x': 1}}")); - request = mock_server_receives_msg ( - server, - MONGOC_QUERY_NONE, - tmp_bson ("{ 'aggregate': 'coll', 'pipeline' : [ { '$changeStream': { " - "'startAfter': {'x': 1}, 'resumeAfter': { '$exists': false }, " - "'startAtOperationTime': { '$exists': false } } } ]}")); + request = mock_server_receives_msg (server, + MONGOC_QUERY_NONE, + tmp_bson ("{ 'aggregate': 'coll', 'pipeline' : [ { '$changeStream': { " + "'startAfter': {'x': 1}, 'resumeAfter': { '$exists': false }, " + "'startAtOperationTime': { '$exists': false } } } ]}")); reply_to_request_simple (request, "{'cursor': {'id': 123, 'ns': " @@ -2577,36 +2278,27 @@ prose_test_18 (void) future = future_change_stream_next (stream, &next_doc); request = mock_server_receives_msg ( - server, - MONGOC_QUERY_NONE, - tmp_bson ("{ 'getMore': {'$numberLong': '123'}, 'collection': 'coll' }")); + server, MONGOC_QUERY_NONE, tmp_bson ("{ 'getMore': {'$numberLong': '123'}, 'collection': 'coll' }")); - reply_to_request_simple ( - request, - "{ 'code': 10107, 'errmsg': 'not primary', 'errorLabels': " - "['ResumableChangeStreamError'], 'ok': 0 }"); + reply_to_request_simple (request, + "{ 'code': 10107, 'errmsg': 'not primary', 'errorLabels': " + "['ResumableChangeStreamError'], 'ok': 0 }"); request_destroy (request); request = mock_server_receives_msg ( - server, - MONGOC_QUERY_NONE, - tmp_bson ( - "{ 'killCursors': 'coll', 'cursors': [{ '$numberLong': '123'}]}")); + server, MONGOC_QUERY_NONE, tmp_bson ("{ 'killCursors': 'coll', 'cursors': [{ '$numberLong': '123'}]}")); reply_to_request_with_ok_and_destroy (request); - request = mock_server_receives_msg ( - server, - MONGOC_QUERY_NONE, - tmp_bson ("{ 'aggregate': 'coll', 'pipeline': [ { " - "'$changeStream': { 'resumeAfter': {'y': 1}, 'startAfter': { " - "'$exists': false }, 'startAtOperationTime': { '$exists': " - "false } } " - "}]}")); + request = mock_server_receives_msg (server, + MONGOC_QUERY_NONE, + tmp_bson ("{ 'aggregate': 'coll', 'pipeline': [ { " + "'$changeStream': { 'resumeAfter': {'y': 1}, 'startAfter': { " + "'$exists': false }, 'startAtOperationTime': { '$exists': " + "false } } " + "}]}")); /* Reply with a 0 cursor ID to prevent a killCursors command. */ - reply_to_request_simple ( - request, - "{'cursor': {'id': 0, 'ns': 'db.coll', 'firstBatch': []}, 'ok': 1 }"); + reply_to_request_simple (request, "{'cursor': {'id': 0, 'ns': 'db.coll', 'firstBatch': []}, 'ok': 1 }"); request_destroy (request); BSON_ASSERT (!future_get_bool (future)); future_destroy (future); @@ -2621,8 +2313,7 @@ prose_test_18 (void) void test_change_stream_install (TestSuite *suite) { - TestSuite_AddMockServerTest ( - suite, "/change_stream/pipeline", test_change_stream_pipeline); + TestSuite_AddMockServerTest (suite, "/change_stream/pipeline", test_change_stream_pipeline); TestSuite_AddFull (suite, "/change_stream/live/single_server", @@ -2660,12 +2351,9 @@ test_change_stream_install (TestSuite *suite) NULL, test_framework_skip_if_not_replset); - TestSuite_AddMockServerTest (suite, - "/change_stream/resumable_error", - test_change_stream_resumable_error); + TestSuite_AddMockServerTest (suite, "/change_stream/resumable_error", test_change_stream_resumable_error); - TestSuite_AddMockServerTest ( - suite, "/change_stream/options", test_change_stream_options); + TestSuite_AddMockServerTest (suite, "/change_stream/options", test_change_stream_options); TestSuite_AddFull (suite, "/change_stream/live/watch", @@ -2682,9 +2370,7 @@ test_change_stream_install (TestSuite *suite) _skip_if_no_start_at_optime, test_framework_skip_if_no_failpoint); - TestSuite_Add (suite, - "/change_stream/server_selection_fails", - test_change_stream_server_selection_fails); + TestSuite_Add (suite, "/change_stream/server_selection_fails", test_change_stream_server_selection_fails); TestSuite_AddFull (suite, "/change_stream/next_after_error", @@ -2699,8 +2385,7 @@ test_change_stream_install (TestSuite *suite) NULL, NULL, test_framework_skip_if_not_replset); - TestSuite_AddMockServerTest ( - suite, "/change_stream/getmore_errors", test_getmore_errors); + TestSuite_AddMockServerTest (suite, "/change_stream/getmore_errors", test_getmore_errors); TestSuite_AddFull (suite, "/change_stream/start_at_operation_time", test_change_stream_start_at_operation_time, @@ -2727,30 +2412,16 @@ test_change_stream_install (TestSuite *suite) test_framework_skip_if_no_crypto, _skip_if_no_start_at_optime, test_framework_skip_if_no_failpoint); - TestSuite_AddFull (suite, - "/change_stream/database", - test_change_stream_database_watch, - NULL, - NULL, - _skip_if_no_db_watch); - TestSuite_AddFull (suite, - "/change_stream/client", - test_change_stream_client_watch, - NULL, - NULL, - _skip_if_no_client_watch); - TestSuite_AddMockServerTest ( - suite, "/change_stream/resume_with_first_doc", test_resume_cases); - TestSuite_AddMockServerTest ( - suite, - "/change_stream/resume_with_first_doc/post_batch_resume_token", - test_resume_cases_with_post_batch_resume_token); - TestSuite_AddFull (suite, - "/change_stream/error_null_doc", - test_error_null_doc, - NULL, - NULL, - _skip_if_no_client_watch); + TestSuite_AddFull ( + suite, "/change_stream/database", test_change_stream_database_watch, NULL, NULL, _skip_if_no_db_watch); + TestSuite_AddFull ( + suite, "/change_stream/client", test_change_stream_client_watch, NULL, NULL, _skip_if_no_client_watch); + TestSuite_AddMockServerTest (suite, "/change_stream/resume_with_first_doc", test_resume_cases); + TestSuite_AddMockServerTest (suite, + "/change_stream/resume_with_first_doc/post_batch_resume_token", + test_resume_cases_with_post_batch_resume_token); + TestSuite_AddFull ( + suite, "/change_stream/error_null_doc", test_error_null_doc, NULL, NULL, _skip_if_no_client_watch); TestSuite_AddFull (suite, "/change_stream/live/prose_test_11", prose_test_11, @@ -2779,11 +2450,8 @@ test_change_stream_install (TestSuite *suite) NULL, test_framework_skip_if_mongos, test_framework_skip_if_not_rs_version_7); - TestSuite_AddMockServerTest ( - suite, "/change_streams/prose_test_17", prose_test_17); - TestSuite_AddMockServerTest ( - suite, "/change_streams/prose_test_18", prose_test_18); + TestSuite_AddMockServerTest (suite, "/change_streams/prose_test_17", prose_test_17); + TestSuite_AddMockServerTest (suite, "/change_streams/prose_test_18", prose_test_18); - install_json_test_suite ( - suite, JSON_DIR, "/change_streams/legacy", &test_change_stream_spec_cb); + install_json_test_suite (suite, JSON_DIR, "/change_streams/legacy", &test_change_stream_spec_cb); } diff --git a/src/libmongoc/tests/test-mongoc-client-pool.c b/src/libmongoc/tests/test-mongoc-client-pool.c index 56995ab5d9..a38e98806f 100644 --- a/src/libmongoc/tests/test-mongoc-client-pool.c +++ b/src/libmongoc/tests/test-mongoc-client-pool.c @@ -50,8 +50,7 @@ test_mongoc_client_pool_pop_timeout (void) int64_t start; int64_t duration_usec; - uri = mongoc_uri_new ( - "mongodb://127.0.0.1/?maxpoolsize=1&waitqueuetimeoutms=2000"); + uri = mongoc_uri_new ("mongodb://127.0.0.1/?maxpoolsize=1&waitqueuetimeoutms=2000"); pool = test_framework_client_pool_new_from_uri (uri, NULL); client = mongoc_client_pool_pop (pool); BSON_ASSERT (client); @@ -212,8 +211,7 @@ test_mongoc_client_pool_set_min_size (void) uri = mongoc_uri_new ("mongodb://127.0.0.1/?maxpoolsize=10&minpoolsize=3"); capture_logs (true); pool = test_framework_client_pool_new_from_uri (uri, NULL); - ASSERT_CAPTURED_LOG ( - "minpoolsize URI option", MONGOC_LOG_LEVEL_WARNING, "is deprecated"); + ASSERT_CAPTURED_LOG ("minpoolsize URI option", MONGOC_LOG_LEVEL_WARNING, "is deprecated"); for (i = 0; i < 10; i++) { client = mongoc_client_pool_pop (pool); @@ -226,9 +224,8 @@ test_mongoc_client_pool_set_min_size (void) BEGIN_IGNORE_DEPRECATIONS mongoc_client_pool_min_size (pool, 7); END_IGNORE_DEPRECATIONS - ASSERT_CAPTURED_LOG ("mongoc_client_pool_min_size", - MONGOC_LOG_LEVEL_WARNING, - "mongoc_client_pool_min_size is deprecated"); + ASSERT_CAPTURED_LOG ( + "mongoc_client_pool_min_size", MONGOC_LOG_LEVEL_WARNING, "mongoc_client_pool_min_size is deprecated"); for (i = 0; i < 10; i++) { client = _mongoc_array_index (&conns, mongoc_client_t *, i); @@ -253,9 +250,7 @@ test_mongoc_client_pool_ssl_disabled (void) ASSERT (uri); capture_logs (true); ASSERT (NULL == test_framework_client_pool_new_from_uri (uri, NULL)); - ASSERT_CAPTURED_LOG ("mongoc_client_pool_new", - MONGOC_LOG_LEVEL_ERROR, - "SSL not enabled in this build."); + ASSERT_CAPTURED_LOG ("mongoc_client_pool_new", MONGOC_LOG_LEVEL_ERROR, "SSL not enabled in this build."); mongoc_uri_destroy (uri); } @@ -276,9 +271,8 @@ test_mongoc_client_pool_handshake (void) /* Be sure we can't set it twice */ capture_logs (true); ASSERT (!mongoc_client_pool_set_appname (pool, "a")); - ASSERT_CAPTURED_LOG ("_mongoc_topology_scanner_set_appname", - MONGOC_LOG_LEVEL_ERROR, - "Cannot set appname more than once"); + ASSERT_CAPTURED_LOG ( + "_mongoc_topology_scanner_set_appname", MONGOC_LOG_LEVEL_ERROR, "Cannot set appname more than once"); capture_logs (false); mongoc_client_pool_destroy (pool); @@ -302,9 +296,8 @@ test_mongoc_client_pool_handshake (void) * the handshake */ capture_logs (true); ASSERT (!mongoc_client_pool_set_appname (pool, "a")); - ASSERT_CAPTURED_LOG ("_mongoc_topology_scanner_set_appname", - MONGOC_LOG_LEVEL_ERROR, - "Cannot set appname after handshake initiated"); + ASSERT_CAPTURED_LOG ( + "_mongoc_topology_scanner_set_appname", MONGOC_LOG_LEVEL_ERROR, "Cannot set appname after handshake initiated"); capture_logs (false); mongoc_uri_destroy (uri); @@ -331,21 +324,14 @@ test_client_pool_destroy_without_pushing (void) /* Push a client back onto the pool so endSessions succeeds to avoid a * warning. */ client_in_pool = mongoc_client_pool_pop (pool); - ret = mongoc_client_command_simple (client_in_pool, - "admin", - cmd, - NULL /* read prefs */, - NULL /* reply */, - &error); + ret = mongoc_client_command_simple (client_in_pool, "admin", cmd, NULL /* read prefs */, NULL /* reply */, &error); ASSERT_OR_PRINT (ret, error); mongoc_client_pool_push (pool, client_in_pool); - ret = mongoc_client_command_simple ( - client1, "admin", cmd, NULL /* read prefs */, NULL /* reply */, &error); + ret = mongoc_client_command_simple (client1, "admin", cmd, NULL /* read prefs */, NULL /* reply */, &error); ASSERT_OR_PRINT (ret, error); - ret = mongoc_client_command_simple ( - client2, "admin", cmd, NULL /* read prefs */, NULL /* reply */, &error); + ret = mongoc_client_command_simple (client2, "admin", cmd, NULL /* read prefs */, NULL /* reply */, &error); ASSERT_OR_PRINT (ret, error); /* Since clients are checked out of pool, it is technically ok to @@ -353,8 +339,7 @@ test_client_pool_destroy_without_pushing (void) mongoc_client_destroy (client1); /* An operation on client2 should still be ok. */ - ret = mongoc_client_command_simple ( - client2, "admin", cmd, NULL /* read prefs */, NULL /* reply */, &error); + ret = mongoc_client_command_simple (client2, "admin", cmd, NULL /* read prefs */, NULL /* reply */, &error); ASSERT_OR_PRINT (ret, error); mongoc_client_destroy (client2); @@ -367,8 +352,7 @@ test_client_pool_destroy_without_pushing (void) static void command_started_cb (const mongoc_apm_command_started_t *event) { - if (strcmp (mongoc_apm_command_started_get_command_name (event), - "endSessions") != 0) { + if (strcmp (mongoc_apm_command_started_get_command_name (event), "endSessions") != 0) { return; } @@ -474,23 +458,14 @@ void test_client_pool_install (TestSuite *suite) { TestSuite_Add (suite, "/ClientPool/basic", test_mongoc_client_pool_basic); - TestSuite_Add ( - suite, "/ClientPool/try_pop", test_mongoc_client_pool_try_pop); - TestSuite_Add ( - suite, "/ClientPool/pop_timeout", test_mongoc_client_pool_pop_timeout); - TestSuite_Add (suite, - "/ClientPool/min_size_zero", - test_mongoc_client_pool_min_size_zero); - TestSuite_Add (suite, - "/ClientPool/min_size_dispose", - test_mongoc_client_pool_min_size_dispose); - TestSuite_Add ( - suite, "/ClientPool/set_max_size", test_mongoc_client_pool_set_max_size); - TestSuite_Add ( - suite, "/ClientPool/set_min_size", test_mongoc_client_pool_set_min_size); - - TestSuite_Add ( - suite, "/ClientPool/handshake", test_mongoc_client_pool_handshake); + TestSuite_Add (suite, "/ClientPool/try_pop", test_mongoc_client_pool_try_pop); + TestSuite_Add (suite, "/ClientPool/pop_timeout", test_mongoc_client_pool_pop_timeout); + TestSuite_Add (suite, "/ClientPool/min_size_zero", test_mongoc_client_pool_min_size_zero); + TestSuite_Add (suite, "/ClientPool/min_size_dispose", test_mongoc_client_pool_min_size_dispose); + TestSuite_Add (suite, "/ClientPool/set_max_size", test_mongoc_client_pool_set_max_size); + TestSuite_Add (suite, "/ClientPool/set_min_size", test_mongoc_client_pool_set_min_size); + + TestSuite_Add (suite, "/ClientPool/handshake", test_mongoc_client_pool_handshake); TestSuite_AddFull (suite, "/ClientPool/create_client_pool_unused_session", @@ -499,13 +474,8 @@ test_client_pool_install (TestSuite *suite) NULL /* ctx */, test_framework_skip_if_no_sessions); #ifndef MONGOC_ENABLE_SSL - TestSuite_Add ( - suite, "/ClientPool/ssl_disabled", test_mongoc_client_pool_ssl_disabled); + TestSuite_Add (suite, "/ClientPool/ssl_disabled", test_mongoc_client_pool_ssl_disabled); #endif - TestSuite_AddLive (suite, - "/ClientPool/destroy_without_push", - test_client_pool_destroy_without_pushing); - TestSuite_AddLive (suite, - "/ClientPool/max_pool_size_exceeded", - test_client_pool_max_pool_size_exceeded); + TestSuite_AddLive (suite, "/ClientPool/destroy_without_push", test_client_pool_destroy_without_pushing); + TestSuite_AddLive (suite, "/ClientPool/max_pool_size_exceeded", test_client_pool_max_pool_size_exceeded); } diff --git a/src/libmongoc/tests/test-mongoc-client-session.c b/src/libmongoc/tests/test-mongoc-client-session.c index 68ab962a7b..9de4e96cea 100644 --- a/src/libmongoc/tests/test-mongoc-client-session.c +++ b/src/libmongoc/tests/test-mongoc-client-session.c @@ -70,10 +70,8 @@ test_session_no_crypto (void *ctx) client = test_framework_new_default_client (); BSON_ASSERT (!mongoc_client_start_session (client, NULL, &error)); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_CLIENT, - MONGOC_ERROR_CLIENT_SESSION_FAILURE, - "need a cryptography library"); + ASSERT_ERROR_CONTAINS ( + error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_SESSION_FAILURE, "need a cryptography library"); mongoc_client_destroy (client); } @@ -182,8 +180,7 @@ _test_session_pool_timeout (bool pooled) bson_t lsid; int64_t almost_timeout_usec; - almost_timeout_usec = - (test_framework_session_timeout_minutes () - 1) * 60 * 1000 * 1000; + almost_timeout_usec = (test_framework_session_timeout_minutes () - 1) * 60 * 1000 * 1000; if (pooled) { pool = test_framework_new_default_client_pool (); @@ -195,26 +192,22 @@ _test_session_pool_timeout (bool pooled) /* * trigger discovery */ - server_id = mongoc_topology_select_server_id ( - client->topology, MONGOC_SS_READ, NULL, NULL, NULL, &error); + server_id = mongoc_topology_select_server_id (client->topology, MONGOC_SS_READ, NULL, NULL, NULL, &error); ASSERT_OR_PRINT (server_id, error); /* * get a session, set last_used_date more than 29 minutes ago and return to * the pool. it's timed out & freed. */ - BSON_ASSERT ( - mongoc_server_session_pool_is_empty (client->topology->session_pool)); + BSON_ASSERT (mongoc_server_session_pool_is_empty (client->topology->session_pool)); s = mongoc_client_start_session (client, NULL, &error); ASSERT_OR_PRINT (s, error); bson_copy_to (mongoc_client_session_get_lsid (s), &lsid); - s->server_session->last_used_usec = - (bson_get_monotonic_time () - almost_timeout_usec - 100); + s->server_session->last_used_usec = (bson_get_monotonic_time () - almost_timeout_usec - 100); mongoc_client_session_destroy (s); - BSON_ASSERT ( - mongoc_server_session_pool_is_empty (client->topology->session_pool)); + BSON_ASSERT (mongoc_server_session_pool_is_empty (client->topology->session_pool)); /* * get a new session, set last_used_date so it has one second left to live, @@ -226,20 +219,17 @@ _test_session_pool_timeout (bool pooled) bson_destroy (&lsid); bson_copy_to (mongoc_client_session_get_lsid (s), &lsid); - s->server_session->last_used_usec = - (bson_get_monotonic_time () + 1000 * 1000 - almost_timeout_usec); + s->server_session->last_used_usec = (bson_get_monotonic_time () + 1000 * 1000 - almost_timeout_usec); mongoc_client_session_destroy (s); - BSON_ASSERT ( - !mongoc_server_session_pool_is_empty (client->topology->session_pool)); + BSON_ASSERT (!mongoc_server_session_pool_is_empty (client->topology->session_pool)); _mongoc_usleep (1500 * 1000); /* getting a new client session must start a new server session */ s = mongoc_client_start_session (client, NULL, &error); ASSERT_SESSIONS_DIFFER (&lsid, mongoc_client_session_get_lsid (s)); - BSON_ASSERT ( - mongoc_server_session_pool_is_empty (client->topology->session_pool)); + BSON_ASSERT (mongoc_server_session_pool_is_empty (client->topology->session_pool)); mongoc_client_session_destroy (s); if (pooled) { @@ -289,8 +279,7 @@ _test_session_pool_reap (bool pooled) int64_t almost_timeout_usec; mongoc_server_session_t *ss; - almost_timeout_usec = - (test_framework_session_timeout_minutes () - 1) * 60 * 1000 * 1000; + almost_timeout_usec = (test_framework_session_timeout_minutes () - 1) * 60 * 1000 * 1000; if (pooled) { pool = test_framework_new_default_client_pool (); @@ -302,8 +291,7 @@ _test_session_pool_reap (bool pooled) /* * trigger discovery */ - r = mongoc_client_command_simple ( - client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); + r = mongoc_client_command_simple (client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); ASSERT_OR_PRINT (r, error); /* @@ -315,12 +303,10 @@ _test_session_pool_reap (bool pooled) bson_copy_to (mongoc_client_session_get_lsid (a), &lsid_a); bson_copy_to (mongoc_client_session_get_lsid (b), &lsid_b); - a->server_session->last_used_usec = - (bson_get_monotonic_time () + 1000 * 1000 - almost_timeout_usec); + a->server_session->last_used_usec = (bson_get_monotonic_time () + 1000 * 1000 - almost_timeout_usec); mongoc_client_session_destroy (a); - BSON_ASSERT (!mongoc_server_session_pool_is_empty ( - client->topology->session_pool)); /* session is pooled */ + BSON_ASSERT (!mongoc_server_session_pool_is_empty (client->topology->session_pool)); /* session is pooled */ _mongoc_usleep (1500 * 1000); @@ -329,10 +315,8 @@ _test_session_pool_reap (bool pooled) */ b->server_session->last_used_usec = bson_get_monotonic_time (); mongoc_client_session_destroy (b); - BSON_ASSERT ( - !mongoc_server_session_pool_is_empty (client->topology->session_pool)); - ss = - mongoc_server_session_pool_get_existing (client->topology->session_pool); + BSON_ASSERT (!mongoc_server_session_pool_is_empty (client->topology->session_pool)); + ss = mongoc_server_session_pool_get_existing (client->topology->session_pool); BSON_ASSERT (ss); ASSERT_SESSIONS_MATCH (&ss->lsid, &lsid_b); mongoc_server_session_pool_return (client->topology->session_pool, ss); @@ -391,19 +375,11 @@ test_session_id_bad (void *ctx) client = test_framework_new_default_client (); for (bad_opt = bad_opts; *bad_opt; bad_opt++) { - r = mongoc_client_read_command_with_opts (client, - "admin", - tmp_bson ("{'ping': 1}"), - NULL, - tmp_bson (*bad_opt), - NULL, - &error); + r = mongoc_client_read_command_with_opts ( + client, "admin", tmp_bson ("{'ping': 1}"), NULL, tmp_bson (*bad_opt), NULL, &error); BSON_ASSERT (!r); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Invalid sessionId"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid sessionId"); memset (&error, 0, sizeof (bson_error_t)); } @@ -428,10 +404,8 @@ _test_session_supported (bool pooled) if (test_framework_session_timeout_minutes () == -1) { BSON_ASSERT (!mongoc_client_start_session (client, NULL, &error)); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_CLIENT, - MONGOC_ERROR_CLIENT_SESSION_FAILURE, - "Server does not support sessions"); + ASSERT_ERROR_CONTAINS ( + error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_SESSION_FAILURE, "Server does not support sessions"); } else { session = mongoc_client_start_session (client, NULL, &error); ASSERT_OR_PRINT (session, error); @@ -484,12 +458,10 @@ _test_mock_end_sessions (bool pooled) mock_server_run (server); if (pooled) { - pool = test_framework_client_pool_new_from_uri ( - mock_server_get_uri (server), NULL); + pool = test_framework_client_pool_new_from_uri (mock_server_get_uri (server), NULL); client = mongoc_client_pool_pop (pool); } else { - client = test_framework_client_new_from_uri (mock_server_get_uri (server), - NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); } session = mongoc_client_start_session (client, NULL, &error); @@ -498,22 +470,16 @@ _test_mock_end_sessions (bool pooled) r = mongoc_client_session_append (session, &opts, &error); ASSERT_OR_PRINT (r, error); - future = future_client_command_with_opts ( - client, "admin", tmp_bson ("{'ping': 1}"), NULL, &opts, NULL, &error); + future = future_client_command_with_opts (client, "admin", tmp_bson ("{'ping': 1}"), NULL, &opts, NULL, &error); - request = mock_server_receives_msg ( - server, 0, tmp_bson ("{'ping': 1, 'lsid': {'$exists': true}}")); + request = mock_server_receives_msg (server, 0, tmp_bson ("{'ping': 1, 'lsid': {'$exists': true}}")); reply_to_request_with_ok_and_destroy (request); BSON_ASSERT (future_get_bool (future)); future_destroy (future); /* before destroying the session, construct the expected endSessions cmd */ - expected_cmd = - BCON_NEW ("endSessions", - "[", - BCON_DOCUMENT (mongoc_client_session_get_lsid (session)), - "]"); + expected_cmd = BCON_NEW ("endSessions", "[", BCON_DOCUMENT (mongoc_client_session_get_lsid (session)), "]"); mongoc_client_session_destroy (session); @@ -563,8 +529,7 @@ test_mock_end_sessions_server_disconnect (void) server = mock_mongos_new (WIRE_VERSION_MAX); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); for (i = 0; i < 12000; i++) { session[i] = mongoc_client_start_session (client, NULL, &error); @@ -612,8 +577,7 @@ endsessions_started_cb (const mongoc_apm_command_started_t *event) endsessions_test_t *test; bson_t *cmd; - if (strcmp (mongoc_apm_command_started_get_command_name (event), - "endSessions") != 0) { + if (strcmp (mongoc_apm_command_started_get_command_name (event), "endSessions") != 0) { return; } @@ -628,13 +592,11 @@ endsessions_succeeded_cb (const mongoc_apm_command_succeeded_t *event) { endsessions_test_t *test; - if (strcmp (mongoc_apm_command_succeeded_get_command_name (event), - "endSessions") != 0) { + if (strcmp (mongoc_apm_command_succeeded_get_command_name (event), "endSessions") != 0) { return; } - test = - (endsessions_test_t *) mongoc_apm_command_succeeded_get_context (event); + test = (endsessions_test_t *) mongoc_apm_command_succeeded_get_context (event); test->succeeded_calls++; } @@ -652,8 +614,7 @@ endsessions_test_init (endsessions_test_t *test, bool pooled) if (pooled) { test->pool = test_framework_new_default_client_pool (); - ASSERT ( - mongoc_client_pool_set_apm_callbacks (test->pool, callbacks, test)); + ASSERT (mongoc_client_pool_set_apm_callbacks (test->pool, callbacks, test)); test->client = mongoc_client_pool_pop (test->pool); } else { test->pool = NULL; @@ -676,18 +637,13 @@ endsessions_test_destroy_client (endsessions_test_t *test) } static void -endsessions_test_get_ended_lsids (endsessions_test_t *test, - size_t index, - bson_t *ended_lsids) +endsessions_test_get_ended_lsids (endsessions_test_t *test, size_t index, bson_t *ended_lsids) { bson_iter_t iter; ASSERT_CMPINT (test->started_calls, >, (int) index); - BSON_ASSERT ( - bson_iter_init_find (&iter, - _mongoc_array_index (&test->cmds, bson_t *, index), - "endSessions")); + BSON_ASSERT (bson_iter_init_find (&iter, _mongoc_array_index (&test->cmds, bson_t *, index), "endSessions")); BSON_ASSERT (BSON_ITER_HOLDS_ARRAY (&iter)); bson_iter_bson (&iter, ended_lsids); @@ -736,8 +692,7 @@ _test_end_sessions (bool pooled) bson_copy_to (mongoc_client_session_get_lsid (cs1), &lsid1); r = mongoc_client_session_append (cs1, &opts1, &error); ASSERT_OR_PRINT (r, error); - r = mongoc_client_command_with_opts ( - client, "admin", tmp_bson ("{'count': 'c'}"), NULL, &opts1, NULL, &error); + r = mongoc_client_command_with_opts (client, "admin", tmp_bson ("{'count': 'c'}"), NULL, &opts1, NULL, &error); ASSERT_OR_PRINT (r, error); cs2 = mongoc_client_start_session (client, NULL, &error); @@ -745,8 +700,7 @@ _test_end_sessions (bool pooled) bson_copy_to (mongoc_client_session_get_lsid (cs2), &lsid2); r = mongoc_client_session_append (cs2, &opts2, &error); ASSERT_OR_PRINT (r, error); - r = mongoc_client_command_with_opts ( - client, "admin", tmp_bson ("{'count': 'c'}"), NULL, &opts2, NULL, &error); + r = mongoc_client_command_with_opts (client, "admin", tmp_bson ("{'count': 'c'}"), NULL, &opts2, NULL, &error); ASSERT_OR_PRINT (r, error); /* @@ -818,8 +772,7 @@ send_ping (mongoc_client_t *client, mongoc_client_session_t *client_session) ret = mongoc_client_session_append (client_session, &opts, &error); ASSERT_OR_PRINT (ret, error); - ret = mongoc_client_command_with_opts ( - client, "admin", &ping_cmd, NULL, &opts, NULL, &error); + ret = mongoc_client_command_with_opts (client, "admin", &ping_cmd, NULL, &opts, NULL, &error); ASSERT_OR_PRINT (ret, error); bson_destroy (&opts); bson_destroy (&ping_cmd); @@ -838,10 +791,8 @@ _test_end_sessions_many (bool pooled) endsessions_test_init (&test, pooled); client = test.client; /* connect */ - ASSERT_OR_PRINT ( - mongoc_client_command_simple ( - client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, &error), - error); + ASSERT_OR_PRINT (mongoc_client_command_simple (client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, &error), + error); /* * create and destroy 10,001 sessions @@ -889,28 +840,20 @@ test_end_sessions_many_pooled (void *ctx) } static void -_test_advance_cluster_time (mongoc_client_session_t *cs, - int new_timestamp, - int new_increment, - bool should_advance) +_test_advance_cluster_time (mongoc_client_session_t *cs, int new_timestamp, int new_increment, bool should_advance) { bson_t *old_cluster_time; bson_t *new_cluster_time; old_cluster_time = bson_copy (mongoc_client_session_get_cluster_time (cs)); - new_cluster_time = - tmp_bson ("{'clusterTime': {'$timestamp': {'t': %d, 'i': %d}}}", - new_timestamp, - new_increment); + new_cluster_time = tmp_bson ("{'clusterTime': {'$timestamp': {'t': %d, 'i': %d}}}", new_timestamp, new_increment); mongoc_client_session_advance_cluster_time (cs, new_cluster_time); if (should_advance) { - assert_match_bson ( - mongoc_client_session_get_cluster_time (cs), new_cluster_time, false); + assert_match_bson (mongoc_client_session_get_cluster_time (cs), new_cluster_time, false); } else { - assert_match_bson ( - mongoc_client_session_get_cluster_time (cs), old_cluster_time, false); + assert_match_bson (mongoc_client_session_get_cluster_time (cs), old_cluster_time, false); } bson_destroy (old_cluster_time); @@ -932,19 +875,15 @@ test_session_advance_cluster_time (void *ctx) capture_logs (true); mongoc_client_session_advance_cluster_time (cs, tmp_bson ("{'foo': 1}")); - ASSERT_CAPTURED_LOG ("mongoc_client_session_advance_cluster_time", - MONGOC_LOG_LEVEL_ERROR, - "Cannot parse cluster time"); + ASSERT_CAPTURED_LOG ( + "mongoc_client_session_advance_cluster_time", MONGOC_LOG_LEVEL_ERROR, "Cannot parse cluster time"); capture_logs (true); - mongoc_client_session_advance_cluster_time (cs, - tmp_bson ("{'clusterTime': 1}")); - ASSERT_CAPTURED_LOG ("mongoc_client_session_advance_cluster_time", - MONGOC_LOG_LEVEL_ERROR, - "Cannot parse cluster time"); + mongoc_client_session_advance_cluster_time (cs, tmp_bson ("{'clusterTime': 1}")); + ASSERT_CAPTURED_LOG ( + "mongoc_client_session_advance_cluster_time", MONGOC_LOG_LEVEL_ERROR, "Cannot parse cluster time"); - mongoc_client_session_advance_cluster_time ( - cs, tmp_bson ("{'clusterTime': {'$timestamp': {'t': 1, 'i': 1}}}")); + mongoc_client_session_advance_cluster_time (cs, tmp_bson ("{'clusterTime': {'$timestamp': {'t': 1, 'i': 1}}}")); _test_advance_cluster_time (cs, 1, 0, false); _test_advance_cluster_time (cs, 2, 2, true); @@ -957,10 +896,7 @@ test_session_advance_cluster_time (void *ctx) static void -_test_advance_operation_time (mongoc_client_session_t *cs, - uint32_t t, - uint32_t i, - bool should_advance) +_test_advance_operation_time (mongoc_client_session_t *cs, uint32_t t, uint32_t i, bool should_advance) { uint32_t old_t, old_i; uint32_t new_t, new_i; @@ -973,8 +909,7 @@ _test_advance_operation_time (mongoc_client_session_t *cs, ASSERT_CMPUINT32 (new_t, ==, t); ASSERT_CMPUINT32 (new_i, ==, i); } else if (new_t == t && new_i == i) { - test_error ("Shouldn't have advanced from operationTime %" PRIu32 - ", %" PRIu32 " to %" PRIu32 ", %" PRIu32, + test_error ("Shouldn't have advanced from operationTime %" PRIu32 ", %" PRIu32 " to %" PRIu32 ", %" PRIu32, old_t, old_i, t, @@ -1057,8 +992,7 @@ started (const mongoc_apm_command_started_t *event) const bson_t *client_session_lsid; bson_t *cmd = bson_copy (mongoc_apm_command_started_get_command (event)); const char *cmd_name = mongoc_apm_command_started_get_command_name (event); - session_test_t *test = - (session_test_t *) mongoc_apm_command_started_get_context (event); + session_test_t *test = (session_test_t *) mongoc_apm_command_started_get_context (event); ctx.strict_numeric_types = false; @@ -1084,13 +1018,11 @@ started (const mongoc_apm_command_started_t *event) if (test->expect_explicit_lsid) { if (!match_bson_with_ctx (&lsid, client_session_lsid, &ctx)) { - test_error ("command %s should have used client session's lsid", - cmd_name); + test_error ("command %s should have used client session's lsid", cmd_name); } } else { if (match_bson_with_ctx (&lsid, client_session_lsid, &ctx)) { - test_error ("command %s should not have used client session's lsid", - cmd_name); + test_error ("command %s should not have used client session's lsid", cmd_name); } } @@ -1099,8 +1031,7 @@ started (const mongoc_apm_command_started_t *event) bson_copy_to (&lsid, &test->sent_lsid); } else { if (!match_bson_with_ctx (&lsid, &test->sent_lsid, &ctx)) { - test_error ("command %s used different lsid than previous command", - cmd_name); + test_error ("command %s used different lsid than previous command", cmd_name); } } } else { @@ -1134,8 +1065,7 @@ succeeded (const mongoc_apm_command_succeeded_t *event) bson_t cluster_time; bson_t *reply = bson_copy (mongoc_apm_command_succeeded_get_reply (event)); const char *cmd_name = mongoc_apm_command_succeeded_get_command_name (event); - session_test_t *test = - (session_test_t *) mongoc_apm_command_succeeded_get_context (event); + session_test_t *test = (session_test_t *) mongoc_apm_command_succeeded_get_context (event); if (test->verbose) { char *s = bson_as_json (reply, NULL); @@ -1172,8 +1102,7 @@ failed (const mongoc_apm_command_failed_t *event) const char *cmd_name; bson_error_t error; - session_test_t *test = - (session_test_t *) mongoc_apm_command_failed_get_context (event); + session_test_t *test = (session_test_t *) mongoc_apm_command_failed_get_context (event); if (!test->verbose) { return; @@ -1201,8 +1130,7 @@ set_session_test_callbacks (session_test_t *test) static session_test_t * -session_test_new (session_test_correct_t correct_client, - session_test_causal_t causal) +session_test_new (session_test_correct_t correct_client, session_test_causal_t causal) { session_test_t *test; mongoc_session_opt_t *cs_opts; @@ -1225,8 +1153,7 @@ session_test_new (session_test_correct_t correct_client, test->session_client = test_framework_new_default_client (); mongoc_client_set_error_api (test->session_client, 2); test->session_db = mongoc_client_get_database (test->session_client, "db"); - test->session_collection = - mongoc_database_get_collection (test->session_db, "collection"); + test->session_collection = mongoc_database_get_collection (test->session_db, "collection"); bson_init (&test->opts); @@ -1242,16 +1169,14 @@ session_test_new (session_test_correct_t correct_client, test->wrong_cs = mongoc_client_start_session (test->client, NULL, &error); ASSERT_OR_PRINT (test->wrong_cs, error); test->db = mongoc_client_get_database (test->client, "db"); - test->collection = - mongoc_database_get_collection (test->db, "collection"); + test->collection = mongoc_database_get_collection (test->db, "collection"); } set_session_test_callbacks (test); cs_opts = mongoc_session_opts_new (); mongoc_session_opts_set_causal_consistency (cs_opts, causal == CAUSAL); - test->cs = - mongoc_client_start_session (test->session_client, cs_opts, &error); + test->cs = mongoc_client_start_session (test->session_client, cs_opts, &error); ASSERT_OR_PRINT (test->cs, error); mongoc_session_opts_destroy (cs_opts); @@ -1265,9 +1190,7 @@ struct check_session_returned_t { }; static int -check_session_returned_visit (mongoc_server_session_t *ss, - mongoc_topology_t *unused, - void *check_state_) +check_session_returned_visit (mongoc_server_session_t *ss, mongoc_topology_t *unused, void *check_state_) { match_ctx_t ctx = {{0}}; struct check_session_returned_t *check_state = check_state_; @@ -1276,8 +1199,7 @@ check_session_returned_visit (mongoc_server_session_t *ss, ctx.strict_numeric_types = false; if (!check_state->found) { - check_state->found = - match_bson_with_ctx (&ss->lsid, check_state->expect_lsid, &ctx); + check_state->found = match_bson_with_ctx (&ss->lsid, check_state->expect_lsid, &ctx); } /* No session will ever be returned to the pool if it has never been used */ ASSERT_CMPINT64 (ss->last_used_usec, !=, SESSION_NEVER_USED); @@ -1294,16 +1216,13 @@ check_session_returned (session_test_t *test, const bson_t *lsid) check_state.found = false; mongoc_server_session_pool_visit_each ( - test->session_client->topology->session_pool, - &check_state, - check_session_returned_visit); + test->session_client->topology->session_pool, &check_state, check_session_returned_visit); /* Server session will only be returned to the pool if it has * been used. It is expected behavior for found to be false if * ss->last_used_usec == SESSION_NEVER_USED */ if (!check_state.found) { - test_error ("server session %s not returned to pool", - bson_as_json (lsid, NULL)); + test_error ("server session %s not returned to pool", bson_as_json (lsid, NULL)); } } @@ -1366,8 +1285,7 @@ session_test_destroy (session_test_t *test) { bson_t session_lsid; size_t i; - bool ss_was_used = - test->cs->server_session->last_used_usec != SESSION_NEVER_USED; + bool ss_was_used = test->cs->server_session->last_used_usec != SESSION_NEVER_USED; bson_copy_to (mongoc_client_session_get_lsid (test->cs), &session_lsid); @@ -1420,10 +1338,7 @@ check_sessions_from_same_client_enforced (session_test_t *test) { if (test->session_client != test->client) { BSON_ASSERT (!test->succeeded); - ASSERT_ERROR_CONTAINS (test->error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Invalid sessionId"); + ASSERT_ERROR_CONTAINS (test->error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid sessionId"); } } @@ -1433,10 +1348,8 @@ check_sessions_with_w0_prohibited (session_test_t *test) { if (test->expect_explicit_lsid && !test->acknowledged) { BSON_ASSERT (!test->succeeded); - ASSERT_ERROR_CONTAINS (test->error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "session with unacknowledged"); + ASSERT_ERROR_CONTAINS ( + test->error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "session with unacknowledged"); } } @@ -1447,8 +1360,7 @@ check_success (session_test_t *test) check_sessions_from_same_client_enforced (test); check_sessions_with_w0_prohibited (test); - if (test->session_client == test->client && - test->expect_explicit_lsid == test->acknowledged) { + if (test->session_client == test->client && test->expect_explicit_lsid == test->acknowledged) { ASSERT_OR_PRINT (test->succeeded, test->error); } @@ -1469,8 +1381,7 @@ check_cluster_time (session_test_t *test) /* fail if cluster_time_greater logs an error */ capture_logs (true); - if (_mongoc_cluster_time_greater (&test->received_cluster_time, - session_time)) { + if (_mongoc_cluster_time_greater (&test->received_cluster_time, session_time)) { test_error ("client session's cluster time is outdated"); } @@ -1497,8 +1408,7 @@ _test_explicit_session_lsid (session_test_fn_t test_fn) test = session_test_new (CORRECT_CLIENT, NOT_CAUSAL); ASSERT_CMPINT64 (test->cs->server_session->last_used_usec, ==, (int64_t) -1); - ASSERT_OR_PRINT ( - mongoc_client_session_append (test->cs, &test->opts, &error), error); + ASSERT_OR_PRINT (mongoc_client_session_append (test->cs, &test->opts, &error), error); start = bson_get_monotonic_time (); test_fn (test); @@ -1520,8 +1430,7 @@ _test_session_from_wrong_client (session_test_fn_t test_fn) bson_error_t error; test = session_test_new (INCORRECT_CLIENT, NOT_CAUSAL); - ASSERT_OR_PRINT ( - mongoc_client_session_append (test->cs, &test->opts, &error), error); + ASSERT_OR_PRINT (mongoc_client_session_append (test->cs, &test->opts, &error), error); test_fn (test); check_success (test); @@ -1544,8 +1453,7 @@ _test_implicit_session_lsid (session_test_fn_t test_fn) test_fn (test); check_success (test); mongoc_collection_drop_with_opts (test->session_collection, NULL, NULL); - ss = mongoc_server_session_pool_get_existing ( - test->client->topology->session_pool); + ss = mongoc_server_session_pool_get_existing (test->client->topology->session_pool); BSON_ASSERT (ss); ASSERT_CMPINT64 (ss->last_used_usec, >=, start); mongoc_server_session_pool_return (test->client->topology->session_pool, ss); @@ -1584,14 +1492,10 @@ parse_reply_time (const bson_t *reply, op_time_t *op_time) } -#define ASSERT_OP_TIMES_EQUAL(_a, _b) \ - if ((_a).t != (_b).t || (_a).i != (_b).i) { \ - test_error (#_a " (%d, %d) does not match " #_b " (%d, %d)", \ - (_a).t, \ - (_a).i, \ - (_b).t, \ - (_b).i); \ - } else \ +#define ASSERT_OP_TIMES_EQUAL(_a, _b) \ + if ((_a).t != (_b).t || (_a).i != (_b).i) { \ + test_error (#_a " (%d, %d) does not match " #_b " (%d, %d)", (_a).t, (_a).i, (_b).t, (_b).i); \ + } else \ ((void) 0) @@ -1608,14 +1512,12 @@ _test_causal_consistency (session_test_fn_t test_fn, bool allow_read_concern) * first causal exchange: don't send readConcern, receive opTime */ test = session_test_new (CORRECT_CLIENT, CAUSAL); - ASSERT_OR_PRINT ( - mongoc_client_session_append (test->cs, &test->opts, &error), error); + ASSERT_OR_PRINT (mongoc_client_session_append (test->cs, &test->opts, &error), error); test_fn (test); check_success (test); BSON_ASSERT (!bson_has_field (first_cmd (test), "readConcern")); - mongoc_client_session_get_operation_time ( - test->cs, &session_time.t, &session_time.i); + mongoc_client_session_get_operation_time (test->cs, &session_time.t, &session_time.i); BSON_ASSERT (session_time.t != 0); parse_reply_time (last_reply (test), &reply_time); ASSERT_OP_TIMES_EQUAL (session_time, reply_time); @@ -1634,8 +1536,7 @@ _test_causal_consistency (session_test_fn_t test_fn, bool allow_read_concern) if (allow_read_concern) { parse_read_concern_time (first_cmd (test), &read_concern_time); ASSERT_OP_TIMES_EQUAL (reply_time, read_concern_time); - mongoc_client_session_get_operation_time ( - test->cs, &session_time.t, &session_time.i); + mongoc_client_session_get_operation_time (test->cs, &session_time.t, &session_time.i); BSON_ASSERT (session_time.t != 0); parse_reply_time (last_reply (test), &reply_time); ASSERT_OP_TIMES_EQUAL (session_time, reply_time); @@ -1644,8 +1545,7 @@ _test_causal_consistency (session_test_fn_t test_fn, bool allow_read_concern) for (i = 0; i < test->cmds.len; i++) { cmd = _mongoc_array_index (&test->cmds, bson_t *, i); if (bson_has_field (cmd, "readConcern")) { - test_error ("Command should not have included readConcern: %s", - bson_as_json (cmd, NULL)); + test_error ("Command should not have included readConcern: %s", bson_as_json (cmd, NULL)); } } } @@ -1695,8 +1595,7 @@ run_count_test (void *ctx) { /* CDRIVER-3612: mongoc_collection_estimated_document_count does not support * explicit sessions */ - _test_implicit_session_lsid ( - (session_test_fn_t) ((TestFnCtx *) ctx)->test_fn); + _test_implicit_session_lsid ((session_test_fn_t) ((TestFnCtx *) ctx)->test_fn); } @@ -1710,8 +1609,7 @@ insert_10_docs (session_test_t *test) /* disable callbacks, we're not testing insert's lsid */ mongoc_client_set_apm_callbacks (test->session_client, NULL, NULL); - bulk = mongoc_collection_create_bulk_operation_with_opts ( - test->session_collection, NULL); + bulk = mongoc_collection_create_bulk_operation_with_opts (test->session_collection, NULL); for (i = 0; i < 10; i++) { mongoc_bulk_operation_insert (bulk, tmp_bson ("{}")); @@ -1729,39 +1627,25 @@ insert_10_docs (session_test_t *test) static void test_cmd (session_test_t *test) { - test->succeeded = - mongoc_client_command_with_opts (test->client, - "db", - tmp_bson ("{'listCollections': 1}"), - NULL, - &test->opts, - NULL, - &test->error); + test->succeeded = mongoc_client_command_with_opts ( + test->client, "db", tmp_bson ("{'listCollections': 1}"), NULL, &test->opts, NULL, &test->error); } static void test_read_cmd (session_test_t *test) { - test->succeeded = - mongoc_client_read_command_with_opts (test->client, - "db", - tmp_bson ("{'listCollections': 1}"), - NULL, - &test->opts, - NULL, - &test->error); + test->succeeded = mongoc_client_read_command_with_opts ( + test->client, "db", tmp_bson ("{'listCollections': 1}"), NULL, &test->opts, NULL, &test->error); } static void test_write_cmd (session_test_t *test) { - bson_t *cmd = - tmp_bson ("{'delete': 'collection', 'deletes': [{'q': {}, 'limit': 1}]}"); + bson_t *cmd = tmp_bson ("{'delete': 'collection', 'deletes': [{'q': {}, 'limit': 1}]}"); - test->succeeded = mongoc_client_write_command_with_opts ( - test->client, "db", cmd, &test->opts, NULL, &test->error); + test->succeeded = mongoc_client_write_command_with_opts (test->client, "db", cmd, &test->opts, NULL, &test->error); } @@ -1774,36 +1658,24 @@ test_read_write_cmd (session_test_t *test) " 'pipeline': [{'$out': 'collection2'}]" "}"); - test->succeeded = mongoc_client_read_write_command_with_opts ( - test->client, "db", cmd, NULL, &test->opts, NULL, &test->error); + test->succeeded = + mongoc_client_read_write_command_with_opts (test->client, "db", cmd, NULL, &test->opts, NULL, &test->error); } static void test_db_cmd (session_test_t *test) { - test->succeeded = - mongoc_database_command_with_opts (test->db, - tmp_bson ("{'listCollections': 1}"), - NULL, - &test->opts, - NULL, - &test->error); + test->succeeded = mongoc_database_command_with_opts ( + test->db, tmp_bson ("{'listCollections': 1}"), NULL, &test->opts, NULL, &test->error); } static void test_count (session_test_t *test) { - test->succeeded = - (-1 != mongoc_collection_count_with_opts (test->collection, - MONGOC_QUERY_NONE, - NULL, - 0, - 0, - &test->opts, - NULL, - &test->error)); + test->succeeded = (-1 != mongoc_collection_count_with_opts ( + test->collection, MONGOC_QUERY_NONE, NULL, 0, 0, &test->opts, NULL, &test->error)); } @@ -1816,8 +1688,7 @@ test_cursor (session_test_t *test) /* ensure multiple batches */ insert_10_docs (test); - cursor = mongoc_collection_find_with_opts ( - test->collection, tmp_bson ("{}"), &test->opts, NULL); + cursor = mongoc_collection_find_with_opts (test->collection, tmp_bson ("{}"), &test->opts, NULL); mongoc_cursor_set_batch_size (cursor, 2); while (mongoc_cursor_next (cursor, &doc)) { @@ -1835,8 +1706,7 @@ test_drop (session_test_t *test) /* create the collection so that "drop" can succeed */ insert_10_docs (test); - test->succeeded = mongoc_collection_drop_with_opts ( - test->collection, &test->opts, &test->error); + test->succeeded = mongoc_collection_drop_with_opts (test->collection, &test->opts, &test->error); } @@ -1846,97 +1716,69 @@ test_drop_index (session_test_t *test) bson_error_t error; bool r; - mongoc_index_model_t *im = mongoc_index_model_new ( - tmp_bson ("{'a': 1}"), tmp_bson ("{'name': 'foo'}")); + mongoc_index_model_t *im = mongoc_index_model_new (tmp_bson ("{'a': 1}"), tmp_bson ("{'name': 'foo'}")); r = mongoc_collection_create_indexes_with_opts ( test->session_collection, &im, 1, &test->opts, NULL /* reply */, &error); mongoc_index_model_destroy (im); ASSERT_OR_PRINT (r, error); - test->succeeded = mongoc_collection_drop_index_with_opts ( - test->collection, "foo", &test->opts, &test->error); + test->succeeded = mongoc_collection_drop_index_with_opts (test->collection, "foo", &test->opts, &test->error); } static void test_create_index (session_test_t *test) { BEGIN_IGNORE_DEPRECATIONS - test->succeeded = - mongoc_collection_create_index_with_opts (test->collection, - tmp_bson ("{'a': 1}"), - NULL, - &test->opts, - NULL, - &test->error); + test->succeeded = mongoc_collection_create_index_with_opts ( + test->collection, tmp_bson ("{'a': 1}"), NULL, &test->opts, NULL, &test->error); END_IGNORE_DEPRECATIONS } static void test_replace_one (session_test_t *test) { - test->succeeded = mongoc_collection_replace_one (test->collection, - tmp_bson ("{}"), - tmp_bson ("{}"), - &test->opts, - NULL, - &test->error); + test->succeeded = mongoc_collection_replace_one ( + test->collection, tmp_bson ("{}"), tmp_bson ("{}"), &test->opts, NULL, &test->error); } static void test_update_one (session_test_t *test) { - test->succeeded = - mongoc_collection_update_one (test->collection, - tmp_bson ("{}"), - tmp_bson ("{'$set': {'x': 1}}"), - &test->opts, - NULL, - &test->error); + test->succeeded = mongoc_collection_update_one ( + test->collection, tmp_bson ("{}"), tmp_bson ("{'$set': {'x': 1}}"), &test->opts, NULL, &test->error); } static void test_update_many (session_test_t *test) { - test->succeeded = - mongoc_collection_update_many (test->collection, - tmp_bson ("{}"), - tmp_bson ("{'$set': {'x': 1}}"), - &test->opts, - NULL, - &test->error); + test->succeeded = mongoc_collection_update_many ( + test->collection, tmp_bson ("{}"), tmp_bson ("{'$set': {'x': 1}}"), &test->opts, NULL, &test->error); } static void test_insert_one (session_test_t *test) { - test->succeeded = mongoc_collection_insert_one ( - test->collection, tmp_bson ("{}"), &test->opts, NULL, &test->error); + test->succeeded = mongoc_collection_insert_one (test->collection, tmp_bson ("{}"), &test->opts, NULL, &test->error); } static void test_insert_many (session_test_t *test) { bson_t *docs[2] = {tmp_bson ("{}"), tmp_bson ("{}")}; - test->succeeded = mongoc_collection_insert_many (test->collection, - (const bson_t **) docs, - 2, - &test->opts, - NULL, - &test->error); + test->succeeded = + mongoc_collection_insert_many (test->collection, (const bson_t **) docs, 2, &test->opts, NULL, &test->error); } static void test_delete_one (session_test_t *test) { - test->succeeded = mongoc_collection_delete_one ( - test->collection, tmp_bson ("{}"), &test->opts, NULL, &test->error); + test->succeeded = mongoc_collection_delete_one (test->collection, tmp_bson ("{}"), &test->opts, NULL, &test->error); } static void test_delete_many (session_test_t *test) { - test->succeeded = mongoc_collection_delete_many ( - test->collection, tmp_bson ("{}"), &test->opts, NULL, &test->error); + test->succeeded = mongoc_collection_delete_many (test->collection, tmp_bson ("{}"), &test->opts, NULL, &test->error); } static void @@ -1949,8 +1791,7 @@ test_rename (session_test_t *test) /* mongoc_collection_rename_with_opts mutates the struct! */ collection = mongoc_collection_copy (test->collection); - test->succeeded = mongoc_collection_rename_with_opts ( - collection, "db", "newname", true, &test->opts, &test->error); + test->succeeded = mongoc_collection_rename_with_opts (collection, "db", "newname", true, &test->opts, &test->error); mongoc_collection_destroy (collection); } @@ -1961,11 +1802,10 @@ test_fam (session_test_t *test) mongoc_find_and_modify_opts_t *fam_opts; fam_opts = mongoc_find_and_modify_opts_new (); - mongoc_find_and_modify_opts_set_update (fam_opts, - tmp_bson ("{'$set': {'x': 1}}")); + mongoc_find_and_modify_opts_set_update (fam_opts, tmp_bson ("{'$set': {'x': 1}}")); BSON_ASSERT (mongoc_find_and_modify_opts_append (fam_opts, &test->opts)); - test->succeeded = mongoc_collection_find_and_modify_with_opts ( - test->collection, tmp_bson ("{}"), fam_opts, NULL, &test->error); + test->succeeded = + mongoc_collection_find_and_modify_with_opts (test->collection, tmp_bson ("{}"), fam_opts, NULL, &test->error); mongoc_find_and_modify_opts_destroy (fam_opts); } @@ -1973,8 +1813,7 @@ test_fam (session_test_t *test) static void test_db_drop (session_test_t *test) { - test->succeeded = - mongoc_database_drop_with_opts (test->db, &test->opts, &test->error); + test->succeeded = mongoc_database_drop_with_opts (test->db, &test->opts, &test->error); } static void @@ -2016,8 +1855,7 @@ test_gridfs_find_one (session_test_t *test) gfs = mongoc_client_get_gridfs (test->client, "test", NULL, &error); ASSERT_OR_PRINT (gfs, error); set_session_test_callbacks (test); - f = mongoc_gridfs_find_one_with_opts ( - gfs, tmp_bson ("{}"), &test->opts, &test->error); + f = mongoc_gridfs_find_one_with_opts (gfs, tmp_bson ("{}"), &test->opts, &test->error); test->succeeded = test->error.domain == 0; @@ -2035,11 +1873,9 @@ test_watch (session_test_t *test) mongoc_change_stream_t *change_stream; insert_10_docs (test); - change_stream = - mongoc_collection_watch (test->collection, tmp_bson ("{}"), &test->opts); + change_stream = mongoc_collection_watch (test->collection, tmp_bson ("{}"), &test->opts); - test->succeeded = - !mongoc_change_stream_error_document (change_stream, &test->error, NULL); + test->succeeded = !mongoc_change_stream_error_document (change_stream, &test->error, NULL); mongoc_change_stream_destroy (change_stream); } @@ -2057,8 +1893,7 @@ test_aggregate (session_test_t *test) bson_copy_to (&test->opts, &opts); BSON_APPEND_INT32 (&opts, "batchSize", 2); - cursor = mongoc_collection_aggregate ( - test->collection, MONGOC_QUERY_NONE, tmp_bson ("{}"), &opts, NULL); + cursor = mongoc_collection_aggregate (test->collection, MONGOC_QUERY_NONE, tmp_bson ("{}"), &opts, NULL); while (mongoc_cursor_next (cursor, &doc)) { } @@ -2076,14 +1911,10 @@ test_create (session_test_t *test) mongoc_collection_t *collection; /* ensure "create" can succeed */ - mongoc_database_write_command_with_opts (test->session_db, - tmp_bson ("{'drop': 'newname'}"), - &test->opts, - NULL, - NULL); + mongoc_database_write_command_with_opts ( + test->session_db, tmp_bson ("{'drop': 'newname'}"), &test->opts, NULL, NULL); - collection = mongoc_database_create_collection ( - test->db, "newname", &test->opts, &test->error); + collection = mongoc_database_create_collection (test->db, "newname", &test->opts, &test->error); test->succeeded = (collection != NULL); @@ -2098,8 +1929,7 @@ test_database_names (session_test_t *test) { char **names; - names = mongoc_client_get_database_names_with_opts ( - test->client, &test->opts, &test->error); + names = mongoc_client_get_database_names_with_opts (test->client, &test->opts, &test->error); test->succeeded = (names != NULL); @@ -2146,8 +1976,7 @@ test_collection_names (session_test_t *test) { char **strv; - strv = mongoc_database_get_collection_names_with_opts ( - test->db, &test->opts, &test->error); + strv = mongoc_database_get_collection_names_with_opts (test->db, &test->opts, &test->error); test->succeeded = (strv != NULL); bson_strfreev (strv); } @@ -2162,8 +1991,7 @@ test_find_indexes (session_test_t *test) /* ensure the collection exists so the listIndexes command succeeds */ insert_10_docs (test); - cursor = - mongoc_collection_find_indexes_with_opts (test->collection, &test->opts); + cursor = mongoc_collection_find_indexes_with_opts (test->collection, &test->opts); while (mongoc_cursor_next (cursor, &doc)) { } @@ -2178,21 +2006,15 @@ _test_bulk (session_test_t *test, mongoc_bulk_operation_t *bulk) { uint32_t i; - test->succeeded = mongoc_bulk_operation_insert_with_opts ( - bulk, tmp_bson ("{}"), NULL, &test->error); + test->succeeded = mongoc_bulk_operation_insert_with_opts (bulk, tmp_bson ("{}"), NULL, &test->error); check_sessions_from_same_client_enforced (test); test->succeeded = mongoc_bulk_operation_update_one_with_opts ( - bulk, - tmp_bson ("{}"), - tmp_bson ("{'$set': {'x': 1}}"), - NULL, - &test->error); + bulk, tmp_bson ("{}"), tmp_bson ("{'$set': {'x': 1}}"), NULL, &test->error); check_sessions_from_same_client_enforced (test); - test->succeeded = mongoc_bulk_operation_remove_one_with_opts ( - bulk, tmp_bson ("{}"), NULL, &test->error); + test->succeeded = mongoc_bulk_operation_remove_one_with_opts (bulk, tmp_bson ("{}"), NULL, &test->error); check_sessions_from_same_client_enforced (test); i = mongoc_bulk_operation_execute (bulk, NULL, &test->error); @@ -2209,8 +2031,7 @@ test_bulk (session_test_t *test) { mongoc_bulk_operation_t *bulk; - bulk = mongoc_collection_create_bulk_operation_with_opts (test->collection, - &test->opts); + bulk = mongoc_collection_create_bulk_operation_with_opts (test->collection, &test->opts); _test_bulk (test, bulk); } @@ -2229,15 +2050,12 @@ test_bulk_set_session (session_test_t *test) bulk = mongoc_bulk_operation_new (true /* ordered */); mongoc_bulk_operation_set_client (bulk, test->client); - mongoc_bulk_operation_set_database (bulk, - mongoc_database_get_name (test->db)); + mongoc_bulk_operation_set_database (bulk, mongoc_database_get_name (test->db)); - mongoc_bulk_operation_set_collection ( - bulk, mongoc_collection_get_name (test->collection)); + mongoc_bulk_operation_set_collection (bulk, mongoc_collection_get_name (test->collection)); if (bson_iter_init_find (&iter, &test->opts, "sessionId")) { - r = _mongoc_client_session_from_iter ( - test->session_client, &iter, &cs, &error); + r = _mongoc_client_session_from_iter (test->session_client, &iter, &cs, &error); ASSERT_OR_PRINT (r, error); mongoc_bulk_operation_set_client_session (bulk, cs); @@ -2260,19 +2078,16 @@ test_bulk_set_client (session_test_t *test) bulk = mongoc_bulk_operation_new (true /* ordered */); if (bson_iter_init_find (&iter, &test->opts, "sessionId")) { - r = _mongoc_client_session_from_iter ( - test->session_client, &iter, &cs, &error); + r = _mongoc_client_session_from_iter (test->session_client, &iter, &cs, &error); ASSERT_OR_PRINT (r, error); mongoc_bulk_operation_set_client_session (bulk, cs); } mongoc_bulk_operation_set_client (bulk, test->client); - mongoc_bulk_operation_set_database (bulk, - mongoc_database_get_name (test->db)); + mongoc_bulk_operation_set_database (bulk, mongoc_database_get_name (test->db)); - mongoc_bulk_operation_set_collection ( - bulk, mongoc_collection_get_name (test->collection)); + mongoc_bulk_operation_set_collection (bulk, mongoc_collection_get_name (test->collection)); _test_bulk (test, bulk); } @@ -2300,8 +2115,7 @@ test_cursor_implicit_session (void *ctx) mongoc_collection_drop_with_opts (test->session_collection, NULL, NULL); insert_10_docs (test); - cursor = mongoc_collection_find_with_opts ( - test->collection, tmp_bson ("{}"), &test->opts, NULL); + cursor = mongoc_collection_find_with_opts (test->collection, tmp_bson ("{}"), &test->opts, NULL); BSON_ASSERT (!cursor->client_session); mongoc_cursor_set_batch_size (cursor, 2); @@ -2311,8 +2125,7 @@ test_cursor_implicit_session (void *ctx) BSON_ASSERT (cursor->client_session); BSON_ASSERT (!cursor->explicit_session); bson_copy_to (&cursor->client_session->server_session->lsid, &find_lsid); - ASSERT_CMPSIZE_T ( - mongoc_server_session_pool_size (topology->session_pool), ==, 0); + ASSERT_CMPSIZE_T (mongoc_server_session_pool_size (topology->session_pool), ==, 0); ASSERT_SESSIONS_MATCH (&test->sent_lsid, &find_lsid); /* push a new server session into the pool. server session is only pushed @@ -2335,8 +2148,7 @@ test_cursor_implicit_session (void *ctx) /* lsid returned after last batch, doesn't wait for mongoc_cursor_destroy */ check_session_returned (test, &find_lsid); - ASSERT_CMPSIZE_T ( - mongoc_server_session_pool_size (topology->session_pool), ==, 2); + ASSERT_CMPSIZE_T (mongoc_server_session_pool_size (topology->session_pool), ==, 2); bson_destroy (&find_lsid); mongoc_cursor_destroy (cursor); @@ -2364,12 +2176,10 @@ test_change_stream_implicit_session (void *ctx) topology = test->client->topology; cs = mongoc_client_start_session (test->client, NULL, &error); ASSERT_OR_PRINT (cs, error); - change_stream = - mongoc_collection_watch (test->session_collection, &pipeline, NULL); + change_stream = mongoc_collection_watch (test->session_collection, &pipeline, NULL); bson_destroy (&pipeline); bson_copy_to (&test->sent_lsid, &aggregate_lsid); - ASSERT_CMPSIZE_T ( - mongoc_server_session_pool_size (topology->session_pool), ==, 0); + ASSERT_CMPSIZE_T (mongoc_server_session_pool_size (topology->session_pool), ==, 0); BSON_ASSERT (change_stream->implicit_session); @@ -2379,8 +2189,7 @@ test_change_stream_implicit_session (void *ctx) bson_reinit (&test->sent_lsid); send_ping (test->client, cs); mongoc_client_session_destroy (cs); - ASSERT_CMPSIZE_T ( - mongoc_server_session_pool_size (topology->session_pool), ==, 1); + ASSERT_CMPSIZE_T (mongoc_server_session_pool_size (topology->session_pool), ==, 1); ss = mongoc_server_session_pool_get_existing (topology->session_pool); BSON_ASSERT (ss); ASSERT_SESSIONS_DIFFER (&aggregate_lsid, &ss->lsid); @@ -2389,15 +2198,10 @@ test_change_stream_implicit_session (void *ctx) /* "getMore" uses the same lsid as "aggregate" did */ bson_reinit (&test->sent_lsid); mongoc_change_stream_next (change_stream, &doc); - ASSERT_SESSIONS_MATCH ( - &test->sent_lsid, &change_stream->implicit_session->server_session->lsid); - ASSERT_SESSIONS_MATCH ( - &test->sent_lsid, - &change_stream->cursor->client_session->server_session->lsid); + ASSERT_SESSIONS_MATCH (&test->sent_lsid, &change_stream->implicit_session->server_session->lsid); + ASSERT_SESSIONS_MATCH (&test->sent_lsid, &change_stream->cursor->client_session->server_session->lsid); ASSERT_SESSIONS_MATCH (&test->sent_lsid, &aggregate_lsid); - ASSERT_OR_PRINT ( - !mongoc_change_stream_error_document (change_stream, &error, NULL), - error); + ASSERT_OR_PRINT (!mongoc_change_stream_error_document (change_stream, &error, NULL), error); bson_destroy (&aggregate_lsid); mongoc_change_stream_destroy (change_stream); session_test_destroy (test); @@ -2418,17 +2222,11 @@ test_cmd_error (void *ctx) * explicit session. command error still updates operation time */ test->expect_explicit_lsid = true; - ASSERT_OR_PRINT ( - mongoc_client_session_append (test->cs, &test->opts, &error), error); + ASSERT_OR_PRINT (mongoc_client_session_append (test->cs, &test->opts, &error), error); BSON_ASSERT (test->cs->operation_timestamp == 0); - BSON_ASSERT (!mongoc_client_command_with_opts (test->session_client, - "db", - tmp_bson ("{'bad': 1}"), - NULL, - &test->opts, - NULL, - NULL)); + BSON_ASSERT (!mongoc_client_command_with_opts ( + test->session_client, "db", tmp_bson ("{'bad': 1}"), NULL, &test->opts, NULL, NULL)); BSON_ASSERT (test->cs->operation_timestamp != 0); @@ -2448,8 +2246,7 @@ test_read_concern (void *ctx) test = session_test_new (CORRECT_CLIENT, CAUSAL); test->expect_explicit_lsid = true; - ASSERT_OR_PRINT ( - mongoc_client_session_append (test->cs, &test->opts, &error), error); + ASSERT_OR_PRINT (mongoc_client_session_append (test->cs, &test->opts, &error), error); /* first exchange sets session's operationTime */ test_read_cmd (test); @@ -2494,8 +2291,7 @@ test_read_concern (void *ctx) test->cs = mongoc_client_start_session (test->client, cs_opts, &error); ASSERT_OR_PRINT (test->cs, error); bson_reinit (&test->opts); - ASSERT_OR_PRINT ( - mongoc_client_session_append (test->cs, &test->opts, &error), error); + ASSERT_OR_PRINT (mongoc_client_session_append (test->cs, &test->opts, &error), error); BSON_ASSERT (mongoc_read_concern_append (rc, &test->opts)); /* set new session's operationTime */ test_read_cmd (test); @@ -2516,13 +2312,11 @@ test_read_concern (void *ctx) * no read concern, not causal */ bson_reinit (&test->opts); - ASSERT_OR_PRINT ( - mongoc_client_session_append (test->cs, &test->opts, &error), error); + ASSERT_OR_PRINT (mongoc_client_session_append (test->cs, &test->opts, &error), error); /* afterClusterTime is not sent */ test_read_cmd (test); check_success (test); - ASSERT_MATCH (last_non_getmore_cmd (test), - "{'readConcern': {'$exists': false}}"); + ASSERT_MATCH (last_non_getmore_cmd (test), "{'readConcern': {'$exists': false}}"); mongoc_session_opts_destroy (cs_opts); mongoc_read_concern_destroy (rc); @@ -2531,9 +2325,7 @@ test_read_concern (void *ctx) static void -_test_unacknowledged (session_test_fn_t test_fn, - bool explicit_cs, - bool inherit_wc) +_test_unacknowledged (session_test_fn_t test_fn, bool explicit_cs, bool inherit_wc) { session_test_t *test; mongoc_write_concern_t *wc; @@ -2550,8 +2342,7 @@ _test_unacknowledged (session_test_fn_t test_fn, mongoc_write_concern_set_w (wc, 0); if (explicit_cs) { - ASSERT_OR_PRINT ( - mongoc_client_session_append (test->cs, &test->opts, &error), error); + ASSERT_OR_PRINT (mongoc_client_session_append (test->cs, &test->opts, &error), error); } if (inherit_wc) { @@ -2578,76 +2369,65 @@ _test_unacknowledged (session_test_fn_t test_fn, static void test_unacknowledged_explicit_cs_inherit_wc (void *ctx) { - _test_unacknowledged ( - (session_test_fn_t) ((TestFnCtx *) ctx)->test_fn, true, true); + _test_unacknowledged ((session_test_fn_t) ((TestFnCtx *) ctx)->test_fn, true, true); } static void test_unacknowledged_implicit_cs_explicit_wc (void *ctx) { - _test_unacknowledged ( - (session_test_fn_t) ((TestFnCtx *) ctx)->test_fn, true, false); + _test_unacknowledged ((session_test_fn_t) ((TestFnCtx *) ctx)->test_fn, true, false); } static void test_unacknowledged_implicit_cs_inherit_wc (void *ctx) { - _test_unacknowledged ( - (session_test_fn_t) ((TestFnCtx *) ctx)->test_fn, false, true); + _test_unacknowledged ((session_test_fn_t) ((TestFnCtx *) ctx)->test_fn, false, true); } static void test_unacknowledged_explicit_cs_explicit_wc (void *ctx) { - _test_unacknowledged ( - (session_test_fn_t) ((TestFnCtx *) ctx)->test_fn, false, false); -} - - -#define add_session_test(_suite, _name, _test_fn, _allow_read_concern) \ - TestSuite_AddFullWithTestFn ( \ - _suite, \ - _name, \ - (_allow_read_concern) ? run_session_test : run_session_test_no_rc, \ - NULL, \ - _test_fn, \ - test_framework_skip_if_no_cluster_time, \ - test_framework_skip_if_no_crypto) - -#define add_session_test_wc(_suite, _name, _test_fn, _allow_read_concern, ...) \ - TestSuite_AddFullWithTestFn ( \ - _suite, \ - _name, \ - (_allow_read_concern) ? run_session_test : run_session_test_no_rc, \ - NULL, \ - _test_fn, \ - test_framework_skip_if_no_cluster_time, \ - test_framework_skip_if_no_crypto, \ - __VA_ARGS__) - -#define add_unacknowledged_test( \ - _suite, _name, _test_fn, _explicit_cs, _inherit_wc) \ - TestSuite_AddFullWithTestFn ( \ - _suite, \ - _name, \ - (_explicit_cs) \ - ? (_inherit_wc ? test_unacknowledged_explicit_cs_inherit_wc \ - : test_unacknowledged_implicit_cs_explicit_wc) \ - : (_inherit_wc ? test_unacknowledged_implicit_cs_inherit_wc \ - : test_unacknowledged_explicit_cs_explicit_wc), \ - NULL, \ - _test_fn, \ - test_framework_skip_if_no_cluster_time, \ + _test_unacknowledged ((session_test_fn_t) ((TestFnCtx *) ctx)->test_fn, false, false); +} + + +#define add_session_test(_suite, _name, _test_fn, _allow_read_concern) \ + TestSuite_AddFullWithTestFn (_suite, \ + _name, \ + (_allow_read_concern) ? run_session_test : run_session_test_no_rc, \ + NULL, \ + _test_fn, \ + test_framework_skip_if_no_cluster_time, \ + test_framework_skip_if_no_crypto) + +#define add_session_test_wc(_suite, _name, _test_fn, _allow_read_concern, ...) \ + TestSuite_AddFullWithTestFn (_suite, \ + _name, \ + (_allow_read_concern) ? run_session_test : run_session_test_no_rc, \ + NULL, \ + _test_fn, \ + test_framework_skip_if_no_cluster_time, \ + test_framework_skip_if_no_crypto, \ + __VA_ARGS__) + +#define add_unacknowledged_test(_suite, _name, _test_fn, _explicit_cs, _inherit_wc) \ + TestSuite_AddFullWithTestFn ( \ + _suite, \ + _name, \ + (_explicit_cs) \ + ? (_inherit_wc ? test_unacknowledged_explicit_cs_inherit_wc : test_unacknowledged_implicit_cs_explicit_wc) \ + : (_inherit_wc ? test_unacknowledged_implicit_cs_inherit_wc : test_unacknowledged_explicit_cs_explicit_wc), \ + NULL, \ + _test_fn, \ + test_framework_skip_if_no_cluster_time, \ test_framework_skip_if_no_crypto) static bool -_test_run_operation (json_test_ctx_t *ctx, - const bson_t *test, - const bson_t *operation) +_test_run_operation (json_test_ctx_t *ctx, const bson_t *test, const bson_t *operation) { bson_t reply; mongoc_client_session_t *session = NULL; @@ -2655,8 +2435,7 @@ _test_run_operation (json_test_ctx_t *ctx, * probably handle this. Let's wait until unified test runner is spec'ed. */ if (bson_has_field (operation, "arguments.session")) { - session = session_from_name ( - ctx, bson_lookup_utf8 (operation, "arguments.session")); + session = session_from_name (ctx, bson_lookup_utf8 (operation, "arguments.session")); } json_test_operation (ctx, test, operation, ctx->collection, session, &reply); @@ -2700,8 +2479,7 @@ _test_session_dirty_helper (bool retry_succeeds) ret = mongoc_client_session_append (session, &opts, &error); ASSERT_OR_PRINT (ret, error); - ret = mongoc_collection_insert_one ( - coll, tmp_bson ("{}"), &opts, NULL /* reply */, &error); + ret = mongoc_collection_insert_one (coll, tmp_bson ("{}"), &opts, NULL /* reply */, &error); ASSERT_OR_PRINT (ret, error); BSON_ASSERT (!session->server_session->dirty); @@ -2730,44 +2508,32 @@ _test_session_dirty_helper (bool retry_succeeds) "closeConnection", BCON_BOOL (true), "}"); - ret = mongoc_client_command_simple (client, - "admin", - failpoint_cmd, - NULL /* read prefs */, - NULL /* reply */, - &error); + ret = mongoc_client_command_simple (client, "admin", failpoint_cmd, NULL /* read prefs */, NULL /* reply */, &error); ASSERT_OR_PRINT (ret, error); - ret = mongoc_collection_insert_one ( - coll, tmp_bson ("{}"), &opts, NULL /* reply */, &error); + ret = mongoc_collection_insert_one (coll, tmp_bson ("{}"), &opts, NULL /* reply */, &error); if (retry_succeeds) { ASSERT_OR_PRINT (ret, error); } else { BSON_ASSERT (!ret); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_SOCKET, - "socket error"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "socket error"); } /* Regardless of whether the retry succeeded, the session should be marked * dirty */ BSON_ASSERT (session->server_session->dirty); - const size_t pooled_session_count_pre = - mongoc_server_session_pool_size (client->topology->session_pool); + const size_t pooled_session_count_pre = mongoc_server_session_pool_size (client->topology->session_pool); mongoc_client_session_destroy (session); - const size_t pooled_session_count_post = - mongoc_server_session_pool_size (client->topology->session_pool); + const size_t pooled_session_count_post = mongoc_server_session_pool_size (client->topology->session_pool); /* Check that destroying in the session did not add it back to the pool. */ ASSERT_CMPSIZE_T (pooled_session_count_pre, ==, pooled_session_count_post); - mongoc_client_command_simple ( - client, - "admin", - tmp_bson ("{'configureFailPoint': 'failCommand', 'mode': 'off'}"), - NULL /* read prefs */, - NULL /* reply */, - &error); + mongoc_client_command_simple (client, + "admin", + tmp_bson ("{'configureFailPoint': 'failCommand', 'mode': 'off'}"), + NULL /* read prefs */, + NULL /* reply */, + &error); bson_destroy (&opts); bson_destroy (failpoint_cmd); @@ -2806,11 +2572,10 @@ test_sessions_snapshot_prose_test_1 (void *ctx) * results in an error. */ r = mongoc_client_start_session (client, session_opts, &error); ASSERT (!r); - ASSERT_ERROR_CONTAINS ( - error, - MONGOC_ERROR_CLIENT, - MONGOC_ERROR_CLIENT_SESSION_FAILURE, - "Only one of causal consistency and snapshot can be enabled."); + ASSERT_ERROR_CONTAINS (error, + MONGOC_ERROR_CLIENT, + MONGOC_ERROR_CLIENT_SESSION_FAILURE, + "Only one of causal consistency and snapshot can be enabled."); mongoc_session_opts_destroy (session_opts); mongoc_client_destroy (client); @@ -2820,9 +2585,8 @@ void test_session_install (TestSuite *suite) { TestSuite_Add (suite, "/Session/opts/clone", test_session_opts_clone); - TestSuite_Add (suite, - "/Session/opts/causal_consistency_and_snapshot", - test_session_opts_causal_consistency_and_snapshot); + TestSuite_Add ( + suite, "/Session/opts/causal_consistency_and_snapshot", test_session_opts_causal_consistency_and_snapshot); TestSuite_AddFull (suite, "/Session/no_crypto", test_session_no_crypto, @@ -2898,14 +2662,10 @@ test_session_install (TestSuite *suite) NULL, TestSuite_CheckLive, test_framework_skip_if_no_crypto); - TestSuite_AddMockServerTest (suite, - "/Session/end/mock/single", - test_mock_end_sessions_single, - test_framework_skip_if_no_crypto); - TestSuite_AddMockServerTest (suite, - "/Session/end/mock/pooled", - test_mock_end_sessions_pooled, - test_framework_skip_if_no_crypto); + TestSuite_AddMockServerTest ( + suite, "/Session/end/mock/single", test_mock_end_sessions_single, test_framework_skip_if_no_crypto); + TestSuite_AddMockServerTest ( + suite, "/Session/end/mock/pooled", test_mock_end_sessions_pooled, test_framework_skip_if_no_crypto); TestSuite_AddMockServerTest (suite, "/Session/end/mock/disconnected", test_mock_end_sessions_server_disconnect, @@ -2960,8 +2720,7 @@ test_session_install (TestSuite *suite) add_session_test (suite, "/Session/cmd", test_cmd, false); add_session_test (suite, "/Session/read_cmd", test_read_cmd, true); add_session_test (suite, "/Session/write_cmd", test_write_cmd, false); - add_session_test ( - suite, "/Session/read_write_cmd", test_read_write_cmd, true); + add_session_test (suite, "/Session/read_write_cmd", test_read_write_cmd, true); add_session_test (suite, "/Session/db_cmd", test_db_cmd, false); TestSuite_AddFullWithTestFn (suite, "/Session/count", @@ -2985,23 +2744,14 @@ test_session_install (TestSuite *suite) add_session_test (suite, "/Session/fam", test_fam, true); add_session_test (suite, "/Session/db_drop", test_db_drop, false); add_session_test (suite, "/Session/gridfs_find", test_gridfs_find, true); - add_session_test ( - suite, "/Session/gridfs_find_one", test_gridfs_find_one, true); - add_session_test_wc (suite, - "/Session/watch", - test_watch, - true, - test_framework_skip_if_not_replset); + add_session_test (suite, "/Session/gridfs_find_one", test_gridfs_find_one, true); + add_session_test_wc (suite, "/Session/watch", test_watch, true, test_framework_skip_if_not_replset); add_session_test (suite, "/Session/aggregate", test_aggregate, true); add_session_test (suite, "/Session/create", test_create, false); - add_session_test ( - suite, "/Session/database_names", test_database_names, true); - add_session_test ( - suite, "/Session/find_databases", test_find_databases, true); - add_session_test ( - suite, "/Session/find_collections", test_find_collections, true); - add_session_test ( - suite, "/Session/collection_names", test_collection_names, true); + add_session_test (suite, "/Session/database_names", test_database_names, true); + add_session_test (suite, "/Session/find_databases", test_find_databases, true); + add_session_test (suite, "/Session/find_collections", test_find_collections, true); + add_session_test (suite, "/Session/collection_names", test_collection_names, true); add_session_test (suite, "/Session/bulk", test_bulk, false); add_session_test (suite, "/Session/find_indexes", test_find_indexes, true); TestSuite_AddFullWithTestFn (suite, @@ -3047,148 +2797,58 @@ test_session_install (TestSuite *suite) test_framework_skip_if_no_cluster_time, test_framework_skip_if_no_crypto); add_unacknowledged_test ( - suite, - "/Session/unacknowledged/insert_one/explicit_cs/inherit_wc", - test_insert_one, - true, - true); + suite, "/Session/unacknowledged/insert_one/explicit_cs/inherit_wc", test_insert_one, true, true); add_unacknowledged_test ( - suite, - "/Session/unacknowledged/insert_one/explicit_cs/explicit_wc", - test_insert_one, - true, - false); + suite, "/Session/unacknowledged/insert_one/explicit_cs/explicit_wc", test_insert_one, true, false); add_unacknowledged_test ( - suite, - "/Session/unacknowledged/insert_one/implicit_cs/inherit_wc", - test_insert_one, - false, - true); + suite, "/Session/unacknowledged/insert_one/implicit_cs/inherit_wc", test_insert_one, false, true); add_unacknowledged_test ( - suite, - "/Session/unacknowledged/insert_one/implicit_cs/explicit_wc", - test_insert_one, - false, - false); - add_unacknowledged_test ( - suite, - "/Session/unacknowledged/bulk/explicit_cs/inherit_wc", - test_bulk, - true, - true); - add_unacknowledged_test ( - suite, - "/Session/unacknowledged/bulk/explicit_cs/explicit_wc", - test_bulk, - true, - false); - add_unacknowledged_test ( - suite, - "/Session/unacknowledged/bulk/implicit_cs/inherit_wc", - test_bulk, - false, - true); - add_unacknowledged_test ( - suite, - "/Session/unacknowledged/bulk/implicit_cs/explicit_wc", - test_bulk, - false, - false); + suite, "/Session/unacknowledged/insert_one/implicit_cs/explicit_wc", test_insert_one, false, false); + add_unacknowledged_test (suite, "/Session/unacknowledged/bulk/explicit_cs/inherit_wc", test_bulk, true, true); + add_unacknowledged_test (suite, "/Session/unacknowledged/bulk/explicit_cs/explicit_wc", test_bulk, true, false); + add_unacknowledged_test (suite, "/Session/unacknowledged/bulk/implicit_cs/inherit_wc", test_bulk, false, true); + add_unacknowledged_test (suite, "/Session/unacknowledged/bulk/implicit_cs/explicit_wc", test_bulk, false, false); /* find_and_modify_with_opts only inherits acknowledged write concerns, so * skip tests that inherit a write concern. Technically, an explicit * unacknowledged write concern doesn't make much sense with findAndModify, * but this is testing the common code path for command execution. */ add_unacknowledged_test ( - suite, - "/Session/unacknowledged/find_and_modify/explicit_cs/explicit_wc", - test_fam, - true, - false); + suite, "/Session/unacknowledged/find_and_modify/explicit_cs/explicit_wc", test_fam, true, false); add_unacknowledged_test ( - suite, - "/Session/unacknowledged/find_and_modify/implicit_cs/explicit_wc", - test_fam, - false, - false); + suite, "/Session/unacknowledged/find_and_modify/implicit_cs/explicit_wc", test_fam, false, false); /* command_with_opts also does not inherit write concerns, but we still want * to test the common code path for command execution. */ + add_unacknowledged_test (suite, "/Session/unacknowledged/db_cmd/explicit_cs/explicit_wc", test_db_cmd, true, false); + add_unacknowledged_test (suite, "/Session/unacknowledged/db_cmd/implicit_cs/explicit_wc", test_db_cmd, false, false); add_unacknowledged_test ( - suite, - "/Session/unacknowledged/db_cmd/explicit_cs/explicit_wc", - test_db_cmd, - true, - false); - add_unacknowledged_test ( - suite, - "/Session/unacknowledged/db_cmd/implicit_cs/explicit_wc", - test_db_cmd, - false, - false); + suite, "/Session/unacknowledged/read_write_cmd/explicit_cs/inherit_wc", test_read_write_cmd, true, true); add_unacknowledged_test ( - suite, - "/Session/unacknowledged/read_write_cmd/explicit_cs/inherit_wc", - test_read_write_cmd, - true, - true); + suite, "/Session/unacknowledged/read_write_cmd/explicit_cs/explicit_wc", test_read_write_cmd, true, false); add_unacknowledged_test ( - suite, - "/Session/unacknowledged/read_write_cmd/explicit_cs/explicit_wc", - test_read_write_cmd, - true, - false); + suite, "/Session/unacknowledged/read_write_cmd/implicit_cs/inherit_wc", test_read_write_cmd, false, true); add_unacknowledged_test ( - suite, - "/Session/unacknowledged/read_write_cmd/implicit_cs/inherit_wc", - test_read_write_cmd, - false, - true); + suite, "/Session/unacknowledged/read_write_cmd/implicit_cs/explicit_wc", test_read_write_cmd, false, false); add_unacknowledged_test ( - suite, - "/Session/unacknowledged/read_write_cmd/implicit_cs/explicit_wc", - test_read_write_cmd, - false, - false); + suite, "/Session/unacknowledged/write_cmd/explicit_cs/inherit_wc", test_write_cmd, true, true); add_unacknowledged_test ( - suite, - "/Session/unacknowledged/write_cmd/explicit_cs/inherit_wc", - test_write_cmd, - true, - true); + suite, "/Session/unacknowledged/write_cmd/explicit_cs/explicit_wc", test_write_cmd, true, false); add_unacknowledged_test ( - suite, - "/Session/unacknowledged/write_cmd/explicit_cs/explicit_wc", - test_write_cmd, - true, - false); + suite, "/Session/unacknowledged/write_cmd/implicit_cs/inherit_wc", test_write_cmd, false, true); add_unacknowledged_test ( - suite, - "/Session/unacknowledged/write_cmd/implicit_cs/inherit_wc", - test_write_cmd, - false, - true); - add_unacknowledged_test ( - suite, - "/Session/unacknowledged/write_cmd/implicit_cs/explicit_wc", - test_write_cmd, - false, - false); - - install_json_test_suite_with_check (suite, - JSON_DIR, - "sessions/legacy", - test_sessions_spec_cb, - test_framework_skip_if_no_sessions); - - TestSuite_AddFull ( - suite, - "/Session/dirty", - test_session_dirty, - NULL /* dtor */, - NULL /* ctx */, - test_framework_skip_if_no_sessions, - test_framework_skip_if_no_failpoint, - /* Tests with retryable writes, requires non-standalone. */ - test_framework_skip_if_single); + suite, "/Session/unacknowledged/write_cmd/implicit_cs/explicit_wc", test_write_cmd, false, false); + + install_json_test_suite_with_check ( + suite, JSON_DIR, "sessions/legacy", test_sessions_spec_cb, test_framework_skip_if_no_sessions); + + TestSuite_AddFull (suite, + "/Session/dirty", + test_session_dirty, + NULL /* dtor */, + NULL /* ctx */, + test_framework_skip_if_no_sessions, + test_framework_skip_if_no_failpoint, + /* Tests with retryable writes, requires non-standalone. */ + test_framework_skip_if_single); TestSuite_AddFull (suite, "/Session/snapshot/prose_test_1", diff --git a/src/libmongoc/tests/test-mongoc-client-side-encryption.c b/src/libmongoc/tests/test-mongoc-client-side-encryption.c index 66af4ddccf..b1a6a3d6f3 100644 --- a/src/libmongoc/tests/test-mongoc-client-side-encryption.c +++ b/src/libmongoc/tests/test-mongoc-client-side-encryption.c @@ -53,8 +53,7 @@ _before_test (json_test_ctx_t *ctx, const bson_t *test) mongoc_write_concern_append (wc, &insert_opts); if (bson_iter_init_find (&iter, ctx->config->scenario, "key_vault_data")) { - keyvault_coll = - mongoc_client_get_collection (client, "keyvault", "datakeys"); + keyvault_coll = mongoc_client_get_collection (client, "keyvault", "datakeys"); /* Drop and recreate, inserting data. */ ret = mongoc_collection_drop (keyvault_coll, &error); @@ -68,8 +67,7 @@ _before_test (json_test_ctx_t *ctx, const bson_t *test) bson_t doc; bson_iter_bson (&iter, &doc); - ret = mongoc_collection_insert_one ( - keyvault_coll, &doc, &insert_opts, NULL /* reply */, &error); + ret = mongoc_collection_insert_one (keyvault_coll, &doc, &insert_opts, NULL /* reply */, &error); ASSERT_OR_PRINT (ret, error); } mongoc_collection_destroy (keyvault_coll); @@ -81,15 +79,12 @@ _before_test (json_test_ctx_t *ctx, const bson_t *test) } static bool -_run_operation (json_test_ctx_t *ctx, - const bson_t *test, - const bson_t *operation) +_run_operation (json_test_ctx_t *ctx, const bson_t *test, const bson_t *operation) { bson_t reply; bool res; - res = - json_test_operation (ctx, test, operation, ctx->collection, NULL, &reply); + res = json_test_operation (ctx, test, operation, ctx->collection, NULL, &reply); bson_destroy (&reply); @@ -131,8 +126,7 @@ _set_extra_bypass (bson_t *extra) static void _set_extra_crypt_shared (bson_t *extra) { - char *const path = - test_framework_getenv ("MONGOC_TEST_CRYPT_SHARED_LIB_PATH"); + char *const path = test_framework_getenv ("MONGOC_TEST_CRYPT_SHARED_LIB_PATH"); if (path) { BSON_APPEND_UTF8 (extra, "cryptSharedLibPath", path); bson_free (path); @@ -155,20 +149,17 @@ _make_aws_kms_provider (bson_t *kms_providers) char *aws_secret_access_key; char *aws_access_key_id; - aws_secret_access_key = - test_framework_getenv_required ("MONGOC_TEST_AWS_SECRET_ACCESS_KEY"); - aws_access_key_id = - test_framework_getenv_required ("MONGOC_TEST_AWS_ACCESS_KEY_ID"); + aws_secret_access_key = test_framework_getenv_required ("MONGOC_TEST_AWS_SECRET_ACCESS_KEY"); + aws_access_key_id = test_framework_getenv_required ("MONGOC_TEST_AWS_ACCESS_KEY_ID"); if (!kms_providers) { kms_providers = bson_new (); } - bson_concat ( - kms_providers, - tmp_bson ("{ 'aws': { 'secretAccessKey': '%s', 'accessKeyId': '%s' }}", - aws_secret_access_key, - aws_access_key_id)); + bson_concat (kms_providers, + tmp_bson ("{ 'aws': { 'secretAccessKey': '%s', 'accessKeyId': '%s' }}", + aws_secret_access_key, + aws_access_key_id)); bson_free (aws_secret_access_key); bson_free (aws_access_key_id); @@ -183,12 +174,9 @@ _make_azure_kms_provider (bson_t *kms_providers) char *azure_client_id; char *azure_client_secret; - azure_tenant_id = - test_framework_getenv_required ("MONGOC_TEST_AZURE_TENANT_ID"); - azure_client_id = - test_framework_getenv_required ("MONGOC_TEST_AZURE_CLIENT_ID"); - azure_client_secret = - test_framework_getenv_required ("MONGOC_TEST_AZURE_CLIENT_SECRET"); + azure_tenant_id = test_framework_getenv_required ("MONGOC_TEST_AZURE_TENANT_ID"); + azure_client_id = test_framework_getenv_required ("MONGOC_TEST_AZURE_CLIENT_ID"); + azure_client_secret = test_framework_getenv_required ("MONGOC_TEST_AZURE_CLIENT_SECRET"); if (!kms_providers) { kms_providers = bson_new (); @@ -216,8 +204,7 @@ _make_gcp_kms_provider (bson_t *kms_providers) gcp_email = test_framework_getenv_required ("MONGOC_TEST_GCP_EMAIL"); - gcp_privatekey = - test_framework_getenv_required ("MONGOC_TEST_GCP_PRIVATEKEY"); + gcp_privatekey = test_framework_getenv_required ("MONGOC_TEST_GCP_PRIVATEKEY"); if (!gcp_email || !gcp_privatekey) { test_error ("Set MONGOC_TEST_GCP_EMAIL and MONGOC_TEST_GCP_PRIVATEKEY to " @@ -228,10 +215,7 @@ _make_gcp_kms_provider (bson_t *kms_providers) kms_providers = bson_new (); } - bson_concat (kms_providers, - tmp_bson ("{ 'gcp': { 'email': '%s', 'privateKey': '%s' }}", - gcp_email, - gcp_privatekey)); + bson_concat (kms_providers, tmp_bson ("{ 'gcp': { 'email': '%s', 'privateKey': '%s' }}", gcp_email, gcp_privatekey)); bson_free (gcp_email); bson_free (gcp_privatekey); @@ -242,8 +226,7 @@ _make_gcp_kms_provider (bson_t *kms_providers) static bson_t * _make_local_kms_provider (bson_t *kms_providers) { - bson_t *local = BCON_NEW ( - "local", "{", "key", BCON_BIN (0, (uint8_t *) LOCAL_MASTERKEY, 96), "}"); + bson_t *local = BCON_NEW ("local", "{", "key", BCON_BIN (0, (uint8_t *) LOCAL_MASTERKEY, 96), "}"); if (!kms_providers) { kms_providers = bson_new (); @@ -262,8 +245,7 @@ _make_kmip_kms_provider (bson_t *kms_providers) kms_providers = bson_new (); } - bson_concat (kms_providers, - tmp_bson ("{ 'kmip': { 'endpoint': 'localhost:5698' } }")); + bson_concat (kms_providers, tmp_bson ("{ 'kmip': { 'endpoint': 'localhost:5698' } }")); return kms_providers; @@ -296,17 +278,13 @@ _make_tls_opts (void) char *kmip_tls_ca_file; char *kmip_tls_certificate_key_file; - kmip_tls_ca_file = - test_framework_getenv_required ("MONGOC_TEST_CSFLE_TLS_CA_FILE"); - kmip_tls_certificate_key_file = test_framework_getenv_required ( - "MONGOC_TEST_CSFLE_TLS_CERTIFICATE_KEY_FILE"); + kmip_tls_ca_file = test_framework_getenv_required ("MONGOC_TEST_CSFLE_TLS_CA_FILE"); + kmip_tls_certificate_key_file = test_framework_getenv_required ("MONGOC_TEST_CSFLE_TLS_CERTIFICATE_KEY_FILE"); - bson_concat ( - tls_opts, - tmp_bson ( - "{ 'kmip': { 'tlsCAFile': '%s', 'tlsCertificateKeyFile': '%s' } }", - kmip_tls_ca_file, - kmip_tls_certificate_key_file)); + bson_concat (tls_opts, + tmp_bson ("{ 'kmip': { 'tlsCAFile': '%s', 'tlsCertificateKeyFile': '%s' } }", + kmip_tls_ca_file, + kmip_tls_certificate_key_file)); bson_free (kmip_tls_ca_file); bson_free (kmip_tls_certificate_key_file); @@ -325,10 +303,7 @@ _make_kms_masterkey (char const *provider) } if (strcmp (provider, "azure") == 0) { - return BCON_NEW ("keyVaultEndpoint", - "key-vault-csfle.vault.azure.net", - "keyName", - "key-name-csfle"); + return BCON_NEW ("keyVaultEndpoint", "key-vault-csfle.vault.azure.net", "keyName", "key-name-csfle"); } if (strcmp (provider, "gcp") == 0) { @@ -363,8 +338,7 @@ _command_started (const mongoc_apm_command_started_t *event) limits_apm_ctx_t *ctx; ctx = (limits_apm_ctx_t *) mongoc_apm_command_started_get_context (event); - if (0 == - strcmp ("insert", mongoc_apm_command_started_get_command_name (event))) { + if (0 == strcmp ("insert", mongoc_apm_command_started_get_command_name (event))) { ctx->num_inserts++; } } @@ -405,19 +379,10 @@ test_bson_size_limits_and_batch_splitting (void *unused) mongoc_client_set_error_api (client, MONGOC_ERROR_API_VERSION_2); coll = mongoc_client_get_collection (client, "db", "coll"); (void) mongoc_collection_drop (coll, NULL); - corpus_schema = get_bson_from_json_file ( - "./src/libmongoc/tests/client_side_encryption_prose/limits-schema.json"); - cmd = BCON_NEW ("create", - "coll", - "validator", - "{", - "$jsonSchema", - BCON_DOCUMENT (corpus_schema), - "}"); - ASSERT_OR_PRINT ( - mongoc_client_command_simple ( - client, "db", cmd, NULL /* read prefs */, NULL /* reply */, &error), - error); + corpus_schema = get_bson_from_json_file ("./src/libmongoc/tests/client_side_encryption_prose/limits-schema.json"); + cmd = BCON_NEW ("create", "coll", "validator", "{", "$jsonSchema", BCON_DOCUMENT (corpus_schema), "}"); + ASSERT_OR_PRINT (mongoc_client_command_simple (client, "db", cmd, NULL /* read prefs */, NULL /* reply */, &error), + error); mongoc_collection_destroy (coll); /* Drop and create the key vault collection, keyvault.datakeys. */ @@ -426,15 +391,11 @@ test_bson_size_limits_and_batch_splitting (void *unused) coll = mongoc_client_get_collection (client, "keyvault", "datakeys"); (void) mongoc_collection_drop (coll, NULL); - datakey = get_bson_from_json_file ( - "./src/libmongoc/tests/client_side_encryption_prose/limits-key.json"); + datakey = get_bson_from_json_file ("./src/libmongoc/tests/client_side_encryption_prose/limits-key.json"); wc = mongoc_write_concern_new (); mongoc_write_concern_set_wmajority (wc, 1000); mongoc_collection_set_write_concern (coll, wc); - ASSERT_OR_PRINT ( - mongoc_collection_insert_one ( - coll, datakey, NULL /* opts */, NULL /* reply */, &error), - error); + ASSERT_OR_PRINT (mongoc_collection_insert_one (coll, datakey, NULL /* opts */, NULL /* reply */, &error), error); mongoc_write_concern_destroy (wc); mongoc_collection_destroy (coll); } @@ -448,12 +409,10 @@ test_bson_size_limits_and_batch_splitting (void *unused) kms_providers = _make_kms_providers (false /* aws */, true /* local */); opts = mongoc_auto_encryption_opts_new (); _check_bypass (opts); - mongoc_auto_encryption_opts_set_keyvault_namespace ( - opts, "keyvault", "datakeys"); + mongoc_auto_encryption_opts_set_keyvault_namespace (opts, "keyvault", "datakeys"); mongoc_auto_encryption_opts_set_kms_providers (opts, kms_providers); - ASSERT_OR_PRINT (mongoc_client_enable_auto_encryption (client, opts, &error), - error); + ASSERT_OR_PRINT (mongoc_client_enable_auto_encryption (client, opts, &error), error); callbacks = mongoc_apm_callbacks_new (); mongoc_apm_set_command_started_cb (callbacks, _command_started); @@ -468,24 +427,16 @@ test_bson_size_limits_and_batch_splitting (void *unused) as = bson_malloc (size_16mib); memset (as, 'a', size_16mib); bson_append_utf8 (docs[0], "unencrypted", -1, as, 2097152); - ASSERT_OR_PRINT ( - mongoc_collection_insert_one ( - coll, docs[0], NULL /* opts */, NULL /* reply */, &error), - error); + ASSERT_OR_PRINT (mongoc_collection_insert_one (coll, docs[0], NULL /* opts */, NULL /* reply */, &error), error); bson_destroy (docs[0]); /* Insert the document `limits/limits-doc.json <../limits/limits-doc.json>`_ * concatenated with ``{ "_id": "encryption_exceeds_2mib", "unencrypted": < * the string "a" repeated (2097152 - 2000) times > }`` */ - docs[0] = get_bson_from_json_file ( - "./src/libmongoc/tests/client_side_encryption_prose/limits-doc.json"); + docs[0] = get_bson_from_json_file ("./src/libmongoc/tests/client_side_encryption_prose/limits-doc.json"); bson_append_utf8 (docs[0], "_id", -1, "encryption_exceeds_2mib", -1); - bson_append_utf8 ( - docs[0], "unencrypted", -1, as, exceeds_2mib_after_encryption); - ASSERT_OR_PRINT ( - mongoc_collection_insert_one ( - coll, docs[0], NULL /* opts */, NULL /* reply */, &error), - error); + bson_append_utf8 (docs[0], "unencrypted", -1, as, exceeds_2mib_after_encryption); + ASSERT_OR_PRINT (mongoc_collection_insert_one (coll, docs[0], NULL /* opts */, NULL /* reply */, &error), error); bson_destroy (docs[0]); /* Insert two documents that each exceed 2MiB but no encryption occurs. @@ -496,13 +447,9 @@ test_bson_size_limits_and_batch_splitting (void *unused) docs[1] = BCON_NEW ("_id", "over_2mib_2"); bson_append_utf8 (docs[1], "unencrypted", -1, as, size_2mib); ctx.num_inserts = 0; - ASSERT_OR_PRINT (mongoc_collection_insert_many (coll, - (const bson_t **) docs, - 2, - NULL /* opts */, - NULL /* reply */, - &error), - error); + ASSERT_OR_PRINT ( + mongoc_collection_insert_many (coll, (const bson_t **) docs, 2, NULL /* opts */, NULL /* reply */, &error), + error); ASSERT_CMPINT (ctx.num_inserts, ==, 2); bson_destroy (docs[0]); bson_destroy (docs[1]); @@ -511,24 +458,16 @@ test_bson_size_limits_and_batch_splitting (void *unused) * the bulk write to succeed and run as two separate inserts. */ - docs[0] = get_bson_from_json_file ( - "./src/libmongoc/tests/client_side_encryption_prose/limits-doc.json"); + docs[0] = get_bson_from_json_file ("./src/libmongoc/tests/client_side_encryption_prose/limits-doc.json"); bson_append_utf8 (docs[0], "_id", -1, "encryption_exceeds_2mib_1", -1); - bson_append_utf8 ( - docs[0], "unencrypted", -1, as, exceeds_2mib_after_encryption); - docs[1] = get_bson_from_json_file ( - "./src/libmongoc/tests/client_side_encryption_prose/limits-doc.json"); + bson_append_utf8 (docs[0], "unencrypted", -1, as, exceeds_2mib_after_encryption); + docs[1] = get_bson_from_json_file ("./src/libmongoc/tests/client_side_encryption_prose/limits-doc.json"); bson_append_utf8 (docs[1], "_id", -1, "encryption_exceeds_2mib_2", -1); - bson_append_utf8 ( - docs[1], "unencrypted", -1, as, exceeds_2mib_after_encryption); + bson_append_utf8 (docs[1], "unencrypted", -1, as, exceeds_2mib_after_encryption); ctx.num_inserts = 0; - ASSERT_OR_PRINT (mongoc_collection_insert_many (coll, - (const bson_t **) docs, - 2, - NULL /* opts */, - NULL /* reply */, - &error), - error); + ASSERT_OR_PRINT ( + mongoc_collection_insert_many (coll, (const bson_t **) docs, 2, NULL /* opts */, NULL /* reply */, &error), + error); ASSERT_CMPINT (ctx.num_inserts, ==, 2); bson_destroy (docs[0]); bson_destroy (docs[1]); @@ -536,22 +475,15 @@ test_bson_size_limits_and_batch_splitting (void *unused) /* Check that inserting close to, but not exceeding, 16MiB, passes */ docs[0] = bson_new (); bson_append_utf8 (docs[0], "_id", -1, "under_16mib", -1); - bson_append_utf8 ( - docs[0], "unencrypted", -1, as, exceeds_16mib_after_encryption); - ASSERT_OR_PRINT ( - mongoc_collection_insert_one ( - coll, docs[0], NULL /* opts */, NULL /* reply */, &error), - error); + bson_append_utf8 (docs[0], "unencrypted", -1, as, exceeds_16mib_after_encryption); + ASSERT_OR_PRINT (mongoc_collection_insert_one (coll, docs[0], NULL /* opts */, NULL /* reply */, &error), error); bson_destroy (docs[0]); /* but.. exceeding 16 MiB fails */ - docs[0] = get_bson_from_json_file ( - "./src/libmongoc/tests/client_side_encryption_prose/limits-doc.json"); + docs[0] = get_bson_from_json_file ("./src/libmongoc/tests/client_side_encryption_prose/limits-doc.json"); bson_append_utf8 (docs[0], "_id", -1, "under_16mib", -1); - bson_append_utf8 ( - docs[0], "unencrypted", -1, as, exceeds_16mib_after_encryption); - BSON_ASSERT (!mongoc_collection_insert_one ( - coll, docs[0], NULL /* opts */, NULL /* reply */, &error)); + bson_append_utf8 (docs[0], "unencrypted", -1, as, exceeds_16mib_after_encryption); + BSON_ASSERT (!mongoc_collection_insert_one (coll, docs[0], NULL /* opts */, NULL /* reply */, &error)); ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_SERVER, 2, "too large"); bson_destroy (docs[0]); @@ -572,24 +504,21 @@ typedef struct { } _datakey_and_double_encryption_ctx_t; static void -_datakey_and_double_encryption_command_started ( - const mongoc_apm_command_started_t *event) +_datakey_and_double_encryption_command_started (const mongoc_apm_command_started_t *event) { _datakey_and_double_encryption_ctx_t *ctx; - ctx = (_datakey_and_double_encryption_ctx_t *) - mongoc_apm_command_started_get_context (event); + ctx = (_datakey_and_double_encryption_ctx_t *) mongoc_apm_command_started_get_context (event); bson_destroy (ctx->last_cmd); ctx->last_cmd = bson_copy (mongoc_apm_command_started_get_command (event)); } static void -test_datakey_and_double_encryption_creating_and_using ( - mongoc_client_encryption_t *client_encryption, - mongoc_client_t *client, - mongoc_client_t *client_encrypted, - const char *kms_provider, - _datakey_and_double_encryption_ctx_t *test_ctx) +test_datakey_and_double_encryption_creating_and_using (mongoc_client_encryption_t *client_encryption, + mongoc_client_t *client, + mongoc_client_t *client_encrypted, + const char *kms_provider, + _datakey_and_double_encryption_ctx_t *test_ctx) { bson_value_t keyid; bson_error_t error; @@ -610,32 +539,28 @@ test_datakey_and_double_encryption_creating_and_using ( opts = mongoc_client_encryption_datakey_opts_new (); if (0 == strcmp (kms_provider, "aws")) { - mongoc_client_encryption_datakey_opts_set_masterkey ( - opts, - tmp_bson ("{ 'region': 'us-east-1', 'key': " - "'arn:aws:kms:us-east-1:579766882180:key/" - "89fcc2c4-08b0-4bd9-9f25-e30687b580d0' }")); + mongoc_client_encryption_datakey_opts_set_masterkey (opts, + tmp_bson ("{ 'region': 'us-east-1', 'key': " + "'arn:aws:kms:us-east-1:579766882180:key/" + "89fcc2c4-08b0-4bd9-9f25-e30687b580d0' }")); } else if (0 == strcmp (kms_provider, "azure")) { mongoc_client_encryption_datakey_opts_set_masterkey ( opts, tmp_bson ("{'keyVaultEndpoint': 'key-vault-csfle.vault.azure.net', " "'keyName': 'key-name-csfle'}")); } else if (0 == strcmp (kms_provider, "gcp")) { - mongoc_client_encryption_datakey_opts_set_masterkey ( - opts, - tmp_bson ("{'projectId': 'devprod-drivers','location': " - "'global','keyRing': 'key-ring-csfle','keyName': " - "'key-name-csfle'}")); - } else if (0 == strcmp (kms_provider, "kmip")) { mongoc_client_encryption_datakey_opts_set_masterkey (opts, - tmp_bson ("{}")); + tmp_bson ("{'projectId': 'devprod-drivers','location': " + "'global','keyRing': 'key-ring-csfle','keyName': " + "'key-name-csfle'}")); + } else if (0 == strcmp (kms_provider, "kmip")) { + mongoc_client_encryption_datakey_opts_set_masterkey (opts, tmp_bson ("{}")); } altname = bson_strdup_printf ("%s_altname", kms_provider); mongoc_client_encryption_datakey_opts_set_keyaltnames (opts, &altname, 1); - ret = mongoc_client_encryption_create_datakey ( - client_encryption, kms_provider, opts, &keyid, &error); + ret = mongoc_client_encryption_create_datakey (client_encryption, kms_provider, opts, &keyid, &error); ASSERT_OR_PRINT (ret, error); /* Expect a BSON binary with subtype 4 to be returned */ @@ -645,31 +570,27 @@ test_datakey_and_double_encryption_creating_and_using ( /* Check that client captured a command_started event for the insert command * containing a majority writeConcern. */ assert_match_bson ( - test_ctx->last_cmd, - tmp_bson ("{'insert': 'datakeys', 'writeConcern': { 'w': 'majority' } }"), - false); + test_ctx->last_cmd, tmp_bson ("{'insert': 'datakeys', 'writeConcern': { 'w': 'majority' } }"), false); /* Use client to run a find on keyvault.datakeys */ coll = mongoc_client_get_collection (client, "keyvault", "datakeys"); bson_init (&filter); BSON_APPEND_VALUE (&filter, "_id", &keyid); - cursor = mongoc_collection_find_with_opts ( - coll, &filter, NULL /* opts */, NULL /* read prefs */); + cursor = mongoc_collection_find_with_opts (coll, &filter, NULL /* opts */, NULL /* read prefs */); mongoc_collection_destroy (coll); /* Expect that exactly one document is returned with the "masterKey.provider" * equal to */ BSON_ASSERT (mongoc_cursor_next (cursor, &doc)); - BSON_ASSERT ( - 0 == strcmp (kms_provider, bson_lookup_utf8 (doc, "masterKey.provider"))); + BSON_ASSERT (0 == strcmp (kms_provider, bson_lookup_utf8 (doc, "masterKey.provider"))); BSON_ASSERT (!mongoc_cursor_next (cursor, &doc)); ASSERT_OR_PRINT (!mongoc_cursor_error (cursor, &error), error); mongoc_cursor_destroy (cursor); /* Call client_encryption.encrypt() with the value "hello " */ encrypt_opts = mongoc_client_encryption_encrypt_opts_new (); - mongoc_client_encryption_encrypt_opts_set_algorithm ( - encrypt_opts, MONGOC_AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC); + mongoc_client_encryption_encrypt_opts_set_algorithm (encrypt_opts, + MONGOC_AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC); mongoc_client_encryption_encrypt_opts_set_keyid (encrypt_opts, &keyid); hello = bson_strdup_printf ("hello %s", kms_provider); @@ -683,8 +604,7 @@ test_datakey_and_double_encryption_creating_and_using ( to_encrypt.value.v_utf8.len = (uint32_t) len; } - ret = mongoc_client_encryption_encrypt ( - client_encryption, &to_encrypt, encrypt_opts, &encrypted, &error); + ret = mongoc_client_encryption_encrypt (client_encryption, &to_encrypt, encrypt_opts, &encrypted, &error); ASSERT_OR_PRINT (ret, error); mongoc_client_encryption_encrypt_opts_destroy (encrypt_opts); @@ -697,17 +617,13 @@ test_datakey_and_double_encryption_creating_and_using ( coll = mongoc_client_get_collection (client_encrypted, "db", "coll"); BSON_APPEND_UTF8 (&to_insert, "_id", kms_provider); BSON_APPEND_VALUE (&to_insert, "value", &encrypted); - ret = mongoc_collection_insert_one ( - coll, &to_insert, NULL /* opts */, NULL /* reply */, &error); + ret = mongoc_collection_insert_one (coll, &to_insert, NULL /* opts */, NULL /* reply */, &error); ASSERT_OR_PRINT (ret, error); /* Use client_encrypted to run a find querying with _id of and * expect value to be "hello ". */ cursor = mongoc_collection_find_with_opts ( - coll, - tmp_bson ("{ '_id': '%s' }", kms_provider), - NULL /* opts */, - NULL /* read prefs */); + coll, tmp_bson ("{ '_id': '%s' }", kms_provider), NULL /* opts */, NULL /* read prefs */); BSON_ASSERT (mongoc_cursor_next (cursor, &doc)); BSON_ASSERT (0 == strcmp (hello, bson_lookup_utf8 (doc, "value"))); BSON_ASSERT (!mongoc_cursor_next (cursor, &doc)); @@ -719,25 +635,20 @@ test_datakey_and_double_encryption_creating_and_using ( * the algorithm AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic, and the * key_alt_name of _altname. */ encrypt_opts = mongoc_client_encryption_encrypt_opts_new (); - mongoc_client_encryption_encrypt_opts_set_algorithm ( - encrypt_opts, MONGOC_AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC); + mongoc_client_encryption_encrypt_opts_set_algorithm (encrypt_opts, + MONGOC_AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC); mongoc_client_encryption_encrypt_opts_set_keyaltname (encrypt_opts, altname); - ret = mongoc_client_encryption_encrypt (client_encryption, - &to_encrypt, - encrypt_opts, - &encrypted_via_altname, - &error); + ret = + mongoc_client_encryption_encrypt (client_encryption, &to_encrypt, encrypt_opts, &encrypted_via_altname, &error); ASSERT_OR_PRINT (ret, error); mongoc_client_encryption_encrypt_opts_destroy (encrypt_opts); /* Expect the return value to be a BSON binary subtype 6. Expect the value to * exactly match the value of encrypted. */ BSON_ASSERT (encrypted_via_altname.value_type == BSON_TYPE_BINARY); - BSON_ASSERT (encrypted_via_altname.value.v_binary.subtype == - BSON_SUBTYPE_ENCRYPTED); - BSON_ASSERT (encrypted_via_altname.value.v_binary.data_len == - encrypted.value.v_binary.data_len); + BSON_ASSERT (encrypted_via_altname.value.v_binary.subtype == BSON_SUBTYPE_ENCRYPTED); + BSON_ASSERT (encrypted_via_altname.value.v_binary.data_len == encrypted.value.v_binary.data_len); BSON_ASSERT (0 == memcmp (encrypted_via_altname.value.v_binary.data, encrypted.value.v_binary.data, encrypted.value.v_binary.data_len)); @@ -769,8 +680,7 @@ test_create_datakey_with_custom_key_material (void *unused) /* Using client, drop the collection keyvault.datakeys. */ { - mongoc_collection_t *const datakeys = - mongoc_client_get_collection (client, "keyvault", "datakeys"); + mongoc_collection_t *const datakeys = mongoc_client_get_collection (client, "keyvault", "datakeys"); (void) mongoc_collection_drop (datakeys, NULL); mongoc_collection_destroy (datakeys); } @@ -778,22 +688,15 @@ test_create_datakey_with_custom_key_material (void *unused) /* Create a ClientEncryption object (referred to as client_encryption) with * client set as the keyVaultClient. */ { - mongoc_client_encryption_opts_t *const client_encryption_opts = - mongoc_client_encryption_opts_new (); - bson_t *const kms_providers = - _make_kms_providers (true /* aws */, true /* local */); + mongoc_client_encryption_opts_t *const client_encryption_opts = mongoc_client_encryption_opts_new (); + bson_t *const kms_providers = _make_kms_providers (true /* aws */, true /* local */); bson_t *const tls_opts = _make_tls_opts (); - mongoc_client_encryption_opts_set_kms_providers (client_encryption_opts, - kms_providers); - mongoc_client_encryption_opts_set_tls_opts (client_encryption_opts, - tls_opts); - mongoc_client_encryption_opts_set_keyvault_namespace ( - client_encryption_opts, "keyvault", "datakeys"); - mongoc_client_encryption_opts_set_keyvault_client (client_encryption_opts, - client); - client_encryption = - mongoc_client_encryption_new (client_encryption_opts, &error); + mongoc_client_encryption_opts_set_kms_providers (client_encryption_opts, kms_providers); + mongoc_client_encryption_opts_set_tls_opts (client_encryption_opts, tls_opts); + mongoc_client_encryption_opts_set_keyvault_namespace (client_encryption_opts, "keyvault", "datakeys"); + mongoc_client_encryption_opts_set_keyvault_client (client_encryption_opts, client); + client_encryption = mongoc_client_encryption_new (client_encryption_opts, &error); ASSERT_OR_PRINT (client_encryption, error); mongoc_client_encryption_opts_destroy (client_encryption_opts); @@ -804,25 +707,19 @@ test_create_datakey_with_custom_key_material (void *unused) /* Using client_encryption, create a data key with a local KMS provider and * the following custom key material: */ { - const char key_material[] = - "xPTAjBRG5JiPm+d3fj6XLi2q5DMXUS/" - "f1f+SMAlhhwkhDRL0kr8r9GDLIGTAGlvC+HVjSIgdL+" - "RKwZCvpXSyxTICWSXTUYsWYPyu3IoHbuBZdmw2faM3WhcRIgbMReU5"; + const char key_material[] = "xPTAjBRG5JiPm+d3fj6XLi2q5DMXUS/" + "f1f+SMAlhhwkhDRL0kr8r9GDLIGTAGlvC+HVjSIgdL+" + "RKwZCvpXSyxTICWSXTUYsWYPyu3IoHbuBZdmw2faM3WhcRIgbMReU5"; uint8_t data[96]; - mongoc_client_encryption_datakey_opts_t *datakey_opts = - mongoc_client_encryption_datakey_opts_new (); + mongoc_client_encryption_datakey_opts_t *datakey_opts = mongoc_client_encryption_datakey_opts_new (); bson_value_t keyid; - BSON_ASSERT ( - mcommon_b64_pton (key_material, data, sizeof (key_material)) == 96); + BSON_ASSERT (mcommon_b64_pton (key_material, data, sizeof (key_material)) == 96); - mongoc_client_encryption_datakey_opts_set_keymaterial ( - datakey_opts, data, sizeof (data)); + mongoc_client_encryption_datakey_opts_set_keymaterial (datakey_opts, data, sizeof (data)); ASSERT_OR_PRINT ( - mongoc_client_encryption_create_datakey ( - client_encryption, "local", datakey_opts, &keyid, &error), - error); + mongoc_client_encryption_create_datakey (client_encryption, "local", datakey_opts, &keyid, &error), error); ASSERT (keyid.value_type == BSON_TYPE_BINARY); ASSERT (keyid.value.v_binary.subtype == BSON_SUBTYPE_UUID); @@ -835,10 +732,9 @@ test_create_datakey_with_custom_key_material (void *unused) /* Find the resulting key document in keyvault.datakeys, save a copy of the * key document, then remove the key document from the collection. */ { - mongoc_collection_t *const datakeys = - mongoc_client_get_collection (client, "keyvault", "datakeys"); - mongoc_cursor_t *cursor = mongoc_collection_find_with_opts ( - datakeys, tmp_bson ("{}"), NULL /* opts */, NULL /* read prefs */); + mongoc_collection_t *const datakeys = mongoc_client_get_collection (client, "keyvault", "datakeys"); + mongoc_cursor_t *cursor = + mongoc_collection_find_with_opts (datakeys, tmp_bson ("{}"), NULL /* opts */, NULL /* read prefs */); const bson_t *bson; ASSERT (mongoc_cursor_next (cursor, &bson)); @@ -854,23 +750,19 @@ test_create_datakey_with_custom_key_material (void *unused) * modified key document into keyvault.datakeys with majority write concern. */ { - mongoc_collection_t *const datakeys = - mongoc_client_get_collection (client, "keyvault", "datakeys"); + mongoc_collection_t *const datakeys = mongoc_client_get_collection (client, "keyvault", "datakeys"); bson_t modified_datakey = BSON_INITIALIZER; uint8_t bytes[16] = {0}; mongoc_write_concern_t *const wc = mongoc_write_concern_new (); bson_t opts = BSON_INITIALIZER; bson_copy_to_excluding_noinit (&datakey, &modified_datakey, "_id", NULL); - BSON_ASSERT (BSON_APPEND_BINARY ( - &modified_datakey, "_id", BSON_SUBTYPE_UUID, bytes, sizeof (bytes))); + BSON_ASSERT (BSON_APPEND_BINARY (&modified_datakey, "_id", BSON_SUBTYPE_UUID, bytes, sizeof (bytes))); mongoc_write_concern_set_w (wc, MONGOC_WRITE_CONCERN_W_MAJORITY); mongoc_write_concern_append (wc, &opts); - ASSERT_OR_PRINT (mongoc_collection_insert_one ( - datakeys, &modified_datakey, &opts, NULL, &error), - error); + ASSERT_OR_PRINT (mongoc_collection_insert_one (datakeys, &modified_datakey, &opts, NULL, &error), error); mongoc_collection_destroy (datakeys); bson_destroy (&modified_datakey); @@ -882,11 +774,9 @@ test_create_datakey_with_custom_key_material (void *unused) * key using the AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic algorithm and * assert the resulting value is equal to the following (given as base64): */ { - const char expected[] = - "AQAAAAAAAAAAAAAAAAAAAAACz0ZOLuuhEYi807ZXTdhbqhLaS2/" - "t9wLifJnnNYwiw79d75QYIZ6M/aYC1h9nCzCjZ7pGUpAuNnkUhnIXM3PjrA=="; - mongoc_client_encryption_encrypt_opts_t *const encrypt_opts = - mongoc_client_encryption_encrypt_opts_new (); + const char expected[] = "AQAAAAAAAAAAAAAAAAAAAAACz0ZOLuuhEYi807ZXTdhbqhLaS2/" + "t9wLifJnnNYwiw79d75QYIZ6M/aYC1h9nCzCjZ7pGUpAuNnkUhnIXM3PjrA=="; + mongoc_client_encryption_encrypt_opts_t *const encrypt_opts = mongoc_client_encryption_encrypt_opts_new (); bson_value_t keyid = {0}; bson_value_t to_encrypt = {0}; bson_value_t ciphertext = {0}; @@ -901,21 +791,17 @@ test_create_datakey_with_custom_key_material (void *unused) to_encrypt.value.v_utf8.len = 4u; mongoc_client_encryption_encrypt_opts_set_keyid (encrypt_opts, &keyid); - mongoc_client_encryption_encrypt_opts_set_algorithm ( - encrypt_opts, MONGOC_AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC); + mongoc_client_encryption_encrypt_opts_set_algorithm (encrypt_opts, + MONGOC_AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC); ASSERT_OR_PRINT ( - mongoc_client_encryption_encrypt ( - client_encryption, &to_encrypt, encrypt_opts, &ciphertext, &error), - error); + mongoc_client_encryption_encrypt (client_encryption, &to_encrypt, encrypt_opts, &ciphertext, &error), error); { char actual[256]; /* Need room for null terminator. */ - ASSERT (mcommon_b64_ntop (ciphertext.value.v_binary.data, - ciphertext.value.v_binary.data_len, - actual, - sizeof (actual)) < 255); + ASSERT (mcommon_b64_ntop ( + ciphertext.value.v_binary.data, ciphertext.value.v_binary.data_len, actual, sizeof (actual)) < 255); ASSERT_CMPSTR (expected, actual); } @@ -956,8 +842,7 @@ test_datakey_and_double_encryption (void *unused) * Enable command monitoring to listen for command_started events. */ client = test_framework_new_default_client (); callbacks = mongoc_apm_callbacks_new (); - mongoc_apm_set_command_started_cb ( - callbacks, _datakey_and_double_encryption_command_started); + mongoc_apm_set_command_started_cb (callbacks, _datakey_and_double_encryption_command_started); mongoc_client_set_apm_callbacks (client, callbacks, &test_ctx); /* Using client, drop the collections keyvault.datakeys and db.coll. */ @@ -974,34 +859,24 @@ test_datakey_and_double_encryption (void *unused) kms_providers = _make_kms_providers (true /* aws */, true /* local */); tls_opts = _make_tls_opts (); _check_bypass (auto_encryption_opts); - mongoc_auto_encryption_opts_set_kms_providers (auto_encryption_opts, - kms_providers); + mongoc_auto_encryption_opts_set_kms_providers (auto_encryption_opts, kms_providers); mongoc_auto_encryption_opts_set_tls_opts (auto_encryption_opts, tls_opts); - mongoc_auto_encryption_opts_set_keyvault_namespace ( - auto_encryption_opts, "keyvault", "datakeys"); - schema_map = get_bson_from_json_file ( - "./src/libmongoc/tests/client_side_encryption_prose/" - "datakey-and-double-encryption-schemamap.json"); - mongoc_auto_encryption_opts_set_schema_map (auto_encryption_opts, - schema_map); + mongoc_auto_encryption_opts_set_keyvault_namespace (auto_encryption_opts, "keyvault", "datakeys"); + schema_map = get_bson_from_json_file ("./src/libmongoc/tests/client_side_encryption_prose/" + "datakey-and-double-encryption-schemamap.json"); + mongoc_auto_encryption_opts_set_schema_map (auto_encryption_opts, schema_map); client_encrypted = test_framework_new_default_client (); - ret = mongoc_client_enable_auto_encryption ( - client_encrypted, auto_encryption_opts, &error); + ret = mongoc_client_enable_auto_encryption (client_encrypted, auto_encryption_opts, &error); ASSERT_OR_PRINT (ret, error); /* Create a ClientEncryption object (referred to as client_encryption) */ client_encryption_opts = mongoc_client_encryption_opts_new (); - mongoc_client_encryption_opts_set_kms_providers (client_encryption_opts, - kms_providers); - mongoc_client_encryption_opts_set_tls_opts (client_encryption_opts, - tls_opts); - mongoc_client_encryption_opts_set_keyvault_namespace ( - client_encryption_opts, "keyvault", "datakeys"); - mongoc_client_encryption_opts_set_keyvault_client (client_encryption_opts, - client); - client_encryption = - mongoc_client_encryption_new (client_encryption_opts, &error); + mongoc_client_encryption_opts_set_kms_providers (client_encryption_opts, kms_providers); + mongoc_client_encryption_opts_set_tls_opts (client_encryption_opts, tls_opts); + mongoc_client_encryption_opts_set_keyvault_namespace (client_encryption_opts, "keyvault", "datakeys"); + mongoc_client_encryption_opts_set_keyvault_client (client_encryption_opts, client); + client_encryption = mongoc_client_encryption_new (client_encryption_opts, &error); ASSERT_OR_PRINT (client_encryption, error); test_datakey_and_double_encryption_creating_and_using ( @@ -1072,8 +947,7 @@ _test_key_vault (bool with_external_key_vault) datakey = get_bson_from_json_file ("./src/libmongoc/tests/" "client_side_encryption_prose/external/" "external-key.json"); - ASSERT_OR_PRINT ( - mongoc_collection_insert_one (coll, datakey, NULL, NULL, &error), error); + ASSERT_OR_PRINT (mongoc_collection_insert_one (coll, datakey, NULL, NULL, &error), error); mongoc_collection_destroy (coll); /* Create a MongoClient configured with auto encryption. */ @@ -1086,48 +960,33 @@ _test_key_vault (bool with_external_key_vault) "external-schema.json"); schema_map = BCON_NEW ("db.coll", BCON_DOCUMENT (schema)); kms_providers = _make_kms_providers (false /* aws */, true /* local */); - mongoc_auto_encryption_opts_set_kms_providers (auto_encryption_opts, - kms_providers); - mongoc_auto_encryption_opts_set_keyvault_namespace ( - auto_encryption_opts, "keyvault", "datakeys"); - mongoc_auto_encryption_opts_set_schema_map (auto_encryption_opts, - schema_map); + mongoc_auto_encryption_opts_set_kms_providers (auto_encryption_opts, kms_providers); + mongoc_auto_encryption_opts_set_keyvault_namespace (auto_encryption_opts, "keyvault", "datakeys"); + mongoc_auto_encryption_opts_set_schema_map (auto_encryption_opts, schema_map); if (with_external_key_vault) { - mongoc_auto_encryption_opts_set_keyvault_client (auto_encryption_opts, - client_external); + mongoc_auto_encryption_opts_set_keyvault_client (auto_encryption_opts, client_external); } - ASSERT_OR_PRINT (mongoc_client_enable_auto_encryption ( - client_encrypted, auto_encryption_opts, &error), - error); + ASSERT_OR_PRINT (mongoc_client_enable_auto_encryption (client_encrypted, auto_encryption_opts, &error), error); /* Create a ClientEncryption object. */ client_encryption_opts = mongoc_client_encryption_opts_new (); - mongoc_client_encryption_opts_set_kms_providers (client_encryption_opts, - kms_providers); - mongoc_client_encryption_opts_set_keyvault_namespace ( - client_encryption_opts, "keyvault", "datakeys"); + mongoc_client_encryption_opts_set_kms_providers (client_encryption_opts, kms_providers); + mongoc_client_encryption_opts_set_keyvault_namespace (client_encryption_opts, "keyvault", "datakeys"); if (with_external_key_vault) { - mongoc_client_encryption_opts_set_keyvault_client (client_encryption_opts, - client_external); + mongoc_client_encryption_opts_set_keyvault_client (client_encryption_opts, client_external); } else { - mongoc_client_encryption_opts_set_keyvault_client (client_encryption_opts, - client); + mongoc_client_encryption_opts_set_keyvault_client (client_encryption_opts, client); } - client_encryption = - mongoc_client_encryption_new (client_encryption_opts, &error); + client_encryption = mongoc_client_encryption_new (client_encryption_opts, &error); ASSERT_OR_PRINT (client_encryption, error); /* Use client_encrypted to insert the document {"encrypted": "test"} into * db.coll. */ coll = mongoc_client_get_collection (client_encrypted, "db", "coll"); - res = mongoc_collection_insert_one ( - coll, tmp_bson ("{'encrypted': 'test'}"), NULL, NULL, &error); + res = mongoc_collection_insert_one (coll, tmp_bson ("{'encrypted': 'test'}"), NULL, NULL, &error); if (with_external_key_vault) { BSON_ASSERT (!res); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_CLIENT, - MONGOC_ERROR_CLIENT_AUTHENTICATE, - "Authentication failed"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_AUTHENTICATE, "Authentication failed"); } else { ASSERT_OR_PRINT (res, error); } @@ -1135,22 +994,18 @@ _test_key_vault (bool with_external_key_vault) /* Use client_encryption to explicitly encrypt the string "test" with key ID * ``LOCALAAAAAAAAAAAAAAAAA==`` and deterministic algorithm. */ encrypt_opts = mongoc_client_encryption_encrypt_opts_new (); - mongoc_client_encryption_encrypt_opts_set_algorithm ( - encrypt_opts, MONGOC_AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC); + mongoc_client_encryption_encrypt_opts_set_algorithm (encrypt_opts, + MONGOC_AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC); BSON_ASSERT (bson_iter_init_find (&iter, datakey, "_id")); keyid = bson_iter_value (&iter); mongoc_client_encryption_encrypt_opts_set_keyid (encrypt_opts, keyid); value.value_type = BSON_TYPE_UTF8; value.value.v_utf8.str = "test"; value.value.v_utf8.len = 4; - res = mongoc_client_encryption_encrypt ( - client_encryption, &value, encrypt_opts, &ciphertext, &error); + res = mongoc_client_encryption_encrypt (client_encryption, &value, encrypt_opts, &ciphertext, &error); if (with_external_key_vault) { BSON_ASSERT (!res); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_CLIENT, - MONGOC_ERROR_CLIENT_AUTHENTICATE, - "Authentication failed"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_AUTHENTICATE, "Authentication failed"); } else { ASSERT_OR_PRINT (res, error); } @@ -1204,35 +1059,22 @@ test_views_are_prohibited (void *unused) coll = mongoc_client_get_collection (client, "db", "view"); (void) mongoc_collection_drop (coll, NULL); res = mongoc_client_command_simple ( - client, - "db", - tmp_bson ("{'create': 'view', 'viewOn': 'coll'}"), - NULL, - NULL, - &error); + client, "db", tmp_bson ("{'create': 'view', 'viewOn': 'coll'}"), NULL, NULL, &error); ASSERT_OR_PRINT (res, error); client_encrypted = test_framework_new_default_client (); auto_encryption_opts = mongoc_auto_encryption_opts_new (); _check_bypass (auto_encryption_opts); kms_providers = _make_kms_providers (false /* aws */, true /* local */); - mongoc_auto_encryption_opts_set_kms_providers (auto_encryption_opts, - kms_providers); - mongoc_auto_encryption_opts_set_keyvault_namespace ( - auto_encryption_opts, "keyvault", "datakeys"); - ASSERT_OR_PRINT (mongoc_client_enable_auto_encryption ( - client_encrypted, auto_encryption_opts, &error), - error); + mongoc_auto_encryption_opts_set_kms_providers (auto_encryption_opts, kms_providers); + mongoc_auto_encryption_opts_set_keyvault_namespace (auto_encryption_opts, "keyvault", "datakeys"); + ASSERT_OR_PRINT (mongoc_client_enable_auto_encryption (client_encrypted, auto_encryption_opts, &error), error); mongoc_collection_destroy (coll); coll = mongoc_client_get_collection (client_encrypted, "db", "view"); - res = mongoc_collection_insert_one ( - coll, tmp_bson ("{'x': 1}"), NULL, NULL, &error); + res = mongoc_collection_insert_one (coll, tmp_bson ("{'x': 1}"), NULL, NULL, &error); BSON_ASSERT (!res); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION, - 1, - "cannot auto encrypt a view"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION, 1, "cannot auto encrypt a view"); bson_destroy (kms_providers); mongoc_collection_destroy (coll); @@ -1255,95 +1097,65 @@ _endpoint_setup (mongoc_client_t *keyvault_client, ASSERT (keyvault_client); - char *mongoc_test_aws_access_key_id = - test_framework_getenv_required ("MONGOC_TEST_AWS_ACCESS_KEY_ID"); - char *mongoc_test_aws_secret_access_key = - test_framework_getenv_required ("MONGOC_TEST_AWS_SECRET_ACCESS_KEY"); - char *mongoc_test_azure_tenant_id = - test_framework_getenv_required ("MONGOC_TEST_AZURE_TENANT_ID"); - char *mongoc_test_azure_client_id = - test_framework_getenv_required ("MONGOC_TEST_AZURE_CLIENT_ID"); - char *mongoc_test_azure_client_secret = - test_framework_getenv_required ("MONGOC_TEST_AZURE_CLIENT_SECRET"); - char *mongoc_test_gcp_email = - test_framework_getenv_required ("MONGOC_TEST_GCP_EMAIL"); - char *mongoc_test_gcp_privatekey = - test_framework_getenv_required ("MONGOC_TEST_GCP_PRIVATEKEY"); - char *ca_file = - test_framework_getenv_required ("MONGOC_TEST_CSFLE_TLS_CA_FILE"); - char *certificate_key_file = test_framework_getenv_required ( - "MONGOC_TEST_CSFLE_TLS_CERTIFICATE_KEY_FILE"); - - - kms_providers = - tmp_bson ("{'aws': {'accessKeyId': '%s', 'secretAccessKey': '%s'}}", - mongoc_test_aws_access_key_id, - mongoc_test_aws_secret_access_key); - bson_concat ( - kms_providers, - tmp_bson ( - "{'azure': {'tenantId': '%s', 'clientId': '%s', 'clientSecret': '%s', " - "'identityPlatformEndpoint': 'login.microsoftonline.com:443'}}", - mongoc_test_azure_tenant_id, - mongoc_test_azure_client_id, - mongoc_test_azure_client_secret)); + char *mongoc_test_aws_access_key_id = test_framework_getenv_required ("MONGOC_TEST_AWS_ACCESS_KEY_ID"); + char *mongoc_test_aws_secret_access_key = test_framework_getenv_required ("MONGOC_TEST_AWS_SECRET_ACCESS_KEY"); + char *mongoc_test_azure_tenant_id = test_framework_getenv_required ("MONGOC_TEST_AZURE_TENANT_ID"); + char *mongoc_test_azure_client_id = test_framework_getenv_required ("MONGOC_TEST_AZURE_CLIENT_ID"); + char *mongoc_test_azure_client_secret = test_framework_getenv_required ("MONGOC_TEST_AZURE_CLIENT_SECRET"); + char *mongoc_test_gcp_email = test_framework_getenv_required ("MONGOC_TEST_GCP_EMAIL"); + char *mongoc_test_gcp_privatekey = test_framework_getenv_required ("MONGOC_TEST_GCP_PRIVATEKEY"); + char *ca_file = test_framework_getenv_required ("MONGOC_TEST_CSFLE_TLS_CA_FILE"); + char *certificate_key_file = test_framework_getenv_required ("MONGOC_TEST_CSFLE_TLS_CERTIFICATE_KEY_FILE"); + + + kms_providers = tmp_bson ("{'aws': {'accessKeyId': '%s', 'secretAccessKey': '%s'}}", + mongoc_test_aws_access_key_id, + mongoc_test_aws_secret_access_key); + bson_concat (kms_providers, + tmp_bson ("{'azure': {'tenantId': '%s', 'clientId': '%s', 'clientSecret': '%s', " + "'identityPlatformEndpoint': 'login.microsoftonline.com:443'}}", + mongoc_test_azure_tenant_id, + mongoc_test_azure_client_id, + mongoc_test_azure_client_secret)); bson_concat (kms_providers, tmp_bson ("{'gcp': { 'email': '%s', 'privateKey': '%s', " "'endpoint': 'oauth2.googleapis.com:443'}}", mongoc_test_gcp_email, mongoc_test_gcp_privatekey)); - bson_concat (kms_providers, - tmp_bson ("{'kmip': { 'endpoint': 'localhost:5698' }}")); - tls_opts = tmp_bson ( - "{'kmip': { 'tlsCAFile': '%s', 'tlsCertificateKeyFile': '%s' }}", - ca_file, - certificate_key_file); - - kms_providers_invalid = - tmp_bson ("{'aws': {'accessKeyId': '%s', 'secretAccessKey': '%s'}}", - mongoc_test_aws_access_key_id, - mongoc_test_aws_secret_access_key); - bson_concat ( - kms_providers_invalid, - tmp_bson ( - "{'azure': {'tenantId': '%s', 'clientId': '%s', 'clientSecret': '%s', " - "'identityPlatformEndpoint': 'doesnotexist.invalid:443'}}", - mongoc_test_azure_tenant_id, - mongoc_test_azure_client_id, - mongoc_test_azure_client_secret)); + bson_concat (kms_providers, tmp_bson ("{'kmip': { 'endpoint': 'localhost:5698' }}")); + tls_opts = + tmp_bson ("{'kmip': { 'tlsCAFile': '%s', 'tlsCertificateKeyFile': '%s' }}", ca_file, certificate_key_file); + + kms_providers_invalid = tmp_bson ("{'aws': {'accessKeyId': '%s', 'secretAccessKey': '%s'}}", + mongoc_test_aws_access_key_id, + mongoc_test_aws_secret_access_key); + bson_concat (kms_providers_invalid, + tmp_bson ("{'azure': {'tenantId': '%s', 'clientId': '%s', 'clientSecret': '%s', " + "'identityPlatformEndpoint': 'doesnotexist.invalid:443'}}", + mongoc_test_azure_tenant_id, + mongoc_test_azure_client_id, + mongoc_test_azure_client_secret)); bson_concat (kms_providers_invalid, tmp_bson ("{'gcp': { 'email': '%s', 'privateKey': '%s', " "'endpoint': 'doesnotexist.invalid'}}", mongoc_test_gcp_email, mongoc_test_gcp_privatekey)); - bson_concat ( - kms_providers_invalid, - tmp_bson ("{'kmip': { 'endpoint': 'doesnotexist.local:5698' }}")); + bson_concat (kms_providers_invalid, tmp_bson ("{'kmip': { 'endpoint': 'doesnotexist.local:5698' }}")); client_encryption_opts = mongoc_client_encryption_opts_new (); - mongoc_client_encryption_opts_set_kms_providers (client_encryption_opts, - kms_providers); - mongoc_client_encryption_opts_set_tls_opts (client_encryption_opts, - tls_opts); - mongoc_client_encryption_opts_set_keyvault_namespace ( - client_encryption_opts, "keyvault", "datakeys"); - mongoc_client_encryption_opts_set_keyvault_client (client_encryption_opts, - keyvault_client); - *client_encryption = - mongoc_client_encryption_new (client_encryption_opts, &error); + mongoc_client_encryption_opts_set_kms_providers (client_encryption_opts, kms_providers); + mongoc_client_encryption_opts_set_tls_opts (client_encryption_opts, tls_opts); + mongoc_client_encryption_opts_set_keyvault_namespace (client_encryption_opts, "keyvault", "datakeys"); + mongoc_client_encryption_opts_set_keyvault_client (client_encryption_opts, keyvault_client); + *client_encryption = mongoc_client_encryption_new (client_encryption_opts, &error); ASSERT_OR_PRINT (client_encryption, error); client_encryption_opts_invalid = mongoc_client_encryption_opts_new (); - mongoc_client_encryption_opts_set_kms_providers ( - client_encryption_opts_invalid, kms_providers_invalid); - mongoc_client_encryption_opts_set_tls_opts (client_encryption_opts_invalid, - tls_opts); - mongoc_client_encryption_opts_set_keyvault_namespace ( - client_encryption_opts_invalid, "keyvault", "datakeys"); - mongoc_client_encryption_opts_set_keyvault_client ( - client_encryption_opts_invalid, keyvault_client); - *client_encryption_invalid = - mongoc_client_encryption_new (client_encryption_opts_invalid, &error); + mongoc_client_encryption_opts_set_kms_providers (client_encryption_opts_invalid, kms_providers_invalid); + mongoc_client_encryption_opts_set_tls_opts (client_encryption_opts_invalid, tls_opts); + mongoc_client_encryption_opts_set_keyvault_namespace (client_encryption_opts_invalid, "keyvault", "datakeys"); + mongoc_client_encryption_opts_set_keyvault_client (client_encryption_opts_invalid, keyvault_client); + *client_encryption_invalid = mongoc_client_encryption_new (client_encryption_opts_invalid, &error); ASSERT_OR_PRINT (client_encryption_invalid, error); mongoc_client_encryption_opts_destroy (client_encryption_opts); @@ -1361,36 +1173,33 @@ _endpoint_setup (mongoc_client_t *keyvault_client, /* Use the returned UUID of the key to explicitly encrypt and decrypt the * string "test" to validate it works. */ -#define TEST_ENCRYPT_DECRYPT(keyid, client_encryption, res, error) \ - do { \ - bson_value_t ciphertext; \ - bson_value_t plaintext; \ - bson_value_t test; \ - mongoc_client_encryption_encrypt_opts_t *encrypt_opts; \ - \ - test.value_type = BSON_TYPE_UTF8; \ - test.value.v_utf8.str = "test"; \ - test.value.v_utf8.len = 4; \ - \ - encrypt_opts = mongoc_client_encryption_encrypt_opts_new (); \ - mongoc_client_encryption_encrypt_opts_set_algorithm ( \ - encrypt_opts, MONGOC_AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC); \ - mongoc_client_encryption_encrypt_opts_set_keyid (encrypt_opts, keyid); \ - res = mongoc_client_encryption_encrypt ( \ - client_encryption, &test, encrypt_opts, &ciphertext, &error); \ - ASSERT_OR_PRINT (res, error); \ - res = mongoc_client_encryption_decrypt ( \ - client_encryption, &ciphertext, &plaintext, &error); \ - ASSERT_OR_PRINT (res, error); \ - if (plaintext.value_type != BSON_TYPE_UTF8) { \ - test_error ( \ - "expected decrypted result to be value type UTF-8, got %s", \ - _mongoc_bson_type_to_str (plaintext.value_type)); \ - } \ - ASSERT_CMPSTR (plaintext.value.v_utf8.str, test.value.v_utf8.str); \ - bson_value_destroy (&ciphertext); \ - bson_value_destroy (&plaintext); \ - mongoc_client_encryption_encrypt_opts_destroy (encrypt_opts); \ +#define TEST_ENCRYPT_DECRYPT(keyid, client_encryption, res, error) \ + do { \ + bson_value_t ciphertext; \ + bson_value_t plaintext; \ + bson_value_t test; \ + mongoc_client_encryption_encrypt_opts_t *encrypt_opts; \ + \ + test.value_type = BSON_TYPE_UTF8; \ + test.value.v_utf8.str = "test"; \ + test.value.v_utf8.len = 4; \ + \ + encrypt_opts = mongoc_client_encryption_encrypt_opts_new (); \ + mongoc_client_encryption_encrypt_opts_set_algorithm (encrypt_opts, \ + MONGOC_AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC); \ + mongoc_client_encryption_encrypt_opts_set_keyid (encrypt_opts, keyid); \ + res = mongoc_client_encryption_encrypt (client_encryption, &test, encrypt_opts, &ciphertext, &error); \ + ASSERT_OR_PRINT (res, error); \ + res = mongoc_client_encryption_decrypt (client_encryption, &ciphertext, &plaintext, &error); \ + ASSERT_OR_PRINT (res, error); \ + if (plaintext.value_type != BSON_TYPE_UTF8) { \ + test_error ("expected decrypted result to be value type UTF-8, got %s", \ + _mongoc_bson_type_to_str (plaintext.value_type)); \ + } \ + ASSERT_CMPSTR (plaintext.value.v_utf8.str, test.value.v_utf8.str); \ + bson_value_destroy (&ciphertext); \ + bson_value_destroy (&plaintext); \ + mongoc_client_encryption_encrypt_opts_destroy (encrypt_opts); \ } while (0) /* Prose Test 7: Custom Endpoint Test */ @@ -1413,17 +1222,14 @@ test_custom_endpoint (void *unused) datakey_opts = mongoc_client_encryption_datakey_opts_new (); /* Case 1: No endpoint, expect to succeed. */ - _endpoint_setup ( - keyvault_client, &client_encryption, &client_encryption_invalid); + _endpoint_setup (keyvault_client, &client_encryption, &client_encryption_invalid); masterkey = BCON_NEW ("region", "us-east-1", "key", "arn:aws:kms:us-east-1:579766882180:key/" "89fcc2c4-08b0-4bd9-9f25-e30687b580d0"); - mongoc_client_encryption_datakey_opts_set_masterkey (datakey_opts, - masterkey); - res = mongoc_client_encryption_create_datakey ( - client_encryption, "aws", datakey_opts, &keyid, &error); + mongoc_client_encryption_datakey_opts_set_masterkey (datakey_opts, masterkey); + res = mongoc_client_encryption_create_datakey (client_encryption, "aws", datakey_opts, &keyid, &error); ASSERT_OR_PRINT (res, error); TEST_ENCRYPT_DECRYPT (&keyid, client_encryption, res, error); @@ -1434,8 +1240,7 @@ test_custom_endpoint (void *unused) /* Case 2: Custom endpoint, with the same as the default. Expect to succeed */ - _endpoint_setup ( - keyvault_client, &client_encryption, &client_encryption_invalid); + _endpoint_setup (keyvault_client, &client_encryption, &client_encryption_invalid); masterkey = BCON_NEW ("region", "us-east-1", "key", @@ -1443,10 +1248,8 @@ test_custom_endpoint (void *unused) "89fcc2c4-08b0-4bd9-9f25-e30687b580d0", "endpoint", "kms.us-east-1.amazonaws.com"); - mongoc_client_encryption_datakey_opts_set_masterkey (datakey_opts, - masterkey); - res = mongoc_client_encryption_create_datakey ( - client_encryption, "aws", datakey_opts, &keyid, &error); + mongoc_client_encryption_datakey_opts_set_masterkey (datakey_opts, masterkey); + res = mongoc_client_encryption_create_datakey (client_encryption, "aws", datakey_opts, &keyid, &error); ASSERT_OR_PRINT (res, error); TEST_ENCRYPT_DECRYPT (&keyid, client_encryption, res, error); @@ -1457,8 +1260,7 @@ test_custom_endpoint (void *unused) /* Case 3: Custom endpoint, with the same as the default but port included. * Expect to succeed */ - _endpoint_setup ( - keyvault_client, &client_encryption, &client_encryption_invalid); + _endpoint_setup (keyvault_client, &client_encryption, &client_encryption_invalid); masterkey = BCON_NEW ("region", "us-east-1", "key", @@ -1466,10 +1268,8 @@ test_custom_endpoint (void *unused) "89fcc2c4-08b0-4bd9-9f25-e30687b580d0", "endpoint", "kms.us-east-1.amazonaws.com:443"); - mongoc_client_encryption_datakey_opts_set_masterkey (datakey_opts, - masterkey); - res = mongoc_client_encryption_create_datakey ( - client_encryption, "aws", datakey_opts, &keyid, &error); + mongoc_client_encryption_datakey_opts_set_masterkey (datakey_opts, masterkey); + res = mongoc_client_encryption_create_datakey (client_encryption, "aws", datakey_opts, &keyid, &error); ASSERT_OR_PRINT (res, error); TEST_ENCRYPT_DECRYPT (&keyid, client_encryption, res, error); @@ -1481,8 +1281,7 @@ test_custom_endpoint (void *unused) /* Case 4: Custom endpoint, with the same as the default but wrong port * included. * Expect to fail with socket error */ - _endpoint_setup ( - keyvault_client, &client_encryption, &client_encryption_invalid); + _endpoint_setup (keyvault_client, &client_encryption, &client_encryption_invalid); masterkey = BCON_NEW ("region", "us-east-1", "key", @@ -1490,14 +1289,9 @@ test_custom_endpoint (void *unused) "89fcc2c4-08b0-4bd9-9f25-e30687b580d0", "endpoint", "kms.us-east-1.amazonaws.com:12345"); - mongoc_client_encryption_datakey_opts_set_masterkey (datakey_opts, - masterkey); - res = mongoc_client_encryption_create_datakey ( - client_encryption, "aws", datakey_opts, &keyid, &error); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_CONNECT, - "Failed to connect"); + mongoc_client_encryption_datakey_opts_set_masterkey (datakey_opts, masterkey); + res = mongoc_client_encryption_create_datakey (client_encryption, "aws", datakey_opts, &keyid, &error); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_CONNECT, "Failed to connect"); BSON_ASSERT (!res); bson_value_destroy (&keyid); bson_destroy (masterkey); @@ -1505,8 +1299,7 @@ test_custom_endpoint (void *unused) mongoc_client_encryption_destroy (client_encryption_invalid); /* Case 5: Custom endpoint, but wrong region. */ - _endpoint_setup ( - keyvault_client, &client_encryption, &client_encryption_invalid); + _endpoint_setup (keyvault_client, &client_encryption, &client_encryption_invalid); masterkey = BCON_NEW ("region", "us-east-1", "key", @@ -1514,11 +1307,9 @@ test_custom_endpoint (void *unused) "89fcc2c4-08b0-4bd9-9f25-e30687b580d0", "endpoint", "kms.us-east-2.amazonaws.com"); - mongoc_client_encryption_datakey_opts_set_masterkey (datakey_opts, - masterkey); + mongoc_client_encryption_datakey_opts_set_masterkey (datakey_opts, masterkey); memset (&error, 0, sizeof (bson_error_t)); - res = mongoc_client_encryption_create_datakey ( - client_encryption, "aws", datakey_opts, &keyid, &error); + res = mongoc_client_encryption_create_datakey (client_encryption, "aws", datakey_opts, &keyid, &error); ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION, 1, ""); BSON_ASSERT (!res); bson_value_destroy (&keyid); @@ -1527,8 +1318,7 @@ test_custom_endpoint (void *unused) mongoc_client_encryption_destroy (client_encryption_invalid); /* Case 6: Custom endpoint to doesnotexist.invalid. */ - _endpoint_setup ( - keyvault_client, &client_encryption, &client_encryption_invalid); + _endpoint_setup (keyvault_client, &client_encryption, &client_encryption_invalid); masterkey = BCON_NEW ("region", "us-east-1", "key", @@ -1536,15 +1326,10 @@ test_custom_endpoint (void *unused) "89fcc2c4-08b0-4bd9-9f25-e30687b580d0", "endpoint", "doesnotexist.invalid"); - mongoc_client_encryption_datakey_opts_set_masterkey (datakey_opts, - masterkey); + mongoc_client_encryption_datakey_opts_set_masterkey (datakey_opts, masterkey); memset (&error, 0, sizeof (bson_error_t)); - res = mongoc_client_encryption_create_datakey ( - client_encryption, "aws", datakey_opts, &keyid, &error); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_NAME_RESOLUTION, - "Failed to resolve"); + res = mongoc_client_encryption_create_datakey (client_encryption, "aws", datakey_opts, &keyid, &error); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_NAME_RESOLUTION, "Failed to resolve"); BSON_ASSERT (!res); bson_value_destroy (&keyid); bson_destroy (masterkey); @@ -1552,16 +1337,10 @@ test_custom_endpoint (void *unused) mongoc_client_encryption_destroy (client_encryption_invalid); /* Case 7: Azure successful case */ - _endpoint_setup ( - keyvault_client, &client_encryption, &client_encryption_invalid); - masterkey = BCON_NEW ("keyVaultEndpoint", - "key-vault-csfle.vault.azure.net", - "keyName", - "key-name-csfle"); - mongoc_client_encryption_datakey_opts_set_masterkey (datakey_opts, - masterkey); - res = mongoc_client_encryption_create_datakey ( - client_encryption, "azure", datakey_opts, &keyid, &error); + _endpoint_setup (keyvault_client, &client_encryption, &client_encryption_invalid); + masterkey = BCON_NEW ("keyVaultEndpoint", "key-vault-csfle.vault.azure.net", "keyName", "key-name-csfle"); + mongoc_client_encryption_datakey_opts_set_masterkey (datakey_opts, masterkey); + res = mongoc_client_encryption_create_datakey (client_encryption, "azure", datakey_opts, &keyid, &error); ASSERT_OR_PRINT (res, error); TEST_ENCRYPT_DECRYPT (&keyid, client_encryption, res, error); @@ -1571,21 +1350,15 @@ test_custom_endpoint (void *unused) mongoc_client_encryption_destroy (client_encryption_invalid); /* Azure invalid case. */ - _endpoint_setup ( - keyvault_client, &client_encryption, &client_encryption_invalid); - res = mongoc_client_encryption_create_datakey ( - client_encryption_invalid, "azure", datakey_opts, &keyid, &error); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_NAME_RESOLUTION, - "Failed to resolve"); + _endpoint_setup (keyvault_client, &client_encryption, &client_encryption_invalid); + res = mongoc_client_encryption_create_datakey (client_encryption_invalid, "azure", datakey_opts, &keyid, &error); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_NAME_RESOLUTION, "Failed to resolve"); BSON_ASSERT (!res); mongoc_client_encryption_destroy (client_encryption); mongoc_client_encryption_destroy (client_encryption_invalid); /* Case 8: GCP successful case. */ - _endpoint_setup ( - keyvault_client, &client_encryption, &client_encryption_invalid); + _endpoint_setup (keyvault_client, &client_encryption, &client_encryption_invalid); masterkey = BCON_NEW ("projectId", "devprod-drivers", "location", @@ -1596,10 +1369,8 @@ test_custom_endpoint (void *unused) "key-name-csfle", "endpoint", "cloudkms.googleapis.com:443"); - mongoc_client_encryption_datakey_opts_set_masterkey (datakey_opts, - masterkey); - res = mongoc_client_encryption_create_datakey ( - client_encryption, "gcp", datakey_opts, &keyid, &error); + mongoc_client_encryption_datakey_opts_set_masterkey (datakey_opts, masterkey); + res = mongoc_client_encryption_create_datakey (client_encryption, "gcp", datakey_opts, &keyid, &error); ASSERT_OR_PRINT (res, error); TEST_ENCRYPT_DECRYPT (&keyid, client_encryption, res, error); @@ -1609,21 +1380,15 @@ test_custom_endpoint (void *unused) mongoc_client_encryption_destroy (client_encryption_invalid); /* GCP invalid case. */ - _endpoint_setup ( - keyvault_client, &client_encryption, &client_encryption_invalid); - res = mongoc_client_encryption_create_datakey ( - client_encryption_invalid, "gcp", datakey_opts, &keyid, &error); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_NAME_RESOLUTION, - "Failed to resolve"); + _endpoint_setup (keyvault_client, &client_encryption, &client_encryption_invalid); + res = mongoc_client_encryption_create_datakey (client_encryption_invalid, "gcp", datakey_opts, &keyid, &error); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_NAME_RESOLUTION, "Failed to resolve"); BSON_ASSERT (!res); mongoc_client_encryption_destroy (client_encryption); mongoc_client_encryption_destroy (client_encryption_invalid); /* Case 9: GCP invalid key endpoint. */ - _endpoint_setup ( - keyvault_client, &client_encryption, &client_encryption_invalid); + _endpoint_setup (keyvault_client, &client_encryption, &client_encryption_invalid); masterkey = BCON_NEW ("projectId", "devprod-drivers", "location", @@ -1634,12 +1399,9 @@ test_custom_endpoint (void *unused) "key-name-csfle", "endpoint", "doesnotexist.invalid:443"); - mongoc_client_encryption_datakey_opts_set_masterkey (datakey_opts, - masterkey); - res = mongoc_client_encryption_create_datakey ( - client_encryption, "gcp", datakey_opts, &keyid, &error); - ASSERT_ERROR_CONTAINS ( - error, MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION, 1, "Invalid KMS response"); + mongoc_client_encryption_datakey_opts_set_masterkey (datakey_opts, masterkey); + res = mongoc_client_encryption_create_datakey (client_encryption, "gcp", datakey_opts, &keyid, &error); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION, 1, "Invalid KMS response"); BSON_ASSERT (!res); bson_destroy (masterkey); @@ -1647,13 +1409,10 @@ test_custom_endpoint (void *unused) mongoc_client_encryption_destroy (client_encryption_invalid); /* Case 10: KMIP no endpoint. */ - _endpoint_setup ( - keyvault_client, &client_encryption, &client_encryption_invalid); + _endpoint_setup (keyvault_client, &client_encryption, &client_encryption_invalid); masterkey = BCON_NEW ("keyId", "1"); - mongoc_client_encryption_datakey_opts_set_masterkey (datakey_opts, - masterkey); - res = mongoc_client_encryption_create_datakey ( - client_encryption, "kmip", datakey_opts, &keyid, &error); + mongoc_client_encryption_datakey_opts_set_masterkey (datakey_opts, masterkey); + res = mongoc_client_encryption_create_datakey (client_encryption, "kmip", datakey_opts, &keyid, &error); ASSERT_OR_PRINT (res, error); TEST_ENCRYPT_DECRYPT (&keyid, client_encryption, res, error); @@ -1661,12 +1420,8 @@ test_custom_endpoint (void *unused) /* Attempt to use client_encryption_invalid with the same masterKey. Expect * an error. */ - res = mongoc_client_encryption_create_datakey ( - client_encryption_invalid, "kmip", datakey_opts, &keyid, &error); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_NAME_RESOLUTION, - "Failed to resolve"); + res = mongoc_client_encryption_create_datakey (client_encryption_invalid, "kmip", datakey_opts, &keyid, &error); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_NAME_RESOLUTION, "Failed to resolve"); BSON_ASSERT (!res); bson_value_destroy (&keyid); @@ -1675,13 +1430,10 @@ test_custom_endpoint (void *unused) mongoc_client_encryption_destroy (client_encryption_invalid); /* Case 11: KMIP overriding with valid endpoint. */ - _endpoint_setup ( - keyvault_client, &client_encryption, &client_encryption_invalid); + _endpoint_setup (keyvault_client, &client_encryption, &client_encryption_invalid); masterkey = BCON_NEW ("keyId", "1", "endpoint", "localhost:5698"); - mongoc_client_encryption_datakey_opts_set_masterkey (datakey_opts, - masterkey); - res = mongoc_client_encryption_create_datakey ( - client_encryption, "kmip", datakey_opts, &keyid, &error); + mongoc_client_encryption_datakey_opts_set_masterkey (datakey_opts, masterkey); + res = mongoc_client_encryption_create_datakey (client_encryption, "kmip", datakey_opts, &keyid, &error); ASSERT_OR_PRINT (res, error); TEST_ENCRYPT_DECRYPT (&keyid, client_encryption, res, error); @@ -1692,17 +1444,11 @@ test_custom_endpoint (void *unused) mongoc_client_encryption_destroy (client_encryption_invalid); /* Case 12: KMIP overriding with invalid endpoint. */ - _endpoint_setup ( - keyvault_client, &client_encryption, &client_encryption_invalid); + _endpoint_setup (keyvault_client, &client_encryption, &client_encryption_invalid); masterkey = BCON_NEW ("keyId", "1", "endpoint", "doesnotexist.local:5698"); - mongoc_client_encryption_datakey_opts_set_masterkey (datakey_opts, - masterkey); - res = mongoc_client_encryption_create_datakey ( - client_encryption, "kmip", datakey_opts, &keyid, &error); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_NAME_RESOLUTION, - "Failed to resolve"); + mongoc_client_encryption_datakey_opts_set_masterkey (datakey_opts, masterkey); + res = mongoc_client_encryption_create_datakey (client_encryption, "kmip", datakey_opts, &keyid, &error); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_NAME_RESOLUTION, "Failed to resolve"); BSON_ASSERT (!res); bson_value_destroy (&keyid); @@ -1767,21 +1513,14 @@ _corpus_field_destroy (corpus_field_t *field) bson_free (field); } -#define LOCAL_UUID \ - "\x2c\xe0\x80\x2c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" -#define AWS_UUID \ - "\x01\x64\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" -#define AZURE_UUID \ - "\x01\x95\x11\x10\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" -#define GCP_UUID \ - "\x18\x23\xc0\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" -#define KMIP_UUID \ - "\x28\xc2\x0f\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" +#define LOCAL_UUID "\x2c\xe0\x80\x2c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" +#define AWS_UUID "\x01\x64\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" +#define AZURE_UUID "\x01\x95\x11\x10\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" +#define GCP_UUID "\x18\x23\xc0\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" +#define KMIP_UUID "\x28\xc2\x0f\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" static void -_corpus_copy_field (mongoc_client_encryption_t *client_encryption, - bson_iter_t *iter, - bson_t *corpus_copied) +_corpus_copy_field (mongoc_client_encryption_t *client_encryption, bson_iter_t *iter, bson_t *corpus_copied) { corpus_field_t *field; const char *key = bson_iter_key (iter); @@ -1790,10 +1529,8 @@ _corpus_copy_field (mongoc_client_encryption_t *client_encryption, bool res; bson_error_t error; - if (0 == strcmp ("_id", key) || 0 == strcmp ("altname_aws", key) || - 0 == strcmp ("altname_local", key) || - 0 == strcmp ("altname_azure", key) || 0 == strcmp ("altname_gcp", key) || - 0 == strcmp ("altname_kmip", key)) { + if (0 == strcmp ("_id", key) || 0 == strcmp ("altname_aws", key) || 0 == strcmp ("altname_local", key) || + 0 == strcmp ("altname_azure", key) || 0 == strcmp ("altname_gcp", key) || 0 == strcmp ("altname_kmip", key)) { bson_append_value (corpus_copied, key, -1, bson_iter_value (iter)); return; } @@ -1808,11 +1545,10 @@ _corpus_copy_field (mongoc_client_encryption_t *client_encryption, /* Otherwise, use explicit encryption. */ encrypt_opts = mongoc_client_encryption_encrypt_opts_new (); if (0 == strcmp ("rand", field->algo)) { - mongoc_client_encryption_encrypt_opts_set_algorithm ( - encrypt_opts, MONGOC_AEAD_AES_256_CBC_HMAC_SHA_512_RANDOM); + mongoc_client_encryption_encrypt_opts_set_algorithm (encrypt_opts, MONGOC_AEAD_AES_256_CBC_HMAC_SHA_512_RANDOM); } else if (0 == strcmp ("det", field->algo)) { - mongoc_client_encryption_encrypt_opts_set_algorithm ( - encrypt_opts, MONGOC_AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC); + mongoc_client_encryption_encrypt_opts_set_algorithm (encrypt_opts, + MONGOC_AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC); } if (0 == strcmp ("id", field->identifier)) { @@ -1833,12 +1569,10 @@ _corpus_copy_field (mongoc_client_encryption_t *client_encryption, } mongoc_client_encryption_encrypt_opts_set_keyid (encrypt_opts, &uuid); } else if (0 == strcmp ("altname", field->identifier)) { - mongoc_client_encryption_encrypt_opts_set_keyaltname (encrypt_opts, - field->kms); + mongoc_client_encryption_encrypt_opts_set_keyaltname (encrypt_opts, field->kms); } - res = mongoc_client_encryption_encrypt ( - client_encryption, &field->value, encrypt_opts, &ciphertext, &error); + res = mongoc_client_encryption_encrypt (client_encryption, &field->value, encrypt_opts, &ciphertext, &error); if (field->allowed) { bson_t new_field; @@ -1875,10 +1609,8 @@ _corpus_check_encrypted (mongoc_client_encryption_t *client_encryption, memset (&match_ctx, 0, sizeof (match_ctx)); key = bson_iter_key (expected_iter); - if (0 == strcmp ("_id", key) || 0 == strcmp ("altname_aws", key) || - 0 == strcmp ("altname_local", key) || - 0 == strcmp ("altname_azure", key) || 0 == strcmp ("altname_gcp", key) || - 0 == strcmp ("altname_kmip", key)) { + if (0 == strcmp ("_id", key) || 0 == strcmp ("altname_aws", key) || 0 == strcmp ("altname_local", key) || + 0 == strcmp ("altname_azure", key) || 0 == strcmp ("altname_gcp", key) || 0 == strcmp ("altname_kmip", key)) { return; } @@ -1890,15 +1622,13 @@ _corpus_check_encrypted (mongoc_client_encryption_t *client_encryption, * in corpus_encrypted_actual. */ if (0 == strcmp (expected->algo, "det")) { - BSON_ASSERT ( - match_bson_value (&expected->value, &actual->value, &match_ctx)); + BSON_ASSERT (match_bson_value (&expected->value, &actual->value, &match_ctx)); } /* If the algo is rand and allowed is true, that the value does not equal the * value of the corresponding field in corpus_encrypted_actual. */ if (0 == strcmp (expected->algo, "rand") && expected->allowed) { - BSON_ASSERT ( - !match_bson_value (&expected->value, &actual->value, &match_ctx)); + BSON_ASSERT (!match_bson_value (&expected->value, &actual->value, &match_ctx)); } /* If allowed is true, decrypt the value with client_encryption. Decrypt the @@ -1909,16 +1639,13 @@ _corpus_check_encrypted (mongoc_client_encryption_t *client_encryption, bson_value_t actual_decrypted; bool res; - res = mongoc_client_encryption_decrypt ( - client_encryption, &expected->value, &expected_decrypted, &error); + res = mongoc_client_encryption_decrypt (client_encryption, &expected->value, &expected_decrypted, &error); ASSERT_OR_PRINT (res, error); - res = mongoc_client_encryption_decrypt ( - client_encryption, &actual->value, &actual_decrypted, &error); + res = mongoc_client_encryption_decrypt (client_encryption, &actual->value, &actual_decrypted, &error); ASSERT_OR_PRINT (res, error); - BSON_ASSERT ( - match_bson_value (&expected_decrypted, &actual_decrypted, &match_ctx)); + BSON_ASSERT (match_bson_value (&expected_decrypted, &actual_decrypted, &match_ctx)); bson_value_destroy (&expected_decrypted); bson_value_destroy (&actual_decrypted); } @@ -1926,8 +1653,7 @@ _corpus_check_encrypted (mongoc_client_encryption_t *client_encryption, /* If allowed is false, validate the value exactly equals the value of the * corresponding field of corpus (neither was encrypted). */ if (!expected->allowed) { - BSON_ASSERT ( - match_bson_value (&expected->value, &actual->value, &match_ctx)); + BSON_ASSERT (match_bson_value (&expected->value, &actual->value, &match_ctx)); } _corpus_field_destroy (expected); @@ -1980,19 +1706,12 @@ _test_corpus (bool local_schema) "client_side_encryption_prose/corpus/" "corpus-schema.json"); schema_map = BCON_NEW ("db.coll", BCON_DOCUMENT (schema)); - create_cmd = BCON_NEW ("create", - "coll", - "validator", - "{", - "$jsonSchema", - BCON_DOCUMENT (schema), - "}"); + create_cmd = BCON_NEW ("create", "coll", "validator", "{", "$jsonSchema", BCON_DOCUMENT (schema), "}"); if (!local_schema) { /* Drop and create the collection db.coll configured with the included * JSON schema corpus-schema.json */ - res = mongoc_client_command_simple ( - client, "db", create_cmd, NULL, NULL, &error); + res = mongoc_client_command_simple (client, "db", create_cmd, NULL, NULL, &error); ASSERT_OR_PRINT (res, error); } @@ -2023,36 +1742,26 @@ _test_corpus (bool local_schema) /* Create a MongoClient configured with auto encryption */ client_encrypted = test_framework_new_default_client (); auto_encryption_opts = mongoc_auto_encryption_opts_new (); - mongoc_auto_encryption_opts_set_schema_map (auto_encryption_opts, - schema_map); + mongoc_auto_encryption_opts_set_schema_map (auto_encryption_opts, schema_map); _check_bypass (auto_encryption_opts); kms_providers = _make_kms_providers (true /* aws */, true /* local */); - mongoc_auto_encryption_opts_set_kms_providers (auto_encryption_opts, - kms_providers); + mongoc_auto_encryption_opts_set_kms_providers (auto_encryption_opts, kms_providers); tls_opts = _make_tls_opts (); mongoc_auto_encryption_opts_set_tls_opts (auto_encryption_opts, tls_opts); - mongoc_auto_encryption_opts_set_keyvault_namespace ( - auto_encryption_opts, "keyvault", "datakeys"); - res = mongoc_client_enable_auto_encryption ( - client_encrypted, auto_encryption_opts, &error); + mongoc_auto_encryption_opts_set_keyvault_namespace (auto_encryption_opts, "keyvault", "datakeys"); + res = mongoc_client_enable_auto_encryption (client_encrypted, auto_encryption_opts, &error); ASSERT_OR_PRINT (res, error); /* Create a ClientEncryption object */ client_encryption_opts = mongoc_client_encryption_opts_new (); - mongoc_client_encryption_opts_set_kms_providers (client_encryption_opts, - kms_providers); - mongoc_client_encryption_opts_set_tls_opts (client_encryption_opts, - tls_opts); - mongoc_client_encryption_opts_set_keyvault_namespace ( - client_encryption_opts, "keyvault", "datakeys"); - mongoc_client_encryption_opts_set_keyvault_client (client_encryption_opts, - client); - client_encryption = - mongoc_client_encryption_new (client_encryption_opts, &error); + mongoc_client_encryption_opts_set_kms_providers (client_encryption_opts, kms_providers); + mongoc_client_encryption_opts_set_tls_opts (client_encryption_opts, tls_opts); + mongoc_client_encryption_opts_set_keyvault_namespace (client_encryption_opts, "keyvault", "datakeys"); + mongoc_client_encryption_opts_set_keyvault_client (client_encryption_opts, client); + client_encryption = mongoc_client_encryption_new (client_encryption_opts, &error); ASSERT_OR_PRINT (client_encryption, error); - corpus = get_bson_from_json_file ( - "./src/libmongoc/tests/client_side_encryption_prose/corpus/corpus.json"); + corpus = get_bson_from_json_file ("./src/libmongoc/tests/client_side_encryption_prose/corpus/corpus.json"); /* Try each field individually */ bson_iter_init (&iter, corpus); @@ -2064,13 +1773,11 @@ _test_corpus (bool local_schema) /* Insert corpus_copied with auto encryption */ mongoc_collection_destroy (coll); coll = mongoc_client_get_collection (client_encrypted, "db", "coll"); - res = - mongoc_collection_insert_one (coll, &corpus_copied, NULL, NULL, &error); + res = mongoc_collection_insert_one (coll, &corpus_copied, NULL, NULL, &error); ASSERT_OR_PRINT (res, error); /* Get the automatically decrypted corpus */ - cursor = - mongoc_collection_find_with_opts (coll, tmp_bson ("{}"), NULL, NULL); + cursor = mongoc_collection_find_with_opts (coll, tmp_bson ("{}"), NULL, NULL); BSON_ASSERT (mongoc_cursor_next (cursor, &corpus_decrypted)); /* It should exactly match corpus. match_bson does a subset match, so match @@ -2080,15 +1787,13 @@ _test_corpus (bool local_schema) mongoc_cursor_destroy (cursor); /* Load corpus-encrypted.json */ - corpus_encrypted_expected = - get_bson_from_json_file ("./src/libmongoc/tests/" - "client_side_encryption_prose/" - "corpus/corpus-encrypted.json"); + corpus_encrypted_expected = get_bson_from_json_file ("./src/libmongoc/tests/" + "client_side_encryption_prose/" + "corpus/corpus-encrypted.json"); /* Get the actual encrypted document from unencrypted client */ mongoc_collection_destroy (coll); coll = mongoc_client_get_collection (client, "db", "coll"); - cursor = - mongoc_collection_find_with_opts (coll, tmp_bson ("{}"), NULL, NULL); + cursor = mongoc_collection_find_with_opts (coll, tmp_bson ("{}"), NULL, NULL); BSON_ASSERT (mongoc_cursor_next (cursor, &corpus_encrypted_actual)); /* Iterate over corpus_encrypted_expected, and check corpus_encrypted_actual @@ -2097,8 +1802,7 @@ _test_corpus (bool local_schema) while (bson_iter_next (&iter)) { bson_iter_t actual_iter; - BSON_ASSERT (bson_iter_init_find ( - &actual_iter, corpus_encrypted_actual, bson_iter_key (&iter))); + BSON_ASSERT (bson_iter_init_find (&actual_iter, corpus_encrypted_actual, bson_iter_key (&iter))); _corpus_check_encrypted (client_encryption, &iter, &actual_iter); } @@ -2157,8 +1861,7 @@ _reset (mongoc_client_pool_t **pool, mongoc_auto_encryption_opts_set_keyvault_namespace (*opts, "db", "keyvault"); kms_providers = _make_kms_providers (false /* aws */, true /* local */); mongoc_auto_encryption_opts_set_kms_providers (*opts, kms_providers); - schema = get_bson_from_json_file ( - "./src/libmongoc/tests/client_side_encryption_prose/schema.json"); + schema = get_bson_from_json_file ("./src/libmongoc/tests/client_side_encryption_prose/schema.json"); BSON_ASSERT (schema); schema_map = BCON_NEW ("db.coll", BCON_DOCUMENT (schema)); mongoc_auto_encryption_opts_set_schema_map (*opts, schema_map); @@ -2188,19 +1891,14 @@ _reset (mongoc_client_pool_t **pool, mongoc_uri_destroy (uri); /* create key */ - coll = mongoc_client_get_collection ( - *singled_threaded_client, "db", "keyvault"); + coll = mongoc_client_get_collection (*singled_threaded_client, "db", "keyvault"); (void) mongoc_collection_drop (coll, NULL); wc = mongoc_write_concern_new (); mongoc_write_concern_set_wmajority (wc, 1000); mongoc_collection_set_write_concern (coll, wc); - datakey = get_bson_from_json_file ( - "./src/libmongoc/tests/client_side_encryption_prose/limits-key.json"); + datakey = get_bson_from_json_file ("./src/libmongoc/tests/client_side_encryption_prose/limits-key.json"); BSON_ASSERT (datakey); - ASSERT_OR_PRINT ( - mongoc_collection_insert_one ( - coll, datakey, NULL /* opts */, NULL /* reply */, &error), - error); + ASSERT_OR_PRINT (mongoc_collection_insert_one (coll, datakey, NULL /* opts */, NULL /* reply */, &error), error); bson_destroy (datakey); mongoc_write_concern_destroy (wc); @@ -2221,11 +1919,8 @@ _perform_op (mongoc_client_t *client_encrypted) ASSERT (client_encrypted); coll = mongoc_client_get_collection (client_encrypted, "db", "coll"); - ret = mongoc_collection_insert_one (coll, - tmp_bson ("{'encrypted_string': 'abc'}"), - NULL /* opts */, - NULL /* reply */, - &error); + ret = mongoc_collection_insert_one ( + coll, tmp_bson ("{'encrypted_string': 'abc'}"), NULL /* opts */, NULL /* reply */, &error); ASSERT_OR_PRINT (ret, error); mongoc_collection_destroy (coll); } @@ -2257,14 +1952,12 @@ test_invalid_single_and_pool_mismatches (void *unused) _reset (&pool, &single_threaded_client, &multi_threaded_client, &opts, true); /* single threaded client, single threaded setter => ok */ - ret = mongoc_client_enable_auto_encryption ( - single_threaded_client, opts, &error); + ret = mongoc_client_enable_auto_encryption (single_threaded_client, opts, &error); ASSERT_OR_PRINT (ret, error); _perform_op (single_threaded_client); /* multi threaded client, single threaded setter => bad */ - ret = mongoc_client_enable_auto_encryption ( - multi_threaded_client, opts, &error); + ret = mongoc_client_enable_auto_encryption (multi_threaded_client, opts, &error); BSON_ASSERT (!ret); ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_CLIENT, @@ -2278,19 +1971,15 @@ test_invalid_single_and_pool_mismatches (void *unused) /* single threaded client, single threaded key vault client => ok */ _reset (&pool, &single_threaded_client, &multi_threaded_client, &opts, true); - mongoc_auto_encryption_opts_set_keyvault_client (opts, - single_threaded_client); - ret = mongoc_client_enable_auto_encryption ( - single_threaded_client, opts, &error); + mongoc_auto_encryption_opts_set_keyvault_client (opts, single_threaded_client); + ret = mongoc_client_enable_auto_encryption (single_threaded_client, opts, &error); ASSERT_OR_PRINT (ret, error); _perform_op (single_threaded_client); /* single threaded client, multi threaded key vault client => bad */ _reset (&pool, &single_threaded_client, &multi_threaded_client, &opts, true); - mongoc_auto_encryption_opts_set_keyvault_client (opts, - multi_threaded_client); - ret = mongoc_client_enable_auto_encryption ( - single_threaded_client, opts, &error); + mongoc_auto_encryption_opts_set_keyvault_client (opts, multi_threaded_client); + ret = mongoc_client_enable_auto_encryption (single_threaded_client, opts, &error); BSON_ASSERT (!ret); ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_CLIENT, @@ -2301,8 +1990,7 @@ test_invalid_single_and_pool_mismatches (void *unused) /* single threaded client, pool key vault client => bad */ _reset (&pool, &single_threaded_client, &multi_threaded_client, &opts, true); mongoc_auto_encryption_opts_set_keyvault_client_pool (opts, pool); - ret = mongoc_client_enable_auto_encryption ( - single_threaded_client, opts, &error); + ret = mongoc_client_enable_auto_encryption (single_threaded_client, opts, &error); BSON_ASSERT (!ret); ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_CLIENT, @@ -2312,8 +2000,7 @@ test_invalid_single_and_pool_mismatches (void *unused) /* pool, singled threaded key vault client => bad */ _reset (&pool, &single_threaded_client, &multi_threaded_client, &opts, true); - mongoc_auto_encryption_opts_set_keyvault_client (opts, - single_threaded_client); + mongoc_auto_encryption_opts_set_keyvault_client (opts, single_threaded_client); ret = mongoc_client_pool_enable_auto_encryption (pool, opts, &error); BSON_ASSERT (!ret); ASSERT_ERROR_CONTAINS (error, @@ -2325,8 +2012,7 @@ test_invalid_single_and_pool_mismatches (void *unused) /* pool, multi threaded key vault client => bad */ _reset (&pool, &single_threaded_client, &multi_threaded_client, &opts, true); - mongoc_auto_encryption_opts_set_keyvault_client (opts, - multi_threaded_client); + mongoc_auto_encryption_opts_set_keyvault_client (opts, multi_threaded_client); ret = mongoc_client_pool_enable_auto_encryption (pool, opts, &error); BSON_ASSERT (!ret); ASSERT_ERROR_CONTAINS (error, @@ -2345,31 +2031,23 @@ test_invalid_single_and_pool_mismatches (void *unused) /* double enabling */ _reset (&pool, &single_threaded_client, &multi_threaded_client, &opts, true); - ret = mongoc_client_enable_auto_encryption ( - single_threaded_client, opts, &error); + ret = mongoc_client_enable_auto_encryption (single_threaded_client, opts, &error); ASSERT_OR_PRINT (ret, error); - ret = mongoc_client_enable_auto_encryption ( - single_threaded_client, opts, &error); + ret = mongoc_client_enable_auto_encryption (single_threaded_client, opts, &error); BSON_ASSERT (!ret); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_CLIENT, - MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE, - "Automatic encryption already set"); + ASSERT_ERROR_CONTAINS ( + error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE, "Automatic encryption already set"); ret = mongoc_client_pool_enable_auto_encryption (pool, opts, &error); ASSERT_OR_PRINT (ret, error); ret = mongoc_client_pool_enable_auto_encryption (pool, opts, &error); BSON_ASSERT (!ret); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_CLIENT, - MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE, - "Automatic encryption already set"); + ASSERT_ERROR_CONTAINS ( + error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_STATE, "Automatic encryption already set"); /* single threaded, using self as key vault client => redundant, but ok */ _reset (&pool, &single_threaded_client, &multi_threaded_client, &opts, true); - mongoc_auto_encryption_opts_set_keyvault_client (opts, - single_threaded_client); - ret = mongoc_client_enable_auto_encryption ( - single_threaded_client, opts, &error); + mongoc_auto_encryption_opts_set_keyvault_client (opts, single_threaded_client); + ret = mongoc_client_enable_auto_encryption (single_threaded_client, opts, &error); ASSERT_OR_PRINT (ret, error); _perform_op (single_threaded_client); @@ -2380,8 +2058,7 @@ test_invalid_single_and_pool_mismatches (void *unused) ASSERT_OR_PRINT (ret, error); _perform_op_pooled (pool); - _reset ( - &pool, &single_threaded_client, &multi_threaded_client, &opts, false); + _reset (&pool, &single_threaded_client, &multi_threaded_client, &opts, false); mongoc_auto_encryption_opts_destroy (opts); } @@ -2401,11 +2078,9 @@ static BSON_THREAD_FUN (_worker_thread, client_ptr) coll = mongoc_client_get_collection (client_encrypted, "db", "coll"); for (i = 0; i < 100; i++) { - ret = mongoc_collection_insert_one ( - coll, to_insert, NULL /* opts */, NULL /* reply */, &error); + ret = mongoc_collection_insert_one (coll, to_insert, NULL /* opts */, NULL /* reply */, &error); ASSERT_OR_PRINT (ret, error); - cursor = mongoc_collection_find_with_opts ( - coll, &filter, NULL /* opts */, NULL /* read_prefs */); + cursor = mongoc_collection_find_with_opts (coll, &filter, NULL /* opts */, NULL /* read_prefs */); mongoc_cursor_next (cursor, &doc); mongoc_cursor_destroy (cursor); } @@ -2447,16 +2122,12 @@ _test_multi_threaded (bool external_key_vault) /* Do setup: create a data key and configure pool for auto encryption. */ coll = mongoc_client_get_collection (client, "db", "keyvault"); (void) mongoc_collection_drop (coll, NULL); - datakey = get_bson_from_json_file ( - "./src/libmongoc/tests/client_side_encryption_prose/limits-key.json"); + datakey = get_bson_from_json_file ("./src/libmongoc/tests/client_side_encryption_prose/limits-key.json"); BSON_ASSERT (datakey); wc = mongoc_write_concern_new (); mongoc_write_concern_set_wmajority (wc, 1000); mongoc_collection_set_write_concern (coll, wc); - ASSERT_OR_PRINT ( - mongoc_collection_insert_one ( - coll, datakey, NULL /* opts */, NULL /* reply */, &error), - error); + ASSERT_OR_PRINT (mongoc_collection_insert_one (coll, datakey, NULL /* opts */, NULL /* reply */, &error), error); /* create pool with auto encryption */ _check_bypass (opts); @@ -2469,8 +2140,7 @@ _test_multi_threaded (bool external_key_vault) mongoc_auto_encryption_opts_set_keyvault_client_pool (opts, pool); } - schema = get_bson_from_json_file ( - "./src/libmongoc/tests/client_side_encryption_prose/schema.json"); + schema = get_bson_from_json_file ("./src/libmongoc/tests/client_side_encryption_prose/schema.json"); BSON_ASSERT (schema); schema_map = BCON_NEW ("db.coll", BCON_DOCUMENT (schema)); mongoc_auto_encryption_opts_set_schema_map (opts, schema_map); @@ -2534,21 +2204,16 @@ test_malformed_explicit (void *unused) /* Create a ClientEncryption object */ client_encryption_opts = mongoc_client_encryption_opts_new (); - mongoc_client_encryption_opts_set_kms_providers (client_encryption_opts, - kms_providers); - mongoc_client_encryption_opts_set_keyvault_namespace ( - client_encryption_opts, "keyvault", "datakeys"); - mongoc_client_encryption_opts_set_keyvault_client (client_encryption_opts, - client); - client_encryption = - mongoc_client_encryption_new (client_encryption_opts, &error); + mongoc_client_encryption_opts_set_kms_providers (client_encryption_opts, kms_providers); + mongoc_client_encryption_opts_set_keyvault_namespace (client_encryption_opts, "keyvault", "datakeys"); + mongoc_client_encryption_opts_set_keyvault_client (client_encryption_opts, client); + client_encryption = mongoc_client_encryption_new (client_encryption_opts, &error); ASSERT_OR_PRINT (client_encryption, error); /* Test attempting to decrypt a malformed value */ ciphertext.value_type = BSON_TYPE_DOUBLE; ciphertext.value.v_double = 1.23; - ret = mongoc_client_encryption_decrypt ( - client_encryption, &ciphertext, &value, &error); + ret = mongoc_client_encryption_decrypt (client_encryption, &ciphertext, &value, &error); BSON_ASSERT (!ret); bson_value_destroy (&value); @@ -2569,12 +2234,10 @@ _check_mongocryptd_not_spawned (void) /* Set up client. */ { mongoc_uri_t *uri = mongoc_uri_new ("mongodb://localhost:27021"); - ASSERT (mongoc_uri_set_option_as_int32 ( - uri, MONGOC_URI_SERVERSELECTIONTIMEOUTMS, 1000)); + ASSERT (mongoc_uri_set_option_as_int32 (uri, MONGOC_URI_SERVERSELECTIONTIMEOUTMS, 1000)); /* Set SERVERSELECTIONTRYONCE to false so client will wait for the full * second before giving up on server selection. */ - ASSERT (mongoc_uri_set_option_as_bool ( - uri, MONGOC_URI_SERVERSELECTIONTRYONCE, false)); + ASSERT (mongoc_uri_set_option_as_bool (uri, MONGOC_URI_SERVERSELECTIONTRYONCE, false)); client = mongoc_client_new_from_uri (uri); /* Bypass the 5 second cooldown so attempts to connect are repeated. @@ -2585,13 +2248,10 @@ _check_mongocryptd_not_spawned (void) mongoc_uri_destroy (uri); } cmd = BCON_NEW (HANDSHAKE_CMD_LEGACY_HELLO, BCON_INT32 (1)); - ret = mongoc_client_command_simple ( - client, "keyvault", cmd, NULL /* read prefs */, NULL /* reply */, &error); + ret = mongoc_client_command_simple (client, "keyvault", cmd, NULL /* read prefs */, NULL /* reply */, &error); BSON_ASSERT (!ret); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_SERVER_SELECTION, - MONGOC_ERROR_SERVER_SELECTION_FAILURE, - "No suitable servers"); + ASSERT_ERROR_CONTAINS ( + error, MONGOC_ERROR_SERVER_SELECTION, MONGOC_ERROR_SERVER_SELECTION_FAILURE, "No suitable servers"); mongoc_client_destroy (client); bson_destroy (cmd); } @@ -2615,10 +2275,8 @@ test_bypass_spawning_via_mongocryptdBypassSpawn (void *unused) auto_encryption_opts = mongoc_auto_encryption_opts_new (); kms_providers = _make_kms_providers (false /* aws */, true /* local */); - mongoc_auto_encryption_opts_set_kms_providers (auto_encryption_opts, - kms_providers); - mongoc_auto_encryption_opts_set_keyvault_namespace ( - auto_encryption_opts, "keyvault", "datakeys"); + mongoc_auto_encryption_opts_set_kms_providers (auto_encryption_opts, kms_providers); + mongoc_auto_encryption_opts_set_keyvault_namespace (auto_encryption_opts, "keyvault", "datakeys"); schema = get_bson_from_json_file ("./src/libmongoc/tests/" "client_side_encryption_prose/external/" "external-schema.json"); @@ -2626,30 +2284,26 @@ test_bypass_spawning_via_mongocryptdBypassSpawn (void *unused) /* Create a MongoClient with encryption enabled */ client_encrypted = test_framework_new_default_client (); - extra = - BCON_NEW ("mongocryptdBypassSpawn", - BCON_BOOL (true), - "mongocryptdSpawnArgs", - "[", - "--pidfilepath=bypass-spawning-mongocryptd.pid", - "--port=27021", - "]", - "mongocryptdURI", - "mongodb://localhost:27021/?serverSelectionTimeoutMS=1000"); + extra = BCON_NEW ("mongocryptdBypassSpawn", + BCON_BOOL (true), + "mongocryptdSpawnArgs", + "[", + "--pidfilepath=bypass-spawning-mongocryptd.pid", + "--port=27021", + "]", + "mongocryptdURI", + "mongodb://localhost:27021/?serverSelectionTimeoutMS=1000"); mongoc_auto_encryption_opts_set_extra (auto_encryption_opts, extra); - mongoc_auto_encryption_opts_set_schema_map (auto_encryption_opts, - schema_map); + mongoc_auto_encryption_opts_set_schema_map (auto_encryption_opts, schema_map); bson_destroy (extra); - ret = mongoc_client_enable_auto_encryption ( - client_encrypted, auto_encryption_opts, &error); + ret = mongoc_client_enable_auto_encryption (client_encrypted, auto_encryption_opts, &error); ASSERT_OR_PRINT (ret, error); /* Insert { 'encrypt': 'test' }. Should fail with a server selection error. */ coll = mongoc_client_get_collection (client_encrypted, "db", "coll"); doc_to_insert = BCON_NEW ("encrypt", "test"); - ret = mongoc_collection_insert_one ( - coll, doc_to_insert, NULL /* opts */, NULL /* reply */, &error); + ret = mongoc_collection_insert_one (coll, doc_to_insert, NULL /* opts */, NULL /* reply */, &error); BSON_ASSERT (!ret); ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_SERVER_SELECTION, @@ -2681,67 +2335,49 @@ test_bypass_spawning_via_helper (const char *auto_encryption_opt) auto_encryption_opts = mongoc_auto_encryption_opts_new (); kms_providers = _make_kms_providers (false /* aws */, true /* local */); - mongoc_auto_encryption_opts_set_kms_providers (auto_encryption_opts, - kms_providers); - mongoc_auto_encryption_opts_set_keyvault_namespace ( - auto_encryption_opts, "keyvault", "datakeys"); + mongoc_auto_encryption_opts_set_kms_providers (auto_encryption_opts, kms_providers); + mongoc_auto_encryption_opts_set_keyvault_namespace (auto_encryption_opts, "keyvault", "datakeys"); if (0 == strcmp (auto_encryption_opt, "bypass_auto_encryption")) { - mongoc_auto_encryption_opts_set_bypass_auto_encryption ( - auto_encryption_opts, true); + mongoc_auto_encryption_opts_set_bypass_auto_encryption (auto_encryption_opts, true); } else if (0 == strcmp (auto_encryption_opt, "bypass_query_analysis")) { - mongoc_auto_encryption_opts_set_bypass_query_analysis ( - auto_encryption_opts, true); + mongoc_auto_encryption_opts_set_bypass_query_analysis (auto_encryption_opts, true); } else if (0 == strcmp (auto_encryption_opt, "cryptSharedLibRequired")) { - bson_t *schema = - get_bson_from_json_file ("./src/libmongoc/tests/" - "client_side_encryption_prose/external/" - "external-schema.json"); + bson_t *schema = get_bson_from_json_file ("./src/libmongoc/tests/" + "client_side_encryption_prose/external/" + "external-schema.json"); BSON_ASSERT (schema); bson_t *schema_map = BCON_NEW ("db.coll", BCON_DOCUMENT (schema)); - mongoc_auto_encryption_opts_set_schema_map (auto_encryption_opts, - schema_map); + mongoc_auto_encryption_opts_set_schema_map (auto_encryption_opts, schema_map); check_crypt_shared = true; - char *env_cryptSharedLibPath = - test_framework_getenv ("MONGOC_TEST_CRYPT_SHARED_LIB_PATH"); + char *env_cryptSharedLibPath = test_framework_getenv ("MONGOC_TEST_CRYPT_SHARED_LIB_PATH"); BSON_ASSERT (env_cryptSharedLibPath); BSON_APPEND_UTF8 (extra, "cryptSharedLibPath", env_cryptSharedLibPath); BSON_APPEND_BOOL (extra, "cryptSharedLibRequired", true); - BSON_APPEND_UTF8 ( - extra, - "mongocryptdURI", - "mongodb://localhost:27021/db?serverSelectionTimeoutMS=1000"); + BSON_APPEND_UTF8 (extra, "mongocryptdURI", "mongodb://localhost:27021/db?serverSelectionTimeoutMS=1000"); bson_free (env_cryptSharedLibPath); bson_destroy (schema); bson_destroy (schema_map); } else { - test_error ("Unexpected 'auto_encryption_opt' argument: %s", - auto_encryption_opt); + test_error ("Unexpected 'auto_encryption_opt' argument: %s", auto_encryption_opt); } /* Create a MongoClient with encryption enabled */ client_encrypted = test_framework_new_default_client (); - BCON_APPEND (extra, - "mongocryptdSpawnArgs", - "[", - "--pidfilepath=bypass-spawning-mongocryptd.pid", - "--port=27021", - "]"); + BCON_APPEND ( + extra, "mongocryptdSpawnArgs", "[", "--pidfilepath=bypass-spawning-mongocryptd.pid", "--port=27021", "]"); mongoc_auto_encryption_opts_set_extra (auto_encryption_opts, extra); bson_destroy (extra); - ret = mongoc_client_enable_auto_encryption ( - client_encrypted, auto_encryption_opts, &error); + ret = mongoc_client_enable_auto_encryption (client_encrypted, auto_encryption_opts, &error); ASSERT_OR_PRINT (ret, error); if (check_crypt_shared) { - BSON_ASSERT (mongoc_client_get_crypt_shared_version (client_encrypted) != - NULL); + BSON_ASSERT (mongoc_client_get_crypt_shared_version (client_encrypted) != NULL); } /* Insert { 'unencrypted': 'test' }. Should succeed. */ coll = mongoc_client_get_collection (client_encrypted, "db", "coll"); doc_to_insert = BCON_NEW ("unencrypted", "test"); - ret = mongoc_collection_insert_one ( - coll, doc_to_insert, NULL /* opts */, NULL /* reply */, &error); + ret = mongoc_collection_insert_one (coll, doc_to_insert, NULL /* opts */, NULL /* reply */, &error); ASSERT_OR_PRINT (ret, error); _check_mongocryptd_not_spawned (); @@ -2791,48 +2427,39 @@ _skip_if_no_crypt_shared (void) } static mongoc_client_encryption_t * -_make_kms_certificate_client_encryption (mongoc_client_t *client, - bson_error_t *error) +_make_kms_certificate_client_encryption (mongoc_client_t *client, bson_error_t *error) { mongoc_client_encryption_t *client_encryption; ASSERT (client); - mongoc_client_encryption_opts_t *client_encryption_opts = - mongoc_client_encryption_opts_new (); + mongoc_client_encryption_opts_t *client_encryption_opts = mongoc_client_encryption_opts_new (); { bson_t *kms_providers = _make_aws_kms_provider (NULL); - mongoc_client_encryption_opts_set_kms_providers (client_encryption_opts, - kms_providers); + mongoc_client_encryption_opts_set_kms_providers (client_encryption_opts, kms_providers); bson_destroy (kms_providers); } { - char *tls_ca_file = - test_framework_getenv_required ("MONGOC_TEST_CSFLE_TLS_CA_FILE"); - char *tls_cert_key_file = test_framework_getenv_required ( - "MONGOC_TEST_CSFLE_TLS_CERTIFICATE_KEY_FILE"); + char *tls_ca_file = test_framework_getenv_required ("MONGOC_TEST_CSFLE_TLS_CA_FILE"); + char *tls_cert_key_file = test_framework_getenv_required ("MONGOC_TEST_CSFLE_TLS_CERTIFICATE_KEY_FILE"); bson_t *tls_opts = tmp_bson ("{ 'aws': { '%s': '%s', '%s': '%s' } }", MONGOC_URI_TLSCAFILE, tls_ca_file, MONGOC_URI_TLSCERTIFICATEKEYFILE, tls_cert_key_file); - mongoc_client_encryption_opts_set_tls_opts (client_encryption_opts, - tls_opts); + mongoc_client_encryption_opts_set_tls_opts (client_encryption_opts, tls_opts); bson_free (tls_cert_key_file); bson_free (tls_ca_file); } - mongoc_client_encryption_opts_set_keyvault_namespace ( - client_encryption_opts, "keyvault", "datakeys"); - mongoc_client_encryption_opts_set_keyvault_client (client_encryption_opts, - client); + mongoc_client_encryption_opts_set_keyvault_namespace (client_encryption_opts, "keyvault", "datakeys"); + mongoc_client_encryption_opts_set_keyvault_client (client_encryption_opts, client); - client_encryption = - mongoc_client_encryption_new (client_encryption_opts, error); + client_encryption = mongoc_client_encryption_new (client_encryption_opts, error); ASSERT_OR_PRINT (client_encryption, (*error)); mongoc_client_encryption_opts_destroy (client_encryption_opts); @@ -2852,23 +2479,17 @@ test_kms_tls_cert_valid (void *unused) mongoc_ssl_opt_t ssl_opts; mongoc_stream_t *tls_stream; - char *tls_ca_file = - test_framework_getenv_required ("MONGOC_TEST_CSFLE_TLS_CA_FILE"); - char *tls_cert_key_file = test_framework_getenv_required ( - "MONGOC_TEST_CSFLE_TLS_CERTIFICATE_KEY_FILE"); + char *tls_ca_file = test_framework_getenv_required ("MONGOC_TEST_CSFLE_TLS_CA_FILE"); + char *tls_cert_key_file = test_framework_getenv_required ("MONGOC_TEST_CSFLE_TLS_CERTIFICATE_KEY_FILE"); BSON_UNUSED (unused); #if defined(MONGOC_ENABLE_SSL_SECURE_CHANNEL) /* Certificate verification fails with Secure Channel given * "127.0.0.1:8999" with error: "hostname doesn't match certificate". */ - ASSERT_OR_PRINT ( - _mongoc_host_list_from_string_with_err (&host, "localhost:8999", &error), - error); + ASSERT_OR_PRINT (_mongoc_host_list_from_string_with_err (&host, "localhost:8999", &error), error); #else - ASSERT_OR_PRINT ( - _mongoc_host_list_from_string_with_err (&host, "127.0.0.1:8999", &error), - error); + ASSERT_OR_PRINT (_mongoc_host_list_from_string_with_err (&host, "127.0.0.1:8999", &error), error); #endif base_stream = mongoc_client_connect_tcp (connecttimeoutms, &host, &error); @@ -2878,12 +2499,9 @@ test_kms_tls_cert_valid (void *unused) ssl_opts.ca_file = tls_ca_file; ssl_opts.pem_file = tls_cert_key_file; - tls_stream = mongoc_stream_tls_new_with_hostname ( - base_stream, host.host, &ssl_opts, is_client); + tls_stream = mongoc_stream_tls_new_with_hostname (base_stream, host.host, &ssl_opts, is_client); - ASSERT_OR_PRINT (mongoc_stream_tls_handshake_block ( - tls_stream, host.host, connecttimeoutms, &error), - error); + ASSERT_OR_PRINT (mongoc_stream_tls_handshake_block (tls_stream, host.host, connecttimeoutms, &error), error); mongoc_stream_destroy (tls_stream); /* Also destroys base_stream. */ @@ -2903,23 +2521,19 @@ test_kms_tls_cert_expired (void *unused) mongoc_client_t *client = test_framework_new_default_client (); - mongoc_client_encryption_t *client_encryption = - _make_kms_certificate_client_encryption (client, &error); + mongoc_client_encryption_t *client_encryption = _make_kms_certificate_client_encryption (client, &error); - mongoc_client_encryption_datakey_opts_t *opts = - mongoc_client_encryption_datakey_opts_new (); + mongoc_client_encryption_datakey_opts_t *opts = mongoc_client_encryption_datakey_opts_new (); BSON_UNUSED (unused); - mongoc_client_encryption_datakey_opts_set_masterkey ( - opts, - tmp_bson ("{ 'region': 'us-east-1', 'key': " - "'arn:aws:kms:us-east-1:579766882180:key/" - "89fcc2c4-08b0-4bd9-9f25-e30687b580d0', " - "'endpoint': '127.0.0.1:9000' }")); + mongoc_client_encryption_datakey_opts_set_masterkey (opts, + tmp_bson ("{ 'region': 'us-east-1', 'key': " + "'arn:aws:kms:us-east-1:579766882180:key/" + "89fcc2c4-08b0-4bd9-9f25-e30687b580d0', " + "'endpoint': '127.0.0.1:9000' }")); - ret = mongoc_client_encryption_create_datakey ( - client_encryption, "aws", opts, &keyid, &error); + ret = mongoc_client_encryption_create_datakey (client_encryption, "aws", opts, &keyid, &error); BSON_ASSERT (!ret); @@ -2951,23 +2565,19 @@ test_kms_tls_cert_wrong_host (void *unused) mongoc_client_t *client = test_framework_new_default_client (); - mongoc_client_encryption_t *client_encryption = - _make_kms_certificate_client_encryption (client, &error); + mongoc_client_encryption_t *client_encryption = _make_kms_certificate_client_encryption (client, &error); - mongoc_client_encryption_datakey_opts_t *opts = - mongoc_client_encryption_datakey_opts_new (); + mongoc_client_encryption_datakey_opts_t *opts = mongoc_client_encryption_datakey_opts_new (); BSON_UNUSED (unused); - mongoc_client_encryption_datakey_opts_set_masterkey ( - opts, - tmp_bson ("{ 'region': 'us-east-1', 'key': " - "'arn:aws:kms:us-east-1:579766882180:key/" - "89fcc2c4-08b0-4bd9-9f25-e30687b580d0', " - "'endpoint': '127.0.0.1:9001' }")); + mongoc_client_encryption_datakey_opts_set_masterkey (opts, + tmp_bson ("{ 'region': 'us-east-1', 'key': " + "'arn:aws:kms:us-east-1:579766882180:key/" + "89fcc2c4-08b0-4bd9-9f25-e30687b580d0', " + "'endpoint': '127.0.0.1:9001' }")); - ret = mongoc_client_encryption_create_datakey ( - client_encryption, "aws", opts, &keyid, &error); + ret = mongoc_client_encryption_create_datakey (client_encryption, "aws", opts, &keyid, &error); BSON_ASSERT (!ret); @@ -2986,17 +2596,10 @@ test_kms_tls_cert_wrong_host (void *unused) mongoc_client_destroy (client); } -typedef enum { - NO_CLIENT_CERT, - WITH_TLS, - INVALID_HOSTNAME, - EXPIRED, - WITH_NAMES -} tls_test_ce_t; +typedef enum { NO_CLIENT_CERT, WITH_TLS, INVALID_HOSTNAME, EXPIRED, WITH_NAMES } tls_test_ce_t; static mongoc_client_encryption_t * -_tls_test_make_client_encryption (mongoc_client_t *keyvault_client, - tls_test_ce_t test_ce) +_tls_test_make_client_encryption (mongoc_client_t *keyvault_client, tls_test_ce_t test_ce) { bson_t *kms_providers; mongoc_client_encryption_opts_t *client_encryption_opts; @@ -3006,35 +2609,23 @@ _tls_test_make_client_encryption (mongoc_client_t *keyvault_client, ASSERT (keyvault_client); - char *mongoc_test_aws_access_key_id = - test_framework_getenv_required ("MONGOC_TEST_AWS_ACCESS_KEY_ID"); - char *mongoc_test_aws_secret_access_key = - test_framework_getenv_required ("MONGOC_TEST_AWS_SECRET_ACCESS_KEY"); - char *mongoc_test_azure_tenant_id = - test_framework_getenv_required ("MONGOC_TEST_AZURE_TENANT_ID"); - char *mongoc_test_azure_client_id = - test_framework_getenv_required ("MONGOC_TEST_AZURE_CLIENT_ID"); - char *mongoc_test_azure_client_secret = - test_framework_getenv_required ("MONGOC_TEST_AZURE_CLIENT_SECRET"); - char *mongoc_test_gcp_email = - test_framework_getenv_required ("MONGOC_TEST_GCP_EMAIL"); - char *mongoc_test_gcp_privatekey = - test_framework_getenv_required ("MONGOC_TEST_GCP_PRIVATEKEY"); - char *ca_file = - test_framework_getenv_required ("MONGOC_TEST_CSFLE_TLS_CA_FILE"); - char *certificate_key_file = test_framework_getenv_required ( - "MONGOC_TEST_CSFLE_TLS_CERTIFICATE_KEY_FILE"); + char *mongoc_test_aws_access_key_id = test_framework_getenv_required ("MONGOC_TEST_AWS_ACCESS_KEY_ID"); + char *mongoc_test_aws_secret_access_key = test_framework_getenv_required ("MONGOC_TEST_AWS_SECRET_ACCESS_KEY"); + char *mongoc_test_azure_tenant_id = test_framework_getenv_required ("MONGOC_TEST_AZURE_TENANT_ID"); + char *mongoc_test_azure_client_id = test_framework_getenv_required ("MONGOC_TEST_AZURE_CLIENT_ID"); + char *mongoc_test_azure_client_secret = test_framework_getenv_required ("MONGOC_TEST_AZURE_CLIENT_SECRET"); + char *mongoc_test_gcp_email = test_framework_getenv_required ("MONGOC_TEST_GCP_EMAIL"); + char *mongoc_test_gcp_privatekey = test_framework_getenv_required ("MONGOC_TEST_GCP_PRIVATEKEY"); + char *ca_file = test_framework_getenv_required ("MONGOC_TEST_CSFLE_TLS_CA_FILE"); + char *certificate_key_file = test_framework_getenv_required ("MONGOC_TEST_CSFLE_TLS_CERTIFICATE_KEY_FILE"); if (test_ce == WITH_TLS) { - kms_providers = - tmp_bson ("{'aws': {'accessKeyId': '%s', 'secretAccessKey': '%s' }}", - mongoc_test_aws_access_key_id, - mongoc_test_aws_secret_access_key); - - tls_opts = tmp_bson ( - "{'aws': {'tlsCaFile': '%s', 'tlsCertificateKeyFile': '%s' }}", - ca_file, - certificate_key_file); + kms_providers = tmp_bson ("{'aws': {'accessKeyId': '%s', 'secretAccessKey': '%s' }}", + mongoc_test_aws_access_key_id, + mongoc_test_aws_secret_access_key); + + tls_opts = + tmp_bson ("{'aws': {'tlsCaFile': '%s', 'tlsCertificateKeyFile': '%s' }}", ca_file, certificate_key_file); bson_concat (kms_providers, tmp_bson ("{'azure': {'tenantId': '%s', 'clientId': '%s', " "'clientSecret': '%s', " @@ -3044,10 +2635,7 @@ _tls_test_make_client_encryption (mongoc_client_t *keyvault_client, mongoc_test_azure_client_secret)); bson_concat ( tls_opts, - tmp_bson ( - "{'azure': {'tlsCaFile': '%s', 'tlsCertificateKeyFile': '%s' }}", - ca_file, - certificate_key_file)); + tmp_bson ("{'azure': {'tlsCaFile': '%s', 'tlsCertificateKeyFile': '%s' }}", ca_file, certificate_key_file)); bson_concat (kms_providers, tmp_bson ("{'gcp': { 'email': '%s', 'privateKey': '%s', " @@ -3056,24 +2644,16 @@ _tls_test_make_client_encryption (mongoc_client_t *keyvault_client, mongoc_test_gcp_privatekey)); bson_concat ( tls_opts, - tmp_bson ( - "{'gcp': {'tlsCaFile': '%s', 'tlsCertificateKeyFile': '%s' }}", - ca_file, - certificate_key_file)); + tmp_bson ("{'gcp': {'tlsCaFile': '%s', 'tlsCertificateKeyFile': '%s' }}", ca_file, certificate_key_file)); - bson_concat (kms_providers, - tmp_bson ("{'kmip': { 'endpoint': '127.0.0.1:5698'}}")); + bson_concat (kms_providers, tmp_bson ("{'kmip': { 'endpoint': '127.0.0.1:5698'}}")); bson_concat ( tls_opts, - tmp_bson ( - "{'kmip': {'tlsCaFile': '%s', 'tlsCertificateKeyFile': '%s' }}", - ca_file, - certificate_key_file)); + tmp_bson ("{'kmip': {'tlsCaFile': '%s', 'tlsCertificateKeyFile': '%s' }}", ca_file, certificate_key_file)); } else if (test_ce == NO_CLIENT_CERT) { - kms_providers = - tmp_bson ("{'aws': {'accessKeyId': '%s', 'secretAccessKey': '%s' }}", - mongoc_test_aws_access_key_id, - mongoc_test_aws_secret_access_key); + kms_providers = tmp_bson ("{'aws': {'accessKeyId': '%s', 'secretAccessKey': '%s' }}", + mongoc_test_aws_access_key_id, + mongoc_test_aws_secret_access_key); bson_concat (kms_providers, tmp_bson ("{'azure': {'tenantId': '%s', 'clientId': '%s', " "'clientSecret': '%s', " @@ -3086,13 +2666,11 @@ _tls_test_make_client_encryption (mongoc_client_t *keyvault_client, "'endpoint': '127.0.0.1:9002'}}", mongoc_test_gcp_email, mongoc_test_gcp_privatekey)); - bson_concat (kms_providers, - tmp_bson ("{'kmip': { 'endpoint': '127.0.0.1:5698' }}")); + bson_concat (kms_providers, tmp_bson ("{'kmip': { 'endpoint': '127.0.0.1:5698' }}")); } else if (test_ce == EXPIRED) { - kms_providers = - tmp_bson ("{'aws': {'accessKeyId': '%s', 'secretAccessKey': '%s' }}", - mongoc_test_aws_access_key_id, - mongoc_test_aws_secret_access_key); + kms_providers = tmp_bson ("{'aws': {'accessKeyId': '%s', 'secretAccessKey': '%s' }}", + mongoc_test_aws_access_key_id, + mongoc_test_aws_secret_access_key); tls_opts = tmp_bson ("{'aws': {'tlsCaFile': '%s'} }", ca_file); bson_concat (kms_providers, @@ -3102,26 +2680,21 @@ _tls_test_make_client_encryption (mongoc_client_t *keyvault_client, mongoc_test_azure_tenant_id, mongoc_test_azure_client_id, mongoc_test_azure_client_secret)); - bson_concat (tls_opts, - tmp_bson ("{'azure': {'tlsCaFile': '%s'} }", ca_file)); + bson_concat (tls_opts, tmp_bson ("{'azure': {'tlsCaFile': '%s'} }", ca_file)); bson_concat (kms_providers, tmp_bson ("{'gcp': { 'email': '%s', 'privateKey': '%s', " "'endpoint': '127.0.0.1:9000'}}", mongoc_test_gcp_email, mongoc_test_gcp_privatekey)); - bson_concat (tls_opts, - tmp_bson ("{'gcp': {'tlsCaFile': '%s'} }", ca_file)); + bson_concat (tls_opts, tmp_bson ("{'gcp': {'tlsCaFile': '%s'} }", ca_file)); - bson_concat (kms_providers, - tmp_bson ("{'kmip': { 'endpoint': '127.0.0.1:9000' }}")); - bson_concat (tls_opts, - tmp_bson ("{'kmip': {'tlsCaFile': '%s'} }", ca_file)); + bson_concat (kms_providers, tmp_bson ("{'kmip': { 'endpoint': '127.0.0.1:9000' }}")); + bson_concat (tls_opts, tmp_bson ("{'kmip': {'tlsCaFile': '%s'} }", ca_file)); } else if (test_ce == INVALID_HOSTNAME) { - kms_providers = - tmp_bson ("{'aws': {'accessKeyId': '%s', 'secretAccessKey': '%s' } }", - mongoc_test_aws_access_key_id, - mongoc_test_aws_secret_access_key); + kms_providers = tmp_bson ("{'aws': {'accessKeyId': '%s', 'secretAccessKey': '%s' } }", + mongoc_test_aws_access_key_id, + mongoc_test_aws_secret_access_key); tls_opts = tmp_bson ("{'aws': {'tlsCaFile': '%s'} }", ca_file); bson_concat (kms_providers, @@ -3131,104 +2704,80 @@ _tls_test_make_client_encryption (mongoc_client_t *keyvault_client, mongoc_test_azure_tenant_id, mongoc_test_azure_client_id, mongoc_test_azure_client_secret)); - bson_concat (tls_opts, - tmp_bson ("{'azure': {'tlsCaFile': '%s'} }", ca_file)); + bson_concat (tls_opts, tmp_bson ("{'azure': {'tlsCaFile': '%s'} }", ca_file)); bson_concat (kms_providers, tmp_bson ("{'gcp': { 'email': '%s', 'privateKey': '%s', " "'endpoint': '127.0.0.1:9001' }}", mongoc_test_gcp_email, mongoc_test_gcp_privatekey)); - bson_concat (tls_opts, - tmp_bson ("{'gcp': {'tlsCaFile': '%s'} }", ca_file)); + bson_concat (tls_opts, tmp_bson ("{'gcp': {'tlsCaFile': '%s'} }", ca_file)); - bson_concat (kms_providers, - tmp_bson ("{'kmip': { 'endpoint': '127.0.0.1:9001' }}")); - bson_concat (tls_opts, - tmp_bson ("{'kmip': {'tlsCaFile': '%s'} }", ca_file)); + bson_concat (kms_providers, tmp_bson ("{'kmip': { 'endpoint': '127.0.0.1:9001' }}")); + bson_concat (tls_opts, tmp_bson ("{'kmip': {'tlsCaFile': '%s'} }", ca_file)); } else if (test_ce == WITH_NAMES) { kms_providers = tmp_bson ("{'aws:no_client_cert': {'accessKeyId': '%s', " "'secretAccessKey': '%s' }}", mongoc_test_aws_access_key_id, mongoc_test_aws_secret_access_key); - tls_opts = - tmp_bson ("{'aws:no_client_cert': {'tlsCaFile': '%s' }}", ca_file); + tls_opts = tmp_bson ("{'aws:no_client_cert': {'tlsCaFile': '%s' }}", ca_file); - bson_concat ( - kms_providers, - tmp_bson ( - "{'aws:with_tls': {'accessKeyId': '%s', 'secretAccessKey': '%s' }}", - mongoc_test_aws_access_key_id, - mongoc_test_aws_secret_access_key)); + bson_concat (kms_providers, + tmp_bson ("{'aws:with_tls': {'accessKeyId': '%s', 'secretAccessKey': '%s' }}", + mongoc_test_aws_access_key_id, + mongoc_test_aws_secret_access_key)); bson_concat (tls_opts, tmp_bson ("{'aws:with_tls': {'tlsCaFile': '%s', " "'tlsCertificateKeyFile': '%s' }}", ca_file, certificate_key_file)); - bson_concat ( - kms_providers, - tmp_bson ( - "{'azure:no_client_cert': {'tenantId': '%s', 'clientId': '%s'," - "'clientSecret': '%s', " - "'identityPlatformEndpoint': '127.0.0.1:9002'" - "}}", - mongoc_test_azure_tenant_id, - mongoc_test_azure_client_id, - mongoc_test_azure_client_secret)); - bson_concat ( - tls_opts, - tmp_bson ("{'azure:no_client_cert': {'tlsCaFile': '%s' }}", ca_file)); + bson_concat (kms_providers, + tmp_bson ("{'azure:no_client_cert': {'tenantId': '%s', 'clientId': '%s'," + "'clientSecret': '%s', " + "'identityPlatformEndpoint': '127.0.0.1:9002'" + "}}", + mongoc_test_azure_tenant_id, + mongoc_test_azure_client_id, + mongoc_test_azure_client_secret)); + bson_concat (tls_opts, tmp_bson ("{'azure:no_client_cert': {'tlsCaFile': '%s' }}", ca_file)); - bson_concat ( - kms_providers, - tmp_bson ("{'azure:with_tls': {'tenantId': '%s', 'clientId': '%s'," - "'clientSecret': '%s', " - "'identityPlatformEndpoint': '127.0.0.1:9002'" - "}}", - mongoc_test_azure_tenant_id, - mongoc_test_azure_client_id, - mongoc_test_azure_client_secret)); + bson_concat (kms_providers, + tmp_bson ("{'azure:with_tls': {'tenantId': '%s', 'clientId': '%s'," + "'clientSecret': '%s', " + "'identityPlatformEndpoint': '127.0.0.1:9002'" + "}}", + mongoc_test_azure_tenant_id, + mongoc_test_azure_client_id, + mongoc_test_azure_client_secret)); bson_concat (tls_opts, tmp_bson ("{'azure:with_tls': {'tlsCaFile': '%s', " "'tlsCertificateKeyFile': '%s' }}", ca_file, certificate_key_file)); - bson_concat ( - kms_providers, - tmp_bson ( - "{'gcp:no_client_cert': { 'email': '%s', 'privateKey': '%s', " - "'endpoint': '127.0.0.1:9002' }}", - mongoc_test_gcp_email, - mongoc_test_gcp_privatekey)); - bson_concat (tls_opts, - tmp_bson ("{'gcp:no_client_cert': {'tlsCaFile': '%s' }}", - ca_file, - certificate_key_file)); + bson_concat (kms_providers, + tmp_bson ("{'gcp:no_client_cert': { 'email': '%s', 'privateKey': '%s', " + "'endpoint': '127.0.0.1:9002' }}", + mongoc_test_gcp_email, + mongoc_test_gcp_privatekey)); + bson_concat (tls_opts, tmp_bson ("{'gcp:no_client_cert': {'tlsCaFile': '%s' }}", ca_file, certificate_key_file)); - bson_concat ( - kms_providers, - tmp_bson ("{'gcp:with_tls': { 'email': '%s', 'privateKey': '%s', " - "'endpoint': '127.0.0.1:9002' }}", - mongoc_test_gcp_email, - mongoc_test_gcp_privatekey)); + bson_concat (kms_providers, + tmp_bson ("{'gcp:with_tls': { 'email': '%s', 'privateKey': '%s', " + "'endpoint': '127.0.0.1:9002' }}", + mongoc_test_gcp_email, + mongoc_test_gcp_privatekey)); bson_concat (tls_opts, tmp_bson ("{'gcp:with_tls': {'tlsCaFile': '%s', " "'tlsCertificateKeyFile': '%s' }}", ca_file, certificate_key_file)); - bson_concat ( - kms_providers, - tmp_bson ("{'kmip:no_client_cert': { 'endpoint': '127.0.0.1:5698'}}")); - bson_concat ( - tls_opts, - tmp_bson ("{'kmip:no_client_cert': {'tlsCaFile': '%s' }}", ca_file)); + bson_concat (kms_providers, tmp_bson ("{'kmip:no_client_cert': { 'endpoint': '127.0.0.1:5698'}}")); + bson_concat (tls_opts, tmp_bson ("{'kmip:no_client_cert': {'tlsCaFile': '%s' }}", ca_file)); - bson_concat ( - kms_providers, - tmp_bson ("{'kmip:with_tls': { 'endpoint': '127.0.0.1:5698'}}")); + bson_concat (kms_providers, tmp_bson ("{'kmip:with_tls': { 'endpoint': '127.0.0.1:5698'}}")); bson_concat (tls_opts, tmp_bson ("{'kmip:with_tls': {'tlsCaFile': '%s', " "'tlsCertificateKeyFile': '%s' }}", @@ -3239,17 +2788,12 @@ _tls_test_make_client_encryption (mongoc_client_t *keyvault_client, } client_encryption_opts = mongoc_client_encryption_opts_new (); - mongoc_client_encryption_opts_set_kms_providers (client_encryption_opts, - kms_providers); - mongoc_client_encryption_opts_set_keyvault_namespace ( - client_encryption_opts, "keyvault", "datakeys"); - mongoc_client_encryption_opts_set_keyvault_client (client_encryption_opts, - keyvault_client); - mongoc_client_encryption_opts_set_tls_opts (client_encryption_opts, - tls_opts); - - client_encryption = - mongoc_client_encryption_new (client_encryption_opts, &error); + mongoc_client_encryption_opts_set_kms_providers (client_encryption_opts, kms_providers); + mongoc_client_encryption_opts_set_keyvault_namespace (client_encryption_opts, "keyvault", "datakeys"); + mongoc_client_encryption_opts_set_keyvault_client (client_encryption_opts, keyvault_client); + mongoc_client_encryption_opts_set_tls_opts (client_encryption_opts, tls_opts); + + client_encryption = mongoc_client_encryption_new (client_encryption_opts, &error); ASSERT_OR_PRINT (client_encryption, error); mongoc_client_encryption_opts_destroy (client_encryption_opts); @@ -3267,33 +2811,25 @@ _tls_test_make_client_encryption (mongoc_client_t *keyvault_client, } #if defined(MONGOC_ENABLE_SSL_OPENSSL) -#define ASSERT_EXPIRED(error) \ - ASSERT_CONTAINS (error.message, "certificate has expired") +#define ASSERT_EXPIRED(error) ASSERT_CONTAINS (error.message, "certificate has expired") #elif defined(MONGOC_ENABLE_SSL_SECURE_TRANSPORT) -#define ASSERT_EXPIRED(error) \ - ASSERT_CONTAINS (error.message, "CSSMERR_TP_CERT_EXPIRED") +#define ASSERT_EXPIRED(error) ASSERT_CONTAINS (error.message, "CSSMERR_TP_CERT_EXPIRED") #elif defined(MONGOC_ENABLE_SSL_SECURE_CHANNEL) -#define ASSERT_EXPIRED(error) \ - ASSERT_CONTAINS (error.message, "certificate has expired") +#define ASSERT_EXPIRED(error) ASSERT_CONTAINS (error.message, "certificate has expired") #elif defined(MONGOC_ENABLE_SSL_LIBRESSL) -#define ASSERT_EXPIRED(error) \ - ASSERT_CONTAINS (error.message, "certificate has expired") +#define ASSERT_EXPIRED(error) ASSERT_CONTAINS (error.message, "certificate has expired") #else #define ASSERT_EXPIRED(error) #endif #if defined(MONGOC_ENABLE_SSL_OPENSSL) -#define ASSERT_INVALID_HOSTNAME(error) \ - ASSERT_CONTAINS (error.message, "IP address mismatch") +#define ASSERT_INVALID_HOSTNAME(error) ASSERT_CONTAINS (error.message, "IP address mismatch") #elif defined(MONGOC_ENABLE_SSL_SECURE_TRANSPORT) -#define ASSERT_INVALID_HOSTNAME(error) \ - ASSERT_CONTAINS (error.message, "Host name mismatch") +#define ASSERT_INVALID_HOSTNAME(error) ASSERT_CONTAINS (error.message, "Host name mismatch") #elif defined(MONGOC_ENABLE_SSL_SECURE_CHANNEL) -#define ASSERT_INVALID_HOSTNAME(error) \ - ASSERT_CONTAINS (error.message, "hostname doesn't match certificate") +#define ASSERT_INVALID_HOSTNAME(error) ASSERT_CONTAINS (error.message, "hostname doesn't match certificate") #elif defined(MONGOC_ENABLE_SSL_LIBRESSL) -#define ASSERT_INVALID_HOSTNAME(error) \ - ASSERT_CONTAINS (error.message, "not present in server certificate") +#define ASSERT_INVALID_HOSTNAME(error) ASSERT_CONTAINS (error.message, "not present in server certificate") #else #define ASSERT_INVALID_HOSTNAME(error) #endif @@ -3312,105 +2848,79 @@ test_kms_tls_options (void *unused) mongoc_client_encryption_datakey_opts_t *dkopts; bson_error_t error; bool res; - const int mongocrypt_errno = - 1; /* libmongocrypt returns all errors with code 1. */ + const int mongocrypt_errno = 1; /* libmongocrypt returns all errors with code 1. */ BSON_UNUSED (unused); keyvault_client = test_framework_new_default_client (); - client_encryption_no_client_cert = - _tls_test_make_client_encryption (keyvault_client, NO_CLIENT_CERT); - client_encryption_with_tls = - _tls_test_make_client_encryption (keyvault_client, WITH_TLS); - client_encryption_expired = - _tls_test_make_client_encryption (keyvault_client, EXPIRED); - client_encryption_invalid_hostname = - _tls_test_make_client_encryption (keyvault_client, INVALID_HOSTNAME); - client_encryption_with_names = - _tls_test_make_client_encryption (keyvault_client, WITH_NAMES); + client_encryption_no_client_cert = _tls_test_make_client_encryption (keyvault_client, NO_CLIENT_CERT); + client_encryption_with_tls = _tls_test_make_client_encryption (keyvault_client, WITH_TLS); + client_encryption_expired = _tls_test_make_client_encryption (keyvault_client, EXPIRED); + client_encryption_invalid_hostname = _tls_test_make_client_encryption (keyvault_client, INVALID_HOSTNAME); + client_encryption_with_names = _tls_test_make_client_encryption (keyvault_client, WITH_NAMES); /* Case 1: AWS - no client cert. */ memset (&error, 0, sizeof (bson_error_t)); dkopts = mongoc_client_encryption_datakey_opts_new (); - mongoc_client_encryption_datakey_opts_set_masterkey ( - dkopts, - tmp_bson ("{ 'region': 'us-east-1', 'key': " - "'arn:aws:kms:us-east-1:579766882180:key/" - "89fcc2c4-08b0-4bd9-9f25-e30687b580d0', 'endpoint': " - "'127.0.0.1:9002' }")); - res = mongoc_client_encryption_create_datakey ( - client_encryption_no_client_cert, "aws", dkopts, &keyid, &error); - ASSERT_ERROR_CONTAINS ( - error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, ""); + mongoc_client_encryption_datakey_opts_set_masterkey (dkopts, + tmp_bson ("{ 'region': 'us-east-1', 'key': " + "'arn:aws:kms:us-east-1:579766882180:key/" + "89fcc2c4-08b0-4bd9-9f25-e30687b580d0', 'endpoint': " + "'127.0.0.1:9002' }")); + res = mongoc_client_encryption_create_datakey (client_encryption_no_client_cert, "aws", dkopts, &keyid, &error); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, ""); ASSERT (!res); mongoc_client_encryption_datakey_opts_destroy (dkopts); /* AWS - named with no client cert. */ memset (&error, 0, sizeof (bson_error_t)); dkopts = mongoc_client_encryption_datakey_opts_new (); - mongoc_client_encryption_datakey_opts_set_masterkey ( - dkopts, - tmp_bson ("{ 'region': 'us-east-1', 'key': " - "'arn:aws:kms:us-east-1:579766882180:key/" - "89fcc2c4-08b0-4bd9-9f25-e30687b580d0', 'endpoint': " - "'127.0.0.1:9002' }")); - res = mongoc_client_encryption_create_datakey (client_encryption_with_names, - "aws:no_client_cert", - dkopts, - &keyid, - &error); - ASSERT_ERROR_CONTAINS ( - error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, ""); + mongoc_client_encryption_datakey_opts_set_masterkey (dkopts, + tmp_bson ("{ 'region': 'us-east-1', 'key': " + "'arn:aws:kms:us-east-1:579766882180:key/" + "89fcc2c4-08b0-4bd9-9f25-e30687b580d0', 'endpoint': " + "'127.0.0.1:9002' }")); + res = mongoc_client_encryption_create_datakey ( + client_encryption_with_names, "aws:no_client_cert", dkopts, &keyid, &error); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, ""); ASSERT (!res); mongoc_client_encryption_datakey_opts_destroy (dkopts); /* AWS - with TLS. */ memset (&error, 0, sizeof (bson_error_t)); dkopts = mongoc_client_encryption_datakey_opts_new (); - mongoc_client_encryption_datakey_opts_set_masterkey ( - dkopts, - tmp_bson ("{ 'region': 'us-east-1', 'key': " - "'arn:aws:kms:us-east-1:579766882180:key/" - "89fcc2c4-08b0-4bd9-9f25-e30687b580d0', 'endpoint': " - "'127.0.0.1:9002' }")); - res = mongoc_client_encryption_create_datakey ( - client_encryption_with_tls, "aws", dkopts, &keyid, &error); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION, - mongocrypt_errno, - "parse error"); + mongoc_client_encryption_datakey_opts_set_masterkey (dkopts, + tmp_bson ("{ 'region': 'us-east-1', 'key': " + "'arn:aws:kms:us-east-1:579766882180:key/" + "89fcc2c4-08b0-4bd9-9f25-e30687b580d0', 'endpoint': " + "'127.0.0.1:9002' }")); + res = mongoc_client_encryption_create_datakey (client_encryption_with_tls, "aws", dkopts, &keyid, &error); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION, mongocrypt_errno, "parse error"); ASSERT (!res); mongoc_client_encryption_datakey_opts_destroy (dkopts); /* AWS - named with TLS. */ memset (&error, 0, sizeof (bson_error_t)); dkopts = mongoc_client_encryption_datakey_opts_new (); - mongoc_client_encryption_datakey_opts_set_masterkey ( - dkopts, - tmp_bson ("{ 'region': 'us-east-1', 'key': " - "'arn:aws:kms:us-east-1:579766882180:key/" - "89fcc2c4-08b0-4bd9-9f25-e30687b580d0', 'endpoint': " - "'127.0.0.1:9002' }")); - res = mongoc_client_encryption_create_datakey ( - client_encryption_with_names, "aws:with_tls", dkopts, &keyid, &error); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION, - mongocrypt_errno, - "parse error"); + mongoc_client_encryption_datakey_opts_set_masterkey (dkopts, + tmp_bson ("{ 'region': 'us-east-1', 'key': " + "'arn:aws:kms:us-east-1:579766882180:key/" + "89fcc2c4-08b0-4bd9-9f25-e30687b580d0', 'endpoint': " + "'127.0.0.1:9002' }")); + res = mongoc_client_encryption_create_datakey (client_encryption_with_names, "aws:with_tls", dkopts, &keyid, &error); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION, mongocrypt_errno, "parse error"); ASSERT (!res); mongoc_client_encryption_datakey_opts_destroy (dkopts); /* AWS - expired. */ memset (&error, 0, sizeof (bson_error_t)); dkopts = mongoc_client_encryption_datakey_opts_new (); - mongoc_client_encryption_datakey_opts_set_masterkey ( - dkopts, - tmp_bson ("{ 'region': 'us-east-1', 'key': " - "'arn:aws:kms:us-east-1:579766882180:key/" - "89fcc2c4-08b0-4bd9-9f25-e30687b580d0', 'endpoint': " - "'127.0.0.1:9000' }")); - res = mongoc_client_encryption_create_datakey ( - client_encryption_expired, "aws", dkopts, &keyid, &error); + mongoc_client_encryption_datakey_opts_set_masterkey (dkopts, + tmp_bson ("{ 'region': 'us-east-1', 'key': " + "'arn:aws:kms:us-east-1:579766882180:key/" + "89fcc2c4-08b0-4bd9-9f25-e30687b580d0', 'endpoint': " + "'127.0.0.1:9000' }")); + res = mongoc_client_encryption_create_datakey (client_encryption_expired, "aws", dkopts, &keyid, &error); ASSERT_EXPIRED (error); ASSERT (!res); mongoc_client_encryption_datakey_opts_destroy (dkopts); @@ -3418,14 +2928,12 @@ test_kms_tls_options (void *unused) /* AWS - invalid hostname. */ memset (&error, 0, sizeof (bson_error_t)); dkopts = mongoc_client_encryption_datakey_opts_new (); - mongoc_client_encryption_datakey_opts_set_masterkey ( - dkopts, - tmp_bson ("{ 'region': 'us-east-1', 'key': " - "'arn:aws:kms:us-east-1:579766882180:key/" - "89fcc2c4-08b0-4bd9-9f25-e30687b580d0', 'endpoint': " - "'127.0.0.1:9001' }")); - res = mongoc_client_encryption_create_datakey ( - client_encryption_invalid_hostname, "aws", dkopts, &keyid, &error); + mongoc_client_encryption_datakey_opts_set_masterkey (dkopts, + tmp_bson ("{ 'region': 'us-east-1', 'key': " + "'arn:aws:kms:us-east-1:579766882180:key/" + "89fcc2c4-08b0-4bd9-9f25-e30687b580d0', 'endpoint': " + "'127.0.0.1:9001' }")); + res = mongoc_client_encryption_create_datakey (client_encryption_invalid_hostname, "aws", dkopts, &keyid, &error); ASSERT_INVALID_HOSTNAME (error); ASSERT (!res); mongoc_client_encryption_datakey_opts_destroy (dkopts); @@ -3434,13 +2942,9 @@ test_kms_tls_options (void *unused) memset (&error, 0, sizeof (bson_error_t)); dkopts = mongoc_client_encryption_datakey_opts_new (); mongoc_client_encryption_datakey_opts_set_masterkey ( - dkopts, - tmp_bson ( - "{ 'keyVaultEndpoint': 'doesnotexist.local', 'keyName': 'foo' }")); - res = mongoc_client_encryption_create_datakey ( - client_encryption_no_client_cert, "azure", dkopts, &keyid, &error); - ASSERT_ERROR_CONTAINS ( - error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, ""); + dkopts, tmp_bson ("{ 'keyVaultEndpoint': 'doesnotexist.local', 'keyName': 'foo' }")); + res = mongoc_client_encryption_create_datakey (client_encryption_no_client_cert, "azure", dkopts, &keyid, &error); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, ""); ASSERT (!res); mongoc_client_encryption_datakey_opts_destroy (dkopts); @@ -3448,16 +2952,10 @@ test_kms_tls_options (void *unused) memset (&error, 0, sizeof (bson_error_t)); dkopts = mongoc_client_encryption_datakey_opts_new (); mongoc_client_encryption_datakey_opts_set_masterkey ( - dkopts, - tmp_bson ( - "{ 'keyVaultEndpoint': 'doesnotexist.local', 'keyName': 'foo' }")); - res = mongoc_client_encryption_create_datakey (client_encryption_with_names, - "azure:no_client_cert", - dkopts, - &keyid, - &error); - ASSERT_ERROR_CONTAINS ( - error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, ""); + dkopts, tmp_bson ("{ 'keyVaultEndpoint': 'doesnotexist.local', 'keyName': 'foo' }")); + res = mongoc_client_encryption_create_datakey ( + client_encryption_with_names, "azure:no_client_cert", dkopts, &keyid, &error); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, ""); ASSERT (!res); mongoc_client_encryption_datakey_opts_destroy (dkopts); @@ -3465,15 +2963,9 @@ test_kms_tls_options (void *unused) memset (&error, 0, sizeof (bson_error_t)); dkopts = mongoc_client_encryption_datakey_opts_new (); mongoc_client_encryption_datakey_opts_set_masterkey ( - dkopts, - tmp_bson ( - "{ 'keyVaultEndpoint': 'doesnotexist.local', 'keyName': 'foo' }")); - res = mongoc_client_encryption_create_datakey ( - client_encryption_with_tls, "azure", dkopts, &keyid, &error); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION, - mongocrypt_errno, - "HTTP status=404"); + dkopts, tmp_bson ("{ 'keyVaultEndpoint': 'doesnotexist.local', 'keyName': 'foo' }")); + res = mongoc_client_encryption_create_datakey (client_encryption_with_tls, "azure", dkopts, &keyid, &error); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION, mongocrypt_errno, "HTTP status=404"); ASSERT (!res); mongoc_client_encryption_datakey_opts_destroy (dkopts); @@ -3481,15 +2973,10 @@ test_kms_tls_options (void *unused) memset (&error, 0, sizeof (bson_error_t)); dkopts = mongoc_client_encryption_datakey_opts_new (); mongoc_client_encryption_datakey_opts_set_masterkey ( - dkopts, - tmp_bson ( - "{ 'keyVaultEndpoint': 'doesnotexist.local', 'keyName': 'foo' }")); - res = mongoc_client_encryption_create_datakey ( - client_encryption_with_names, "azure:with_tls", dkopts, &keyid, &error); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION, - mongocrypt_errno, - "HTTP status=404"); + dkopts, tmp_bson ("{ 'keyVaultEndpoint': 'doesnotexist.local', 'keyName': 'foo' }")); + res = + mongoc_client_encryption_create_datakey (client_encryption_with_names, "azure:with_tls", dkopts, &keyid, &error); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION, mongocrypt_errno, "HTTP status=404"); ASSERT (!res); mongoc_client_encryption_datakey_opts_destroy (dkopts); @@ -3497,11 +2984,8 @@ test_kms_tls_options (void *unused) memset (&error, 0, sizeof (bson_error_t)); dkopts = mongoc_client_encryption_datakey_opts_new (); mongoc_client_encryption_datakey_opts_set_masterkey ( - dkopts, - tmp_bson ( - "{ 'keyVaultEndpoint': 'doesnotexist.local', 'keyName': 'foo' }")); - res = mongoc_client_encryption_create_datakey ( - client_encryption_expired, "azure", dkopts, &keyid, &error); + dkopts, tmp_bson ("{ 'keyVaultEndpoint': 'doesnotexist.local', 'keyName': 'foo' }")); + res = mongoc_client_encryption_create_datakey (client_encryption_expired, "azure", dkopts, &keyid, &error); ASSERT_EXPIRED (error); ASSERT (!res); mongoc_client_encryption_datakey_opts_destroy (dkopts); @@ -3510,11 +2994,8 @@ test_kms_tls_options (void *unused) memset (&error, 0, sizeof (bson_error_t)); dkopts = mongoc_client_encryption_datakey_opts_new (); mongoc_client_encryption_datakey_opts_set_masterkey ( - dkopts, - tmp_bson ( - "{ 'keyVaultEndpoint': 'doesnotexist.local', 'keyName': 'foo' }")); - res = mongoc_client_encryption_create_datakey ( - client_encryption_invalid_hostname, "azure", dkopts, &keyid, &error); + dkopts, tmp_bson ("{ 'keyVaultEndpoint': 'doesnotexist.local', 'keyName': 'foo' }")); + res = mongoc_client_encryption_create_datakey (client_encryption_invalid_hostname, "azure", dkopts, &keyid, &error); ASSERT_INVALID_HOSTNAME (error); ASSERT (!res); mongoc_client_encryption_datakey_opts_destroy (dkopts); @@ -3526,10 +3007,8 @@ test_kms_tls_options (void *unused) dkopts, tmp_bson ("{ 'projectId': 'pid', 'location': 'l', 'keyRing': 'kr', " "'keyName': 'kn' }")); - res = mongoc_client_encryption_create_datakey ( - client_encryption_no_client_cert, "gcp", dkopts, &keyid, &error); - ASSERT_ERROR_CONTAINS ( - error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, ""); + res = mongoc_client_encryption_create_datakey (client_encryption_no_client_cert, "gcp", dkopts, &keyid, &error); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, ""); ASSERT (!res); mongoc_client_encryption_datakey_opts_destroy (dkopts); @@ -3540,13 +3019,9 @@ test_kms_tls_options (void *unused) dkopts, tmp_bson ("{ 'projectId': 'pid', 'location': 'l', 'keyRing': 'kr', " "'keyName': 'kn' }")); - res = mongoc_client_encryption_create_datakey (client_encryption_with_names, - "gcp:no_client_cert", - dkopts, - &keyid, - &error); - ASSERT_ERROR_CONTAINS ( - error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, ""); + res = mongoc_client_encryption_create_datakey ( + client_encryption_with_names, "gcp:no_client_cert", dkopts, &keyid, &error); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, ""); ASSERT (!res); mongoc_client_encryption_datakey_opts_destroy (dkopts); @@ -3557,12 +3032,8 @@ test_kms_tls_options (void *unused) dkopts, tmp_bson ("{ 'projectId': 'pid', 'location': 'l', 'keyRing': 'kr', " "'keyName': 'kn' }")); - res = mongoc_client_encryption_create_datakey ( - client_encryption_with_tls, "gcp", dkopts, &keyid, &error); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION, - mongocrypt_errno, - "HTTP status=404"); + res = mongoc_client_encryption_create_datakey (client_encryption_with_tls, "gcp", dkopts, &keyid, &error); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION, mongocrypt_errno, "HTTP status=404"); ASSERT (!res); mongoc_client_encryption_datakey_opts_destroy (dkopts); @@ -3573,12 +3044,8 @@ test_kms_tls_options (void *unused) dkopts, tmp_bson ("{ 'projectId': 'pid', 'location': 'l', 'keyRing': 'kr', " "'keyName': 'kn' }")); - res = mongoc_client_encryption_create_datakey ( - client_encryption_with_names, "gcp:with_tls", dkopts, &keyid, &error); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION, - mongocrypt_errno, - "HTTP status=404"); + res = mongoc_client_encryption_create_datakey (client_encryption_with_names, "gcp:with_tls", dkopts, &keyid, &error); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION, mongocrypt_errno, "HTTP status=404"); ASSERT (!res); mongoc_client_encryption_datakey_opts_destroy (dkopts); @@ -3589,8 +3056,7 @@ test_kms_tls_options (void *unused) dkopts, tmp_bson ("{ 'projectId': 'pid', 'location': 'l', 'keyRing': 'kr', " "'keyName': 'kn' }")); - res = mongoc_client_encryption_create_datakey ( - client_encryption_expired, "gcp", dkopts, &keyid, &error); + res = mongoc_client_encryption_create_datakey (client_encryption_expired, "gcp", dkopts, &keyid, &error); ASSERT_EXPIRED (error); ASSERT (!res); mongoc_client_encryption_datakey_opts_destroy (dkopts); @@ -3602,8 +3068,7 @@ test_kms_tls_options (void *unused) dkopts, tmp_bson ("{ 'projectId': 'pid', 'location': 'l', 'keyRing': 'kr', " "'keyName': 'kn' }")); - res = mongoc_client_encryption_create_datakey ( - client_encryption_invalid_hostname, "gcp", dkopts, &keyid, &error); + res = mongoc_client_encryption_create_datakey (client_encryption_invalid_hostname, "gcp", dkopts, &keyid, &error); ASSERT_INVALID_HOSTNAME (error); ASSERT (!res); mongoc_client_encryption_datakey_opts_destroy (dkopts); @@ -3611,37 +3076,27 @@ test_kms_tls_options (void *unused) /* Case 4: KMIP - no client cert. */ memset (&error, 0, sizeof (bson_error_t)); dkopts = mongoc_client_encryption_datakey_opts_new (); - mongoc_client_encryption_datakey_opts_set_masterkey (dkopts, - tmp_bson ("{}")); - res = mongoc_client_encryption_create_datakey ( - client_encryption_no_client_cert, "kmip", dkopts, &keyid, &error); - ASSERT_ERROR_CONTAINS ( - error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, ""); + mongoc_client_encryption_datakey_opts_set_masterkey (dkopts, tmp_bson ("{}")); + res = mongoc_client_encryption_create_datakey (client_encryption_no_client_cert, "kmip", dkopts, &keyid, &error); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, ""); ASSERT (!res); mongoc_client_encryption_datakey_opts_destroy (dkopts); /* KMIP - named with no client cert. */ memset (&error, 0, sizeof (bson_error_t)); dkopts = mongoc_client_encryption_datakey_opts_new (); - mongoc_client_encryption_datakey_opts_set_masterkey (dkopts, - tmp_bson ("{}")); - res = mongoc_client_encryption_create_datakey (client_encryption_with_names, - "kmip:no_client_cert", - dkopts, - &keyid, - &error); - ASSERT_ERROR_CONTAINS ( - error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, ""); + mongoc_client_encryption_datakey_opts_set_masterkey (dkopts, tmp_bson ("{}")); + res = mongoc_client_encryption_create_datakey ( + client_encryption_with_names, "kmip:no_client_cert", dkopts, &keyid, &error); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, ""); ASSERT (!res); mongoc_client_encryption_datakey_opts_destroy (dkopts); /* KMIP - with TLS. */ memset (&error, 0, sizeof (bson_error_t)); dkopts = mongoc_client_encryption_datakey_opts_new (); - mongoc_client_encryption_datakey_opts_set_masterkey (dkopts, - tmp_bson ("{}")); - res = mongoc_client_encryption_create_datakey ( - client_encryption_with_tls, "kmip", dkopts, &keyid, &error); + mongoc_client_encryption_datakey_opts_set_masterkey (dkopts, tmp_bson ("{}")); + res = mongoc_client_encryption_create_datakey (client_encryption_with_tls, "kmip", dkopts, &keyid, &error); ASSERT_OR_PRINT (res, error); bson_value_destroy (&keyid); mongoc_client_encryption_datakey_opts_destroy (dkopts); @@ -3649,10 +3104,9 @@ test_kms_tls_options (void *unused) /* KMIP - named with TLS. */ memset (&error, 0, sizeof (bson_error_t)); dkopts = mongoc_client_encryption_datakey_opts_new (); - mongoc_client_encryption_datakey_opts_set_masterkey (dkopts, - tmp_bson ("{}")); - res = mongoc_client_encryption_create_datakey ( - client_encryption_with_names, "kmip:with_tls", dkopts, &keyid, &error); + mongoc_client_encryption_datakey_opts_set_masterkey (dkopts, tmp_bson ("{}")); + res = + mongoc_client_encryption_create_datakey (client_encryption_with_names, "kmip:with_tls", dkopts, &keyid, &error); ASSERT_OR_PRINT (res, error); bson_value_destroy (&keyid); mongoc_client_encryption_datakey_opts_destroy (dkopts); @@ -3660,10 +3114,8 @@ test_kms_tls_options (void *unused) /* KMIP - expired. */ memset (&error, 0, sizeof (bson_error_t)); dkopts = mongoc_client_encryption_datakey_opts_new (); - mongoc_client_encryption_datakey_opts_set_masterkey (dkopts, - tmp_bson ("{}")); - res = mongoc_client_encryption_create_datakey ( - client_encryption_expired, "kmip", dkopts, &keyid, &error); + mongoc_client_encryption_datakey_opts_set_masterkey (dkopts, tmp_bson ("{}")); + res = mongoc_client_encryption_create_datakey (client_encryption_expired, "kmip", dkopts, &keyid, &error); ASSERT_EXPIRED (error); ASSERT (!res); mongoc_client_encryption_datakey_opts_destroy (dkopts); @@ -3671,10 +3123,8 @@ test_kms_tls_options (void *unused) /* KMIP - invalid hostname. */ memset (&error, 0, sizeof (bson_error_t)); dkopts = mongoc_client_encryption_datakey_opts_new (); - mongoc_client_encryption_datakey_opts_set_masterkey (dkopts, - tmp_bson ("{}")); - res = mongoc_client_encryption_create_datakey ( - client_encryption_invalid_hostname, "kmip", dkopts, &keyid, &error); + mongoc_client_encryption_datakey_opts_set_masterkey (dkopts, tmp_bson ("{}")); + res = mongoc_client_encryption_create_datakey (client_encryption_invalid_hostname, "kmip", dkopts, &keyid, &error); ASSERT_INVALID_HOSTNAME (error); ASSERT (!res); mongoc_client_encryption_datakey_opts_destroy (dkopts); @@ -3694,8 +3144,7 @@ test_kms_tls_options_extra_rejected (void *unused) mongoc_client_encryption_opts_t *ce_opts; mongoc_client_t *keyvault_client; bson_error_t error; - bson_t *kms_providers = - tmp_bson ("{'aws': {'accessKeyId': 'foo', 'secretAccessKey': 'bar'}}"); + bson_t *kms_providers = tmp_bson ("{'aws': {'accessKeyId': 'foo', 'secretAccessKey': 'bar'}}"); BSON_UNUSED (unused); @@ -3703,30 +3152,25 @@ test_kms_tls_options_extra_rejected (void *unused) /* Test that the "local" KMS provider is rejected. */ ce_opts = mongoc_client_encryption_opts_new (); - mongoc_client_encryption_opts_set_keyvault_namespace ( - ce_opts, "keyvault", "datakeys"); + mongoc_client_encryption_opts_set_keyvault_namespace (ce_opts, "keyvault", "datakeys"); mongoc_client_encryption_opts_set_keyvault_client (ce_opts, keyvault_client); mongoc_client_encryption_opts_set_kms_providers (ce_opts, kms_providers); - mongoc_client_encryption_opts_set_tls_opts ( - ce_opts, tmp_bson ("{'local': {'tlsCaFile': 'ca.pem'}}")); + mongoc_client_encryption_opts_set_tls_opts (ce_opts, tmp_bson ("{'local': {'tlsCaFile': 'ca.pem'}}")); ce = mongoc_client_encryption_new (ce_opts, &error); - ASSERT_ERROR_CONTAINS ( - error, - MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION, - MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG, - "Cannot configure TLS options for KMS provider: local"); + ASSERT_ERROR_CONTAINS (error, + MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION, + MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG, + "Cannot configure TLS options for KMS provider: local"); ASSERT (NULL == ce); mongoc_client_encryption_opts_destroy (ce_opts); /* Test that insecure TLS options are rejected. */ memset (&error, 0, sizeof (bson_error_t)); ce_opts = mongoc_client_encryption_opts_new (); - mongoc_client_encryption_opts_set_keyvault_namespace ( - ce_opts, "keyvault", "datakeys"); + mongoc_client_encryption_opts_set_keyvault_namespace (ce_opts, "keyvault", "datakeys"); mongoc_client_encryption_opts_set_keyvault_client (ce_opts, keyvault_client); mongoc_client_encryption_opts_set_kms_providers (ce_opts, kms_providers); - mongoc_client_encryption_opts_set_tls_opts ( - ce_opts, tmp_bson ("{'aws': {'tlsInsecure': true}}")); + mongoc_client_encryption_opts_set_tls_opts (ce_opts, tmp_bson ("{'aws': {'tlsInsecure': true}}")); ce = mongoc_client_encryption_new (ce_opts, &error); ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION, @@ -3739,12 +3183,10 @@ test_kms_tls_options_extra_rejected (void *unused) /* Test that extra TLS options are rejected. */ memset (&error, 0, sizeof (bson_error_t)); ce_opts = mongoc_client_encryption_opts_new (); - mongoc_client_encryption_opts_set_keyvault_namespace ( - ce_opts, "keyvault", "datakeys"); + mongoc_client_encryption_opts_set_keyvault_namespace (ce_opts, "keyvault", "datakeys"); mongoc_client_encryption_opts_set_keyvault_client (ce_opts, keyvault_client); mongoc_client_encryption_opts_set_kms_providers (ce_opts, kms_providers); - mongoc_client_encryption_opts_set_tls_opts ( - ce_opts, tmp_bson ("{'aws': {'extra': true}}")); + mongoc_client_encryption_opts_set_tls_opts (ce_opts, tmp_bson ("{'aws': {'extra': true}}")); ce = mongoc_client_encryption_new (ce_opts, &error); ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION, @@ -3757,14 +3199,11 @@ test_kms_tls_options_extra_rejected (void *unused) /* Test that TLS options for duplicate providers are rejected. */ memset (&error, 0, sizeof (bson_error_t)); ce_opts = mongoc_client_encryption_opts_new (); - mongoc_client_encryption_opts_set_keyvault_namespace ( - ce_opts, "keyvault", "datakeys"); + mongoc_client_encryption_opts_set_keyvault_namespace (ce_opts, "keyvault", "datakeys"); mongoc_client_encryption_opts_set_keyvault_client (ce_opts, keyvault_client); mongoc_client_encryption_opts_set_kms_providers (ce_opts, kms_providers); mongoc_client_encryption_opts_set_tls_opts ( - ce_opts, - tmp_bson ( - "{'aws': {'tlsCAFile': 'foo.pem'}, 'aws': {'tlsCAFile': 'foo.pem'}}")); + ce_opts, tmp_bson ("{'aws': {'tlsCAFile': 'foo.pem'}, 'aws': {'tlsCAFile': 'foo.pem'}}")); ce = mongoc_client_encryption_new (ce_opts, &error); ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION, @@ -3776,14 +3215,11 @@ test_kms_tls_options_extra_rejected (void *unused) /* Test that tlsDisableOCSPEndpointCheck may be set. */ memset (&error, 0, sizeof (bson_error_t)); ce_opts = mongoc_client_encryption_opts_new (); - mongoc_client_encryption_opts_set_keyvault_namespace ( - ce_opts, "keyvault", "datakeys"); + mongoc_client_encryption_opts_set_keyvault_namespace (ce_opts, "keyvault", "datakeys"); mongoc_client_encryption_opts_set_keyvault_client (ce_opts, keyvault_client); mongoc_client_encryption_opts_set_kms_providers (ce_opts, kms_providers); mongoc_client_encryption_opts_set_tls_opts ( - ce_opts, - tmp_bson ("{'aws': {'%s': true}}", - MONGOC_URI_TLSDISABLEOCSPENDPOINTCHECK)); + ce_opts, tmp_bson ("{'aws': {'%s': true}}", MONGOC_URI_TLSDISABLEOCSPENDPOINTCHECK)); ce = mongoc_client_encryption_new (ce_opts, &error); ASSERT_OR_PRINT (ce, error); mongoc_client_encryption_destroy (ce); @@ -3805,12 +3241,12 @@ static ee_fixture * explicit_encryption_setup (void) { ee_fixture *eef = (ee_fixture *) bson_malloc0 (sizeof (ee_fixture)); - bson_t *encryptedFields = get_bson_from_json_file ( - "./src/libmongoc/tests/client_side_encryption_prose/explicit_encryption/" - "encryptedFields.json"); - bson_t *key1Document = get_bson_from_json_file ( - "./src/libmongoc/tests/client_side_encryption_prose/explicit_encryption/" - "key1-document.json"); + bson_t *encryptedFields = + get_bson_from_json_file ("./src/libmongoc/tests/client_side_encryption_prose/explicit_encryption/" + "encryptedFields.json"); + bson_t *key1Document = + get_bson_from_json_file ("./src/libmongoc/tests/client_side_encryption_prose/explicit_encryption/" + "key1-document.json"); mongoc_client_t *setupClient = test_framework_new_default_client (); @@ -3828,8 +3264,7 @@ explicit_encryption_setup (void) * ``encryptedFields`` as an option. */ { mongoc_database_t *db = mongoc_client_get_database (setupClient, "db"); - mongoc_collection_t *coll = - mongoc_database_get_collection (db, "explicit_encryption"); + mongoc_collection_t *coll = mongoc_database_get_collection (db, "explicit_encryption"); bson_error_t error; bson_t *opts; @@ -3842,8 +3277,7 @@ explicit_encryption_setup (void) } mongoc_collection_destroy (coll); - coll = mongoc_database_create_collection ( - db, "explicit_encryption", opts, &error); + coll = mongoc_database_create_collection (db, "explicit_encryption", opts, &error); ASSERT_OR_PRINT (coll, error); mongoc_collection_destroy (coll); @@ -3853,10 +3287,8 @@ explicit_encryption_setup (void) /* Drop and create the collection ``keyvault.datakeys``. */ { - mongoc_database_t *db = - mongoc_client_get_database (setupClient, "keyvault"); - mongoc_collection_t *coll = - mongoc_database_get_collection (db, "datakeys"); + mongoc_database_t *db = mongoc_client_get_database (setupClient, "keyvault"); + mongoc_collection_t *coll = mongoc_database_get_collection (db, "datakeys"); bson_error_t error; bson_t iopts = BSON_INITIALIZER; mongoc_write_concern_t *wc; @@ -3868,17 +3300,14 @@ explicit_encryption_setup (void) } mongoc_collection_destroy (coll); - coll = mongoc_database_create_collection ( - db, "datakeys", NULL /* opts */, &error); + coll = mongoc_database_create_collection (db, "datakeys", NULL /* opts */, &error); ASSERT_OR_PRINT (coll, error); /* Insert keyDocument1 with write concern majority */ wc = mongoc_write_concern_new (); mongoc_write_concern_set_w (wc, MONGOC_WRITE_CONCERN_W_MAJORITY); ASSERT (mongoc_write_concern_append (wc, &iopts)); - ASSERT_OR_PRINT (mongoc_collection_insert_one ( - coll, key1Document, &iopts, NULL /* reply */, &error), - error); + ASSERT_OR_PRINT (mongoc_collection_insert_one (coll, key1Document, &iopts, NULL /* reply */, &error), error); mongoc_write_concern_destroy (wc); bson_destroy (&iopts); @@ -3890,15 +3319,12 @@ explicit_encryption_setup (void) /* Create a ClientEncryption object named ``clientEncryption`` */ { - mongoc_client_encryption_opts_t *ceOpts = - mongoc_client_encryption_opts_new (); + mongoc_client_encryption_opts_t *ceOpts = mongoc_client_encryption_opts_new (); bson_t *kms_providers = _make_local_kms_provider (NULL); bson_error_t error; - mongoc_client_encryption_opts_set_keyvault_client (ceOpts, - eef->keyVaultClient); - mongoc_client_encryption_opts_set_keyvault_namespace ( - ceOpts, "keyvault", "datakeys"); + mongoc_client_encryption_opts_set_keyvault_client (ceOpts, eef->keyVaultClient); + mongoc_client_encryption_opts_set_keyvault_namespace (ceOpts, "keyvault", "datakeys"); mongoc_client_encryption_opts_set_kms_providers (ceOpts, kms_providers); eef->clientEncryption = mongoc_client_encryption_new (ceOpts, &error); @@ -3910,24 +3336,19 @@ explicit_encryption_setup (void) /* Create a MongoClient named ``encryptedClient``. */ { - mongoc_auto_encryption_opts_t *aeOpts = - mongoc_auto_encryption_opts_new (); + mongoc_auto_encryption_opts_t *aeOpts = mongoc_auto_encryption_opts_new (); bson_t *kms_providers = _make_local_kms_provider (NULL); bson_error_t error; - mongoc_auto_encryption_opts_set_keyvault_namespace ( - aeOpts, "keyvault", "datakeys"); + mongoc_auto_encryption_opts_set_keyvault_namespace (aeOpts, "keyvault", "datakeys"); mongoc_auto_encryption_opts_set_kms_providers (aeOpts, kms_providers); mongoc_auto_encryption_opts_set_bypass_query_analysis (aeOpts, true); eef->encryptedClient = test_framework_new_default_client (); - ASSERT_OR_PRINT (mongoc_client_enable_auto_encryption ( - eef->encryptedClient, aeOpts, &error), - error); + ASSERT_OR_PRINT (mongoc_client_enable_auto_encryption (eef->encryptedClient, aeOpts, &error), error); bson_destroy (kms_providers); mongoc_auto_encryption_opts_destroy (aeOpts); - eef->encryptedColl = mongoc_client_get_collection ( - eef->encryptedClient, "db", "explicit_encryption"); + eef->encryptedColl = mongoc_client_get_collection (eef->encryptedClient, "db", "explicit_encryption"); } mongoc_client_destroy (setupClient); @@ -3975,16 +3396,15 @@ range_explicit_encryption_setup (const char *typeStr) ree_fixture *reef = (ree_fixture *) bson_malloc0 (sizeof (ree_fixture)); reef->typeStr = typeStr; reef->fieldName = bson_strdup_printf ("encrypted%s", typeStr); - char *filepath = - bson_strdup_printf ("./src/libmongoc/tests/client_side_encryption_prose/" - "explicit_encryption/range-encryptedFields-%s.json", - typeStr); + char *filepath = bson_strdup_printf ("./src/libmongoc/tests/client_side_encryption_prose/" + "explicit_encryption/range-encryptedFields-%s.json", + typeStr); bson_t *encryptedFields = get_bson_from_json_file (filepath); ASSERT (encryptedFields); bson_free (filepath); - bson_t *key1Document = get_bson_from_json_file ( - "./src/libmongoc/tests/client_side_encryption_prose/explicit_encryption/" - "key1-document.json"); + bson_t *key1Document = + get_bson_from_json_file ("./src/libmongoc/tests/client_side_encryption_prose/explicit_encryption/" + "key1-document.json"); ASSERT (key1Document); mongoc_client_t *setupClient = test_framework_new_default_client (); @@ -4003,8 +3423,7 @@ range_explicit_encryption_setup (const char *typeStr) * ``encryptedFields`` as an option. */ { mongoc_database_t *db = mongoc_client_get_database (setupClient, "db"); - mongoc_collection_t *coll = - mongoc_database_get_collection (db, "explicit_encryption"); + mongoc_collection_t *coll = mongoc_database_get_collection (db, "explicit_encryption"); bson_error_t error; bson_t *opts; @@ -4017,8 +3436,7 @@ range_explicit_encryption_setup (const char *typeStr) } mongoc_collection_destroy (coll); - coll = mongoc_database_create_collection ( - db, "explicit_encryption", opts, &error); + coll = mongoc_database_create_collection (db, "explicit_encryption", opts, &error); ASSERT_OR_PRINT (coll, error); mongoc_collection_destroy (coll); @@ -4028,10 +3446,8 @@ range_explicit_encryption_setup (const char *typeStr) /* Drop and create the collection ``keyvault.datakeys``. */ { - mongoc_database_t *db = - mongoc_client_get_database (setupClient, "keyvault"); - mongoc_collection_t *coll = - mongoc_database_get_collection (db, "datakeys"); + mongoc_database_t *db = mongoc_client_get_database (setupClient, "keyvault"); + mongoc_collection_t *coll = mongoc_database_get_collection (db, "datakeys"); bson_error_t error; bson_t iopts = BSON_INITIALIZER; mongoc_write_concern_t *wc; @@ -4043,17 +3459,14 @@ range_explicit_encryption_setup (const char *typeStr) } mongoc_collection_destroy (coll); - coll = mongoc_database_create_collection ( - db, "datakeys", NULL /* opts */, &error); + coll = mongoc_database_create_collection (db, "datakeys", NULL /* opts */, &error); ASSERT_OR_PRINT (coll, error); /* Insert keyDocument1 with write concern majority */ wc = mongoc_write_concern_new (); mongoc_write_concern_set_w (wc, MONGOC_WRITE_CONCERN_W_MAJORITY); ASSERT (mongoc_write_concern_append (wc, &iopts)); - ASSERT_OR_PRINT (mongoc_collection_insert_one ( - coll, key1Document, &iopts, NULL /* reply */, &error), - error); + ASSERT_OR_PRINT (mongoc_collection_insert_one (coll, key1Document, &iopts, NULL /* reply */, &error), error); mongoc_write_concern_destroy (wc); bson_destroy (&iopts); @@ -4065,15 +3478,12 @@ range_explicit_encryption_setup (const char *typeStr) /* Create a ClientEncryption object named ``clientEncryption`` */ { - mongoc_client_encryption_opts_t *ceOpts = - mongoc_client_encryption_opts_new (); + mongoc_client_encryption_opts_t *ceOpts = mongoc_client_encryption_opts_new (); bson_t *kms_providers = _make_local_kms_provider (NULL); bson_error_t error; - mongoc_client_encryption_opts_set_keyvault_client (ceOpts, - reef->keyVaultClient); - mongoc_client_encryption_opts_set_keyvault_namespace ( - ceOpts, "keyvault", "datakeys"); + mongoc_client_encryption_opts_set_keyvault_client (ceOpts, reef->keyVaultClient); + mongoc_client_encryption_opts_set_keyvault_namespace (ceOpts, "keyvault", "datakeys"); mongoc_client_encryption_opts_set_kms_providers (ceOpts, kms_providers); reef->clientEncryption = mongoc_client_encryption_new (ceOpts, &error); @@ -4085,47 +3495,35 @@ range_explicit_encryption_setup (const char *typeStr) /* Create a MongoClient named ``encryptedClient``. */ { - mongoc_auto_encryption_opts_t *aeOpts = - mongoc_auto_encryption_opts_new (); + mongoc_auto_encryption_opts_t *aeOpts = mongoc_auto_encryption_opts_new (); bson_t *kms_providers = _make_local_kms_provider (NULL); bson_error_t error; - mongoc_auto_encryption_opts_set_keyvault_namespace ( - aeOpts, "keyvault", "datakeys"); + mongoc_auto_encryption_opts_set_keyvault_namespace (aeOpts, "keyvault", "datakeys"); mongoc_auto_encryption_opts_set_kms_providers (aeOpts, kms_providers); mongoc_auto_encryption_opts_set_bypass_query_analysis (aeOpts, true); reef->encryptedClient = test_framework_new_default_client (); - ASSERT_OR_PRINT (mongoc_client_enable_auto_encryption ( - reef->encryptedClient, aeOpts, &error), - error); + ASSERT_OR_PRINT (mongoc_client_enable_auto_encryption (reef->encryptedClient, aeOpts, &error), error); bson_destroy (kms_providers); mongoc_auto_encryption_opts_destroy (aeOpts); - reef->encryptedColl = mongoc_client_get_collection ( - reef->encryptedClient, "db", "explicit_encryption"); + reef->encryptedColl = mongoc_client_get_collection (reef->encryptedClient, "db", "explicit_encryption"); } /* Create the values 0, 6, 30, 200, and 201 as BSON values. */ { - if (0 == strcmp ("DecimalNoPrecision", typeStr) || - 0 == strcmp ("DecimalPrecision", typeStr)) { + if (0 == strcmp ("DecimalNoPrecision", typeStr) || 0 == strcmp ("DecimalPrecision", typeStr)) { reef->zero.value_type = BSON_TYPE_DECIMAL128; - ASSERT ( - bson_decimal128_from_string ("0", &reef->zero.value.v_decimal128)); + ASSERT (bson_decimal128_from_string ("0", &reef->zero.value.v_decimal128)); reef->six.value_type = BSON_TYPE_DECIMAL128; - ASSERT ( - bson_decimal128_from_string ("6", &reef->six.value.v_decimal128)); + ASSERT (bson_decimal128_from_string ("6", &reef->six.value.v_decimal128)); reef->thirty.value_type = BSON_TYPE_DECIMAL128; - ASSERT (bson_decimal128_from_string ( - "30", &reef->thirty.value.v_decimal128)); + ASSERT (bson_decimal128_from_string ("30", &reef->thirty.value.v_decimal128)); reef->twoHundred.value_type = BSON_TYPE_DECIMAL128; - ASSERT (bson_decimal128_from_string ( - "200", &reef->twoHundred.value.v_decimal128)); + ASSERT (bson_decimal128_from_string ("200", &reef->twoHundred.value.v_decimal128)); reef->twoHundredOne.value_type = BSON_TYPE_DECIMAL128; - ASSERT (bson_decimal128_from_string ( - "201", &reef->twoHundredOne.value.v_decimal128)); - } else if (0 == strcmp ("DoubleNoPrecision", typeStr) || - 0 == strcmp ("DoublePrecision", typeStr)) { + ASSERT (bson_decimal128_from_string ("201", &reef->twoHundredOne.value.v_decimal128)); + } else if (0 == strcmp ("DoubleNoPrecision", typeStr) || 0 == strcmp ("DoublePrecision", typeStr)) { reef->zero.value_type = BSON_TYPE_DOUBLE; reef->zero.value.v_double = 0; reef->six.value_type = BSON_TYPE_DOUBLE; @@ -4178,24 +3576,15 @@ range_explicit_encryption_setup (const char *typeStr) { reef->ro = mongoc_client_encryption_encrypt_range_opts_new (); mongoc_client_encryption_encrypt_range_opts_set_sparsity (reef->ro, 1); - if (0 == strcmp ("DoubleNoPrecision", typeStr) || - 0 == strcmp ("DecimalNoPrecision", typeStr)) { + if (0 == strcmp ("DoubleNoPrecision", typeStr) || 0 == strcmp ("DecimalNoPrecision", typeStr)) { // DoubleNoPrecision does not need more range options. - } else if (0 == strcmp ("DoublePrecision", typeStr) || - 0 == strcmp ("DecimalPrecision", typeStr)) { - mongoc_client_encryption_encrypt_range_opts_set_min (reef->ro, - &reef->zero); - mongoc_client_encryption_encrypt_range_opts_set_max ( - reef->ro, &reef->twoHundred); - mongoc_client_encryption_encrypt_range_opts_set_precision (reef->ro, - 2); - } else if (0 == strcmp ("Date", typeStr) || - 0 == strcmp ("Int", typeStr) || - 0 == strcmp ("Long", typeStr)) { - mongoc_client_encryption_encrypt_range_opts_set_min (reef->ro, - &reef->zero); - mongoc_client_encryption_encrypt_range_opts_set_max ( - reef->ro, &reef->twoHundred); + } else if (0 == strcmp ("DoublePrecision", typeStr) || 0 == strcmp ("DecimalPrecision", typeStr)) { + mongoc_client_encryption_encrypt_range_opts_set_min (reef->ro, &reef->zero); + mongoc_client_encryption_encrypt_range_opts_set_max (reef->ro, &reef->twoHundred); + mongoc_client_encryption_encrypt_range_opts_set_precision (reef->ro, 2); + } else if (0 == strcmp ("Date", typeStr) || 0 == strcmp ("Int", typeStr) || 0 == strcmp ("Long", typeStr)) { + mongoc_client_encryption_encrypt_range_opts_set_min (reef->ro, &reef->zero); + mongoc_client_encryption_encrypt_range_opts_set_max (reef->ro, &reef->twoHundred); } else { test_error ("Unexpected type string: %s\n", typeStr); } @@ -4209,8 +3598,7 @@ range_explicit_encryption_setup (const char *typeStr) eo = mongoc_client_encryption_encrypt_opts_new (); mongoc_client_encryption_encrypt_opts_set_keyid (eo, &reef->key1ID); - mongoc_client_encryption_encrypt_opts_set_algorithm ( - eo, MONGOC_ENCRYPT_ALGORITHM_RANGEPREVIEW); + mongoc_client_encryption_encrypt_opts_set_algorithm (eo, MONGOC_ENCRYPT_ALGORITHM_RANGEPREVIEW); mongoc_client_encryption_encrypt_opts_set_contention_factor (eo, 0); mongoc_client_encryption_encrypt_opts_set_range_opts (eo, reef->ro); @@ -4223,17 +3611,12 @@ range_explicit_encryption_setup (const char *typeStr) for (size_t i = 0; i < sizeof values / sizeof values[0]; i++) { bson_value_t *value = values[i]; bson_value_t ciphertext; - ok = mongoc_client_encryption_encrypt ( - reef->clientEncryption, value, eo, &ciphertext, &error); + ok = mongoc_client_encryption_encrypt (reef->clientEncryption, value, eo, &ciphertext, &error); ASSERT_OR_PRINT (ok, error); bson_t *doc = bson_new (); BSON_APPEND_INT32 (doc, "_id", (int32_t) i); BSON_APPEND_VALUE (doc, reef->fieldName, &ciphertext); - ok = mongoc_collection_insert_one (reef->encryptedColl, - doc, - NULL /* opts */, - NULL /* reply */, - &error); + ok = mongoc_collection_insert_one (reef->encryptedColl, doc, NULL /* opts */, NULL /* reply */, &error); ASSERT_OR_PRINT (ok, error); bson_destroy (doc); bson_value_destroy (&ciphertext); @@ -4270,9 +3653,7 @@ range_explicit_encryption_destroy (ree_fixture *reef) // variadic args are a list of const bson_value_t *. The variadic args must be // NULL terminated. static void -range_explicit_encryption_assert_cursor_results (ree_fixture *reef, - mongoc_cursor_t *cursor, - ...) +range_explicit_encryption_assert_cursor_results (ree_fixture *reef, mongoc_cursor_t *cursor, ...) { const bson_t *got; va_list args; @@ -4286,26 +3667,22 @@ range_explicit_encryption_assert_cursor_results (ree_fixture *reef, } if (!mongoc_cursor_next (cursor, &got)) { if (mongoc_cursor_error (cursor, &error)) { - test_error ("Got unexpected error in mongoc_cursor_next: %s", - error.message); + test_error ("Got unexpected error in mongoc_cursor_next: %s", error.message); } - test_error ("Expected document with value: %s but got end of cursor", - bson_value_to_str (expect)); + test_error ("Expected document with value: %s but got end of cursor", bson_value_to_str (expect)); } bson_iter_t goti; const bson_value_t *gotv; if (!bson_iter_init_find (&goti, got, reef->fieldName)) { - test_error ("Expected to find field %s, but got %s", - reef->fieldName, - bson_as_canonical_extended_json (got, NULL)); + test_error ( + "Expected to find field %s, but got %s", reef->fieldName, bson_as_canonical_extended_json (got, NULL)); } gotv = bson_iter_value (&goti); ASSERT_BSONVALUE_EQ (expect, gotv); } va_end (args); if (mongoc_cursor_next (cursor, &got)) { - test_error ("Expected end of cursor, but got extra document: %s", - bson_as_canonical_extended_json (got, NULL)); + test_error ("Expected end of cursor, but got extra document: %s", bson_as_canonical_extended_json (got, NULL)); } } @@ -4323,20 +3700,17 @@ test_range_explicit_encryption_case1 (void *ctx) eo = mongoc_client_encryption_encrypt_opts_new (); mongoc_client_encryption_encrypt_opts_set_keyid (eo, &reef->key1ID); - mongoc_client_encryption_encrypt_opts_set_algorithm ( - eo, MONGOC_ENCRYPT_ALGORITHM_RANGEPREVIEW); + mongoc_client_encryption_encrypt_opts_set_algorithm (eo, MONGOC_ENCRYPT_ALGORITHM_RANGEPREVIEW); mongoc_client_encryption_encrypt_opts_set_contention_factor (eo, 0); mongoc_client_encryption_encrypt_opts_set_range_opts (eo, reef->ro); /* Use clientEncryption.encrypt() to encrypt the value 6. */ - ok = mongoc_client_encryption_encrypt ( - reef->clientEncryption, &reef->six, eo, &insertPayload, &error); + ok = mongoc_client_encryption_encrypt (reef->clientEncryption, &reef->six, eo, &insertPayload, &error); ASSERT_OR_PRINT (ok, error); /* Use clientEncryption to decrypt insertPayload. Assert the returned value equals 6. */ - ok = mongoc_client_encryption_decrypt ( - reef->clientEncryption, &insertPayload, &decrypted, &error); + ok = mongoc_client_encryption_decrypt (reef->clientEncryption, &insertPayload, &decrypted, &error); ASSERT_OR_PRINT (ok, error); ASSERT_BSONVALUE_EQ (&decrypted, &reef->six); @@ -4357,27 +3731,21 @@ test_range_explicit_encryption_case2 (void *ctx) // Encrypt. bson_t findPayload; { - mongoc_client_encryption_encrypt_opts_t *eo = - mongoc_client_encryption_encrypt_opts_new (); + mongoc_client_encryption_encrypt_opts_t *eo = mongoc_client_encryption_encrypt_opts_new (); mongoc_client_encryption_encrypt_opts_set_keyid (eo, &reef->key1ID); - mongoc_client_encryption_encrypt_opts_set_algorithm ( - eo, MONGOC_ENCRYPT_ALGORITHM_RANGEPREVIEW); - mongoc_client_encryption_encrypt_opts_set_query_type ( - eo, MONGOC_ENCRYPT_QUERY_TYPE_RANGEPREVIEW); + mongoc_client_encryption_encrypt_opts_set_algorithm (eo, MONGOC_ENCRYPT_ALGORITHM_RANGEPREVIEW); + mongoc_client_encryption_encrypt_opts_set_query_type (eo, MONGOC_ENCRYPT_QUERY_TYPE_RANGEPREVIEW); mongoc_client_encryption_encrypt_opts_set_contention_factor (eo, 0); mongoc_client_encryption_encrypt_opts_set_range_opts (eo, reef->ro); - bsonBuildDecl ( - expr, - kv ("$and", - array ( // - doc (kv (reef->fieldName, // - doc (kv ("$gte", value (reef->six))))), // - doc (kv (reef->fieldName, - doc (kv ("$lte", value (reef->twoHundred)))))))); - - ok = mongoc_client_encryption_encrypt_expression ( - reef->clientEncryption, &expr, eo, &findPayload, &error); + bsonBuildDecl (expr, + kv ("$and", + array ( // + doc (kv (reef->fieldName, // + doc (kv ("$gte", value (reef->six))))), // + doc (kv (reef->fieldName, doc (kv ("$lte", value (reef->twoHundred)))))))); + + ok = mongoc_client_encryption_encrypt_expression (reef->clientEncryption, &expr, eo, &findPayload, &error); ASSERT_OR_PRINT (ok, error); bson_destroy (&expr); mongoc_client_encryption_encrypt_opts_destroy (eo); @@ -4386,8 +3754,8 @@ test_range_explicit_encryption_case2 (void *ctx) // Query and check results. { bson_t *opts = tmp_bson ("{'sort': { '_id': 1 }}"); - mongoc_cursor_t *cursor = mongoc_collection_find_with_opts ( - reef->encryptedColl, &findPayload, opts, NULL /* read_prefs */); + mongoc_cursor_t *cursor = + mongoc_collection_find_with_opts (reef->encryptedColl, &findPayload, opts, NULL /* read_prefs */); range_explicit_encryption_assert_cursor_results ( reef, cursor, &reef->six, &reef->thirty, &reef->twoHundred, NULL); mongoc_cursor_destroy (cursor); @@ -4409,13 +3777,10 @@ test_range_explicit_encryption_case3 (void *ctx) // Encrypt. bson_t findPayload; { - mongoc_client_encryption_encrypt_opts_t *eo = - mongoc_client_encryption_encrypt_opts_new (); + mongoc_client_encryption_encrypt_opts_t *eo = mongoc_client_encryption_encrypt_opts_new (); mongoc_client_encryption_encrypt_opts_set_keyid (eo, &reef->key1ID); - mongoc_client_encryption_encrypt_opts_set_algorithm ( - eo, MONGOC_ENCRYPT_ALGORITHM_RANGEPREVIEW); - mongoc_client_encryption_encrypt_opts_set_query_type ( - eo, MONGOC_ENCRYPT_QUERY_TYPE_RANGEPREVIEW); + mongoc_client_encryption_encrypt_opts_set_algorithm (eo, MONGOC_ENCRYPT_ALGORITHM_RANGEPREVIEW); + mongoc_client_encryption_encrypt_opts_set_query_type (eo, MONGOC_ENCRYPT_QUERY_TYPE_RANGEPREVIEW); mongoc_client_encryption_encrypt_opts_set_contention_factor (eo, 0); mongoc_client_encryption_encrypt_opts_set_range_opts (eo, reef->ro); @@ -4424,11 +3789,9 @@ test_range_explicit_encryption_case3 (void *ctx) array ( // doc (kv (reef->fieldName, // doc (kv ("$gte", value (reef->zero))))), // - doc (kv (reef->fieldName, - doc (kv ("$lte", value (reef->six)))))))); + doc (kv (reef->fieldName, doc (kv ("$lte", value (reef->six)))))))); - ok = mongoc_client_encryption_encrypt_expression ( - reef->clientEncryption, &expr, eo, &findPayload, &error); + ok = mongoc_client_encryption_encrypt_expression (reef->clientEncryption, &expr, eo, &findPayload, &error); ASSERT_OR_PRINT (ok, error); bson_destroy (&expr); mongoc_client_encryption_encrypt_opts_destroy (eo); @@ -4437,10 +3800,9 @@ test_range_explicit_encryption_case3 (void *ctx) // Query and check results. { bson_t *opts = tmp_bson ("{'sort': { '_id': 1 }}"); - mongoc_cursor_t *cursor = mongoc_collection_find_with_opts ( - reef->encryptedColl, &findPayload, opts, NULL /* read_prefs */); - range_explicit_encryption_assert_cursor_results ( - reef, cursor, &reef->zero, &reef->six, NULL); + mongoc_cursor_t *cursor = + mongoc_collection_find_with_opts (reef->encryptedColl, &findPayload, opts, NULL /* read_prefs */); + range_explicit_encryption_assert_cursor_results (reef, cursor, &reef->zero, &reef->six, NULL); mongoc_cursor_destroy (cursor); } @@ -4460,13 +3822,10 @@ test_range_explicit_encryption_case4 (void *ctx) // Encrypt. bson_t findPayload; { - mongoc_client_encryption_encrypt_opts_t *eo = - mongoc_client_encryption_encrypt_opts_new (); + mongoc_client_encryption_encrypt_opts_t *eo = mongoc_client_encryption_encrypt_opts_new (); mongoc_client_encryption_encrypt_opts_set_keyid (eo, &reef->key1ID); - mongoc_client_encryption_encrypt_opts_set_algorithm ( - eo, MONGOC_ENCRYPT_ALGORITHM_RANGEPREVIEW); - mongoc_client_encryption_encrypt_opts_set_query_type ( - eo, MONGOC_ENCRYPT_QUERY_TYPE_RANGEPREVIEW); + mongoc_client_encryption_encrypt_opts_set_algorithm (eo, MONGOC_ENCRYPT_ALGORITHM_RANGEPREVIEW); + mongoc_client_encryption_encrypt_opts_set_query_type (eo, MONGOC_ENCRYPT_QUERY_TYPE_RANGEPREVIEW); mongoc_client_encryption_encrypt_opts_set_contention_factor (eo, 0); mongoc_client_encryption_encrypt_opts_set_range_opts (eo, reef->ro); @@ -4477,8 +3836,7 @@ test_range_explicit_encryption_case4 (void *ctx) doc (kv ("$gt", value (reef->thirty))))) // ))); - ok = mongoc_client_encryption_encrypt_expression ( - reef->clientEncryption, &expr, eo, &findPayload, &error); + ok = mongoc_client_encryption_encrypt_expression (reef->clientEncryption, &expr, eo, &findPayload, &error); ASSERT_OR_PRINT (ok, error); bson_destroy (&expr); mongoc_client_encryption_encrypt_opts_destroy (eo); @@ -4487,10 +3845,9 @@ test_range_explicit_encryption_case4 (void *ctx) // Query and check results. { bson_t *opts = tmp_bson ("{'sort': { '_id': 1 }}"); - mongoc_cursor_t *cursor = mongoc_collection_find_with_opts ( - reef->encryptedColl, &findPayload, opts, NULL /* read_prefs */); - range_explicit_encryption_assert_cursor_results ( - reef, cursor, &reef->twoHundred, NULL); + mongoc_cursor_t *cursor = + mongoc_collection_find_with_opts (reef->encryptedColl, &findPayload, opts, NULL /* read_prefs */); + range_explicit_encryption_assert_cursor_results (reef, cursor, &reef->twoHundred, NULL); mongoc_cursor_destroy (cursor); } @@ -4510,28 +3867,23 @@ test_range_explicit_encryption_case5 (void *ctx) // Encrypt. bson_t findPayload; { - mongoc_client_encryption_encrypt_opts_t *eo = - mongoc_client_encryption_encrypt_opts_new (); + mongoc_client_encryption_encrypt_opts_t *eo = mongoc_client_encryption_encrypt_opts_new (); mongoc_client_encryption_encrypt_opts_set_keyid (eo, &reef->key1ID); - mongoc_client_encryption_encrypt_opts_set_algorithm ( - eo, MONGOC_ENCRYPT_ALGORITHM_RANGEPREVIEW); - mongoc_client_encryption_encrypt_opts_set_query_type ( - eo, MONGOC_ENCRYPT_QUERY_TYPE_RANGEPREVIEW); + mongoc_client_encryption_encrypt_opts_set_algorithm (eo, MONGOC_ENCRYPT_ALGORITHM_RANGEPREVIEW); + mongoc_client_encryption_encrypt_opts_set_query_type (eo, MONGOC_ENCRYPT_QUERY_TYPE_RANGEPREVIEW); mongoc_client_encryption_encrypt_opts_set_contention_factor (eo, 0); mongoc_client_encryption_encrypt_opts_set_range_opts (eo, reef->ro); char *fieldPath = bson_strdup_printf ("$%s", reef->fieldName); // Encrypt this: // {'$and': [ { '$lt': [ '$encrypted', 30 ] } ] } } - bsonBuildDecl ( - expr, - kv ("$and", - array ( // - doc (kv ("$lt", // - array (cstr (fieldPath), value (reef->thirty))))))); - - ok = mongoc_client_encryption_encrypt_expression ( - reef->clientEncryption, &expr, eo, &findPayload, &error); + bsonBuildDecl (expr, + kv ("$and", + array ( // + doc (kv ("$lt", // + array (cstr (fieldPath), value (reef->thirty))))))); + + ok = mongoc_client_encryption_encrypt_expression (reef->clientEncryption, &expr, eo, &findPayload, &error); ASSERT_OR_PRINT (ok, error); bson_free (fieldPath); bson_destroy (&expr); @@ -4542,10 +3894,9 @@ test_range_explicit_encryption_case5 (void *ctx) { bson_t *opts = tmp_bson ("{'sort': { '_id': 1 }}"); bsonBuildDecl (filter, kv ("$expr", bson (findPayload))); - mongoc_cursor_t *cursor = mongoc_collection_find_with_opts ( - reef->encryptedColl, &filter, opts, NULL /* read_prefs */); - range_explicit_encryption_assert_cursor_results ( - reef, cursor, &reef->zero, &reef->six, NULL); + mongoc_cursor_t *cursor = + mongoc_collection_find_with_opts (reef->encryptedColl, &filter, opts, NULL /* read_prefs */); + range_explicit_encryption_assert_cursor_results (reef, cursor, &reef->zero, &reef->six, NULL); bson_destroy (&filter); mongoc_cursor_destroy (cursor); } @@ -4562,8 +3913,7 @@ test_range_explicit_encryption_case6 (void *ctx) // This test case should be skipped if the encrypted field is // encryptedDoubleNoPrecision or encryptedDecimalNoPrecision. - if (0 == strcmp (typeStr, "DoubleNoPrecision") || - 0 == strcmp (typeStr, "DecimalNoPrecision")) { + if (0 == strcmp (typeStr, "DoubleNoPrecision") || 0 == strcmp (typeStr, "DecimalNoPrecision")) { MONGOC_DEBUG ("skipping test"); return; } @@ -4575,19 +3925,13 @@ test_range_explicit_encryption_case6 (void *ctx) // Encrypt. bson_value_t insertPayload; { - mongoc_client_encryption_encrypt_opts_t *eo = - mongoc_client_encryption_encrypt_opts_new (); + mongoc_client_encryption_encrypt_opts_t *eo = mongoc_client_encryption_encrypt_opts_new (); mongoc_client_encryption_encrypt_opts_set_keyid (eo, &reef->key1ID); - mongoc_client_encryption_encrypt_opts_set_algorithm ( - eo, MONGOC_ENCRYPT_ALGORITHM_RANGEPREVIEW); + mongoc_client_encryption_encrypt_opts_set_algorithm (eo, MONGOC_ENCRYPT_ALGORITHM_RANGEPREVIEW); mongoc_client_encryption_encrypt_opts_set_contention_factor (eo, 0); mongoc_client_encryption_encrypt_opts_set_range_opts (eo, reef->ro); - ok = mongoc_client_encryption_encrypt (reef->clientEncryption, - &reef->twoHundredOne, - eo, - &insertPayload, - &error); + ok = mongoc_client_encryption_encrypt (reef->clientEncryption, &reef->twoHundredOne, eo, &insertPayload, &error); ASSERT (!ok); mongoc_client_encryption_encrypt_opts_destroy (eo); } @@ -4604,8 +3948,7 @@ test_range_explicit_encryption_case7 (void *ctx) // This test case should be skipped if the encrypted field is // encryptedDoubleNoPrecision or encryptedDecimalNoPrecision. - if (0 == strcmp (typeStr, "DoubleNoPrecision") || - 0 == strcmp (typeStr, "DecimalNoPrecision")) { + if (0 == strcmp (typeStr, "DoubleNoPrecision") || 0 == strcmp (typeStr, "DecimalNoPrecision")) { MONGOC_DEBUG ("skipping test"); return; } @@ -4617,11 +3960,9 @@ test_range_explicit_encryption_case7 (void *ctx) // Encrypt. bson_value_t insertPayload; { - mongoc_client_encryption_encrypt_opts_t *eo = - mongoc_client_encryption_encrypt_opts_new (); + mongoc_client_encryption_encrypt_opts_t *eo = mongoc_client_encryption_encrypt_opts_new (); mongoc_client_encryption_encrypt_opts_set_keyid (eo, &reef->key1ID); - mongoc_client_encryption_encrypt_opts_set_algorithm ( - eo, MONGOC_ENCRYPT_ALGORITHM_RANGEPREVIEW); + mongoc_client_encryption_encrypt_opts_set_algorithm (eo, MONGOC_ENCRYPT_ALGORITHM_RANGEPREVIEW); mongoc_client_encryption_encrypt_opts_set_contention_factor (eo, 0); mongoc_client_encryption_encrypt_opts_set_range_opts (eo, reef->ro); @@ -4634,8 +3975,7 @@ test_range_explicit_encryption_case7 (void *ctx) wrongType.value.v_int32 = 6; } - ok = mongoc_client_encryption_encrypt ( - reef->clientEncryption, &wrongType, eo, &insertPayload, &error); + ok = mongoc_client_encryption_encrypt (reef->clientEncryption, &wrongType, eo, &insertPayload, &error); ASSERT (!ok); mongoc_client_encryption_encrypt_opts_destroy (eo); } @@ -4653,10 +3993,8 @@ test_range_explicit_encryption_case8 (void *ctx) // This test case should be skipped if the encrypted field is // encryptedDoublePrecision or encryptedDoubleNoPrecision or // encryptedDecimalPrecision or encryptedDecimalNoPrecision. - if (0 == strcmp (typeStr, "DoubleNoPrecision") || - 0 == strcmp (typeStr, "DoublePrecision") || - 0 == strcmp (typeStr, "DecimalPrecision") || - 0 == strcmp (typeStr, "DecimalNoPrecision")) { + if (0 == strcmp (typeStr, "DoubleNoPrecision") || 0 == strcmp (typeStr, "DoublePrecision") || + 0 == strcmp (typeStr, "DecimalPrecision") || 0 == strcmp (typeStr, "DecimalNoPrecision")) { MONGOC_DEBUG ("skipping test"); return; } @@ -4668,17 +4006,14 @@ test_range_explicit_encryption_case8 (void *ctx) // Encrypt. bson_value_t insertPayload; { - mongoc_client_encryption_encrypt_opts_t *eo = - mongoc_client_encryption_encrypt_opts_new (); + mongoc_client_encryption_encrypt_opts_t *eo = mongoc_client_encryption_encrypt_opts_new (); mongoc_client_encryption_encrypt_opts_set_keyid (eo, &reef->key1ID); - mongoc_client_encryption_encrypt_opts_set_algorithm ( - eo, MONGOC_ENCRYPT_ALGORITHM_RANGEPREVIEW); + mongoc_client_encryption_encrypt_opts_set_algorithm (eo, MONGOC_ENCRYPT_ALGORITHM_RANGEPREVIEW); mongoc_client_encryption_encrypt_opts_set_contention_factor (eo, 0); mongoc_client_encryption_encrypt_range_opts_set_precision (reef->ro, 2); mongoc_client_encryption_encrypt_opts_set_range_opts (eo, reef->ro); - ok = mongoc_client_encryption_encrypt ( - reef->clientEncryption, &reef->six, eo, &insertPayload, &error); + ok = mongoc_client_encryption_encrypt (reef->clientEncryption, &reef->six, eo, &insertPayload, &error); ASSERT (!ok); mongoc_client_encryption_encrypt_opts_destroy (eo); } @@ -4711,22 +4046,15 @@ test_explicit_encryption_case1 (void *unused) eopts = mongoc_client_encryption_encrypt_opts_new (); mongoc_client_encryption_encrypt_opts_set_keyid (eopts, &eef->key1ID); - mongoc_client_encryption_encrypt_opts_set_algorithm ( - eopts, MONGOC_ENCRYPT_ALGORITHM_INDEXED); + mongoc_client_encryption_encrypt_opts_set_algorithm (eopts, MONGOC_ENCRYPT_ALGORITHM_INDEXED); mongoc_client_encryption_encrypt_opts_set_contention_factor (eopts, 0); - ok = mongoc_client_encryption_encrypt ( - eef->clientEncryption, &plaintext, eopts, &insertPayload, &error); + ok = mongoc_client_encryption_encrypt (eef->clientEncryption, &plaintext, eopts, &insertPayload, &error); ASSERT_OR_PRINT (ok, error); - ASSERT ( - BSON_APPEND_VALUE (&to_insert, "encryptedIndexed", &insertPayload)); + ASSERT (BSON_APPEND_VALUE (&to_insert, "encryptedIndexed", &insertPayload)); - ok = mongoc_collection_insert_one (eef->encryptedColl, - &to_insert, - NULL /* opts */, - NULL /* reply */, - &error); + ok = mongoc_collection_insert_one (eef->encryptedColl, &to_insert, NULL /* opts */, NULL /* reply */, &error); ASSERT_OR_PRINT (ok, error); bson_value_destroy (&insertPayload); @@ -4745,25 +4073,20 @@ test_explicit_encryption_case1 (void *unused) eopts = mongoc_client_encryption_encrypt_opts_new (); mongoc_client_encryption_encrypt_opts_set_keyid (eopts, &eef->key1ID); - mongoc_client_encryption_encrypt_opts_set_algorithm ( - eopts, MONGOC_ENCRYPT_ALGORITHM_INDEXED); - mongoc_client_encryption_encrypt_opts_set_query_type ( - eopts, MONGOC_ENCRYPT_QUERY_TYPE_EQUALITY); + mongoc_client_encryption_encrypt_opts_set_algorithm (eopts, MONGOC_ENCRYPT_ALGORITHM_INDEXED); + mongoc_client_encryption_encrypt_opts_set_query_type (eopts, MONGOC_ENCRYPT_QUERY_TYPE_EQUALITY); mongoc_client_encryption_encrypt_opts_set_contention_factor (eopts, 0); - ok = mongoc_client_encryption_encrypt ( - eef->clientEncryption, &plaintext, eopts, &findPayload, &error); + ok = mongoc_client_encryption_encrypt (eef->clientEncryption, &plaintext, eopts, &findPayload, &error); ASSERT_OR_PRINT (ok, error); ASSERT (BSON_APPEND_VALUE (&filter, "encryptedIndexed", &findPayload)); - cursor = mongoc_collection_find_with_opts ( - eef->encryptedColl, &filter, NULL /* opts */, NULL /* read_prefs */); + cursor = mongoc_collection_find_with_opts (eef->encryptedColl, &filter, NULL /* opts */, NULL /* read_prefs */); ASSERT (mongoc_cursor_next (cursor, &got)); ASSERT_OR_PRINT (!mongoc_cursor_error (cursor, &error), error); ASSERT_MATCH (got, "{ 'encryptedIndexed': 'encrypted indexed value' }"); - ASSERT (!mongoc_cursor_next (cursor, &got) && - "expected one document to be returned, got more than one"); + ASSERT (!mongoc_cursor_next (cursor, &got) && "expected one document to be returned, got more than one"); bson_value_destroy (&findPayload); mongoc_cursor_destroy (cursor); @@ -4799,22 +4122,15 @@ test_explicit_encryption_case2 (void *unused) eopts = mongoc_client_encryption_encrypt_opts_new (); mongoc_client_encryption_encrypt_opts_set_keyid (eopts, &eef->key1ID); - mongoc_client_encryption_encrypt_opts_set_algorithm ( - eopts, MONGOC_ENCRYPT_ALGORITHM_INDEXED); + mongoc_client_encryption_encrypt_opts_set_algorithm (eopts, MONGOC_ENCRYPT_ALGORITHM_INDEXED); mongoc_client_encryption_encrypt_opts_set_contention_factor (eopts, 10); - ok = mongoc_client_encryption_encrypt ( - eef->clientEncryption, &plaintext, eopts, &insertPayload, &error); + ok = mongoc_client_encryption_encrypt (eef->clientEncryption, &plaintext, eopts, &insertPayload, &error); ASSERT_OR_PRINT (ok, error); - ASSERT ( - BSON_APPEND_VALUE (&to_insert, "encryptedIndexed", &insertPayload)); + ASSERT (BSON_APPEND_VALUE (&to_insert, "encryptedIndexed", &insertPayload)); - ok = mongoc_collection_insert_one (eef->encryptedColl, - &to_insert, - NULL /* opts */, - NULL /* reply */, - &error); + ok = mongoc_collection_insert_one (eef->encryptedColl, &to_insert, NULL /* opts */, NULL /* reply */, &error); ASSERT_OR_PRINT (ok, error); bson_value_destroy (&insertPayload); @@ -4833,25 +4149,20 @@ test_explicit_encryption_case2 (void *unused) eopts = mongoc_client_encryption_encrypt_opts_new (); mongoc_client_encryption_encrypt_opts_set_keyid (eopts, &eef->key1ID); - mongoc_client_encryption_encrypt_opts_set_algorithm ( - eopts, MONGOC_ENCRYPT_ALGORITHM_INDEXED); - mongoc_client_encryption_encrypt_opts_set_query_type ( - eopts, MONGOC_ENCRYPT_QUERY_TYPE_EQUALITY); + mongoc_client_encryption_encrypt_opts_set_algorithm (eopts, MONGOC_ENCRYPT_ALGORITHM_INDEXED); + mongoc_client_encryption_encrypt_opts_set_query_type (eopts, MONGOC_ENCRYPT_QUERY_TYPE_EQUALITY); mongoc_client_encryption_encrypt_opts_set_contention_factor (eopts, 0); - ok = mongoc_client_encryption_encrypt ( - eef->clientEncryption, &plaintext, eopts, &findPayload, &error); + ok = mongoc_client_encryption_encrypt (eef->clientEncryption, &plaintext, eopts, &findPayload, &error); ASSERT_OR_PRINT (ok, error); ASSERT (BSON_APPEND_VALUE (&filter, "encryptedIndexed", &findPayload)); - cursor = mongoc_collection_find_with_opts ( - eef->encryptedColl, &filter, NULL /* opts */, NULL /* read_prefs */); + cursor = mongoc_collection_find_with_opts (eef->encryptedColl, &filter, NULL /* opts */, NULL /* read_prefs */); while (mongoc_cursor_next (cursor, &got)) { got_count++; - ASSERT_MATCH (got, - "{ 'encryptedIndexed': 'encrypted indexed value' }"); + ASSERT_MATCH (got, "{ 'encryptedIndexed': 'encrypted indexed value' }"); } ASSERT_OR_PRINT (!mongoc_cursor_error (cursor, &error), error); ASSERT_CMPINT (got_count, <, 10); @@ -4872,25 +4183,20 @@ test_explicit_encryption_case2 (void *unused) eopts = mongoc_client_encryption_encrypt_opts_new (); mongoc_client_encryption_encrypt_opts_set_keyid (eopts, &eef->key1ID); - mongoc_client_encryption_encrypt_opts_set_algorithm ( - eopts, MONGOC_ENCRYPT_ALGORITHM_INDEXED); - mongoc_client_encryption_encrypt_opts_set_query_type ( - eopts, MONGOC_ENCRYPT_QUERY_TYPE_EQUALITY); + mongoc_client_encryption_encrypt_opts_set_algorithm (eopts, MONGOC_ENCRYPT_ALGORITHM_INDEXED); + mongoc_client_encryption_encrypt_opts_set_query_type (eopts, MONGOC_ENCRYPT_QUERY_TYPE_EQUALITY); mongoc_client_encryption_encrypt_opts_set_contention_factor (eopts, 10); - ok = mongoc_client_encryption_encrypt ( - eef->clientEncryption, &plaintext, eopts, &findPayload, &error); + ok = mongoc_client_encryption_encrypt (eef->clientEncryption, &plaintext, eopts, &findPayload, &error); ASSERT_OR_PRINT (ok, error); ASSERT (BSON_APPEND_VALUE (&filter, "encryptedIndexed", &findPayload)); - cursor = mongoc_collection_find_with_opts ( - eef->encryptedColl, &filter, NULL /* opts */, NULL /* read_prefs */); + cursor = mongoc_collection_find_with_opts (eef->encryptedColl, &filter, NULL /* opts */, NULL /* read_prefs */); while (mongoc_cursor_next (cursor, &got)) { got_count++; - ASSERT_MATCH (got, - "{ 'encryptedIndexed': 'encrypted indexed value' }"); + ASSERT_MATCH (got, "{ 'encryptedIndexed': 'encrypted indexed value' }"); } ASSERT_OR_PRINT (!mongoc_cursor_error (cursor, &error), error); ASSERT_CMPINT (got_count, ==, 10); @@ -4928,22 +4234,15 @@ test_explicit_encryption_case3 (void *unused) eopts = mongoc_client_encryption_encrypt_opts_new (); mongoc_client_encryption_encrypt_opts_set_keyid (eopts, &eef->key1ID); - mongoc_client_encryption_encrypt_opts_set_algorithm ( - eopts, MONGOC_ENCRYPT_ALGORITHM_UNINDEXED); + mongoc_client_encryption_encrypt_opts_set_algorithm (eopts, MONGOC_ENCRYPT_ALGORITHM_UNINDEXED); - ok = mongoc_client_encryption_encrypt ( - eef->clientEncryption, &plaintext, eopts, &insertPayload, &error); + ok = mongoc_client_encryption_encrypt (eef->clientEncryption, &plaintext, eopts, &insertPayload, &error); ASSERT_OR_PRINT (ok, error); ASSERT (BSON_APPEND_INT32 (&to_insert, "_id", 1)); - ASSERT ( - BSON_APPEND_VALUE (&to_insert, "encryptedUnindexed", &insertPayload)); - - ok = mongoc_collection_insert_one (eef->encryptedColl, - &to_insert, - NULL /* opts */, - NULL /* reply */, - &error); + ASSERT (BSON_APPEND_VALUE (&to_insert, "encryptedUnindexed", &insertPayload)); + + ok = mongoc_collection_insert_one (eef->encryptedColl, &to_insert, NULL /* opts */, NULL /* reply */, &error); ASSERT_OR_PRINT (ok, error); bson_value_destroy (&insertPayload); @@ -4960,14 +4259,11 @@ test_explicit_encryption_case3 (void *unused) ASSERT (BSON_APPEND_INT32 (&filter, "_id", 1)); - cursor = mongoc_collection_find_with_opts ( - eef->encryptedColl, &filter, NULL /* opts */, NULL /* read_prefs */); + cursor = mongoc_collection_find_with_opts (eef->encryptedColl, &filter, NULL /* opts */, NULL /* read_prefs */); ASSERT (mongoc_cursor_next (cursor, &got)); ASSERT_OR_PRINT (!mongoc_cursor_error (cursor, &error), error); - ASSERT_MATCH (got, - "{ 'encryptedUnindexed': 'encrypted unindexed value' }"); - ASSERT (!mongoc_cursor_next (cursor, &got) && - "expected one document to be returned, got more than one"); + ASSERT_MATCH (got, "{ 'encryptedUnindexed': 'encrypted unindexed value' }"); + ASSERT (!mongoc_cursor_next (cursor, &got) && "expected one document to be returned, got more than one"); mongoc_cursor_destroy (cursor); bson_destroy (&filter); @@ -4998,12 +4294,10 @@ test_explicit_encryption_case4 (void *unused) { eopts = mongoc_client_encryption_encrypt_opts_new (); mongoc_client_encryption_encrypt_opts_set_keyid (eopts, &eef->key1ID); - mongoc_client_encryption_encrypt_opts_set_algorithm ( - eopts, MONGOC_ENCRYPT_ALGORITHM_INDEXED); + mongoc_client_encryption_encrypt_opts_set_algorithm (eopts, MONGOC_ENCRYPT_ALGORITHM_INDEXED); mongoc_client_encryption_encrypt_opts_set_contention_factor (eopts, 0); - ok = mongoc_client_encryption_encrypt ( - eef->clientEncryption, &plaintext, eopts, &payload, &error); + ok = mongoc_client_encryption_encrypt (eef->clientEncryption, &plaintext, eopts, &payload, &error); ASSERT_OR_PRINT (ok, error); mongoc_client_encryption_encrypt_opts_destroy (eopts); @@ -5013,8 +4307,7 @@ test_explicit_encryption_case4 (void *unused) { bson_value_t got; - ok = mongoc_client_encryption_decrypt ( - eef->clientEncryption, &payload, &got, &error); + ok = mongoc_client_encryption_decrypt (eef->clientEncryption, &payload, &got, &error); ASSERT_OR_PRINT (ok, error); ASSERT (got.value_type == BSON_TYPE_UTF8); ASSERT_CMPSTR (got.value.v_utf8.str, "encrypted indexed value"); @@ -5047,11 +4340,9 @@ test_explicit_encryption_case5 (void *unused) { eopts = mongoc_client_encryption_encrypt_opts_new (); mongoc_client_encryption_encrypt_opts_set_keyid (eopts, &eef->key1ID); - mongoc_client_encryption_encrypt_opts_set_algorithm ( - eopts, MONGOC_ENCRYPT_ALGORITHM_UNINDEXED); + mongoc_client_encryption_encrypt_opts_set_algorithm (eopts, MONGOC_ENCRYPT_ALGORITHM_UNINDEXED); - ok = mongoc_client_encryption_encrypt ( - eef->clientEncryption, &plaintext, eopts, &payload, &error); + ok = mongoc_client_encryption_encrypt (eef->clientEncryption, &plaintext, eopts, &payload, &error); ASSERT_OR_PRINT (ok, error); mongoc_client_encryption_encrypt_opts_destroy (eopts); @@ -5061,8 +4352,7 @@ test_explicit_encryption_case5 (void *unused) { bson_value_t got; - ok = mongoc_client_encryption_decrypt ( - eef->clientEncryption, &payload, &got, &error); + ok = mongoc_client_encryption_decrypt (eef->clientEncryption, &payload, &got, &error); ASSERT_OR_PRINT (ok, error); ASSERT (got.value_type == BSON_TYPE_UTF8); ASSERT_CMPSTR (got.value.v_utf8.str, "encrypted unindexed value"); @@ -5074,8 +4364,7 @@ test_explicit_encryption_case5 (void *unused) } static void -_test_unique_index_on_keyaltnames_setup ( - void (*test_case) (mongoc_client_encryption_t *, const bson_value_t *keyid)) +_test_unique_index_on_keyaltnames_setup (void (*test_case) (mongoc_client_encryption_t *, const bson_value_t *keyid)) { mongoc_client_t *client = NULL; mongoc_database_t *keyvault = NULL; @@ -5089,8 +4378,7 @@ _test_unique_index_on_keyaltnames_setup ( /* Using client, drop the collection keyvault.datakeys. */ { - mongoc_collection_t *const datakeys = - mongoc_database_get_collection (keyvault, "datakeys"); + mongoc_collection_t *const datakeys = mongoc_database_get_collection (keyvault, "datakeys"); mongoc_collection_drop (datakeys, &error); mongoc_collection_destroy (datakeys); } @@ -5098,23 +4386,19 @@ _test_unique_index_on_keyaltnames_setup ( /* Using client, create a unique index on keyAltNames with a partial index * filter for only documents where keyAltNames exists. */ { - mongoc_collection_t *const datakeys = - mongoc_database_get_collection (keyvault, "datakeys"); + mongoc_collection_t *const datakeys = mongoc_database_get_collection (keyvault, "datakeys"); - mongoc_index_model_t *im = mongoc_index_model_new ( - tmp_bson ("{'keyAltNames': 1}"), tmp_bson (BSON_STR ({ - "name" : "keyAltNames_1", - "unique" : true, - "partialFilterExpression" : {"keyAltNames" : {"$exists" : true}} - }))); + mongoc_index_model_t *im = + mongoc_index_model_new (tmp_bson ("{'keyAltNames': 1}"), tmp_bson (BSON_STR ({ + "name" : "keyAltNames_1", + "unique" : true, + "partialFilterExpression" : {"keyAltNames" : {"$exists" : true}} + }))); - bson_t *const command_opts = - tmp_bson ("{'writeConcern': { 'w': 'majority' }}"); + bson_t *const command_opts = tmp_bson ("{'writeConcern': { 'w': 'majority' }}"); ASSERT_OR_PRINT ( - mongoc_collection_create_indexes_with_opts ( - datakeys, &im, 1, command_opts, NULL /* reply */, &error), - error); + mongoc_collection_create_indexes_with_opts (datakeys, &im, 1, command_opts, NULL /* reply */, &error), error); mongoc_index_model_destroy (im); mongoc_collection_destroy (datakeys); } @@ -5122,22 +4406,15 @@ _test_unique_index_on_keyaltnames_setup ( /* Create a ClientEncryption object (referred to as client_encryption) with * client set as the keyVaultClient. */ { - mongoc_client_encryption_opts_t *const client_encryption_opts = - mongoc_client_encryption_opts_new (); - bson_t *const kms_providers = - _make_kms_providers (true /* aws */, true /* local */); + mongoc_client_encryption_opts_t *const client_encryption_opts = mongoc_client_encryption_opts_new (); + bson_t *const kms_providers = _make_kms_providers (true /* aws */, true /* local */); bson_t *const tls_opts = _make_tls_opts (); - mongoc_client_encryption_opts_set_kms_providers (client_encryption_opts, - kms_providers); - mongoc_client_encryption_opts_set_tls_opts (client_encryption_opts, - tls_opts); - mongoc_client_encryption_opts_set_keyvault_namespace ( - client_encryption_opts, "keyvault", "datakeys"); - mongoc_client_encryption_opts_set_keyvault_client (client_encryption_opts, - client); - client_encryption = - mongoc_client_encryption_new (client_encryption_opts, &error); + mongoc_client_encryption_opts_set_kms_providers (client_encryption_opts, kms_providers); + mongoc_client_encryption_opts_set_tls_opts (client_encryption_opts, tls_opts); + mongoc_client_encryption_opts_set_keyvault_namespace (client_encryption_opts, "keyvault", "datakeys"); + mongoc_client_encryption_opts_set_keyvault_client (client_encryption_opts, client); + client_encryption = mongoc_client_encryption_new (client_encryption_opts, &error); ASSERT_OR_PRINT (client_encryption, error); mongoc_client_encryption_opts_destroy (client_encryption_opts); @@ -5148,17 +4425,13 @@ _test_unique_index_on_keyaltnames_setup ( /* Using client_encryption, create a data key with a local KMS provider * and the keyAltName "def" (referred to as "the existing key"). */ { - mongoc_client_encryption_datakey_opts_t *const opts = - mongoc_client_encryption_datakey_opts_new (); + mongoc_client_encryption_datakey_opts_t *const opts = mongoc_client_encryption_datakey_opts_new (); const char *const keyaltname[] = {"def"}; - mongoc_client_encryption_datakey_opts_set_keyaltnames ( - opts, (char **) keyaltname, 1u); + mongoc_client_encryption_datakey_opts_set_keyaltnames (opts, (char **) keyaltname, 1u); ASSERT_OR_PRINT ( - mongoc_client_encryption_create_datakey ( - client_encryption, "local", opts, &existing_key, &error), - error); + mongoc_client_encryption_create_datakey (client_encryption, "local", opts, &existing_key, &error), error); mongoc_client_encryption_datakey_opts_destroy (opts); } @@ -5172,9 +4445,8 @@ _test_unique_index_on_keyaltnames_setup ( } static void -_test_unique_index_on_keyaltnames_case_1 ( - mongoc_client_encryption_t *client_encryption, - const bson_value_t *existing_key) +_test_unique_index_on_keyaltnames_case_1 (mongoc_client_encryption_t *client_encryption, + const bson_value_t *existing_key) { bson_error_t error; @@ -5183,16 +4455,13 @@ _test_unique_index_on_keyaltnames_case_1 ( /* Step 1: Use client_encryption to create a new local data key with a * keyAltName "abc" and assert the operation does not fail. */ { - mongoc_client_encryption_datakey_opts_t *const opts = - mongoc_client_encryption_datakey_opts_new (); + mongoc_client_encryption_datakey_opts_t *const opts = mongoc_client_encryption_datakey_opts_new (); const char *const keyaltname[] = {"abc"}; bson_value_t keyid; - mongoc_client_encryption_datakey_opts_set_keyaltnames ( - opts, (char **) keyaltname, 1u); + mongoc_client_encryption_datakey_opts_set_keyaltnames (opts, (char **) keyaltname, 1u); - ASSERT_OR_PRINT (mongoc_client_encryption_create_datakey ( - client_encryption, "local", opts, &keyid, &error), + ASSERT_OR_PRINT (mongoc_client_encryption_create_datakey (client_encryption, "local", opts, &keyid, &error), error); mongoc_client_encryption_datakey_opts_destroy (opts); @@ -5202,20 +4471,14 @@ _test_unique_index_on_keyaltnames_case_1 ( /* Step 2: Repeat Step 1 and assert the operation fails due to a duplicate * key server error (error code 11000). */ { - mongoc_client_encryption_datakey_opts_t *const opts = - mongoc_client_encryption_datakey_opts_new (); + mongoc_client_encryption_datakey_opts_t *const opts = mongoc_client_encryption_datakey_opts_new (); const char *const keyaltname[] = {"abc"}; bson_value_t keyid; - mongoc_client_encryption_datakey_opts_set_keyaltnames ( - opts, (char **) keyaltname, 1u); + mongoc_client_encryption_datakey_opts_set_keyaltnames (opts, (char **) keyaltname, 1u); - ASSERT (!mongoc_client_encryption_create_datakey ( - client_encryption, "local", opts, &keyid, &error)); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COLLECTION, - MONGOC_ERROR_DUPLICATE_KEY, - "keyAltNames: \"abc\""); + ASSERT (!mongoc_client_encryption_create_datakey (client_encryption, "local", opts, &keyid, &error)); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COLLECTION, MONGOC_ERROR_DUPLICATE_KEY, "keyAltNames: \"abc\""); mongoc_client_encryption_datakey_opts_destroy (opts); bson_value_destroy (&keyid); @@ -5225,20 +4488,14 @@ _test_unique_index_on_keyaltnames_case_1 ( * keyAltName "def" and assert the operation fails due to a duplicate key * server error (error code 11000). */ { - mongoc_client_encryption_datakey_opts_t *const opts = - mongoc_client_encryption_datakey_opts_new (); + mongoc_client_encryption_datakey_opts_t *const opts = mongoc_client_encryption_datakey_opts_new (); const char *const keyaltname[] = {"def"}; bson_value_t keyid; - mongoc_client_encryption_datakey_opts_set_keyaltnames ( - opts, (char **) keyaltname, 1u); + mongoc_client_encryption_datakey_opts_set_keyaltnames (opts, (char **) keyaltname, 1u); - ASSERT (!mongoc_client_encryption_create_datakey ( - client_encryption, "local", opts, &keyid, &error)); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COLLECTION, - MONGOC_ERROR_DUPLICATE_KEY, - "keyAltNames: \"def\""); + ASSERT (!mongoc_client_encryption_create_datakey (client_encryption, "local", opts, &keyid, &error)); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COLLECTION, MONGOC_ERROR_DUPLICATE_KEY, "keyAltNames: \"def\""); mongoc_client_encryption_datakey_opts_destroy (opts); bson_value_destroy (&keyid); @@ -5246,27 +4503,23 @@ _test_unique_index_on_keyaltnames_case_1 ( } static void -_test_unique_index_on_keyaltnames_case_2 ( - mongoc_client_encryption_t *client_encryption, - const bson_value_t *existing_key) +_test_unique_index_on_keyaltnames_case_2 (mongoc_client_encryption_t *client_encryption, + const bson_value_t *existing_key) { bson_value_t new_key; bson_error_t error; - mongoc_client_encryption_datakey_opts_t *const opts = - mongoc_client_encryption_datakey_opts_new (); + mongoc_client_encryption_datakey_opts_t *const opts = mongoc_client_encryption_datakey_opts_new (); /* Step 1: Use client_encryption to create a new local data key and assert * the operation does not fail. */ - ASSERT_OR_PRINT (mongoc_client_encryption_create_datakey ( - client_encryption, "local", opts, &new_key, &error), + ASSERT_OR_PRINT (mongoc_client_encryption_create_datakey (client_encryption, "local", opts, &new_key, &error), error); /* Step 2: Use client_encryption to add a keyAltName "abc" to the key created * in Step 1 and assert the operation does not fail. */ { bson_t key_doc; - ASSERT_OR_PRINT (mongoc_client_encryption_add_key_alt_name ( - client_encryption, &new_key, "abc", &key_doc, &error), + ASSERT_OR_PRINT (mongoc_client_encryption_add_key_alt_name (client_encryption, &new_key, "abc", &key_doc, &error), error); bson_destroy (&key_doc); } @@ -5275,11 +4528,9 @@ _test_unique_index_on_keyaltnames_case_2 ( * returned key document contains the keyAltName "abc" added in Step 2. */ { bson_t key_doc; - ASSERT_OR_PRINT (mongoc_client_encryption_add_key_alt_name ( - client_encryption, &new_key, "abc", &key_doc, &error), + ASSERT_OR_PRINT (mongoc_client_encryption_add_key_alt_name (client_encryption, &new_key, "abc", &key_doc, &error), error); - ASSERT ( - match_bson (&key_doc, tmp_bson ("{'keyAltNames': ['abc']}"), false)); + ASSERT (match_bson (&key_doc, tmp_bson ("{'keyAltNames': ['abc']}"), false)); bson_destroy (&key_doc); } @@ -5288,12 +4539,8 @@ _test_unique_index_on_keyaltnames_case_2 ( * error (error code 11000). */ { bson_t key_doc; - ASSERT (!mongoc_client_encryption_add_key_alt_name ( - client_encryption, &new_key, "def", &key_doc, &error)); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_QUERY, - MONGOC_ERROR_DUPLICATE_KEY, - "keyAltNames: \"def\""); + ASSERT (!mongoc_client_encryption_add_key_alt_name (client_encryption, &new_key, "def", &key_doc, &error)); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_QUERY, MONGOC_ERROR_DUPLICATE_KEY, "keyAltNames: \"def\""); bson_destroy (&key_doc); } @@ -5303,11 +4550,8 @@ _test_unique_index_on_keyaltnames_case_2 ( { bson_t key_doc; ASSERT_OR_PRINT ( - mongoc_client_encryption_add_key_alt_name ( - client_encryption, existing_key, "def", &key_doc, &error), - error); - ASSERT ( - match_bson (&key_doc, tmp_bson ("{'keyAltNames': ['def']}"), false)); + mongoc_client_encryption_add_key_alt_name (client_encryption, existing_key, "def", &key_doc, &error), error); + ASSERT (match_bson (&key_doc, tmp_bson ("{'keyAltNames': ['def']}"), false)); bson_destroy (&key_doc); } @@ -5321,11 +4565,9 @@ test_unique_index_on_keyaltnames (void *unused) { BSON_UNUSED (unused); - _test_unique_index_on_keyaltnames_setup ( - _test_unique_index_on_keyaltnames_case_1); + _test_unique_index_on_keyaltnames_setup (_test_unique_index_on_keyaltnames_case_1); - _test_unique_index_on_keyaltnames_setup ( - _test_unique_index_on_keyaltnames_case_2); + _test_unique_index_on_keyaltnames_setup (_test_unique_index_on_keyaltnames_case_2); } typedef struct { @@ -5346,30 +4588,23 @@ typedef struct { static void decryption_events_succeeded_cb (const mongoc_apm_command_succeeded_t *event) { - decryption_events_fixture *def = - (decryption_events_fixture *) mongoc_apm_command_succeeded_get_context ( - event); + decryption_events_fixture *def = (decryption_events_fixture *) mongoc_apm_command_succeeded_get_context (event); /* Only match the 'aggregate' command. */ - if (0 != strcmp (mongoc_apm_command_succeeded_get_command_name (event), - "aggregate")) { + if (0 != strcmp (mongoc_apm_command_succeeded_get_command_name (event), "aggregate")) { return; } ASSERT_CMPSTR (def->aggEvent.gotType, "none"); def->aggEvent.gotType = "succeeded"; - def->aggEvent.gotSucceededReply = - bson_copy (mongoc_apm_command_succeeded_get_reply (event)); + def->aggEvent.gotSucceededReply = bson_copy (mongoc_apm_command_succeeded_get_reply (event)); } static void decryption_events_failed_cb (const mongoc_apm_command_failed_t *event) { - decryption_events_fixture *def = - (decryption_events_fixture *) mongoc_apm_command_failed_get_context ( - event); + decryption_events_fixture *def = (decryption_events_fixture *) mongoc_apm_command_failed_get_context (event); /* Only match the 'aggregate' command. */ - if (0 != strcmp (mongoc_apm_command_failed_get_command_name (event), - "aggregate")) { + if (0 != strcmp (mongoc_apm_command_failed_get_command_name (event), "aggregate")) { return; } ASSERT_CMPSTR (def->aggEvent.gotType, "none"); @@ -5380,8 +4615,7 @@ decryption_events_failed_cb (const mongoc_apm_command_failed_t *event) decryption_events_fixture * decryption_events_setup (void) { - decryption_events_fixture *def = (decryption_events_fixture *) bson_malloc0 ( - sizeof (decryption_events_fixture)); + decryption_events_fixture *def = (decryption_events_fixture *) bson_malloc0 (sizeof (decryption_events_fixture)); mongoc_client_encryption_t *clientEncryption; bson_value_t keyID; @@ -5390,8 +4624,7 @@ decryption_events_setup (void) /* Drop and create the collection ``db.decryption_events`` */ { - mongoc_collection_t *coll = mongoc_client_get_collection ( - def->setupClient, "db", "decryption_events"); + mongoc_collection_t *coll = mongoc_client_get_collection (def->setupClient, "db", "decryption_events"); bson_error_t error; if (!mongoc_collection_drop (coll, &error)) { @@ -5404,15 +4637,12 @@ decryption_events_setup (void) /* Create a ClientEncryption object */ { - mongoc_client_encryption_opts_t *ceOpts = - mongoc_client_encryption_opts_new (); + mongoc_client_encryption_opts_t *ceOpts = mongoc_client_encryption_opts_new (); bson_t *kms_providers = _make_local_kms_provider (NULL); bson_error_t error; - mongoc_client_encryption_opts_set_keyvault_client (ceOpts, - def->setupClient); - mongoc_client_encryption_opts_set_keyvault_namespace ( - ceOpts, "keyvault", "datakeys"); + mongoc_client_encryption_opts_set_keyvault_client (ceOpts, def->setupClient); + mongoc_client_encryption_opts_set_keyvault_namespace (ceOpts, "keyvault", "datakeys"); mongoc_client_encryption_opts_set_kms_providers (ceOpts, kms_providers); clientEncryption = mongoc_client_encryption_new (ceOpts, &error); @@ -5430,8 +4660,7 @@ decryption_events_setup (void) dkOpts = mongoc_client_encryption_datakey_opts_new (); - res = mongoc_client_encryption_create_datakey ( - clientEncryption, "local", dkOpts, &keyID, &error); + res = mongoc_client_encryption_create_datakey (clientEncryption, "local", dkOpts, &keyID, &error); ASSERT_OR_PRINT (res, error); mongoc_client_encryption_datakey_opts_destroy (dkOpts); @@ -5451,14 +4680,11 @@ decryption_events_setup (void) plaintext.value.v_utf8.len = (uint32_t) len; - mongoc_client_encryption_encrypt_opts_set_algorithm ( - eOpts, MONGOC_AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC); + mongoc_client_encryption_encrypt_opts_set_algorithm (eOpts, MONGOC_AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC); mongoc_client_encryption_encrypt_opts_set_keyid (eOpts, &keyID); - ASSERT_OR_PRINT ( - mongoc_client_encryption_encrypt ( - clientEncryption, &plaintext, eOpts, &def->ciphertext, &error), - error); + ASSERT_OR_PRINT (mongoc_client_encryption_encrypt (clientEncryption, &plaintext, eOpts, &def->ciphertext, &error), + error); mongoc_client_encryption_encrypt_opts_destroy (eOpts); } @@ -5469,36 +4695,28 @@ decryption_events_setup (void) ASSERT (def->ciphertext.value_type == BSON_TYPE_BINARY); /* Change the last data byte to make malformed. The last data byte is * part of the HMAC tag. */ - def->malformedCiphertext.value.v_binary - .data[def->malformedCiphertext.value.v_binary.data_len - 1]++; + def->malformedCiphertext.value.v_binary.data[def->malformedCiphertext.value.v_binary.data_len - 1]++; } /* Create a MongoClient with automatic decryption. */ { - mongoc_auto_encryption_opts_t *aeOpts = - mongoc_auto_encryption_opts_new (); + mongoc_auto_encryption_opts_t *aeOpts = mongoc_auto_encryption_opts_new (); bson_t *kms_providers = _make_local_kms_provider (NULL); bson_error_t error; mongoc_uri_t *uri; - mongoc_auto_encryption_opts_set_keyvault_namespace ( - aeOpts, "keyvault", "datakeys"); + mongoc_auto_encryption_opts_set_keyvault_namespace (aeOpts, "keyvault", "datakeys"); mongoc_auto_encryption_opts_set_kms_providers (aeOpts, kms_providers); uri = test_framework_get_uri (); /* disable retryable reads so only one event is emitted on failure. */ mongoc_uri_set_option_as_bool (uri, MONGOC_URI_RETRYREADS, false); - def->encryptedClient = - test_framework_client_new_from_uri (uri, NULL /* api */); + def->encryptedClient = test_framework_client_new_from_uri (uri, NULL /* api */); test_framework_set_ssl_opts (def->encryptedClient); - ASSERT (mongoc_client_set_error_api (def->encryptedClient, - MONGOC_ERROR_API_VERSION_2)); - ASSERT_OR_PRINT (mongoc_client_enable_auto_encryption ( - def->encryptedClient, aeOpts, &error), - error); + ASSERT (mongoc_client_set_error_api (def->encryptedClient, MONGOC_ERROR_API_VERSION_2)); + ASSERT_OR_PRINT (mongoc_client_enable_auto_encryption (def->encryptedClient, aeOpts, &error), error); - def->encryptedColl = mongoc_client_get_collection ( - def->encryptedClient, "db", "decryption_events"); + def->encryptedColl = mongoc_client_get_collection (def->encryptedClient, "db", "decryption_events"); bson_destroy (kms_providers); mongoc_auto_encryption_opts_destroy (aeOpts); @@ -5546,33 +4764,27 @@ test_decryption_events_case1 (void *unused) BSON_UNUSED (unused); - got = mongoc_client_command_simple ( - def->setupClient, - "admin", - tmp_bson ("{'configureFailPoint': 'failCommand', 'mode': {'times': 1}, " - "'data': {'errorCode': 123, 'failCommands': ['aggregate']}}"), - NULL /* read prefs */, - NULL /* reply */, - &error); + got = mongoc_client_command_simple (def->setupClient, + "admin", + tmp_bson ("{'configureFailPoint': 'failCommand', 'mode': {'times': 1}, " + "'data': {'errorCode': 123, 'failCommands': ['aggregate']}}"), + NULL /* read prefs */, + NULL /* reply */, + &error); ASSERT_OR_PRINT (got, error); - cursor = mongoc_collection_aggregate (def->encryptedColl, - MONGOC_QUERY_NONE, - tmp_bson ("{}"), - NULL /* opts */, - NULL /* read prefs */); + cursor = mongoc_collection_aggregate ( + def->encryptedColl, MONGOC_QUERY_NONE, tmp_bson ("{}"), NULL /* opts */, NULL /* read prefs */); got = mongoc_cursor_next (cursor, &found); - ASSERT_WITH_MSG (!got, - "Expected error in mongoc_cursor_next, but got success"); + ASSERT_WITH_MSG (!got, "Expected error in mongoc_cursor_next, but got success"); ASSERT (mongoc_cursor_error (cursor, &error)); ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_SERVER, 123, "failpoint"); ASSERT_CMPSTR (def->aggEvent.gotType, "failed"); - ASSERT_ERROR_CONTAINS ( - def->aggEvent.gotFailedError, MONGOC_ERROR_SERVER, 123, "failpoint"); + ASSERT_ERROR_CONTAINS (def->aggEvent.gotFailedError, MONGOC_ERROR_SERVER, 123, "failpoint"); ASSERT (!got); mongoc_cursor_destroy (cursor); decryption_events_fixture_destroy (def); @@ -5594,34 +4806,26 @@ test_decryption_events_case2 (void *unused) BSON_UNUSED (unused); - got = mongoc_client_command_simple ( - def->setupClient, - "admin", - tmp_bson ("{'configureFailPoint': 'failCommand', 'mode': {'times': 1}, " - "'data': {'errorCode': 123, 'closeConnection': true, " - "'failCommands': ['aggregate']}}"), - NULL /* read prefs */, - NULL /* reply */, - &error); + got = mongoc_client_command_simple (def->setupClient, + "admin", + tmp_bson ("{'configureFailPoint': 'failCommand', 'mode': {'times': 1}, " + "'data': {'errorCode': 123, 'closeConnection': true, " + "'failCommands': ['aggregate']}}"), + NULL /* read prefs */, + NULL /* reply */, + &error); ASSERT_OR_PRINT (got, error); - cursor = mongoc_collection_aggregate (def->encryptedColl, - MONGOC_QUERY_NONE, - tmp_bson ("{}"), - NULL /* opts */, - NULL /* read prefs */); + cursor = mongoc_collection_aggregate ( + def->encryptedColl, MONGOC_QUERY_NONE, tmp_bson ("{}"), NULL /* opts */, NULL /* read prefs */); got = mongoc_cursor_next (cursor, &found); - ASSERT_WITH_MSG (!got, - "Expected error in mongoc_cursor_next, but got success"); + ASSERT_WITH_MSG (!got, "Expected error in mongoc_cursor_next, but got success"); ASSERT (mongoc_cursor_error (cursor, &error)); - ASSERT_ERROR_CONTAINS ( - error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "socket error"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "socket error"); ASSERT_CMPSTR (def->aggEvent.gotType, "failed"); - ASSERT_ERROR_CONTAINS (def->aggEvent.gotFailedError, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_SOCKET, - "socket error"); + ASSERT_ERROR_CONTAINS ( + def->aggEvent.gotFailedError, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "socket error"); ASSERT (!got); mongoc_cursor_destroy (cursor); decryption_events_fixture_destroy (def); @@ -5646,26 +4850,17 @@ test_decryption_events_case3 (void *unused) BSON_APPEND_VALUE (&to_insert, "encrypted", &def->malformedCiphertext); - got = mongoc_collection_insert_one (def->encryptedColl, - &to_insert, - NULL /* opts */, - NULL /* reply */, - &error); + got = mongoc_collection_insert_one (def->encryptedColl, &to_insert, NULL /* opts */, NULL /* reply */, &error); ASSERT_OR_PRINT (got, error); - cursor = mongoc_collection_aggregate (def->encryptedColl, - MONGOC_QUERY_NONE, - tmp_bson ("{}"), - NULL /* opts */, - NULL /* read prefs */); + cursor = mongoc_collection_aggregate ( + def->encryptedColl, MONGOC_QUERY_NONE, tmp_bson ("{}"), NULL /* opts */, NULL /* read prefs */); got = mongoc_cursor_next (cursor, &found); - ASSERT_WITH_MSG (!got, - "Expected error in mongoc_cursor_next, but got success"); + ASSERT_WITH_MSG (!got, "Expected error in mongoc_cursor_next, but got success"); ASSERT (mongoc_cursor_error (cursor, &error)); - ASSERT_ERROR_CONTAINS ( - error, MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION, 1, "HMAC validation failure"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION, 1, "HMAC validation failure"); ASSERT_CMPSTR (def->aggEvent.gotType, "succeeded"); ASSERT_MATCH (def->aggEvent.gotSucceededReply, @@ -5696,18 +4891,11 @@ test_decryption_events_case4 (void *unused) BSON_APPEND_VALUE (&to_insert, "encrypted", &def->ciphertext); - got = mongoc_collection_insert_one (def->encryptedColl, - &to_insert, - NULL /* opts */, - NULL /* reply */, - &error); + got = mongoc_collection_insert_one (def->encryptedColl, &to_insert, NULL /* opts */, NULL /* reply */, &error); ASSERT_OR_PRINT (got, error); - cursor = mongoc_collection_aggregate (def->encryptedColl, - MONGOC_QUERY_NONE, - tmp_bson ("{}"), - NULL /* opts */, - NULL /* read prefs */); + cursor = mongoc_collection_aggregate ( + def->encryptedColl, MONGOC_QUERY_NONE, tmp_bson ("{}"), NULL /* opts */, NULL /* read prefs */); got = mongoc_cursor_next (cursor, &found); ASSERT_OR_PRINT (!mongoc_cursor_error (cursor, &error), error); ASSERT (got); @@ -5724,16 +4912,12 @@ test_decryption_events_case4 (void *unused) } static void -_test_rewrap_with_separate_client_encryption (const char *src_provider, - const char *dst_provider) +_test_rewrap_with_separate_client_encryption (const char *src_provider, const char *dst_provider) { mongoc_uri_t *const uri = test_framework_get_uri (); - mongoc_client_encryption_opts_t *const ce_opts = - mongoc_client_encryption_opts_new (); - mongoc_client_t *const src_client = - test_framework_client_new_from_uri (uri, NULL); - mongoc_client_t *const dst_client = - test_framework_client_new_from_uri (uri, NULL); + mongoc_client_encryption_opts_t *const ce_opts = mongoc_client_encryption_opts_new (); + mongoc_client_t *const src_client = test_framework_client_new_from_uri (uri, NULL); + mongoc_client_t *const dst_client = test_framework_client_new_from_uri (uri, NULL); bson_error_t error = {0}; bson_value_t keyid = {0}; @@ -5748,14 +4932,12 @@ _test_rewrap_with_separate_client_encryption (const char *src_provider, { mongoc_client_encryption_opts_set_keyvault_client (ce_opts, src_client); - mongoc_client_encryption_opts_set_keyvault_namespace ( - ce_opts, "keyvault", "datakeys"); + mongoc_client_encryption_opts_set_keyvault_namespace (ce_opts, "keyvault", "datakeys"); { bson_t *const kms_providers = _make_kms_providers (true, true); BSON_ASSERT (kms_providers); - mongoc_client_encryption_opts_set_kms_providers (ce_opts, - kms_providers); + mongoc_client_encryption_opts_set_kms_providers (ce_opts, kms_providers); bson_destroy (kms_providers); } @@ -5770,8 +4952,7 @@ _test_rewrap_with_separate_client_encryption (const char *src_provider, // 1. Drop the collection keyvault.datakeys. { - mongoc_collection_t *datakeys = - mongoc_client_get_collection (src_client, "keyvault", "datakeys"); + mongoc_collection_t *datakeys = mongoc_client_get_collection (src_client, "keyvault", "datakeys"); ASSERT (datakeys); (void) mongoc_collection_drop (datakeys, NULL); mongoc_collection_destroy (datakeys); @@ -5779,28 +4960,23 @@ _test_rewrap_with_separate_client_encryption (const char *src_provider, // 2. Create a ClientEncryption object named clientEncryption1 with these // options: (see ce_opts). - mongoc_client_encryption_t *clientEncryption1 = - mongoc_client_encryption_new (ce_opts, &error); + mongoc_client_encryption_t *clientEncryption1 = mongoc_client_encryption_new (ce_opts, &error); ASSERT_OR_PRINT (clientEncryption1, error); // 3. Call clientEncryption1.createDataKey with srcProvider and these // options: (see below). { - mongoc_client_encryption_datakey_opts_t *dk_opts = - mongoc_client_encryption_datakey_opts_new (); + mongoc_client_encryption_datakey_opts_t *dk_opts = mongoc_client_encryption_datakey_opts_new (); { bson_t *const src_masterkey = _make_kms_masterkey (src_provider); BSON_ASSERT (src_masterkey); - mongoc_client_encryption_datakey_opts_set_masterkey (dk_opts, - src_masterkey); + mongoc_client_encryption_datakey_opts_set_masterkey (dk_opts, src_masterkey); bson_destroy (src_masterkey); } ASSERT_OR_PRINT ( - mongoc_client_encryption_create_datakey ( - clientEncryption1, src_provider, dk_opts, &keyid, &error), - error); + mongoc_client_encryption_create_datakey (clientEncryption1, src_provider, dk_opts, &keyid, &error), error); mongoc_client_encryption_datakey_opts_destroy (dk_opts); } @@ -5816,25 +4992,19 @@ _test_rewrap_with_separate_client_encryption (const char *src_provider, bson_value.value_type = BSON_TYPE_UTF8; bson_value.value.v_utf8.str = message; - bson_value.value.v_utf8.len = - (uint32_t) strlen (bson_value.value.v_utf8.str); + bson_value.value.v_utf8.len = (uint32_t) strlen (bson_value.value.v_utf8.str); - mongoc_client_encryption_encrypt_opts_t *const e_opts = - mongoc_client_encryption_encrypt_opts_new (); + mongoc_client_encryption_encrypt_opts_t *const e_opts = mongoc_client_encryption_encrypt_opts_new (); mongoc_client_encryption_encrypt_opts_set_keyid (e_opts, &keyid); - mongoc_client_encryption_encrypt_opts_set_algorithm ( - e_opts, MONGOC_AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC); - ASSERT_OR_PRINT ( - mongoc_client_encryption_encrypt ( - clientEncryption1, &bson_value, e_opts, &ciphertext, &error), - error); + mongoc_client_encryption_encrypt_opts_set_algorithm (e_opts, MONGOC_AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC); + ASSERT_OR_PRINT (mongoc_client_encryption_encrypt (clientEncryption1, &bson_value, e_opts, &ciphertext, &error), + error); mongoc_client_encryption_encrypt_opts_destroy (e_opts); } // 5. Create a ClientEncryption object named clientEncryption2 with these // options: (see ce_opts). - mongoc_client_encryption_t *clientEncryption2 = - mongoc_client_encryption_new (ce_opts, &error); + mongoc_client_encryption_t *clientEncryption2 = mongoc_client_encryption_new (ce_opts, &error); ASSERT_OR_PRINT (clientEncryption2, error); mongoc_client_encryption_rewrap_many_datakey_result_t *const result = @@ -5847,27 +5017,20 @@ _test_rewrap_with_separate_client_encryption (const char *src_provider, { bson_t *const dst_masterkey = _make_kms_masterkey (dst_provider); BSON_ASSERT (dst_masterkey); - ASSERT_OR_PRINT ( - mongoc_client_encryption_rewrap_many_datakey (clientEncryption2, - NULL, - dst_provider, - dst_masterkey, - result, - &error), - error); + ASSERT_OR_PRINT (mongoc_client_encryption_rewrap_many_datakey ( + clientEncryption2, NULL, dst_provider, dst_masterkey, result, &error), + error); bson_destroy (dst_masterkey); } // Assert that the returned // RewrapManyDataKeyResult.bulkWriteResult.modifiedCount is 1. const bson_t *const bulk_write_result = - mongoc_client_encryption_rewrap_many_datakey_result_get_bulk_write_result ( - result); + mongoc_client_encryption_rewrap_many_datakey_result_get_bulk_write_result (result); ASSERT (bulk_write_result); - ASSERT_WITH_MSG ( - match_bson (bulk_write_result, tmp_bson ("{'nModified': 1}"), false), - "'%s' does not match expected value", - tmp_json (bulk_write_result)); + ASSERT_WITH_MSG (match_bson (bulk_write_result, tmp_bson ("{'nModified': 1}"), false), + "'%s' does not match expected value", + tmp_json (bulk_write_result)); } // 7. Call clientEncryption1.decrypt with the ciphertext. Assert the return @@ -5875,8 +5038,7 @@ _test_rewrap_with_separate_client_encryption (const char *src_provider, { bson_value_t decrypted = {0}; - ASSERT (mongoc_client_encryption_decrypt ( - clientEncryption1, &ciphertext, &decrypted, &error)); + ASSERT (mongoc_client_encryption_decrypt (clientEncryption1, &ciphertext, &decrypted, &error)); ASSERT (decrypted.value_type == BSON_TYPE_UTF8); ASSERT (decrypted.value.v_utf8.len != 0u); @@ -5890,8 +5052,7 @@ _test_rewrap_with_separate_client_encryption (const char *src_provider, { bson_value_t decrypted = {0}; - ASSERT (mongoc_client_encryption_decrypt ( - clientEncryption2, &ciphertext, &decrypted, &error)); + ASSERT (mongoc_client_encryption_decrypt (clientEncryption2, &ciphertext, &decrypted, &error)); ASSERT (decrypted.value_type == BSON_TYPE_UTF8); ASSERT (decrypted.value.v_utf8.len != 0u); @@ -5942,10 +5103,8 @@ test_rewrap_without_provider (void *unused) BSON_UNUSED (unused); mongoc_uri_t *const uri = test_framework_get_uri (); - mongoc_client_encryption_opts_t *const ce_opts = - mongoc_client_encryption_opts_new (); - mongoc_client_t *const key_vault_client = - test_framework_client_new_from_uri (uri, NULL); + mongoc_client_encryption_opts_t *const ce_opts = mongoc_client_encryption_opts_new (); + mongoc_client_t *const key_vault_client = test_framework_client_new_from_uri (uri, NULL); bson_error_t error = {0}; @@ -5956,16 +5115,13 @@ test_rewrap_without_provider (void *unused) test_framework_set_ssl_opts (key_vault_client); { - mongoc_client_encryption_opts_set_keyvault_client (ce_opts, - key_vault_client); - mongoc_client_encryption_opts_set_keyvault_namespace ( - ce_opts, "keyvault", "datakeys"); + mongoc_client_encryption_opts_set_keyvault_client (ce_opts, key_vault_client); + mongoc_client_encryption_opts_set_keyvault_namespace (ce_opts, "keyvault", "datakeys"); { bson_t *const kms_providers = _make_kms_providers (true, true); BSON_ASSERT (kms_providers); - mongoc_client_encryption_opts_set_kms_providers (ce_opts, - kms_providers); + mongoc_client_encryption_opts_set_kms_providers (ce_opts, kms_providers); bson_destroy (kms_providers); } @@ -5979,28 +5135,21 @@ test_rewrap_without_provider (void *unused) // 1. Create a ClientEncryption object named clientEncryption with these // options: (see ce_opts). - mongoc_client_encryption_t *clientEncryption = - mongoc_client_encryption_new (ce_opts, &error); + mongoc_client_encryption_t *clientEncryption = mongoc_client_encryption_new (ce_opts, &error); ASSERT_OR_PRINT (clientEncryption, error); // 2. Call ``clientEncryption.rewrapManyDataKey`` with an empty ``filter`` // and these options: (see below). { - bool ok = - mongoc_client_encryption_rewrap_many_datakey (clientEncryption, - NULL /* filter */, - NULL /* kms_provider */, - tmp_bson ("{}"), - NULL /* result */, - &error); + bool ok = mongoc_client_encryption_rewrap_many_datakey ( + clientEncryption, NULL /* filter */, NULL /* kms_provider */, tmp_bson ("{}"), NULL /* result */, &error); // Assert an error is returned from the driver suggesting that the // ``provider`` option is required. ASSERT_WITH_MSG (!ok, "expected error, but got success"); - ASSERT_ERROR_CONTAINS ( - error, - MONGOC_ERROR_CLIENT, - MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG, - "expected 'provider' to be set to identify type of 'master_key'"); + ASSERT_ERROR_CONTAINS (error, + MONGOC_ERROR_CLIENT, + MONGOC_ERROR_CLIENT_INVALID_ENCRYPTION_ARG, + "expected 'provider' to be set to identify type of 'master_key'"); } mongoc_client_encryption_destroy (clientEncryption); @@ -6016,8 +5165,7 @@ test_qe_docs_example (void *unused) { bson_error_t error; mongoc_client_t *const client = test_framework_new_default_client (); - bson_t *const kmsProviders = - _make_kms_providers (false /* with aws */, true /* with local */); + bson_t *const kmsProviders = _make_kms_providers (false /* with aws */, true /* with local */); bson_value_t key1ID; bson_value_t key2ID; bson_t *encryptedFieldsMap; @@ -6051,19 +5199,14 @@ test_qe_docs_example (void *unused) ceOpts = mongoc_client_encryption_opts_new (); mongoc_client_encryption_opts_set_kms_providers (ceOpts, kmsProviders); - mongoc_client_encryption_opts_set_keyvault_namespace ( - ceOpts, "keyvault", "datakeys"); + mongoc_client_encryption_opts_set_keyvault_namespace (ceOpts, "keyvault", "datakeys"); mongoc_client_encryption_opts_set_keyvault_client (ceOpts, client); ce = mongoc_client_encryption_new (ceOpts, &error); ASSERT_OR_PRINT (ce, error); dkOpts = mongoc_client_encryption_datakey_opts_new (); - ASSERT_OR_PRINT (mongoc_client_encryption_create_datakey ( - ce, "local", dkOpts, &key1ID, &error), - error); - ASSERT_OR_PRINT (mongoc_client_encryption_create_datakey ( - ce, "local", dkOpts, &key2ID, &error), - error); + ASSERT_OR_PRINT (mongoc_client_encryption_create_datakey (ce, "local", dkOpts, &key1ID, &error), error); + ASSERT_OR_PRINT (mongoc_client_encryption_create_datakey (ce, "local", dkOpts, &key2ID, &error), error); mongoc_client_encryption_datakey_opts_destroy (dkOpts); mongoc_client_encryption_destroy (ce); @@ -6103,19 +5246,14 @@ test_qe_docs_example (void *unused) encryptedClient = test_framework_new_default_client (); aeOpts = mongoc_auto_encryption_opts_new (); mongoc_auto_encryption_opts_set_kms_providers (aeOpts, kmsProviders); - mongoc_auto_encryption_opts_set_keyvault_namespace ( - aeOpts, "keyvault", "datakeys"); - mongoc_auto_encryption_opts_set_encrypted_fields_map (aeOpts, - encryptedFieldsMap); - ASSERT_OR_PRINT ( - mongoc_client_enable_auto_encryption (encryptedClient, aeOpts, &error), - error); + mongoc_auto_encryption_opts_set_keyvault_namespace (aeOpts, "keyvault", "datakeys"); + mongoc_auto_encryption_opts_set_encrypted_fields_map (aeOpts, encryptedFieldsMap); + ASSERT_OR_PRINT (mongoc_client_enable_auto_encryption (encryptedClient, aeOpts, &error), error); /* Create the Queryable Encryption collection docsExample.encrypted. */ db = mongoc_client_get_database (encryptedClient, "docsExamples"); /* Because docsExample.encrypted is in encryptedFieldsMap, it is created * with Queryable Encryption support. */ - encryptedColl = mongoc_database_create_collection ( - db, "encrypted", NULL /* opts */, &error); + encryptedColl = mongoc_database_create_collection (db, "encrypted", NULL /* opts */, &error); ASSERT_OR_PRINT (encryptedColl, error); mongoc_database_destroy (db); @@ -6132,23 +5270,14 @@ test_qe_docs_example (void *unused) bool found; bson_iter_t iter; - to_insert = BCON_NEW ("_id", - BCON_INT32 (1), - "encryptedIndexed", - "indexedValue", - "encryptedUnindexed", - "unindexedValue"); - - ASSERT_OR_PRINT (mongoc_collection_insert_one (encryptedColl, - to_insert, - NULL /* opts */, - NULL /* reply */, - &error), - error); + to_insert = + BCON_NEW ("_id", BCON_INT32 (1), "encryptedIndexed", "indexedValue", "encryptedUnindexed", "unindexedValue"); + + ASSERT_OR_PRINT ( + mongoc_collection_insert_one (encryptedColl, to_insert, NULL /* opts */, NULL /* reply */, &error), error); filter = BCON_NEW ("encryptedIndexed", "indexedValue"); - cursor = mongoc_collection_find_with_opts ( - encryptedColl, filter, NULL /* opts */, NULL /* read prefs */); + cursor = mongoc_collection_find_with_opts (encryptedColl, filter, NULL /* opts */, NULL /* read prefs */); found = mongoc_cursor_next (cursor, &got); ASSERT_OR_PRINT (!mongoc_cursor_error (cursor, &error), error); ASSERT (found); @@ -6157,8 +5286,7 @@ test_qe_docs_example (void *unused) ASSERT_CMPSTR (bson_iter_utf8 (&iter, NULL /* length */), "indexedValue"); ASSERT (bson_iter_init_find (&iter, got, "encryptedUnindexed")); ASSERT (BSON_ITER_HOLDS_UTF8 (&iter)); - ASSERT_CMPSTR (bson_iter_utf8 (&iter, NULL /* length */), - "unindexedValue"); + ASSERT_CMPSTR (bson_iter_utf8 (&iter, NULL /* length */), "unindexedValue"); mongoc_cursor_destroy (cursor); bson_destroy (filter); @@ -6174,11 +5302,9 @@ test_qe_docs_example (void *unused) bool found; bson_iter_t iter; - unencryptedColl = - mongoc_client_get_collection (client, "docsExamples", "encrypted"); + unencryptedColl = mongoc_client_get_collection (client, "docsExamples", "encrypted"); filter = BCON_NEW ("_id", BCON_INT32 (1)); - cursor = mongoc_collection_find_with_opts ( - unencryptedColl, filter, NULL /* opts */, NULL /* read prefs */); + cursor = mongoc_collection_find_with_opts (unencryptedColl, filter, NULL /* opts */, NULL /* read prefs */); found = mongoc_cursor_next (cursor, &got); ASSERT_OR_PRINT (!mongoc_cursor_error (cursor, &error), error); ASSERT (found); @@ -6208,10 +5334,7 @@ struct kms_callback_data { }; static bool -_kms_callback (void *userdata, - const bson_t *params, - bson_t *out, - bson_error_t *error) +_kms_callback (void *userdata, const bson_t *params, bson_t *out, bson_error_t *error) { struct kms_callback_data *ctx = userdata; @@ -6219,21 +5342,12 @@ _kms_callback (void *userdata, ctx->value = 42; if (ctx->set_error) { - bson_set_error (error, - MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION, - 1729, - "%s", - ctx->set_error); + bson_set_error (error, MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION, 1729, "%s", ctx->set_error); return false; } if (ctx->provide_creds) { uint8_t keydata[96] = {0}; - BCON_APPEND (out, - "local", - "{", - "key", - BCON_BIN (BSON_SUBTYPE_BINARY, keydata, sizeof keydata), - "}"); + BCON_APPEND (out, "local", "{", "key", BCON_BIN (BSON_SUBTYPE_BINARY, keydata, sizeof keydata), "}"); } return true; } @@ -6242,8 +5356,7 @@ static void test_kms_callback (void *unused) { // No interesting datakey options - mongoc_client_encryption_datakey_opts_t *dk_opts = - mongoc_client_encryption_datakey_opts_new (); + mongoc_client_encryption_datakey_opts_t *dk_opts = mongoc_client_encryption_datakey_opts_new (); // Create a client encryption object mongoc_client_encryption_opts_t *opts = mongoc_client_encryption_opts_new (); @@ -6255,61 +5368,49 @@ test_kms_callback (void *unused) // Given it an on-demand 'local' provider bson_t *empty_local = tmp_bson ("{'local': {}}"); mongoc_client_encryption_opts_set_kms_providers (opts, empty_local); - mongoc_client_encryption_opts_set_keyvault_namespace ( - opts, "testing", "testing"); + mongoc_client_encryption_opts_set_keyvault_namespace (opts, "testing", "testing"); { // Attempting to create a key from 'local' will fail immediately // Create a client encryption object for it. bson_error_t error; - mongoc_client_encryption_t *enc = - mongoc_client_encryption_new (opts, &error); + mongoc_client_encryption_t *enc = mongoc_client_encryption_new (opts, &error); ASSERT_OR_PRINT (enc, error); bson_value_t keyid; - mongoc_client_encryption_create_datakey ( - enc, "local", dk_opts, &keyid, &error); + mongoc_client_encryption_create_datakey (enc, "local", dk_opts, &keyid, &error); mongoc_client_encryption_destroy (enc); - ASSERT_ERROR_CONTAINS ( - error, MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION, 1, "no kms provider set"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION, 1, "no kms provider set"); } { // Now attach a callback struct kms_callback_data callback_data = {0}; - mongoc_client_encryption_opts_set_kms_credential_provider_callback ( - opts, _kms_callback, &callback_data); + mongoc_client_encryption_opts_set_kms_credential_provider_callback (opts, _kms_callback, &callback_data); BSON_ASSERT (callback_data.value == 0); bson_error_t error; - mongoc_client_encryption_t *enc = - mongoc_client_encryption_new (opts, &error); + mongoc_client_encryption_t *enc = mongoc_client_encryption_new (opts, &error); ASSERT_OR_PRINT (enc, error); bson_value_t keyid; { - mongoc_client_encryption_create_datakey ( - enc, "local", dk_opts, &keyid, &error); + mongoc_client_encryption_create_datakey (enc, "local", dk_opts, &keyid, &error); // The callback will have set a value when it was called BSON_ASSERT (callback_data.value == 42); // But we still get an error, because we didn't fill in 'local' - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION, - 1, - "no kms provider set"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION, 1, "no kms provider set"); } { // Now actually provide a key callback_data.provide_creds = true; - ASSERT_OR_PRINT (mongoc_client_encryption_create_datakey ( - enc, "local", dk_opts, &keyid, &error), - error); + ASSERT_OR_PRINT (mongoc_client_encryption_create_datakey (enc, "local", dk_opts, &keyid, &error), error); // The callback will have set a value when it was called BSON_ASSERT (callback_data.value == 42); @@ -6318,21 +5419,16 @@ test_kms_callback (void *unused) // Clear the value and tell the callback to set its own error callback_data.value = 0; - callback_data.set_error = - "This is the error that should appear from the callback"; + callback_data.set_error = "This is the error that should appear from the callback"; { - mongoc_client_encryption_create_datakey ( - enc, "local", dk_opts, &keyid, &error); + mongoc_client_encryption_create_datakey (enc, "local", dk_opts, &keyid, &error); // It was called again: BSON_ASSERT (callback_data.value == 42); // This time the callback provided an error ASSERT_ERROR_CONTAINS ( - error, - MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION, - 1729, - "This is the error that should appear from the callback"); + error, MONGOC_ERROR_CLIENT_SIDE_ENCRYPTION, 1729, "This is the error that should appear from the callback"); } mongoc_client_encryption_destroy (enc); @@ -6347,13 +5443,11 @@ static void _test_auto_aws (bool should_succeed) { // Datakey options for AWS - mongoc_client_encryption_datakey_opts_t *dk_opts = - mongoc_client_encryption_datakey_opts_new (); - mongoc_client_encryption_datakey_opts_set_masterkey ( - dk_opts, - tmp_bson ("{ 'region': 'us-east-1', 'key': " - "'arn:aws:kms:us-east-1:579766882180:key/" - "89fcc2c4-08b0-4bd9-9f25-e30687b580d0' }")); + mongoc_client_encryption_datakey_opts_t *dk_opts = mongoc_client_encryption_datakey_opts_new (); + mongoc_client_encryption_datakey_opts_set_masterkey (dk_opts, + tmp_bson ("{ 'region': 'us-east-1', 'key': " + "'arn:aws:kms:us-east-1:579766882180:key/" + "89fcc2c4-08b0-4bd9-9f25-e30687b580d0' }")); // Create a client encryption object mongoc_client_encryption_opts_t *opts = mongoc_client_encryption_opts_new (); @@ -6363,20 +5457,17 @@ _test_auto_aws (bool should_succeed) // Given it an on-demand 'aws' provider bson_t *empty_aws = tmp_bson ("{'aws': {}}"); mongoc_client_encryption_opts_set_kms_providers (opts, empty_aws); - mongoc_client_encryption_opts_set_keyvault_namespace ( - opts, "testing", "testing"); + mongoc_client_encryption_opts_set_keyvault_namespace (opts, "testing", "testing"); { // Attempting to create a key from 'aws' will require credentials in the // environment immediately. Create a client encryption object for it. bson_error_t error; - mongoc_client_encryption_t *enc = - mongoc_client_encryption_new (opts, &error); + mongoc_client_encryption_t *enc = mongoc_client_encryption_new (opts, &error); ASSERT_OR_PRINT (enc, error); bson_value_t keyid; - mongoc_client_encryption_create_datakey ( - enc, "aws", dk_opts, &keyid, &error); + mongoc_client_encryption_create_datakey (enc, "aws", dk_opts, &keyid, &error); mongoc_client_encryption_destroy (enc); if (should_succeed) { @@ -6385,8 +5476,7 @@ _test_auto_aws (bool should_succeed) } else { // We should encounter an error while attempting to connect to the EC2 // metadata server. - ASSERT_ERROR_CONTAINS ( - error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_AUTHENTICATE, ""); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_AUTHENTICATE, ""); } } @@ -6447,8 +5537,7 @@ test_drop_qe_null_error (void *unused) { bson_error_t error; mongoc_client_t *const client = test_framework_new_default_client (); - bson_t *const kmsProviders = - _make_kms_providers (false /* with aws */, true /* with local */); + bson_t *const kmsProviders = _make_kms_providers (false /* with aws */, true /* with local */); bson_t *encryptedFieldsMap; mongoc_client_t *encryptedClient; mongoc_auto_encryption_opts_t *aeOpts; @@ -6461,13 +5550,9 @@ test_drop_qe_null_error (void *unused) encryptedClient = test_framework_new_default_client (); aeOpts = mongoc_auto_encryption_opts_new (); mongoc_auto_encryption_opts_set_kms_providers (aeOpts, kmsProviders); - mongoc_auto_encryption_opts_set_keyvault_namespace ( - aeOpts, "keyvault", "datakeys"); - mongoc_auto_encryption_opts_set_encrypted_fields_map (aeOpts, - encryptedFieldsMap); - ASSERT_OR_PRINT ( - mongoc_client_enable_auto_encryption (encryptedClient, aeOpts, &error), - error); + mongoc_auto_encryption_opts_set_keyvault_namespace (aeOpts, "keyvault", "datakeys"); + mongoc_auto_encryption_opts_set_encrypted_fields_map (aeOpts, encryptedFieldsMap); + ASSERT_OR_PRINT (mongoc_client_enable_auto_encryption (encryptedClient, aeOpts, &error), error); coll = mongoc_client_get_collection (encryptedClient, "db", "encrypted"); ASSERT (mongoc_collection_drop (coll, NULL)); @@ -6514,37 +5599,31 @@ test_auto_datakeys (void *unused) doc (kv ("keyId", cstr ("keepme"))), // doc (kv ("keyId", null))); bson_t out_fields = BSON_INITIALIZER; - bool okay = _mongoc_encryptedFields_fill_auto_datakeys ( - &out_fields, &in_fields, _auto_datakeys, NULL, &error); + bool okay = _mongoc_encryptedFields_fill_auto_datakeys (&out_fields, &in_fields, _auto_datakeys, NULL, &error); ASSERT_ERROR_CONTAINS (error, 0, 0, ""); ASSERT (okay); bsonParse ( // out_fields, - require ( - keyWithType ("0", doc), // - parse (require (allOf (key ("keyId"), strEqual ("keepme")), nop))), - require ( - keyWithType ("1", doc), - parse (require (allOf (keyWithType ("keyId", int32)), - do (ASSERT_CMPINT32 (bsonAs (int32), ==, 42)))))); + require (keyWithType ("0", doc), // + parse (require (allOf (key ("keyId"), strEqual ("keepme")), nop))), + require (keyWithType ("1", doc), + parse (require (allOf (keyWithType ("keyId", int32)), do (ASSERT_CMPINT32 (bsonAs (int32), ==, 42)))))); ASSERT (bsonParseError == NULL); bson_destroy (&out_fields); // Do it again, but we will generate an error - okay = _mongoc_encryptedFields_fill_auto_datakeys ( - &out_fields, &in_fields, _auto_datakeys_error, NULL, &error); + okay = _mongoc_encryptedFields_fill_auto_datakeys (&out_fields, &in_fields, _auto_datakeys_error, NULL, &error); ASSERT (!okay); ASSERT_ERROR_CONTAINS (error, 42, 1729, "I am an error"); bson_destroy (&out_fields); // Do it again, but we will generate an error without the factory setting the // error - okay = _mongoc_encryptedFields_fill_auto_datakeys ( - &out_fields, &in_fields, _auto_datakeys_error_noset, NULL, &error); + okay = + _mongoc_encryptedFields_fill_auto_datakeys (&out_fields, &in_fields, _auto_datakeys_error_noset, NULL, &error); ASSERT (!okay); // Generic error, since the factory didn't provide one: - ASSERT_ERROR_CONTAINS ( - error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "indicated failure"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "indicated failure"); bson_destroy (&out_fields); bson_destroy (&in_fields); } @@ -6577,12 +5656,10 @@ CEC_TEST (test_create_encrypted_collection_simple, const char *kmsProvider) // Drop prior data { - mongoc_collection_t *const coll = - mongoc_client_get_collection (client, "keyvault", "datakeys"); + mongoc_collection_t *const coll = mongoc_client_get_collection (client, "keyvault", "datakeys"); if (coll) { mongoc_collection_drop (coll, &error); - bool okay = - error.code == 0 || strstr (error.message, "ns not found") != NULL; + bool okay = error.code == 0 || strstr (error.message, "ns not found") != NULL; ASSERT_OR_PRINT (okay, error); } mongoc_collection_destroy (coll); @@ -6593,42 +5670,35 @@ CEC_TEST (test_create_encrypted_collection_simple, const char *kmsProvider) } // Create a CE - mongoc_client_encryption_opts_t *const ceOpts = - mongoc_client_encryption_opts_new (); + mongoc_client_encryption_opts_t *const ceOpts = mongoc_client_encryption_opts_new (); mongoc_client_encryption_opts_set_kms_providers (ceOpts, kmsProviders); mongoc_client_encryption_opts_set_tls_opts (ceOpts, tlsOptions); - mongoc_client_encryption_opts_set_keyvault_namespace ( - ceOpts, "keyvault", "datakeys"); + mongoc_client_encryption_opts_set_keyvault_namespace (ceOpts, "keyvault", "datakeys"); mongoc_client_encryption_opts_set_keyvault_client (ceOpts, client); - mongoc_client_encryption_t *const ce = - mongoc_client_encryption_new (ceOpts, &error); + mongoc_client_encryption_t *const ce = mongoc_client_encryption_new (ceOpts, &error); mongoc_client_encryption_opts_destroy (ceOpts); ASSERT_OR_PRINT (ce, error); // Create the encrypted collection - bsonBuildDecl (ccOpts, - kv ("encryptedFields", - doc (kv ("fields", - array (doc (kv ("path", cstr ("ssn")), - kv ("bsonType", cstr ("string")), - kv ("keyId", null))))))); + bsonBuildDecl ( + ccOpts, + kv ("encryptedFields", + doc (kv ("fields", + array (doc (kv ("path", cstr ("ssn")), kv ("bsonType", cstr ("string")), kv ("keyId", null))))))); mongoc_database_t *const db = mongoc_client_get_database (client, dbName); bson_t *const mkey = _make_kms_masterkey (kmsProvider); - mongoc_collection_t *const coll = - mongoc_client_encryption_create_encrypted_collection ( - ce, db, "test-coll", &ccOpts, NULL, kmsProvider, mkey, &error); + mongoc_collection_t *const coll = mongoc_client_encryption_create_encrypted_collection ( + ce, db, "test-coll", &ccOpts, NULL, kmsProvider, mkey, &error); ASSERT_OR_PRINT (coll, error); bson_destroy (&ccOpts); bson_destroy (mkey); bsonBuildDecl (doc, kv ("ssn", cstr ("123-45-6789"))); - const bool okay = - mongoc_collection_insert_one (coll, &doc, NULL, NULL, &error); + const bool okay = mongoc_collection_insert_one (coll, &doc, NULL, NULL, &error); // Expect a failure: We didn't encrypt the field, and we don't have // auto-encryption enabled, but the server expects this to be encrypted. ASSERT (!okay); - ASSERT_ERROR_CONTAINS ( - error, MONGOC_ERROR_COLLECTION, 121, "failed validation"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COLLECTION, 121, "failed validation"); bson_destroy (&doc); bson_destroy (kmsProviders); @@ -6641,11 +5711,10 @@ CEC_TEST (test_create_encrypted_collection_simple, const char *kmsProvider) } static void -test_create_encrypted_collection_no_encryptedFields_helper ( - mongoc_client_t *client, - const char *dbName, - const char *collName, - const char *kmsProvider) +test_create_encrypted_collection_no_encryptedFields_helper (mongoc_client_t *client, + const char *dbName, + const char *collName, + const char *kmsProvider) { bson_error_t error = {0}; bson_t *const kmsProviders = _make_kms_providers (true, true); @@ -6655,12 +5724,10 @@ test_create_encrypted_collection_no_encryptedFields_helper ( // Drop prior data { - mongoc_collection_t *const coll = - mongoc_client_get_collection (client, "keyvault", "datakeys"); + mongoc_collection_t *const coll = mongoc_client_get_collection (client, "keyvault", "datakeys"); if (coll) { mongoc_collection_drop (coll, &error); - bool okay = - error.code == 0 || strstr (error.message, "ns not found") != NULL; + bool okay = error.code == 0 || strstr (error.message, "ns not found") != NULL; ASSERT_OR_PRINT (okay, error); } mongoc_collection_destroy (coll); @@ -6671,15 +5738,12 @@ test_create_encrypted_collection_no_encryptedFields_helper ( } // Create a CE - mongoc_client_encryption_opts_t *const ceOpts = - mongoc_client_encryption_opts_new (); + mongoc_client_encryption_opts_t *const ceOpts = mongoc_client_encryption_opts_new (); mongoc_client_encryption_opts_set_kms_providers (ceOpts, kmsProviders); mongoc_client_encryption_opts_set_tls_opts (ceOpts, tlsOptions); - mongoc_client_encryption_opts_set_keyvault_namespace ( - ceOpts, "keyvault", "datakeys"); + mongoc_client_encryption_opts_set_keyvault_namespace (ceOpts, "keyvault", "datakeys"); mongoc_client_encryption_opts_set_keyvault_client (ceOpts, client); - mongoc_client_encryption_t *const ce = - mongoc_client_encryption_new (ceOpts, &error); + mongoc_client_encryption_t *const ce = mongoc_client_encryption_new (ceOpts, &error); mongoc_client_encryption_opts_destroy (ceOpts); ASSERT_OR_PRINT (ce, error); @@ -6688,12 +5752,9 @@ test_create_encrypted_collection_no_encryptedFields_helper ( mongoc_database_t *const db = mongoc_client_get_database (client, dbName); bson_t *const mkey = _make_kms_masterkey (kmsProvider); mongoc_collection_t *const coll = - mongoc_client_encryption_create_encrypted_collection ( - ce, db, collName, &ccOpts, NULL, kmsProvider, mkey, &error); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "No 'encryptedFields' are defined"); + mongoc_client_encryption_create_encrypted_collection (ce, db, collName, &ccOpts, NULL, kmsProvider, mkey, &error); + ASSERT_ERROR_CONTAINS ( + error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "No 'encryptedFields' are defined"); bson_destroy (&ccOpts); bson_destroy (mkey); @@ -6705,8 +5766,7 @@ test_create_encrypted_collection_no_encryptedFields_helper ( mongoc_client_encryption_destroy (ce); } -CEC_TEST (test_create_encrypted_collection_no_encryptedFields, - const char *kmsProvider) +CEC_TEST (test_create_encrypted_collection_no_encryptedFields, const char *kmsProvider) { const char *dbName = "cec-test-db"; const char *collName = "test-coll"; @@ -6714,8 +5774,7 @@ CEC_TEST (test_create_encrypted_collection_no_encryptedFields, // Test with a default client. { mongoc_client_t *const client = test_framework_new_default_client (); - test_create_encrypted_collection_no_encryptedFields_helper ( - client, dbName, collName, kmsProvider); + test_create_encrypted_collection_no_encryptedFields_helper (client, dbName, collName, kmsProvider); mongoc_client_destroy (client); } @@ -6724,25 +5783,18 @@ CEC_TEST (test_create_encrypted_collection_no_encryptedFields, // target collection was configured in encryptedFieldsMap. { mongoc_client_t *const client = test_framework_new_default_client (); - mongoc_auto_encryption_opts_t *aeOpts = - mongoc_auto_encryption_opts_new (); - bson_t *const kmsProviders = - _make_kms_providers (true /* with aws */, true /* with local */); + mongoc_auto_encryption_opts_t *aeOpts = mongoc_auto_encryption_opts_new (); + bson_t *const kmsProviders = _make_kms_providers (true /* with aws */, true /* with local */); char *namespace = bson_strdup_printf ("%s.%s", dbName, collName); - bson_t *encryptedFieldsMap = - tmp_bson ("{'%s': {'fields': []}}", namespace); + bson_t *encryptedFieldsMap = tmp_bson ("{'%s': {'fields': []}}", namespace); bson_error_t error; mongoc_auto_encryption_opts_set_kms_providers (aeOpts, kmsProviders); - mongoc_auto_encryption_opts_set_keyvault_namespace ( - aeOpts, "keyvault", "datakeys"); - mongoc_auto_encryption_opts_set_encrypted_fields_map (aeOpts, - encryptedFieldsMap); - ASSERT_OR_PRINT ( - mongoc_client_enable_auto_encryption (client, aeOpts, &error), error); + mongoc_auto_encryption_opts_set_keyvault_namespace (aeOpts, "keyvault", "datakeys"); + mongoc_auto_encryption_opts_set_encrypted_fields_map (aeOpts, encryptedFieldsMap); + ASSERT_OR_PRINT (mongoc_client_enable_auto_encryption (client, aeOpts, &error), error); - test_create_encrypted_collection_no_encryptedFields_helper ( - client, dbName, collName, kmsProvider); + test_create_encrypted_collection_no_encryptedFields_helper (client, dbName, collName, kmsProvider); bson_free (namespace); bson_destroy (kmsProviders); @@ -6751,8 +5803,7 @@ CEC_TEST (test_create_encrypted_collection_no_encryptedFields, } } -CEC_TEST (test_create_encrypted_collection_bad_keyId, - const char *const kmsProvider) +CEC_TEST (test_create_encrypted_collection_bad_keyId, const char *const kmsProvider) { bson_error_t error = {0}; mongoc_client_t *const client = test_framework_new_default_client (); @@ -6763,12 +5814,10 @@ CEC_TEST (test_create_encrypted_collection_bad_keyId, // Drop prior data { - mongoc_collection_t *const coll = - mongoc_client_get_collection (client, "keyvault", "datakeys"); + mongoc_collection_t *const coll = mongoc_client_get_collection (client, "keyvault", "datakeys"); if (coll) { mongoc_collection_drop (coll, &error); - bool okay = - error.code == 0 || strstr (error.message, "ns not found") != NULL; + bool okay = error.code == 0 || strstr (error.message, "ns not found") != NULL; ASSERT_OR_PRINT (okay, error); } mongoc_collection_destroy (coll); @@ -6779,34 +5828,28 @@ CEC_TEST (test_create_encrypted_collection_bad_keyId, } // Create a CE - mongoc_client_encryption_opts_t *const ceOpts = - mongoc_client_encryption_opts_new (); + mongoc_client_encryption_opts_t *const ceOpts = mongoc_client_encryption_opts_new (); mongoc_client_encryption_opts_set_kms_providers (ceOpts, kmsProviders); mongoc_client_encryption_opts_set_tls_opts (ceOpts, tlsOptions); - mongoc_client_encryption_opts_set_keyvault_namespace ( - ceOpts, "keyvault", "datakeys"); + mongoc_client_encryption_opts_set_keyvault_namespace (ceOpts, "keyvault", "datakeys"); mongoc_client_encryption_opts_set_keyvault_client (ceOpts, client); - mongoc_client_encryption_t *const ce = - mongoc_client_encryption_new (ceOpts, &error); + mongoc_client_encryption_t *const ce = mongoc_client_encryption_new (ceOpts, &error); mongoc_client_encryption_opts_destroy (ceOpts); ASSERT_OR_PRINT (ce, error); // Create the encrypted collection - bsonBuildDecl (ccOpts, - kv ("encryptedFields", - doc (kv ("fields", - array (doc (kv ("path", cstr ("ssn")), - kv ("bsonType", cstr ("string")), - kv ("keyId", bool (true)))))))); + bsonBuildDecl ( + ccOpts, + kv ("encryptedFields", + doc (kv ( + "fields", + array (doc (kv ("path", cstr ("ssn")), kv ("bsonType", cstr ("string")), kv ("keyId", bool (true)))))))); mongoc_database_t *const db = mongoc_client_get_database (client, dbName); bson_t *const mkey = _make_kms_masterkey (kmsProvider); - mongoc_collection_t *const coll = - mongoc_client_encryption_create_encrypted_collection ( - ce, db, "test-coll", &ccOpts, NULL, kmsProvider, mkey, &error); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_QUERY, - MONGOC_ERROR_PROTOCOL_INVALID_REPLY, - "create.encryptedFields.fields.keyId"); + mongoc_collection_t *const coll = mongoc_client_encryption_create_encrypted_collection ( + ce, db, "test-coll", &ccOpts, NULL, kmsProvider, mkey, &error); + ASSERT_ERROR_CONTAINS ( + error, MONGOC_ERROR_QUERY, MONGOC_ERROR_PROTOCOL_INVALID_REPLY, "create.encryptedFields.fields.keyId"); bson_destroy (&ccOpts); bson_destroy (mkey); @@ -6820,8 +5863,7 @@ CEC_TEST (test_create_encrypted_collection_bad_keyId, } // Implements Prose Test 21. Case: 4. -CEC_TEST (test_create_encrypted_collection_insert, - const char *const kmsProvider) +CEC_TEST (test_create_encrypted_collection_insert, const char *const kmsProvider) { bson_error_t error = {0}; mongoc_client_t *const client = test_framework_new_default_client (); @@ -6832,12 +5874,10 @@ CEC_TEST (test_create_encrypted_collection_insert, // Drop prior data { - mongoc_collection_t *const coll = - mongoc_client_get_collection (client, "keyvault", "datakeys"); + mongoc_collection_t *const coll = mongoc_client_get_collection (client, "keyvault", "datakeys"); if (coll) { mongoc_collection_drop (coll, &error); - bool okay = - error.code == 0 || strstr (error.message, "ns not found") != NULL; + bool okay = error.code == 0 || strstr (error.message, "ns not found") != NULL; ASSERT_OR_PRINT (okay, error); } mongoc_collection_destroy (coll); @@ -6848,31 +5888,26 @@ CEC_TEST (test_create_encrypted_collection_insert, } // Create a CE - mongoc_client_encryption_opts_t *const ceOpts = - mongoc_client_encryption_opts_new (); + mongoc_client_encryption_opts_t *const ceOpts = mongoc_client_encryption_opts_new (); mongoc_client_encryption_opts_set_kms_providers (ceOpts, kmsProviders); mongoc_client_encryption_opts_set_tls_opts (ceOpts, tlsOptions); - mongoc_client_encryption_opts_set_keyvault_namespace ( - ceOpts, "keyvault", "datakeys"); + mongoc_client_encryption_opts_set_keyvault_namespace (ceOpts, "keyvault", "datakeys"); mongoc_client_encryption_opts_set_keyvault_client (ceOpts, client); - mongoc_client_encryption_t *const ce = - mongoc_client_encryption_new (ceOpts, &error); + mongoc_client_encryption_t *const ce = mongoc_client_encryption_new (ceOpts, &error); mongoc_client_encryption_opts_destroy (ceOpts); ASSERT_OR_PRINT (ce, error); // Create the encrypted collection - bsonBuildDecl (ccOpts, - kv ("encryptedFields", - doc (kv ("fields", - array (doc (kv ("path", cstr ("ssn")), - kv ("bsonType", cstr ("string")), - kv ("keyId", null))))))); + bsonBuildDecl ( + ccOpts, + kv ("encryptedFields", + doc (kv ("fields", + array (doc (kv ("path", cstr ("ssn")), kv ("bsonType", cstr ("string")), kv ("keyId", null))))))); mongoc_database_t *const db = mongoc_client_get_database (client, dbName); bson_t new_opts; bson_t *const mkey = _make_kms_masterkey (kmsProvider); - mongoc_collection_t *const coll = - mongoc_client_encryption_create_encrypted_collection ( - ce, db, "testing1", &ccOpts, &new_opts, kmsProvider, mkey, &error); + mongoc_collection_t *const coll = mongoc_client_encryption_create_encrypted_collection ( + ce, db, "testing1", &ccOpts, &new_opts, kmsProvider, mkey, &error); ASSERT_OR_PRINT (coll, error); bson_destroy (&ccOpts); bson_destroy (mkey); @@ -6880,22 +5915,18 @@ CEC_TEST (test_create_encrypted_collection_insert, // Extract the encryption key ID that was generated by // CreateEncryptedCollection: bson_value_t new_keyid; - bsonParse ( - new_opts, - require ( - keyWithType ("encryptedFields", doc), - parse (require ( - keyWithType ("fields", array), - visitEach (require (type (doc)), - parse (require (key ("keyId"), - require (type (binary)), - do ({ - bson_value_copy ( - bson_iter_value ( - (bson_iter_t *) &bsonVisitIter), - &new_keyid); - }), - halt))))))); + bsonParse (new_opts, + require (keyWithType ("encryptedFields", doc), + parse (require (keyWithType ("fields", array), + visitEach (require (type (doc)), + parse (require (key ("keyId"), + require (type (binary)), + do ({ + bson_value_copy (bson_iter_value (( + bson_iter_t *) &bsonVisitIter), + &new_keyid); + }), + halt))))))); ASSERT_CMPSTR (bsonParseError, NULL); // Generate some plaintext: @@ -6905,14 +5936,11 @@ CEC_TEST (test_create_encrypted_collection_insert, plain.value.v_utf8.len = (uint32_t) strlen (plain.value.v_utf8.str); // Encrypt the value using the new encryption key: - mongoc_client_encryption_encrypt_opts_t *eo = - mongoc_client_encryption_encrypt_opts_new (); + mongoc_client_encryption_encrypt_opts_t *eo = mongoc_client_encryption_encrypt_opts_new (); mongoc_client_encryption_encrypt_opts_set_keyid (eo, &new_keyid); - mongoc_client_encryption_encrypt_opts_set_algorithm ( - eo, MONGOC_ENCRYPT_ALGORITHM_UNINDEXED); + mongoc_client_encryption_encrypt_opts_set_algorithm (eo, MONGOC_ENCRYPT_ALGORITHM_UNINDEXED); bson_value_t ciphertext; - bool okay = - mongoc_client_encryption_encrypt (ce, &plain, eo, &ciphertext, &error); + bool okay = mongoc_client_encryption_encrypt (ce, &plain, eo, &ciphertext, &error); ASSERT_OR_PRINT (okay, error); mongoc_client_encryption_encrypt_opts_destroy (eo); bson_value_destroy (&new_keyid); @@ -6962,13 +5990,11 @@ static BSON_THREAD_FUN (listen_socket, arg) server_addr.sin_port = htons (0); mongoc_socklen_t addr_len = (mongoc_socklen_t) sizeof server_addr; - int r = - mongoc_socket_bind (socket, (struct sockaddr *) &server_addr, addr_len); + int r = mongoc_socket_bind (socket, (struct sockaddr *) &server_addr, addr_len); BSON_ASSERT (r == 0); // forward the port and ip for mongocryptdURI - r = mongoc_socket_getsockname ( - socket, (struct sockaddr *) &server_addr, &addr_len); + r = mongoc_socket_getsockname (socket, (struct sockaddr *) &server_addr, &addr_len); BSON_ASSERT (r == 0); bson_mutex_lock (&args->mutex); @@ -6981,8 +6007,7 @@ static BSON_THREAD_FUN (listen_socket, arg) r = mongoc_socket_listen (socket, 100); BSON_ASSERT (r == 0); _mongoc_usleep (1000); // wait to see if received connection - mongoc_socket_t *ret = - mongoc_socket_accept (socket, bson_get_monotonic_time () + 100); + mongoc_socket_t *ret = mongoc_socket_accept (socket, bson_get_monotonic_time () + 100); if (ret) { // not null received a connection and test should fail args->failed = true; @@ -7015,20 +6040,15 @@ test_bypass_mongocryptd_shared_library (void *unused) listen_socket_args_t *args = bson_malloc0 (sizeof (listen_socket_args_t)); bson_mutex_init (&args->mutex); mongoc_cond_init (&args->cond); - ASSERT_CMPINT ( - 0, ==, mcommon_thread_create (&socket_thread, listen_socket, args)); + ASSERT_CMPINT (0, ==, mcommon_thread_create (&socket_thread, listen_socket, args)); // configure mongoclient with auto encryption - char *env_cryptSharedLibPath = - test_framework_getenv ("MONGOC_TEST_CRYPT_SHARED_LIB_PATH"); + char *env_cryptSharedLibPath = test_framework_getenv ("MONGOC_TEST_CRYPT_SHARED_LIB_PATH"); BSON_ASSERT (env_cryptSharedLibPath); auto_encryption_opts = mongoc_auto_encryption_opts_new (); - kms_providers = BCON_NEW ( - "local", "{", "key", BCON_BIN (0, (uint8_t *) LOCAL_MASTERKEY, 96), "}"); - mongoc_auto_encryption_opts_set_kms_providers (auto_encryption_opts, - kms_providers); - mongoc_auto_encryption_opts_set_keyvault_namespace ( - auto_encryption_opts, "keyvault", "datakeys"); + kms_providers = BCON_NEW ("local", "{", "key", BCON_BIN (0, (uint8_t *) LOCAL_MASTERKEY, 96), "}"); + mongoc_auto_encryption_opts_set_kms_providers (auto_encryption_opts, kms_providers); + mongoc_auto_encryption_opts_set_keyvault_namespace (auto_encryption_opts, "keyvault", "datakeys"); // wait for port and ip to be set on the other thread bson_mutex_lock (&args->mutex); @@ -7050,18 +6070,14 @@ test_bypass_mongocryptd_shared_library (void *unused) bson_free (env_cryptSharedLibPath); // get the client client_encrypted = test_framework_new_default_client (); - bool ret = mongoc_client_enable_auto_encryption ( - client_encrypted, auto_encryption_opts, &error); + bool ret = mongoc_client_enable_auto_encryption (client_encrypted, auto_encryption_opts, &error); ASSERT_OR_PRINT (ret, error); // insert a document db = mongoc_client_get_database (client_encrypted, "db"); coll = mongoc_database_get_collection (db, "coll"); - ret = mongoc_collection_insert_one (coll, - tmp_bson ("{'unencrypted': 'test'}"), - NULL /* opts */, - NULL /* reply */, - &error); + ret = mongoc_collection_insert_one ( + coll, tmp_bson ("{'unencrypted': 'test'}"), NULL /* opts */, NULL /* reply */, &error); ASSERT_OR_PRINT (ret, error); // Wait for listener thread to complete. @@ -7089,22 +6105,20 @@ test_bypass_mongocryptd_shared_library (void *unused) void test_client_side_encryption_install (TestSuite *suite) { - install_json_test_suite_with_check ( - suite, - JSON_DIR, - "client_side_encryption/legacy", - test_client_side_encryption_cb, - test_framework_skip_if_no_client_side_encryption); + install_json_test_suite_with_check (suite, + JSON_DIR, + "client_side_encryption/legacy", + test_client_side_encryption_cb, + test_framework_skip_if_no_client_side_encryption); /* Prose tests from the spec. */ - TestSuite_AddFull ( - suite, - "/client_side_encryption/create_datakey_with_custom_key_material", - test_create_datakey_with_custom_key_material, - NULL, - NULL, - test_framework_skip_if_no_client_side_encryption, - test_framework_skip_if_max_wire_version_less_than_8, - test_framework_skip_if_offline /* requires AWS */); + TestSuite_AddFull (suite, + "/client_side_encryption/create_datakey_with_custom_key_material", + test_create_datakey_with_custom_key_material, + NULL, + NULL, + test_framework_skip_if_no_client_side_encryption, + test_framework_skip_if_max_wire_version_less_than_8, + test_framework_skip_if_offline /* requires AWS */); TestSuite_AddFull (suite, "/client_side_encryption/datakey_and_double_encryption", test_datakey_and_double_encryption, @@ -7113,23 +6127,21 @@ test_client_side_encryption_install (TestSuite *suite) test_framework_skip_if_no_client_side_encryption, test_framework_skip_if_max_wire_version_less_than_8, test_framework_skip_if_offline /* requires AWS */); - TestSuite_AddFull ( - suite, - "/client_side_encryption/external_key_vault", - test_external_key_vault, - NULL, - NULL, - test_framework_skip_if_no_client_side_encryption, - test_framework_skip_if_max_wire_version_less_than_8, - test_framework_skip_if_no_auth /* requires auth for error check */); - TestSuite_AddFull ( - suite, - "/client_side_encryption/bson_size_limits_and_batch_splitting", - test_bson_size_limits_and_batch_splitting, - NULL, - NULL, - test_framework_skip_if_no_client_side_encryption, - test_framework_skip_if_max_wire_version_less_than_8); + TestSuite_AddFull (suite, + "/client_side_encryption/external_key_vault", + test_external_key_vault, + NULL, + NULL, + test_framework_skip_if_no_client_side_encryption, + test_framework_skip_if_max_wire_version_less_than_8, + test_framework_skip_if_no_auth /* requires auth for error check */); + TestSuite_AddFull (suite, + "/client_side_encryption/bson_size_limits_and_batch_splitting", + test_bson_size_limits_and_batch_splitting, + NULL, + NULL, + test_framework_skip_if_no_client_side_encryption, + test_framework_skip_if_max_wire_version_less_than_8); TestSuite_AddFull (suite, "/client_side_encryption/views_are_prohibited", test_views_are_prohibited, @@ -7145,15 +6157,14 @@ test_client_side_encryption_install (TestSuite *suite) test_framework_skip_if_no_client_side_encryption, test_framework_skip_if_max_wire_version_less_than_8, test_framework_skip_if_offline /* requires AWS */); - TestSuite_AddFull ( - suite, - "/client_side_encryption/custom_endpoint", - test_custom_endpoint, - NULL, - NULL, - test_framework_skip_if_no_client_side_encryption, - test_framework_skip_if_max_wire_version_less_than_8, - test_framework_skip_if_offline /* requires AWS, Azure, and GCP */); + TestSuite_AddFull (suite, + "/client_side_encryption/custom_endpoint", + test_custom_endpoint, + NULL, + NULL, + test_framework_skip_if_no_client_side_encryption, + test_framework_skip_if_max_wire_version_less_than_8, + test_framework_skip_if_offline /* requires AWS, Azure, and GCP */); TestSuite_AddFull (suite, "/client_side_encryption/bypass_spawning_mongocryptd/" "mongocryptdBypassSpawn", @@ -7253,18 +6264,17 @@ test_client_side_encryption_install (TestSuite *suite) NULL, test_framework_skip_if_no_client_side_encryption, test_framework_skip_if_max_wire_version_less_than_8); - TestSuite_AddFull ( - suite, - "/client_side_encryption/kms_tls_options", - test_kms_tls_options, - NULL, - NULL, - test_framework_skip_if_no_client_side_encryption, - test_framework_skip_if_max_wire_version_less_than_8, - test_framework_skip_if_offline /* requires AWS, Azure, and GCP */, - /* Do not run on Windows due to CDRIVER-4181. Tests use a literal IP with - a TLS connection. */ - test_framework_skip_if_windows); + TestSuite_AddFull (suite, + "/client_side_encryption/kms_tls_options", + test_kms_tls_options, + NULL, + NULL, + test_framework_skip_if_no_client_side_encryption, + test_framework_skip_if_max_wire_version_less_than_8, + test_framework_skip_if_offline /* requires AWS, Azure, and GCP */, + /* Do not run on Windows due to CDRIVER-4181. Tests use a literal IP with + a TLS connection. */ + test_framework_skip_if_windows); TestSuite_AddFull (suite, "/client_side_encryption/kms_tls_options/extra_rejected", @@ -7273,17 +6283,16 @@ test_client_side_encryption_install (TestSuite *suite) NULL, test_framework_skip_if_no_client_side_encryption); - TestSuite_AddFull ( - suite, - "/client_side_encryption/explicit_encryption/case1", - test_explicit_encryption_case1, - NULL /* dtor */, - NULL /* ctx */, - test_framework_skip_if_no_client_side_encryption, - test_framework_skip_if_max_wire_version_less_than_21, - // Remove skip_if_serverless once DRIVERS-2589 is resolved. - test_framework_skip_if_serverless, - test_framework_skip_if_single); + TestSuite_AddFull (suite, + "/client_side_encryption/explicit_encryption/case1", + test_explicit_encryption_case1, + NULL /* dtor */, + NULL /* ctx */, + test_framework_skip_if_no_client_side_encryption, + test_framework_skip_if_max_wire_version_less_than_21, + // Remove skip_if_serverless once DRIVERS-2589 is resolved. + test_framework_skip_if_serverless, + test_framework_skip_if_single); TestSuite_AddFull (suite, "/client_side_encryption/explicit_encryption/case2", @@ -7296,41 +6305,38 @@ test_client_side_encryption_install (TestSuite *suite) test_framework_skip_if_serverless, test_framework_skip_if_single); - TestSuite_AddFull ( - suite, - "/client_side_encryption/explicit_encryption/case3", - test_explicit_encryption_case3, - NULL /* dtor */, - NULL /* ctx */, - test_framework_skip_if_no_client_side_encryption, - test_framework_skip_if_max_wire_version_less_than_21, - // Remove skip_if_serverless once DRIVERS-2589 is resolved. - test_framework_skip_if_serverless, - test_framework_skip_if_single); - - TestSuite_AddFull ( - suite, - "/client_side_encryption/explicit_encryption/case4", - test_explicit_encryption_case4, - NULL /* dtor */, - NULL /* ctx */, - test_framework_skip_if_no_client_side_encryption, - test_framework_skip_if_max_wire_version_less_than_21, - // Remove skip_if_serverless once DRIVERS-2589 is resolved. - test_framework_skip_if_serverless, - test_framework_skip_if_single); - - TestSuite_AddFull ( - suite, - "/client_side_encryption/explicit_encryption/case5", - test_explicit_encryption_case5, - NULL /* dtor */, - NULL /* ctx */, - test_framework_skip_if_no_client_side_encryption, - test_framework_skip_if_max_wire_version_less_than_21, - // Remove skip_if_serverless once DRIVERS-2589 is resolved. - test_framework_skip_if_serverless, - test_framework_skip_if_single); + TestSuite_AddFull (suite, + "/client_side_encryption/explicit_encryption/case3", + test_explicit_encryption_case3, + NULL /* dtor */, + NULL /* ctx */, + test_framework_skip_if_no_client_side_encryption, + test_framework_skip_if_max_wire_version_less_than_21, + // Remove skip_if_serverless once DRIVERS-2589 is resolved. + test_framework_skip_if_serverless, + test_framework_skip_if_single); + + TestSuite_AddFull (suite, + "/client_side_encryption/explicit_encryption/case4", + test_explicit_encryption_case4, + NULL /* dtor */, + NULL /* ctx */, + test_framework_skip_if_no_client_side_encryption, + test_framework_skip_if_max_wire_version_less_than_21, + // Remove skip_if_serverless once DRIVERS-2589 is resolved. + test_framework_skip_if_serverless, + test_framework_skip_if_single); + + TestSuite_AddFull (suite, + "/client_side_encryption/explicit_encryption/case5", + test_explicit_encryption_case5, + NULL /* dtor */, + NULL /* ctx */, + test_framework_skip_if_no_client_side_encryption, + test_framework_skip_if_max_wire_version_less_than_21, + // Remove skip_if_serverless once DRIVERS-2589 is resolved. + test_framework_skip_if_serverless, + test_framework_skip_if_single); TestSuite_AddFull (suite, "/client_side_encryption/decryption_events/case1", @@ -7365,17 +6371,16 @@ test_client_side_encryption_install (TestSuite *suite) test_framework_skip_if_no_client_side_encryption, test_framework_skip_if_max_wire_version_less_than_8); - TestSuite_AddFull ( - suite, - "/client_side_encryption/qe_docs_example", - test_qe_docs_example, - NULL /* dtor */, - NULL /* ctx */, - test_framework_skip_if_no_client_side_encryption, - test_framework_skip_if_max_wire_version_less_than_21, - // Remove skip_if_serverless once DRIVERS-2589 is resolved. - test_framework_skip_if_serverless, - test_framework_skip_if_single); + TestSuite_AddFull (suite, + "/client_side_encryption/qe_docs_example", + test_qe_docs_example, + NULL /* dtor */, + NULL /* ctx */, + test_framework_skip_if_no_client_side_encryption, + test_framework_skip_if_max_wire_version_less_than_21, + // Remove skip_if_serverless once DRIVERS-2589 is resolved. + test_framework_skip_if_serverless, + test_framework_skip_if_single); TestSuite_AddFull (suite, "/client_side_encryption/kms/callback", @@ -7411,69 +6416,59 @@ test_client_side_encryption_install (TestSuite *suite) test_framework_skip_if_no_client_side_encryption, test_framework_skip_if_max_wire_version_less_than_8); + TestSuite_AddFull (suite, "/client_side_encryption/auto_datakeys", test_auto_datakeys, NULL, NULL, NULL); + + TestSuite_AddFull (suite, + "/client_side_encryption/createEncryptedCollection/simple", + test_create_encrypted_collection_simple, + NULL, + NULL, + test_framework_skip_if_no_client_side_encryption, + test_framework_skip_if_max_wire_version_less_than_21, + // Remove skip_if_serverless once DRIVERS-2589 is resolved. + test_framework_skip_if_serverless, + test_framework_skip_if_single); + + TestSuite_AddFull (suite, + "/client_side_encryption/createEncryptedCollection/" + "missing-encryptedFields", + test_create_encrypted_collection_no_encryptedFields, + NULL, + NULL, + test_framework_skip_if_no_client_side_encryption, + test_framework_skip_if_max_wire_version_less_than_21, + // Remove skip_if_serverless once DRIVERS-2589 is resolved. + test_framework_skip_if_serverless, + test_framework_skip_if_single); + TestSuite_AddFull (suite, + "/client_side_encryption/createEncryptedCollection/" + "bad-keyId", + test_create_encrypted_collection_bad_keyId, + NULL, + NULL, + test_framework_skip_if_no_client_side_encryption, + test_framework_skip_if_max_wire_version_less_than_21, + // Remove skip_if_serverless once DRIVERS-2589 is resolved. + test_framework_skip_if_serverless, + test_framework_skip_if_single); + TestSuite_AddFull (suite, + "/client_side_encryption/createEncryptedCollection/insert", + test_create_encrypted_collection_insert, + NULL, + NULL, + test_framework_skip_if_no_client_side_encryption, + test_framework_skip_if_max_wire_version_less_than_21, + // Remove skip_if_serverless once DRIVERS-2589 is resolved. + test_framework_skip_if_serverless, + test_framework_skip_if_single); TestSuite_AddFull (suite, - "/client_side_encryption/auto_datakeys", - test_auto_datakeys, + "/client_side_encryption/bypass_mongocryptd_shared_library", + test_bypass_mongocryptd_shared_library, NULL, NULL, - NULL); - - TestSuite_AddFull ( - suite, - "/client_side_encryption/createEncryptedCollection/simple", - test_create_encrypted_collection_simple, - NULL, - NULL, - test_framework_skip_if_no_client_side_encryption, - test_framework_skip_if_max_wire_version_less_than_21, - // Remove skip_if_serverless once DRIVERS-2589 is resolved. - test_framework_skip_if_serverless, - test_framework_skip_if_single); - - TestSuite_AddFull ( - suite, - "/client_side_encryption/createEncryptedCollection/" - "missing-encryptedFields", - test_create_encrypted_collection_no_encryptedFields, - NULL, - NULL, - test_framework_skip_if_no_client_side_encryption, - test_framework_skip_if_max_wire_version_less_than_21, - // Remove skip_if_serverless once DRIVERS-2589 is resolved. - test_framework_skip_if_serverless, - test_framework_skip_if_single); - TestSuite_AddFull ( - suite, - "/client_side_encryption/createEncryptedCollection/" - "bad-keyId", - test_create_encrypted_collection_bad_keyId, - NULL, - NULL, - test_framework_skip_if_no_client_side_encryption, - test_framework_skip_if_max_wire_version_less_than_21, - // Remove skip_if_serverless once DRIVERS-2589 is resolved. - test_framework_skip_if_serverless, - test_framework_skip_if_single); - TestSuite_AddFull ( - suite, - "/client_side_encryption/createEncryptedCollection/insert", - test_create_encrypted_collection_insert, - NULL, - NULL, - test_framework_skip_if_no_client_side_encryption, - test_framework_skip_if_max_wire_version_less_than_21, - // Remove skip_if_serverless once DRIVERS-2589 is resolved. - test_framework_skip_if_serverless, - test_framework_skip_if_single); - TestSuite_AddFull ( - suite, - "/client_side_encryption/bypass_mongocryptd_shared_library", - test_bypass_mongocryptd_shared_library, - NULL, - NULL, - test_framework_skip_if_no_client_side_encryption, - test_framework_skip_if_max_wire_version_less_than_17, - _skip_if_no_crypt_shared); + test_framework_skip_if_no_client_side_encryption, + test_framework_skip_if_max_wire_version_less_than_17, + _skip_if_no_crypt_shared); // Add test cases for prose test: 22. Range Explicit Encryption. { @@ -7508,36 +6503,32 @@ test_client_side_encryption_install (TestSuite *suite) const char *rangeType = rangeTypes[i]; rangeCase rc = rangeCases[j]; - char *test_name = bson_strdup_printf ( - "/client_side_encryption/range_explicit_encryption/%s/%s", - rc.name, - rangeType); + char *test_name = + bson_strdup_printf ("/client_side_encryption/range_explicit_encryption/%s/%s", rc.name, rangeType); // Skip DecimalNoPrecision if not a replica set. if (0 == strcmp (rangeType, "DecimalNoPrecision")) { - TestSuite_AddFull ( - suite, - test_name, - rc.fn, - NULL /* dtor */, - (void *) rangeTypes[i] /* ctx */, - test_framework_skip_if_no_client_side_encryption, - test_framework_skip_if_max_wire_version_less_than_21, - // Remove skip_if_serverless once DRIVERS-2589 is resolved. - test_framework_skip_if_serverless, - test_framework_skip_if_not_replset); + TestSuite_AddFull (suite, + test_name, + rc.fn, + NULL /* dtor */, + (void *) rangeTypes[i] /* ctx */, + test_framework_skip_if_no_client_side_encryption, + test_framework_skip_if_max_wire_version_less_than_21, + // Remove skip_if_serverless once DRIVERS-2589 is resolved. + test_framework_skip_if_serverless, + test_framework_skip_if_not_replset); } else { - TestSuite_AddFull ( - suite, - test_name, - rc.fn, - NULL /* dtor */, - (void *) rangeTypes[i] /* ctx */, - test_framework_skip_if_no_client_side_encryption, - test_framework_skip_if_max_wire_version_less_than_21, - // Remove skip_if_serverless once DRIVERS-2589 is resolved. - test_framework_skip_if_serverless, - test_framework_skip_if_single); + TestSuite_AddFull (suite, + test_name, + rc.fn, + NULL /* dtor */, + (void *) rangeTypes[i] /* ctx */, + test_framework_skip_if_no_client_side_encryption, + test_framework_skip_if_max_wire_version_less_than_21, + // Remove skip_if_serverless once DRIVERS-2589 is resolved. + test_framework_skip_if_serverless, + test_framework_skip_if_single); } bson_free (test_name); diff --git a/src/libmongoc/tests/test-mongoc-client.c b/src/libmongoc/tests/test-mongoc-client.c index f6cf06d39d..94c88ac829 100644 --- a/src/libmongoc/tests/test-mongoc-client.c +++ b/src/libmongoc/tests/test-mongoc-client.c @@ -44,32 +44,23 @@ test_client_cmd_w_server_id (void) future_t *future; request_t *request; - rs = mock_rs_with_auto_hello (WIRE_VERSION_MIN, - true /* has primary */, - 1 /* secondary */, - 0 /* arbiters */); + rs = mock_rs_with_auto_hello (WIRE_VERSION_MIN, true /* has primary */, 1 /* secondary */, 0 /* arbiters */); mock_rs_run (rs); client = test_framework_client_new_from_uri (mock_rs_get_uri (rs), NULL); /* use serverId instead of prefs to select the secondary */ opts = tmp_bson ("{'serverId': 2, 'readConcern': {'level': 'local'}}"); - future = future_client_read_command_with_opts (client, - "db", - tmp_bson ("{'ping': 1}"), - NULL /* prefs */, - opts, - &reply, - &error); + future = future_client_read_command_with_opts ( + client, "db", tmp_bson ("{'ping': 1}"), NULL /* prefs */, opts, &reply, &error); /* recognized that wire version is recent enough for readConcern */ - request = - mock_rs_receives_msg (rs, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db'," - " 'ping': 1," - " 'readConcern': {'level': 'local'}," - " 'serverId': {'$exists': false}}")); + request = mock_rs_receives_msg (rs, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'db'," + " 'ping': 1," + " 'readConcern': {'level': 'local'}," + " 'serverId': {'$exists': false}}")); ASSERT (mock_rs_request_is_to_secondary (rs, request)); reply_to_request_simple (request, "{'ok': 1}"); @@ -97,23 +88,15 @@ test_client_cmd_w_server_id_sharded (void) server = mock_mongos_new (WIRE_VERSION_MIN); mock_server_run (server); mock_server_auto_endsessions (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); opts = tmp_bson ("{'serverId': 1}"); - future = future_client_read_command_with_opts (client, - "db", - tmp_bson ("{'ping': 1}"), - NULL /* prefs */, - opts, - &reply, - &error); + future = future_client_read_command_with_opts ( + client, "db", tmp_bson ("{'ping': 1}"), NULL /* prefs */, opts, &reply, &error); /* does NOT set secondaryOk, since this is a sharded topology */ request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db', 'ping': 1, 'serverId': {'$exists': false}}")); + server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', 'ping': 1, 'serverId': {'$exists': false}}")); reply_to_request_with_ok_and_destroy (request); ASSERT_OR_PRINT (future_get_bool (future), error); @@ -137,41 +120,20 @@ test_server_id_option (void *ctx) client = test_framework_new_default_client (); cmd = tmp_bson ("{'ping': 1}"); - r = mongoc_client_read_command_with_opts (client, - "test", - cmd, - NULL /* prefs */, - tmp_bson ("{'serverId': 'foo'}"), - NULL, - &error); + r = mongoc_client_read_command_with_opts ( + client, "test", cmd, NULL /* prefs */, tmp_bson ("{'serverId': 'foo'}"), NULL, &error); ASSERT (!r); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "must be an integer"); - - r = mongoc_client_read_command_with_opts (client, - "test", - cmd, - NULL /* prefs */, - tmp_bson ("{'serverId': 0}"), - NULL, - &error); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "must be an integer"); + + r = mongoc_client_read_command_with_opts ( + client, "test", cmd, NULL /* prefs */, tmp_bson ("{'serverId': 0}"), NULL, &error); ASSERT (!r); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "must be >= 1"); - - r = mongoc_client_read_command_with_opts (client, - "test", - cmd, - NULL /* prefs */, - tmp_bson ("{'serverId': 1}"), - NULL, - &error); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "must be >= 1"); + + r = mongoc_client_read_command_with_opts ( + client, "test", cmd, NULL /* prefs */, tmp_bson ("{'serverId': 1}"), NULL, &error); ASSERT_OR_PRINT (r, error); @@ -205,21 +167,15 @@ test_client_cmd_w_write_concern (void *ctx) bad_wc->wtimeout = -10; mongoc_write_concern_append (good_wc, opts); - ASSERT_OR_PRINT (mongoc_client_write_command_with_opts ( - client, "test", command, opts, &reply, &error), - error); + ASSERT_OR_PRINT (mongoc_client_write_command_with_opts (client, "test", command, opts, &reply, &error), error); bson_reinit (opts); bson_destroy (&reply); mongoc_write_concern_append_bad (bad_wc, opts); - ASSERT (!mongoc_client_write_command_with_opts ( - client, "test", command, opts, &reply, &error)); + ASSERT (!mongoc_client_write_command_with_opts (client, "test", command, opts, &reply, &error)); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Invalid writeConcern"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid writeConcern"); bad_wc->wtimeout = 0; bson_destroy (&reply); error.code = 0; @@ -231,8 +187,7 @@ test_client_cmd_w_write_concern (void *ctx) mongoc_write_concern_append_bad (bad_wc, opts); /* bad write concern in opts */ - ASSERT (!mongoc_client_write_command_with_opts ( - client, "test", command, opts, &reply, &error)); + ASSERT (!mongoc_client_write_command_with_opts (client, "test", command, opts, &reply, &error)); assert_wc_oob_error (&error); bson_destroy (&reply); } @@ -268,13 +223,11 @@ test_client_cmd_write_concern (void) /* set up client and wire protocol version */ server = mock_server_with_auto_hello (WIRE_VERSION_MIN); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); /* command with invalid writeConcern */ cmd = tmp_bson ("{'$db': 'test', 'foo' : 1, 'writeConcern' : {'w' : 99 }}"); - future = - future_client_command_simple (client, "test", cmd, NULL, &reply, &error); + future = future_client_command_simple (client, "test", cmd, NULL, &reply, &error); request = mock_server_receives_msg (server, MONGOC_MSG_NONE, cmd); BSON_ASSERT (request); @@ -285,8 +238,7 @@ test_client_cmd_write_concern (void) bson_destroy (&reply); /* standalone response */ - future = - future_client_command_simple (client, "test", cmd, NULL, &reply, &error); + future = future_client_command_simple (client, "test", cmd, NULL, &reply, &error); request = mock_server_receives_msg (server, MONGOC_MSG_NONE, cmd); BSON_ASSERT (request); @@ -300,13 +252,11 @@ test_client_cmd_write_concern (void) bson_destroy (&reply); /* replicaset response */ - future = - future_client_command_simple (client, "test", cmd, NULL, &reply, &error); + future = future_client_command_simple (client, "test", cmd, NULL, &reply, &error); request = mock_server_receives_msg (server, MONGOC_MSG_NONE, cmd); - reply_to_request_simple ( - request, - "{ 'ok' : 1, 'n': 1, " - "'writeConcernError': {'code': 17, 'errmsg': 'foo'}}"); + reply_to_request_simple (request, + "{ 'ok' : 1, 'n': 1, " + "'writeConcernError': {'code': 17, 'errmsg': 'foo'}}"); BSON_ASSERT (future_get_bool (future)); bson_destroy (&reply); @@ -331,21 +281,18 @@ test_client_cmd_write_concern_fam (void) server = mock_server_with_auto_hello (WIRE_VERSION_MIN); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); wc = mongoc_write_concern_new (); mongoc_write_concern_set_w (wc, 2); mongoc_client_set_write_concern (client, wc); fam = tmp_bson ("{'findAndModify': 'collection'}"); - future = future_client_read_write_command_with_opts ( - client, "test", fam, NULL, NULL, &reply, &error); + future = future_client_read_write_command_with_opts (client, "test", fam, NULL, NULL, &reply, &error); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'test', 'findAndModify': 'collection', " - "'writeConcern': {'w': 2}}")); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'test', 'findAndModify': 'collection', " + "'writeConcern': {'w': 2}}")); reply_to_request_with_ok_and_destroy (request); BSON_ASSERT (future_get_bool (future)); @@ -361,8 +308,7 @@ test_client_cmd_write_concern_fam (void) static char * gen_test_user (void) { - return bson_strdup_printf ( - "testuser_%u_%u", (unsigned) time (NULL), (unsigned) gettestpid ()); + return bson_strdup_printf ("testuser_%u_%u", (unsigned) time (NULL), (unsigned) gettestpid ()); } @@ -371,8 +317,7 @@ gen_good_uri (const char *username, const char *dbname) { char *host = test_framework_get_host (); uint16_t port = test_framework_get_port (); - char *uri = bson_strdup_printf ( - "mongodb://%s:testpass@%s:%hu/%s", username, host, port, dbname); + char *uri = bson_strdup_printf ("mongodb://%s:testpass@%s:%hu/%s", username, host, port, dbname); bson_free (host); return uri; @@ -415,12 +360,8 @@ test_mongoc_client_authenticate (void *context) bson_init (&roles); BCON_APPEND (&roles, "0", "{", "role", "read", "db", "test", "}"); - r = mongoc_database_add_user (database, - username, - "testpass", - tmp_bson ("[{'role': 'read', 'db': 'test'}]"), - NULL, - &error); + r = mongoc_database_add_user ( + database, username, "testpass", tmp_bson ("[{'role': 'read', 'db': 'test'}]"), NULL, &error); ASSERT_OR_PRINT (r, error); mongoc_database_destroy (database); @@ -430,8 +371,7 @@ test_mongoc_client_authenticate (void *context) */ bson_init (&q); uri_str_no_auth = test_framework_get_uri_str_no_auth ("test"); - uri_str_auth = - test_framework_add_user_password (uri_str_no_auth, username, "testpass"); + uri_str_auth = test_framework_add_user_password (uri_str_no_auth, username, "testpass"); auth_client = test_framework_client_new (uri_str_auth, NULL); test_framework_set_ssl_opts (auth_client); collection = mongoc_client_get_collection (auth_client, "test", "test"); @@ -499,26 +439,20 @@ test_mongoc_client_speculative_auth_failure (bool pooled) bson_init (&roles); BCON_APPEND (&roles, "0", "{", "role", "read", "db", "test", "}"); - r = mongoc_database_add_user (database, - username, - "testpass", - tmp_bson ("[{'role': 'read', 'db': 'test'}]"), - NULL, - &error); + r = mongoc_database_add_user ( + database, username, "testpass", tmp_bson ("[{'role': 'read', 'db': 'test'}]"), NULL, &error); ASSERT_OR_PRINT (r, error); mongoc_database_destroy (database); bson_init (&q); uri_str_no_auth = test_framework_get_uri_str_no_auth ("test"); - uri_str_auth = - test_framework_add_user_password (uri_str_no_auth, username, "testpass"); + uri_str_auth = test_framework_add_user_password (uri_str_no_auth, username, "testpass"); { mongoc_uri_t *const uri = mongoc_uri_new (uri_str_auth); - ASSERT ( - mongoc_uri_set_option_as_bool (uri, MONGOC_URI_RETRYREADS, false)); + ASSERT (mongoc_uri_set_option_as_bool (uri, MONGOC_URI_RETRYREADS, false)); if (pooled) { pool = test_framework_client_pool_new_from_uri (uri, NULL); @@ -536,15 +470,14 @@ test_mongoc_client_speculative_auth_failure (bool pooled) database = mongoc_client_get_database (admin_client, "admin"); /* Enable failpoint to break saslContinue */ - r = mongoc_database_command_simple ( - database, - tmp_bson ("{'configureFailPoint': 'failCommand', " - "'mode': {'times': 1}, " - "'data': {'failCommands': ['saslContinue'], 'closeConnection': " - "true, 'errorCode': 10107}}"), - NULL, - NULL, - &error); + r = mongoc_database_command_simple (database, + tmp_bson ("{'configureFailPoint': 'failCommand', " + "'mode': {'times': 1}, " + "'data': {'failCommands': ['saslContinue'], 'closeConnection': " + "true, 'errorCode': 10107}}"), + NULL, + NULL, + &error); ASSERT_OR_PRINT (r, error); mongoc_database_destroy (database); @@ -559,20 +492,13 @@ test_mongoc_client_speculative_auth_failure (bool pooled) * error on saslContinue and subsequently attempt to start auth from the * beginning. The failpoint closes the stream causing an error from * saslStart. */ - if (pooled && - test_framework_max_wire_version_at_least (WIRE_VERSION_4_4)) { - ASSERT_CAPTURED_LOG ("cluster", - MONGOC_LOG_LEVEL_WARNING, - "Failed to send \"saslStart\" command"); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_CLIENT, - MONGOC_ERROR_CLIENT_AUTHENTICATE, - "Failed to send \"saslStart\" command"); + if (pooled && test_framework_max_wire_version_at_least (WIRE_VERSION_4_4)) { + ASSERT_CAPTURED_LOG ("cluster", MONGOC_LOG_LEVEL_WARNING, "Failed to send \"saslStart\" command"); + ASSERT_ERROR_CONTAINS ( + error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_AUTHENTICATE, "Failed to send \"saslStart\" command"); } else { - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_CLIENT, - MONGOC_ERROR_CLIENT_AUTHENTICATE, - "Failed to send \"saslContinue\" command"); + ASSERT_ERROR_CONTAINS ( + error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_AUTHENTICATE, "Failed to send \"saslContinue\" command"); } } capture_logs (false); @@ -657,8 +583,7 @@ test_mongoc_client_authenticate_cached (bool pooled) for (i = 0; i < 10; i++) { mongoc_topology_scanner_node_t *scanner_node; - cursor = - mongoc_collection_find_with_opts (collection, &insert, NULL, NULL); + cursor = mongoc_collection_find_with_opts (collection, &insert, NULL, NULL); r = mongoc_cursor_next (cursor, &doc); ASSERT_OR_PRINT (!mongoc_cursor_error (cursor, &error), error); ASSERT (r); @@ -668,8 +593,7 @@ test_mongoc_client_authenticate_cached (bool pooled) if (pooled) { mongoc_cluster_disconnect_node (&client->cluster, server_id); } else { - scanner_node = mongoc_topology_scanner_get_node ( - client->topology->scanner, server_id); + scanner_node = mongoc_topology_scanner_get_node (client->topology->scanner, server_id); mongoc_stream_destroy (scanner_node->stream); scanner_node->stream = NULL; } @@ -719,8 +643,7 @@ test_mongoc_client_authenticate_failure (void *context) bson_t empty = BSON_INITIALIZER; char *host = test_framework_get_host (); char *uri_str_no_auth = test_framework_get_uri_str_no_auth (NULL); - char *bad_uri_str = - test_framework_add_user_password (uri_str_no_auth, "baduser", "badpass"); + char *bad_uri_str = test_framework_add_user_password (uri_str_no_auth, "baduser", "badpass"); BSON_UNUSED (context); @@ -754,8 +677,7 @@ test_mongoc_client_authenticate_failure (void *context) * Try various commands while in the failed state to ensure we get the * same sort of errors. */ - r = - mongoc_collection_update_one (collection, &q, &empty, NULL, NULL, &error); + r = mongoc_collection_update_one (collection, &q, &empty, NULL, NULL, &error); BSON_ASSERT (!r); ASSERT_CMPINT (error.domain, ==, MONGOC_ERROR_CLIENT); ASSERT_CMPINT (error.code, ==, MONGOC_ERROR_CLIENT_AUTHENTICATE); @@ -795,22 +717,19 @@ test_mongoc_client_authenticate_timeout (void *context) mongoc_uri_set_option_as_int32 (uri, "socketTimeoutMS", 10); client = test_framework_client_new_from_uri (uri, NULL); - future = future_client_command_simple ( - client, "test", tmp_bson ("{'ping': 1}"), NULL, &reply, &error); + future = future_client_command_simple (client, "test", tmp_bson ("{'ping': 1}"), NULL, &reply, &error); - request = mock_server_receives_msg ( - server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'admin'}")); + request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'admin'}")); ASSERT (request); ASSERT_CMPSTR (request->command_name, "saslStart"); /* don't reply */ BSON_ASSERT (!future_get_bool (future)); - ASSERT_ERROR_CONTAINS ( - error, - MONGOC_ERROR_CLIENT, - MONGOC_ERROR_CLIENT_AUTHENTICATE, - "Failed to send \"saslStart\" command with database \"admin\""); + ASSERT_ERROR_CONTAINS (error, + MONGOC_ERROR_CLIENT, + MONGOC_ERROR_CLIENT_AUTHENTICATE, + "Failed to send \"saslStart\" command with database \"admin\""); bson_destroy (&reply); future_destroy (future); @@ -918,8 +837,7 @@ test_mongoc_client_command (void) bson_append_int32 (&cmd, "ping", 4, 1); - cursor = mongoc_client_command ( - client, "admin", MONGOC_QUERY_NONE, 0, 1, 0, &cmd, NULL, NULL); + cursor = mongoc_client_command (client, "admin", MONGOC_QUERY_NONE, 0, 1, 0, &cmd, NULL, NULL); r = mongoc_cursor_next (cursor, &doc); BSON_ASSERT (r); @@ -953,15 +871,7 @@ test_mongoc_client_command_defaults (void) mongoc_client_set_read_prefs (client, read_prefs); mongoc_client_set_read_concern (client, read_concern); - cursor = mongoc_client_command (client, - "admin", - MONGOC_QUERY_NONE, - 0, - 0, - 0, - tmp_bson ("{'ping': 1}"), - NULL, - NULL); + cursor = mongoc_client_command (client, "admin", MONGOC_QUERY_NONE, 0, 0, 0, tmp_bson ("{'ping': 1}"), NULL, NULL); /* Read and Write Concern spec: "If your driver offers a generic RunCommand * method on your database object, ReadConcern MUST NOT be applied @@ -997,13 +907,11 @@ test_mongoc_client_command_secondary (void) read_prefs = mongoc_read_prefs_new (MONGOC_READ_SECONDARY); - cursor = mongoc_client_command ( - client, "admin", MONGOC_QUERY_NONE, 0, 1, 0, &cmd, NULL, read_prefs); + cursor = mongoc_client_command (client, "admin", MONGOC_QUERY_NONE, 0, 1, 0, &cmd, NULL, read_prefs); mongoc_cursor_next (cursor, &reply); if (test_framework_is_replset ()) { - BSON_ASSERT (test_framework_server_is_secondary ( - client, mongoc_cursor_get_hint (cursor))); + BSON_ASSERT (test_framework_server_is_secondary (client, mongoc_cursor_get_hint (cursor))); } mongoc_read_prefs_destroy (read_prefs); @@ -1044,45 +952,36 @@ _test_command_read_prefs (bool simple, bool pooled) client = test_framework_client_new_from_uri (uri, NULL); } - ASSERT_CMPINT ( - MONGOC_READ_SECONDARY, - ==, - mongoc_read_prefs_get_mode (mongoc_client_get_read_prefs (client))); + ASSERT_CMPINT (MONGOC_READ_SECONDARY, ==, mongoc_read_prefs_get_mode (mongoc_client_get_read_prefs (client))); cmd = tmp_bson ("{'foo': 1}"); if (simple) { /* simple, without read preference */ - future = - future_client_command_simple (client, "db", cmd, NULL, NULL, &error); + future = future_client_command_simple (client, "db", cmd, NULL, NULL, &error); - request = mock_server_receives_msg ( - server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', 'foo': 1}")); + request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', 'foo': 1}")); reply_to_request_with_ok_and_destroy (request); ASSERT_OR_PRINT (future_get_bool (future), error); future_destroy (future); /* with read preference */ - future = future_client_command_simple ( - client, "db", cmd, secondary_pref, NULL, &error); - - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db'," - " 'foo': 1," - " '$readPreference': {'mode': 'secondary'}}")); + future = future_client_command_simple (client, "db", cmd, secondary_pref, NULL, &error); + + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'db'," + " 'foo': 1," + " '$readPreference': {'mode': 'secondary'}}")); reply_to_request_with_ok_and_destroy (request); ASSERT_OR_PRINT (future_get_bool (future), error); future_destroy (future); } else { /* not simple, no read preference */ - cursor = mongoc_client_command ( - client, "db", MONGOC_QUERY_NONE, 0, 0, 0, cmd, NULL, NULL); + cursor = mongoc_client_command (client, "db", MONGOC_QUERY_NONE, 0, 0, 0, cmd, NULL, NULL); future = future_cursor_next (cursor, &reply); - request = mock_server_receives_msg ( - server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', 'foo': 1}")); + request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', 'foo': 1}")); reply_to_request_with_ok_and_destroy (request); ASSERT (future_get_bool (future)); @@ -1090,15 +989,13 @@ _test_command_read_prefs (bool simple, bool pooled) mongoc_cursor_destroy (cursor); /* with read preference */ - cursor = mongoc_client_command ( - client, "db", MONGOC_QUERY_NONE, 0, 0, 0, cmd, NULL, secondary_pref); + cursor = mongoc_client_command (client, "db", MONGOC_QUERY_NONE, 0, 0, 0, cmd, NULL, secondary_pref); future = future_cursor_next (cursor, &reply); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db'," - " 'foo': 1," - " '$readPreference': {'mode': 'secondary'}}")); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'db'," + " 'foo': 1," + " '$readPreference': {'mode': 'secondary'}}")); reply_to_request_with_ok_and_destroy (request); ASSERT (future_get_bool (future)); @@ -1157,15 +1054,7 @@ test_command_not_found (void) mongoc_cursor_t *cursor; client = test_framework_new_default_client (); - cursor = mongoc_client_command (client, - "test", - MONGOC_QUERY_NONE, - 0, - 0, - 0, - tmp_bson ("{'foo': 1}"), - NULL, - NULL); + cursor = mongoc_client_command (client, "test", MONGOC_QUERY_NONE, 0, 0, 0, tmp_bson ("{'foo': 1}"), NULL, NULL); ASSERT (!mongoc_cursor_next (cursor, &doc)); ASSERT (mongoc_cursor_error (cursor, &error)); @@ -1185,8 +1074,7 @@ test_command_not_found_simple (void) bson_error_t error; client = test_framework_new_default_client (); - ASSERT (!mongoc_client_command_simple ( - client, "test", tmp_bson ("{'foo': 1}"), NULL, &reply, &error)); + ASSERT (!mongoc_client_command_simple (client, "test", tmp_bson ("{'foo': 1}"), NULL, &reply, &error)); ASSERT_CMPINT (error.domain, ==, MONGOC_ERROR_QUERY); ASSERT_CMPINT (error.code, ==, MONGOC_ERROR_QUERY_COMMAND_NOT_FOUND); @@ -1211,18 +1099,15 @@ test_command_with_opts_read_prefs (void) server = mock_mongos_new (WIRE_VERSION_MIN); mock_server_run (server); mock_server_auto_endsessions (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); read_prefs = mongoc_read_prefs_new (MONGOC_READ_SECONDARY); mongoc_client_set_read_prefs (client, read_prefs); /* read prefs omitted for command that writes */ cmd = tmp_bson ("{'create': 'db'}"); - future = future_client_write_command_with_opts ( - client, "admin", cmd, NULL /* opts */, NULL, &error); + future = future_client_write_command_with_opts (client, "admin", cmd, NULL /* opts */, NULL, &error); - request = mock_server_receives_msg ( - server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'admin', 'create': 'db'}")); + request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'admin', 'create': 'db'}")); reply_to_request_with_ok_and_destroy (request); ASSERT_OR_PRINT (future_get_bool (future), error); @@ -1230,17 +1115,15 @@ test_command_with_opts_read_prefs (void) /* read prefs are included for read command */ cmd = tmp_bson ("{'count': 'collection'}"); - future = future_client_read_command_with_opts ( - client, "admin", cmd, NULL, NULL /* opts */, NULL, &error); + future = future_client_read_command_with_opts (client, "admin", cmd, NULL, NULL /* opts */, NULL, &error); /* Server Selection Spec: For all read preference modes that are not * 'primary', drivers MUST set '$readPreference'. */ - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'admin'," - " 'count': 'collection'," - " '$readPreference': {'mode': 'secondary'}}")); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'admin'," + " 'count': 'collection'," + " '$readPreference': {'mode': 'secondary'}}")); reply_to_request_with_ok_and_destroy (request); ASSERT_OR_PRINT (future_get_bool (future), error); @@ -1249,16 +1132,14 @@ test_command_with_opts_read_prefs (void) /* read prefs not included for read/write command, but read concern is */ cmd = tmp_bson ("{'whatever': 1}"); opts = tmp_bson ("{'readConcern': {'level': 'majority'}}"); - future = future_client_read_write_command_with_opts ( - client, "admin", cmd, NULL, opts, NULL, &error); + future = future_client_read_write_command_with_opts (client, "admin", cmd, NULL, opts, NULL, &error); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'admin'," - " 'whatever': 1," - " 'readConcern': {'level': 'majority'}," - " '$readPreference': {'$exists': false}}")); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'admin'," + " 'whatever': 1," + " 'readConcern': {'level': 'majority'}," + " '$readPreference': {'$exists': false}}")); reply_to_request_with_ok_and_destroy (request); ASSERT_OR_PRINT (future_get_bool (future), error); @@ -1281,10 +1162,7 @@ test_read_write_cmd_with_opts (void) future_t *future; request_t *request; - rs = mock_rs_with_auto_hello (WIRE_VERSION_MIN, - true /* has primary */, - 1 /* secondary */, - 0 /* arbiters */); + rs = mock_rs_with_auto_hello (WIRE_VERSION_MIN, true /* has primary */, 1 /* secondary */, 0 /* arbiters */); mock_rs_run (rs); client = test_framework_client_new_from_uri (mock_rs_get_uri (rs), NULL); @@ -1296,8 +1174,7 @@ test_read_write_cmd_with_opts (void) future = future_client_read_write_command_with_opts ( client, "db", tmp_bson ("{'ping': 1}"), secondary, NULL, &reply, &error); - request = mock_rs_receives_msg ( - rs, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', 'ping': 1}")); + request = mock_rs_receives_msg (rs, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', 'ping': 1}")); ASSERT (mock_rs_request_is_to_primary (rs, request)); reply_to_request_simple (request, "{'ok': 1}"); @@ -1328,20 +1205,15 @@ test_read_command_with_opts (void) server = mock_mongos_new (WIRE_VERSION_MIN); mock_server_run (server); mock_server_auto_endsessions (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); /* collation allowed */ cmd = tmp_bson ("{'create': 'db'}"); opts = tmp_bson ("{'collation': {'locale': 'en_US'}}"); - future = future_client_write_command_with_opts ( - client, "admin", cmd, opts, NULL, &error); + future = future_client_write_command_with_opts (client, "admin", cmd, opts, NULL, &error); request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ( - "{'$db': 'admin', 'create': 'db', 'collation': {'locale': 'en_US'}}")); + server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'admin', 'create': 'db', 'collation': {'locale': 'en_US'}}")); reply_to_request_with_ok_and_destroy (request); ASSERT_OR_PRINT (future_get_bool (future), error); @@ -1350,13 +1222,10 @@ test_read_command_with_opts (void) /* writeConcern included */ cmd = tmp_bson ("{'create': 'db'}"); opts = tmp_bson ("{'writeConcern': {'w': 1}}"); - future = future_client_write_command_with_opts ( - client, "admin", cmd, opts, NULL, &error); + future = future_client_write_command_with_opts (client, "admin", cmd, opts, NULL, &error); request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'admin', 'create': 'db', 'writeConcern': {'w': 1}}")); + server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'admin', 'create': 'db', 'writeConcern': {'w': 1}}")); reply_to_request_with_ok_and_destroy (request); ASSERT_OR_PRINT (future_get_bool (future), error); @@ -1366,13 +1235,10 @@ test_read_command_with_opts (void) wc = mongoc_write_concern_new (); mongoc_write_concern_set_w (wc, 1); mongoc_client_set_write_concern (client, wc); - future = future_client_write_command_with_opts ( - client, "admin", cmd, NULL /* opts */, NULL, &error); + future = future_client_write_command_with_opts (client, "admin", cmd, NULL /* opts */, NULL, &error); request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'admin', 'create': 'db', 'writeConcern': {'w': 1}}")); + server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'admin', 'create': 'db', 'writeConcern': {'w': 1}}")); reply_to_request_with_ok_and_destroy (request); ASSERT_OR_PRINT (future_get_bool (future), error); @@ -1384,13 +1250,10 @@ test_read_command_with_opts (void) wc = mongoc_write_concern_new (); mongoc_write_concern_set_w (wc, 4); mongoc_client_set_write_concern (client, wc); - future = future_client_write_command_with_opts ( - client, "admin", cmd, opts, NULL, &error); + future = future_client_write_command_with_opts (client, "admin", cmd, opts, NULL, &error); request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'admin', 'create': 'db', 'writeConcern': {'w': 2}}")); + server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'admin', 'create': 'db', 'writeConcern': {'w': 2}}")); reply_to_request_with_ok_and_destroy (request); ASSERT_OR_PRINT (future_get_bool (future), error); @@ -1402,15 +1265,13 @@ test_read_command_with_opts (void) mongoc_read_concern_set_level (read_concern, "local"); opts = tmp_bson (NULL); mongoc_read_concern_append (read_concern, opts); - future = future_client_read_command_with_opts ( - client, "admin", cmd, NULL, opts, NULL, &error); + future = future_client_read_command_with_opts (client, "admin", cmd, NULL, opts, NULL, &error); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'admin'," - " 'count': 'collection'," - " 'readConcern': {'level': 'local'}}")); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'admin'," + " 'count': 'collection'," + " 'readConcern': {'level': 'local'}}")); reply_to_request_with_ok_and_destroy (request); ASSERT_OR_PRINT (future_get_bool (future), error); @@ -1418,15 +1279,13 @@ test_read_command_with_opts (void) /* apply client's readConcern by default */ mongoc_client_set_read_concern (client, read_concern); - future = future_client_read_command_with_opts ( - client, "admin", cmd, NULL, NULL /* opts */, NULL, &error); + future = future_client_read_command_with_opts (client, "admin", cmd, NULL, NULL /* opts */, NULL, &error); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'admin'," - " 'count': 'collection'," - " 'readConcern': {'level': 'local'}}")); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'admin'," + " 'count': 'collection'," + " 'readConcern': {'level': 'local'}}")); reply_to_request_with_ok_and_destroy (request); ASSERT_OR_PRINT (future_get_bool (future), error); @@ -1456,8 +1315,7 @@ test_command_with_opts (void) mock_server_run (server); mock_server_auto_endsessions (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); /* client's write concern, read concern, read prefs are ignored */ wc = mongoc_write_concern_new (); @@ -1472,16 +1330,14 @@ test_command_with_opts (void) mongoc_client_set_read_prefs (client, prefs); cmd = tmp_bson ("{'create': 'db'}"); - future = future_client_command_with_opts ( - client, "admin", cmd, NULL, NULL, NULL, &error); + future = future_client_command_with_opts (client, "admin", cmd, NULL, NULL, NULL, &error); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'admin'," - " 'create': 'db'," - " 'readConcern': {'$exists': false}," - " 'writeConcern': {'$exists': false}}")); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'admin'," + " 'create': 'db'," + " 'readConcern': {'$exists': false}," + " 'writeConcern': {'$exists': false}}")); reply_to_request_with_ok_and_destroy (request); ASSERT_OR_PRINT (future_get_bool (future), error); @@ -1490,17 +1346,15 @@ test_command_with_opts (void) /* write concern, read concern, and read preference passed in explicitly */ mongoc_write_concern_append (wc, &opts); mongoc_read_concern_append (read_concern, &opts); - future = future_client_command_with_opts ( - client, "admin", cmd, prefs, &opts, NULL, &error); + future = future_client_command_with_opts (client, "admin", cmd, prefs, &opts, NULL, &error); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'admin'," - " 'create':'db'," - " 'writeConcern': {'w': 2}," - " 'readConcern': {'level':'majority'}," - " '$readPreference': {'mode':'secondary'}}")); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'admin'," + " 'create':'db'," + " 'writeConcern': {'w': 2}," + " 'readConcern': {'level':'majority'}," + " '$readPreference': {'mode':'secondary'}}")); reply_to_request_with_ok_and_destroy (request); ASSERT_OR_PRINT (future_get_bool (future), error); @@ -1535,8 +1389,7 @@ test_command_with_opts_op_msg (void) mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); /* client's write concern, read concern, read prefs are ignored */ wc = mongoc_write_concern_new (); @@ -1551,17 +1404,15 @@ test_command_with_opts_op_msg (void) mongoc_client_set_read_prefs (client, prefs); cmd = tmp_bson ("{'create': 'db'}"); - future = future_client_command_with_opts ( - client, "admin", cmd, NULL, NULL, NULL, &error); + future = future_client_command_with_opts (client, "admin", cmd, NULL, NULL, NULL, &error); - request = mock_server_receives_msg ( - server, - 0, - tmp_bson ("{" - " 'create': 'db'," - " 'readConcern': {'$exists': false}," - " 'writeConcern': {'$exists': false}" - "}")); + request = mock_server_receives_msg (server, + 0, + tmp_bson ("{" + " 'create': 'db'," + " 'readConcern': {'$exists': false}," + " 'writeConcern': {'$exists': false}" + "}")); reply_to_request_with_ok_and_destroy (request); ASSERT_OR_PRINT (future_get_bool (future), error); @@ -1570,20 +1421,18 @@ test_command_with_opts_op_msg (void) /* write concern, read concern, and read preference passed in explicitly */ mongoc_write_concern_append (wc, &opts); mongoc_read_concern_append (read_concern, &opts); - future = future_client_command_with_opts ( - client, "admin", cmd, prefs, &opts, NULL, &error); - - request = mock_server_receives_msg ( - server, - 0, - tmp_bson ("{" - " 'create':'db'," - " 'writeConcern': {'w': 2}," - " 'readConcern': {'level':'majority'}," - " '$readPreference': {" - " 'mode':'secondary'" - " }" - "}")); + future = future_client_command_with_opts (client, "admin", cmd, prefs, &opts, NULL, &error); + + request = mock_server_receives_msg (server, + 0, + tmp_bson ("{" + " 'create':'db'," + " 'writeConcern': {'w': 2}," + " 'readConcern': {'level':'majority'}," + " '$readPreference': {" + " 'mode':'secondary'" + " }" + "}")); reply_to_request_with_ok_and_destroy (request); ASSERT_OR_PRINT (future_get_bool (future), error); @@ -1607,36 +1456,24 @@ test_command_empty (void) bool r; client = test_framework_new_default_client (); - r = mongoc_client_command_simple ( - client, "admin", tmp_bson ("{}"), NULL, NULL, &error); + r = mongoc_client_command_simple (client, "admin", tmp_bson ("{}"), NULL, NULL, &error); ASSERT (!r); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Empty command document"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Empty command document"); - r = mongoc_client_command_with_opts ( - client, "admin", tmp_bson ("{}"), NULL, tmp_bson ("{}"), NULL, &error); + r = mongoc_client_command_with_opts (client, "admin", tmp_bson ("{}"), NULL, tmp_bson ("{}"), NULL, &error); ASSERT (!r); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Empty command document"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Empty command document"); wc = mongoc_write_concern_new (); mongoc_write_concern_set_w (wc, 1); mongoc_client_set_write_concern (client, wc); - r = mongoc_client_write_command_with_opts ( - client, "admin", tmp_bson ("{}"), NULL, NULL, &error); + r = mongoc_client_write_command_with_opts (client, "admin", tmp_bson ("{}"), NULL, NULL, &error); ASSERT (!r); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Empty command document"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Empty command document"); mongoc_write_concern_destroy (wc); mongoc_client_destroy (client); @@ -1655,16 +1492,13 @@ test_command_no_errmsg (void) server = mock_server_with_auto_hello (WIRE_VERSION_MIN); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); mongoc_client_set_error_api (client, 2); cmd = tmp_bson ("{'command': 1}"); - future = - future_client_command_simple (client, "admin", cmd, NULL, NULL, &error); + future = future_client_command_simple (client, "admin", cmd, NULL, NULL, &error); - request = mock_server_receives_msg ( - server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'admin'}")); + request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'admin'}")); /* auth errors have $err, not errmsg. we'd raised "Unknown command error", * see CDRIVER-1928 */ @@ -1700,39 +1534,30 @@ test_unavailable_seeds (void) } uri_str = uri_strs = bson_malloc0 (7 * sizeof (char *)); + *(uri_str++) = bson_strdup_printf ("mongodb://%s", mock_server_get_host_and_port (servers[0])); + *(uri_str++) = bson_strdup_printf ( - "mongodb://%s", mock_server_get_host_and_port (servers[0])); + "mongodb://%s,%s", mock_server_get_host_and_port (servers[0]), mock_server_get_host_and_port (servers[1])); - *(uri_str++) = - bson_strdup_printf ("mongodb://%s,%s", - mock_server_get_host_and_port (servers[0]), - mock_server_get_host_and_port (servers[1])); + *(uri_str++) = bson_strdup_printf ("mongodb://%s,%s/?replicaSet=rs", + mock_server_get_host_and_port (servers[0]), + mock_server_get_host_and_port (servers[1])); - *(uri_str++) = - bson_strdup_printf ("mongodb://%s,%s/?replicaSet=rs", - mock_server_get_host_and_port (servers[0]), - mock_server_get_host_and_port (servers[1])); + *(uri_str++) = bson_strdup_printf ("mongodb://u:p@%s", mock_server_get_host_and_port (servers[0])); *(uri_str++) = bson_strdup_printf ( - "mongodb://u:p@%s", mock_server_get_host_and_port (servers[0])); + "mongodb://u:p@%s,%s", mock_server_get_host_and_port (servers[0]), mock_server_get_host_and_port (servers[1])); - *(uri_str++) = - bson_strdup_printf ("mongodb://u:p@%s,%s", - mock_server_get_host_and_port (servers[0]), - mock_server_get_host_and_port (servers[1])); - - *(uri_str++) = - bson_strdup_printf ("mongodb://u:p@%s,%s/?replicaSet=rs", - mock_server_get_host_and_port (servers[0]), - mock_server_get_host_and_port (servers[1])); + *(uri_str++) = bson_strdup_printf ("mongodb://u:p@%s,%s/?replicaSet=rs", + mock_server_get_host_and_port (servers[0]), + mock_server_get_host_and_port (servers[1])); for (i = 0; i < (sizeof (uri_strs) / sizeof (const char *)); i++) { client = test_framework_client_new (uri_strs[i], NULL); BSON_ASSERT (client); collection = mongoc_client_get_collection (client, "test", "test"); - cursor = - mongoc_collection_find_with_opts (collection, &query, NULL, NULL); + cursor = mongoc_collection_find_with_opts (collection, &query, NULL, NULL); BSON_ASSERT (!mongoc_cursor_next (cursor, &doc)); BSON_ASSERT (mongoc_cursor_error (cursor, &error)); ASSERT_CMPINT (error.domain, ==, MONGOC_ERROR_SERVER_SELECTION); @@ -1807,12 +1632,11 @@ test_seed_list (bool rs, connection_option_t connection_option, bool pooled) mock_server_run (down_servers[i]); } - uri_str = - bson_strdup_printf ("mongodb://%s,%s,%s,%s", - mock_server_get_host_and_port (server), - mock_server_get_host_and_port (down_servers[0]), - mock_server_get_host_and_port (down_servers[1]), - mock_server_get_host_and_port (down_servers[2])); + uri_str = bson_strdup_printf ("mongodb://%s,%s,%s,%s", + mock_server_get_host_and_port (server), + mock_server_get_host_and_port (down_servers[0]), + mock_server_get_host_and_port (down_servers[1]), + mock_server_get_host_and_port (down_servers[2])); uri = mongoc_uri_new (uri_str); BSON_ASSERT (uri); @@ -1859,21 +1683,14 @@ test_seed_list (bool rs, connection_option_t connection_option, bool pooled) if (connection_option == CONNECT || connection_option == RECONNECT) { /* only localhost:port responds to initial discovery. the other seeds are * discarded from replica set topology, but remain for sharded. */ - ASSERT_OR_PRINT (mongoc_client_command_simple (client, - "test", - tmp_bson ("{'foo': 1}"), - primary_pref, - &reply, - &error), - error); + ASSERT_OR_PRINT ( + mongoc_client_command_simple (client, "test", tmp_bson ("{'foo': 1}"), primary_pref, &reply, &error), error); bson_destroy (&reply); /* td may be invalidated by client_command_simple */ mc_tpld_renew_ref (&td, topology); - ASSERT_CMPINT (discovered_nodes_len, - ==, - (int) mc_tpld_servers_const (td.ptr)->items_len); + ASSERT_CMPINT (discovered_nodes_len, ==, (int) mc_tpld_servers_const (td.ptr)->items_len); if (rs) { ASSERT_CMPINT (td.ptr->type, ==, MONGOC_TOPOLOGY_RS_WITH_PRIMARY); @@ -1888,9 +1705,8 @@ test_seed_list (bool rs, connection_option_t connection_option, bool pooled) } if (connection_option == RECONNECT) { - id = mongoc_set_find_id (mc_tpld_servers_const (td.ptr), - host_equals, - (void *) mock_server_get_host_and_port (server)); + id = mongoc_set_find_id ( + mc_tpld_servers_const (td.ptr), host_equals, (void *) mock_server_get_host_and_port (server)); ASSERT_CMPINT (id, !=, 0); _mongoc_topology_invalidate_server (topology, id); mc_tpld_renew_ref (&td, topology); @@ -1900,21 +1716,14 @@ test_seed_list (bool rs, connection_option_t connection_option, bool pooled) ASSERT_CMPINT (td.ptr->type, ==, MONGOC_TOPOLOGY_SHARDED); } - ASSERT_OR_PRINT (mongoc_client_command_simple (client, - "test", - tmp_bson ("{'foo': 1}"), - primary_pref, - &reply, - &error), - error); + ASSERT_OR_PRINT ( + mongoc_client_command_simple (client, "test", tmp_bson ("{'foo': 1}"), primary_pref, &reply, &error), error); bson_destroy (&reply); /* td may be invalidated by client_command_simple */ mc_tpld_renew_ref (&td, topology); - ASSERT_CMPINT (discovered_nodes_len, - ==, - (int) mc_tpld_servers_const (td.ptr)->items_len); + ASSERT_CMPINT (discovered_nodes_len, ==, (int) mc_tpld_servers_const (td.ptr)->items_len); if (pooled) { ASSERT_CMPINT ((int) client->cluster.nodes->items_len, ==, 1); @@ -2060,11 +1869,9 @@ test_recovering (void *ctx) prefs = mongoc_read_prefs_new (MONGOC_READ_PRIMARY); /* recovering member matches no read mode */ - for (read_mode = MONGOC_READ_PRIMARY; read_mode <= MONGOC_READ_NEAREST; - read_mode++) { + for (read_mode = MONGOC_READ_PRIMARY; read_mode <= MONGOC_READ_NEAREST; read_mode++) { mongoc_read_prefs_set_mode (prefs, read_mode); - BSON_ASSERT (!mongoc_topology_select ( - client->topology, MONGOC_SS_READ, prefs, NULL, &error)); + BSON_ASSERT (!mongoc_topology_select (client->topology, MONGOC_SS_READ, prefs, NULL, &error)); } mongoc_read_prefs_destroy (prefs); @@ -2086,8 +1893,7 @@ test_server_status (void) BSON_ASSERT (client); BEGIN_IGNORE_DEPRECATIONS - ASSERT_OR_PRINT ( - mongoc_client_get_server_status (client, NULL, &reply, &error), error); + ASSERT_OR_PRINT (mongoc_client_get_server_status (client, NULL, &reply, &error), error); END_IGNORE_DEPRECATIONS BSON_ASSERT (bson_iter_init_find (&iter, &reply, "host")); @@ -2111,20 +1917,11 @@ test_get_database_names (void) char **names; mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); future = future_client_get_database_names_with_opts (client, NULL, &error); request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'admin', 'listDatabases': 1, 'nameOnly': true}")); - reply_to_request ( - request, - 0, - 0, - 0, - 1, - "{'ok': 1.0, 'databases': [{'name': 'a'}, {'name': 'local'}]}"); + server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'admin', 'listDatabases': 1, 'nameOnly': true}")); + reply_to_request (request, 0, 0, 0, 1, "{'ok': 1.0, 'databases': [{'name': 'a'}, {'name': 'local'}]}"); names = future_get_char_ptr_ptr (future); BSON_ASSERT (!strcmp (names[0], "a")); BSON_ASSERT (!strcmp (names[1], "local")); @@ -2136,11 +1933,8 @@ test_get_database_names (void) future = future_client_get_database_names_with_opts (client, NULL, &error); request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'admin', 'listDatabases': 1, 'nameOnly': true}")); - reply_to_request ( - request, 0, 0, 0, 1, "{'ok': 0.0, 'code': 17, 'errmsg': 'err'}"); + server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'admin', 'listDatabases': 1, 'nameOnly': true}")); + reply_to_request (request, 0, 0, 0, 1, "{'ok': 0.0, 'code': 17, 'errmsg': 'err'}"); names = future_get_char_ptr_ptr (future); BSON_ASSERT (!names); @@ -2203,8 +1997,7 @@ _test_mongoc_client_ipv6 (bool pooled) #endif ASSERT_OR_PRINT ( - mongoc_client_read_command_with_opts ( - client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, NULL, &error), + mongoc_client_read_command_with_opts (client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, NULL, &error), error); if (pooled) { @@ -2249,8 +2042,7 @@ test_mongoc_client_unix_domain_socket (void *context) BSON_ASSERT (client); ASSERT_OR_PRINT ( - mongoc_client_read_command_with_opts ( - client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, NULL, &error), + mongoc_client_read_command_with_opts (client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, NULL, &error), error); mongoc_client_destroy (client); @@ -2278,8 +2070,7 @@ test_mongoc_client_mismatched_me (void) prefs = mongoc_read_prefs_new (MONGOC_READ_SECONDARY); /* any operation should fail with server selection error */ - future = future_client_command_simple ( - client, "admin", tmp_bson ("{'ping': 1}"), prefs, NULL, &error); + future = future_client_command_simple (client, "admin", tmp_bson ("{'ping': 1}"), prefs, NULL, &error); request = mock_server_receives_any_hello (server); @@ -2299,12 +2090,9 @@ test_mongoc_client_mismatched_me (void) reply_to_request_simple (request, reply); BSON_ASSERT (!future_get_bool (future)); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_SERVER_SELECTION, - MONGOC_ERROR_SERVER_SELECTION_FAILURE, - "No suitable servers"); - ASSERT_CAPTURED_LOG ( - "client", MONGOC_LOG_LEVEL_WARNING, "Last server removed from topology"); + ASSERT_ERROR_CONTAINS ( + error, MONGOC_ERROR_SERVER_SELECTION, MONGOC_ERROR_SERVER_SELECTION_FAILURE, "No suitable servers"); + ASSERT_CAPTURED_LOG ("client", MONGOC_LOG_LEVEL_WARNING, "Last server removed from topology"); capture_logs (false); bson_free (reply); @@ -2334,9 +2122,7 @@ _test_mongoc_client_ssl_opts (bool pooled) int add_ssl_to_uri; host_and_port = test_framework_get_host_and_port (); - uri_str = bson_strdup_printf ( - "mongodb://%s/?serverSelectionTimeoutMS=1000&connectTimeoutMS=1000", - host_and_port); + uri_str = bson_strdup_printf ("mongodb://%s/?serverSelectionTimeoutMS=1000&connectTimeoutMS=1000", host_and_port); uri_str_auth = test_framework_add_user_password_from_env (uri_str); uri_str_auth_ssl = bson_strdup_printf ("%s&ssl=true", uri_str_auth); @@ -2361,8 +2147,7 @@ _test_mongoc_client_ssl_opts (bool pooled) } /* any operation */ - ret = mongoc_client_command_simple ( - client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); + ret = mongoc_client_command_simple (client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); if (test_framework_get_ssl ()) { ASSERT_OR_PRINT (ret, error); @@ -2421,9 +2206,7 @@ test_client_buildinfo_hang (void) bson_append_int32 (&command, "buildInfo", -1, 1); /* Prior to a bug fix this command caused a hang - see CDRIVER-3318 */ - ASSERT_OR_PRINT ( - mongoc_database_command_simple (database, &command, NULL, &reply, &error), - error); + ASSERT_OR_PRINT (mongoc_database_command_simple (database, &command, NULL, &reply, &error), error); bson_destroy (&command); bson_destroy (&reply); @@ -2441,11 +2224,8 @@ static void test_mongoc_client_ssl_disabled (void) { capture_logs (true); - ASSERT (NULL == - test_framework_client_new ("mongodb://host/?ssl=true", NULL)); - ASSERT_CAPTURED_LOG ("mongoc_client_new", - MONGOC_LOG_LEVEL_ERROR, - "SSL not enabled in this build."); + ASSERT (NULL == test_framework_client_new ("mongodb://host/?ssl=true", NULL)); + ASSERT_CAPTURED_LOG ("mongoc_client_new", MONGOC_LOG_LEVEL_ERROR, "SSL not enabled in this build."); capture_logs (false); } #endif @@ -2474,16 +2254,14 @@ _test_mongoc_client_get_description (bool pooled) ASSERT (NULL == mongoc_client_get_server_description (client, 1234)); collection = get_test_collection (client, "test_mongoc_client_description"); - cursor = mongoc_collection_find_with_opts ( - collection, tmp_bson ("{}"), NULL, NULL); + cursor = mongoc_collection_find_with_opts (collection, tmp_bson ("{}"), NULL, NULL); ASSERT (!mongoc_cursor_next (cursor, &doc)); server_id = mongoc_cursor_get_hint (cursor); ASSERT (0 != server_id); sd = mongoc_client_get_server_description (client, server_id); ASSERT (sd); mongoc_cursor_get_host (cursor, &host); - ASSERT (_mongoc_host_list_compare_one (&host, - mongoc_server_description_host (sd))); + ASSERT (_mongoc_host_list_compare_one (&host, mongoc_server_description_host (sd))); mongoc_server_description_destroy (sd); mongoc_cursor_destroy (cursor); @@ -2572,9 +2350,7 @@ test_mongoc_client_descriptions_pooled (void *unused) * first address returned by getaddrinfo may be IPv6, and failure to * connect may take a couple seconds. See CDRIVER-3639. */ if (bson_get_monotonic_time () - start > 3 * 1000 * 1000) { - test_error ("still have %d descriptions, not expected %d, after 1 sec", - (int) n, - (int) expected_n); + test_error ("still have %d descriptions, not expected %d, after 1 sec", (int) n, (int) expected_n); } sds = mongoc_client_get_server_descriptions (client, &n); @@ -2591,8 +2367,7 @@ is_standalone_or_rs_primary_or_mongos (const char *server_type) { BSON_ASSERT_PARAM (server_type); // Avoid -Woverlength-strings in ASSERT macros. - return strcmp (server_type, "Standalone") == 0 || - strcmp (server_type, "RSPrimary") == 0 || + return strcmp (server_type, "Standalone") == 0 || strcmp (server_type, "RSPrimary") == 0 || strcmp (server_type, "Mongos") == 0; } @@ -2601,8 +2376,7 @@ is_standalone_or_rs_secondary_or_mongos (const char *server_type) { BSON_ASSERT_PARAM (server_type); // Avoid -Woverlength-strings in ASSERT macros. - return strcmp (server_type, "Standalone") == 0 || - strcmp (server_type, "RSSecondary") == 0 || + return strcmp (server_type, "Standalone") == 0 || strcmp (server_type, "RSSecondary") == 0 || strcmp (server_type, "Mongos") == 0; } @@ -2611,8 +2385,7 @@ is_standalone_or_mongos (const char *server_type) { BSON_ASSERT_PARAM (server_type); // Avoid -Woverlength-strings in ASSERT macros. - return strcmp (server_type, "Standalone") == 0 || - strcmp (server_type, "Mongos") == 0; + return strcmp (server_type, "Standalone") == 0 || strcmp (server_type, "Mongos") == 0; } @@ -2733,10 +2506,8 @@ _test_mongoc_client_select_server_error (bool pooled) &error); ASSERT (!sd); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_SERVER_SELECTION, - MONGOC_ERROR_SERVER_SELECTION_FAILURE, - "Cannot use read preference"); + ASSERT_ERROR_CONTAINS ( + error, MONGOC_ERROR_SERVER_SELECTION, MONGOC_ERROR_SERVER_SELECTION_FAILURE, "Cannot use read preference"); sd = mongoc_client_select_server (client, false, /* for reads */ @@ -2832,8 +2603,7 @@ _test_mongoc_client_select_server_retry (bool retry_succeeds) /* second selection requires ping, which fails */ future = future_client_select_server (client, true, NULL, &error); - request = mock_server_receives_msg ( - server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'admin', 'ping': 1}")); + request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'admin', 'ping': 1}")); reply_to_request_with_hang_up (request); request_destroy (request); @@ -2900,14 +2670,12 @@ _test_mongoc_client_fetch_stream_retry (bool retry_succeeds) client = test_framework_client_new_from_uri (uri, NULL); /* first time succeeds */ - future = future_client_command_simple ( - client, "db", tmp_bson ("{'cmd': 1}"), NULL, NULL, &error); + future = future_client_command_simple (client, "db", tmp_bson ("{'cmd': 1}"), NULL, NULL, &error); request = mock_server_receives_any_hello (server); reply_to_request_simple (request, hello); request_destroy (request); - request = mock_server_receives_msg ( - server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', 'cmd': 1}")); + request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', 'cmd': 1}")); reply_to_request_with_ok_and_destroy (request); ASSERT_OR_PRINT (future_get_bool (future), error); @@ -2917,11 +2685,9 @@ _test_mongoc_client_fetch_stream_retry (bool retry_succeeds) _mongoc_usleep (100 * 1000); /* second selection requires ping, which fails */ - future = future_client_command_simple ( - client, "db", tmp_bson ("{'cmd': 1}"), NULL, NULL, &error); + future = future_client_command_simple (client, "db", tmp_bson ("{'cmd': 1}"), NULL, NULL, &error); - request = mock_server_receives_msg ( - server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'admin', 'ping': 1}")); + request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'admin', 'ping': 1}")); reply_to_request_with_hang_up (request); request_destroy (request); @@ -2932,8 +2698,7 @@ _test_mongoc_client_fetch_stream_retry (bool retry_succeeds) reply_to_request_simple (request, hello); request_destroy (request); - request = mock_server_receives_msg ( - server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', 'cmd': 1}")); + request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', 'cmd': 1}")); reply_to_request_simple (request, "{'ok': 1}"); ASSERT_OR_PRINT (future_get_bool (future), error); @@ -2964,13 +2729,9 @@ test_mongoc_client_fetch_stream_retry_fail (void) } -#if defined(MONGOC_ENABLE_SSL_OPENSSL) || \ - defined(MONGOC_ENABLE_SSL_SECURE_TRANSPORT) +#if defined(MONGOC_ENABLE_SSL_OPENSSL) || defined(MONGOC_ENABLE_SSL_SECURE_TRANSPORT) static bool -_cmd (mock_server_t *server, - mongoc_client_t *client, - bool server_replies, - bson_error_t *error) +_cmd (mock_server_t *server, mongoc_client_t *client, bool server_replies, bson_error_t *error) { future_t *future; request_t *request; @@ -2978,10 +2739,8 @@ _cmd (mock_server_t *server, ASSERT (client); - future = future_client_command_simple ( - client, "db", tmp_bson ("{'cmd': 1}"), NULL, NULL, error); - request = mock_server_receives_msg ( - server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', 'cmd': 1}")); + future = future_client_command_simple (client, "db", tmp_bson ("{'cmd': 1}"), NULL, NULL, error); + request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', 'cmd': 1}")); ASSERT (request); if (server_replies) { @@ -3022,21 +2781,18 @@ test_client_set_ssl_copies_args (bool pooled) mock_server_run (server); if (pooled) { - pool = test_framework_client_pool_new_from_uri ( - mock_server_get_uri (server), NULL); + pool = test_framework_client_pool_new_from_uri (mock_server_get_uri (server), NULL); mongoc_client_pool_set_ssl_opts (pool, &client_opts); client = mongoc_client_pool_pop (pool); } else { - client = test_framework_client_new_from_uri (mock_server_get_uri (server), - NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); mongoc_client_set_ssl_opts (client, &client_opts); } /* Now change the client ca string to be something else */ bson_strncpy (mutable_client_ca, "garbage", ca_bufsize); - ASSERT_OR_PRINT (_cmd (server, client, true /* server replies */, &error), - error); + ASSERT_OR_PRINT (_cmd (server, client, true /* server replies */, &error), error); if (pooled) { mongoc_client_pool_push (pool, client); @@ -3097,8 +2853,7 @@ _test_ssl_reconnect (bool pooled) mongoc_client_set_ssl_opts (client, &client_opts); } - ASSERT_OR_PRINT (_cmd (server, client, true /* server replies */, &error), - error); + ASSERT_OR_PRINT (_cmd (server, client, true /* server replies */, &error), error); /* man-in-the-middle: certificate changed, for example expired */ server_opts.pem_file = CERT_EXPIRED; @@ -3108,22 +2863,19 @@ _test_ssl_reconnect (bool pooled) capture_logs (true); ASSERT (!_cmd (server, client, false /* server hangs up */, &error)); if (pooled) { - ASSERT_CAPTURED_LOG ( - "failed to write data because server closed the connection", - MONGOC_LOG_LEVEL_WARNING, - "Failed to buffer 4 bytes"); + ASSERT_CAPTURED_LOG ("failed to write data because server closed the connection", + MONGOC_LOG_LEVEL_WARNING, + "Failed to buffer 4 bytes"); } capture_logs (false); /* next operation comes on a new connection, server verification fails */ capture_logs (true); - future = future_client_command_simple ( - client, "db", tmp_bson ("{'cmd': 1}"), NULL, NULL, &error); + future = future_client_command_simple (client, "db", tmp_bson ("{'cmd': 1}"), NULL, NULL, &error); ASSERT (!future_get_bool (future)); ASSERT_CONTAINS (error.message, "TLS handshake failed"); if (pooled) { - ASSERT_CAPTURED_LOG ( - "cluster", MONGOC_LOG_LEVEL_WARNING, "TLS handshake failed"); + ASSERT_CAPTURED_LOG ("cluster", MONGOC_LOG_LEVEL_WARNING, "TLS handshake failed"); } capture_logs (false); @@ -3171,9 +2923,7 @@ test_mongoc_client_application_handshake (void) /* Check that setting too long a name causes failure */ capture_logs (true); ASSERT (!mongoc_client_set_appname (client, big_string)); - ASSERT_CAPTURED_LOG ("_mongoc_topology_scanner_set_appname", - MONGOC_LOG_LEVEL_ERROR, - "is invalid"); + ASSERT_CAPTURED_LOG ("_mongoc_topology_scanner_set_appname", MONGOC_LOG_LEVEL_ERROR, "is invalid"); clear_captured_logs (); /* Success case */ @@ -3181,9 +2931,8 @@ test_mongoc_client_application_handshake (void) /* Make sure we can't set it twice */ ASSERT (!mongoc_client_set_appname (client, "a")); - ASSERT_CAPTURED_LOG ("_mongoc_topology_scanner_set_appname", - MONGOC_LOG_LEVEL_ERROR, - "Cannot set appname more than once"); + ASSERT_CAPTURED_LOG ( + "_mongoc_topology_scanner_set_appname", MONGOC_LOG_LEVEL_ERROR, "Cannot set appname more than once"); capture_logs (false); mongoc_client_destroy (client); @@ -3213,8 +2962,7 @@ _force_hello_with_ping (mongoc_client_t *client, int heartbeat_ms) _mongoc_usleep (heartbeat_ms * 2 * 1000); /* Send a ping */ - future = future_client_command_simple ( - client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, NULL); + future = future_client_command_simple (client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, NULL); ASSERT (future); return future; } @@ -3228,8 +2976,7 @@ _respond_to_ping (future_t *future, mock_server_t *server) ASSERT (future); - request = mock_server_receives_msg ( - server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'admin', 'ping': 1}")); + request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'admin', 'ping': 1}")); reply_to_request_with_ok_and_destroy (request); @@ -3247,13 +2994,12 @@ test_mongoc_handshake_pool (void) mongoc_client_t *client1; mongoc_client_t *client2; mongoc_client_pool_t *pool; - const char *const server_reply = - tmp_str ("{'ok': 1," - " '" HANDSHAKE_RESPONSE_LEGACY_HELLO "': true," - " 'minWireVersion': %d," - " 'maxWireVersion': %d}", - WIRE_VERSION_MIN, - WIRE_VERSION_MAX); + const char *const server_reply = tmp_str ("{'ok': 1," + " '" HANDSHAKE_RESPONSE_LEGACY_HELLO "': true," + " 'minWireVersion': %d," + " 'maxWireVersion': %d}", + WIRE_VERSION_MIN, + WIRE_VERSION_MAX); future_t *future; server = mock_server_new (); @@ -3271,16 +3017,14 @@ test_mongoc_handshake_pool (void) request_destroy (request1); client2 = mongoc_client_pool_pop (pool); - future = future_client_command_simple ( - client2, "test", tmp_bson ("{'ping': 1}"), NULL, NULL, NULL); + future = future_client_command_simple (client2, "test", tmp_bson ("{'ping': 1}"), NULL, NULL, NULL); request2 = mock_server_receives_legacy_hello (server, NULL); _assert_hello_valid (request2, true); reply_to_request_simple (request2, server_reply); request_destroy (request2); - request2 = mock_server_receives_msg ( - server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'test'}")); + request2 = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'test'}")); reply_to_request_with_ok_and_destroy (request2); ASSERT (future_get_bool (future)); future_destroy (future); @@ -3453,14 +3197,13 @@ test_client_appname (bool pooled, bool use_uri) future = _force_hello_with_ping (client, heartbeat_ms); } - request_t *const request = - mock_server_receives_any_hello_with_match (server, - "{'client': {" - " 'application': {" - " 'name': 'testapp'}}}", - "{'client': {" - " 'application': {" - " 'name': 'testapp'}}}"); + request_t *const request = mock_server_receives_any_hello_with_match (server, + "{'client': {" + " 'application': {" + " 'name': 'testapp'}}}", + "{'client': {" + " 'application': {" + " 'name': 'testapp'}}}"); reply_to_request_simple (request, server_reply); if (!pooled) { @@ -3533,10 +3276,8 @@ _test_null_error_pointer (bool pooled) } /* connect */ - future = future_client_command_simple ( - client, "test", tmp_bson ("{'ping': 1}"), NULL, NULL, NULL); - request = mock_server_receives_msg ( - server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'test', 'ping': 1}")); + future = future_client_command_simple (client, "test", tmp_bson ("{'ping': 1}"), NULL, NULL, NULL); + request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'test', 'ping': 1}")); reply_to_request_with_ok_and_destroy (request); ASSERT (future_get_bool (future)); future_destroy (future); @@ -3548,22 +3289,18 @@ _test_null_error_pointer (bool pooled) } else { mongoc_topology_scanner_node_t *scanner_node; - scanner_node = - mongoc_topology_scanner_get_node (client->topology->scanner, 1); + scanner_node = mongoc_topology_scanner_get_node (client->topology->scanner, 1); mongoc_stream_destroy (scanner_node->stream); scanner_node->stream = NULL; } /* doesn't abort with assertion failure */ capture_logs (true); - future = future_client_command_simple ( - client, "test", tmp_bson ("{'ping': 1}"), NULL, NULL, NULL /* error */); + future = future_client_command_simple (client, "test", tmp_bson ("{'ping': 1}"), NULL, NULL, NULL /* error */); ASSERT (!future_get_bool (future)); future_destroy (future); if (pooled) { - ASSERT_CAPTURED_LOG ("cluster", - MONGOC_LOG_LEVEL_WARNING, - "Failed to connect to target host"); + ASSERT_CAPTURED_LOG ("cluster", MONGOC_LOG_LEVEL_WARNING, "Failed to connect to target host"); } capture_logs (false); @@ -3626,8 +3363,7 @@ test_client_reset_sessions (void) server = mock_mongos_new (WIRE_VERSION_MAX); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); ASSERT (client->generation == 0); @@ -3640,16 +3376,13 @@ test_client_reset_sessions (void) mongoc_client_reset (client); ASSERT (client->generation == 1); - ASSERT ( - !_mongoc_client_lookup_session (client, csid, &session_lookup, &error)); + ASSERT (!_mongoc_client_lookup_session (client, csid, &session_lookup, &error)); /* Ensure that resetting did not send endSessions. To do this, we wait for a ping, so if we receive endSessions instead we will fail. */ - future = future_client_command_with_opts ( - client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, NULL, &error); + future = future_client_command_with_opts (client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, NULL, &error); - request = mock_server_receives_msg ( - server, 0, tmp_bson ("{'ping': 1, 'lsid': {'$exists': true}}")); + request = mock_server_receives_msg (server, 0, tmp_bson ("{'ping': 1, 'lsid': {'$exists': true}}")); reply_to_request_with_ok_and_destroy (request); ASSERT (future_get_bool (future)); @@ -3661,14 +3394,10 @@ test_client_reset_sessions (void) bson_copy_to (mongoc_client_session_get_lsid (session), &lsid); res = (mongoc_client_session_append (session, &opts, &error)); ASSERT_OR_PRINT (res, error); - future = future_client_command_with_opts ( - client, "admin", tmp_bson ("{'ping': 1}"), NULL, &opts, NULL, &error); + future = future_client_command_with_opts (client, "admin", tmp_bson ("{'ping': 1}"), NULL, &opts, NULL, &error); ASSERT (!future_get_bool (future)); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Invalid sessionId"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid sessionId"); /* Add an autoresponder for endSessions to unblock the test. */ mock_server_auto_endsessions (server); @@ -3697,19 +3426,16 @@ test_client_reset_cursors (void) server = mock_server_with_auto_hello (WIRE_VERSION_MIN); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); /* Ensure that cursors with an old client generation don't send killCursors. This test should timeout and fail if the client does send killCursors. */ coll = mongoc_client_get_collection (client, "test", "test"); - cursor = mongoc_collection_find ( - coll, MONGOC_QUERY_NONE, 0, 0, 0, tmp_bson (NULL), NULL, NULL); + cursor = mongoc_collection_find (coll, MONGOC_QUERY_NONE, 0, 0, 0, tmp_bson (NULL), NULL, NULL); future = future_cursor_next (cursor, &doc); - request = mock_server_receives_msg ( - server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'test', 'find': 'test'}")); + request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'test', 'find': 'test'}")); reply_to_request_simple (request, "{'ok': 1," @@ -3727,10 +3453,8 @@ test_client_reset_cursors (void) sending any requests to the server. */ ASSERT (!mongoc_cursor_next (cursor, &doc)); ASSERT (mongoc_cursor_error (cursor, &error)); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_CURSOR, - MONGOC_ERROR_CURSOR_INVALID_CURSOR, - "Cannot advance cursor after client reset"); + ASSERT_ERROR_CONTAINS ( + error, MONGOC_ERROR_CURSOR, MONGOC_ERROR_CURSOR_INVALID_CURSOR, "Cannot advance cursor after client reset"); mongoc_cursor_destroy (cursor); @@ -3740,11 +3464,9 @@ test_client_reset_cursors (void) /* Expect a ping here, and send one after destroying cursor. If a killCursors command intervened, this test will fail. */ database = mongoc_client_get_database (client, "admin"); - future = future_database_command_simple ( - database, tmp_bson ("{'ping': 1}"), NULL, NULL, NULL); + future = future_database_command_simple (database, tmp_bson ("{'ping': 1}"), NULL, NULL, NULL); - request = mock_server_receives_msg ( - server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'admin', 'ping': 1}")); + request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'admin', 'ping': 1}")); reply_to_request_with_ok_and_destroy (request); ASSERT (future_get_bool (future)); @@ -3791,8 +3513,7 @@ test_client_reset_connections (void) int autoresponder_id; server = mock_server_new (); - autoresponder_id = - mock_server_auto_hello (server, "{ 'isWritablePrimary': true }"); + autoresponder_id = mock_server_auto_hello (server, "{ 'isWritablePrimary': true }"); mock_server_run (server); /* After calling reset, check that connections are left as-is. Set @@ -3802,11 +3523,9 @@ test_client_reset_connections (void) client = test_framework_client_new_from_uri (uri, NULL); database = mongoc_client_get_database (client, "admin"); - future = future_database_command_simple ( - database, tmp_bson ("{'ping': 1}"), NULL, NULL, NULL); + future = future_database_command_simple (database, tmp_bson ("{'ping': 1}"), NULL, NULL, NULL); - request = mock_server_receives_msg ( - server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'admin', 'ping': 1}")); + request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'admin', 'ping': 1}")); BSON_ASSERT (request); reply_to_request_with_ok_and_destroy (request); @@ -3872,18 +3591,11 @@ test_invalid_server_id (void) bool ret; client = test_framework_client_new ("mongodb://localhost", NULL); - ret = mongoc_client_command_simple_with_server_id (client, - "admin", - tmp_bson ("{'ping': 1}"), - NULL /* read prefs */, - 123, - NULL /* reply */, - &error); + ret = mongoc_client_command_simple_with_server_id ( + client, "admin", tmp_bson ("{'ping': 1}"), NULL /* read prefs */, 123, NULL /* reply */, &error); BSON_ASSERT (!ret); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Could not find server with id: 123"); + ASSERT_ERROR_CONTAINS ( + error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Could not find server with id: 123"); mongoc_client_destroy (client); } @@ -3897,14 +3609,12 @@ test_ssl_opts_override (void) mongoc_client_t *client; mongoc_ssl_opt_t ssl_opts = {0}; - uri = mongoc_uri_new ( - "mongodb://localhost:27017/?tls=true&tlsDisableOCSPEndpointCheck=true"); + uri = mongoc_uri_new ("mongodb://localhost:27017/?tls=true&tlsDisableOCSPEndpointCheck=true"); client = test_framework_client_new_from_uri (uri, NULL); ssl_opts.allow_invalid_hostname = true; mongoc_client_set_ssl_opts (client, &ssl_opts); BSON_ASSERT (client->ssl_opts.allow_invalid_hostname); - BSON_ASSERT (((_mongoc_internal_tls_opts_t *) client->ssl_opts.internal) - ->tls_disable_ocsp_endpoint_check); + BSON_ASSERT (((_mongoc_internal_tls_opts_t *) client->ssl_opts.internal)->tls_disable_ocsp_endpoint_check); mongoc_uri_destroy (uri); mongoc_client_destroy (client); } @@ -3941,23 +3651,17 @@ test_mongoc_client_recv_network_error (void) server = mock_server_with_auto_hello (WIRE_VERSION_MAX); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); - - future = future_client_command_simple (client, - "admin", - tmp_bson ("{'ping': 1}"), - NULL /* read prefs */, - NULL /* reply */, - &error); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + + future = future_client_command_simple ( + client, "admin", tmp_bson ("{'ping': 1}"), NULL /* read prefs */, NULL /* reply */, &error); request = mock_server_receives_request (server); reply_to_request_with_ok_and_destroy (request); future_wait (future); future_destroy (future); /* The server should be a standalone. */ - sd = mongoc_topology_description_server_by_id_const ( - mc_tpld_unsafe_get_const (client->topology), 1, &error); + sd = mongoc_topology_description_server_by_id_const (mc_tpld_unsafe_get_const (client->topology), 1, &error); ASSERT_OR_PRINT (sd, error); generation = mc_tpl_sd_get_generation (sd, &kZeroServiceId); BSON_ASSERT (sd->type == MONGOC_SERVER_STANDALONE); @@ -3965,22 +3669,17 @@ test_mongoc_client_recv_network_error (void) /* A network error when calling _mongoc_client_recv should mark the server * unknown and increment the generation. */ - _mongoc_buffer_init (&buffer, - NULL /* initial buffer */, - 0 /* initial length */, - NULL /* realloc fn */, - NULL /* realloc ctx */); + _mongoc_buffer_init ( + &buffer, NULL /* initial buffer */, 0 /* initial length */, NULL /* realloc fn */, NULL /* realloc ctx */); rpc = mcd_rpc_message_new (); - stream = mongoc_cluster_stream_for_server ( - &client->cluster, 1, false, NULL, NULL, &error); + stream = mongoc_cluster_stream_for_server (&client->cluster, 1, false, NULL, NULL, &error); ASSERT_OR_PRINT (stream, error); BSON_ASSERT (!_mongoc_client_recv (client, rpc, &buffer, stream, &error)); td = mc_tpld_take_ref (client->topology); sd = mongoc_topology_description_server_by_id_const (td.ptr, 1, &error); ASSERT_OR_PRINT (sd, error); - ASSERT_CMPINT ( - mc_tpl_sd_get_generation (sd, &kZeroServiceId), ==, generation + 1); + ASSERT_CMPINT (mc_tpl_sd_get_generation (sd, &kZeroServiceId), ==, generation + 1); BSON_ASSERT (sd->type == MONGOC_SERVER_UNKNOWN); mongoc_client_destroy (client); @@ -4001,28 +3700,23 @@ test_mongoc_client_get_handshake_hello_response_single (void) client = test_framework_new_default_client (); /* Perform server selection to establish a connection. */ - monitor_sd = mongoc_client_select_server ( - client, false /* for writes */, NULL /* read prefs */, &error); + monitor_sd = mongoc_client_select_server (client, false /* for writes */, NULL /* read prefs */, &error); ASSERT_OR_PRINT (monitor_sd, error); - BSON_ASSERT ( - 0 != strcmp ("Unknown", mongoc_server_description_type (monitor_sd))); + BSON_ASSERT (0 != strcmp ("Unknown", mongoc_server_description_type (monitor_sd))); /* Invalidate the server. */ _mongoc_topology_invalidate_server (client->topology, monitor_sd->id); /* Get the new invalidated server description from monitoring. */ - invalidated_sd = - mongoc_client_get_server_description (client, monitor_sd->id); + invalidated_sd = mongoc_client_get_server_description (client, monitor_sd->id); BSON_ASSERT (NULL != invalidated_sd); ASSERT_CMPSTR ("Unknown", mongoc_server_description_type (invalidated_sd)); /* The previously established connection should have a valid server * description. */ - handshake_sd = mongoc_client_get_handshake_description ( - client, monitor_sd->id, NULL /* opts */, &error); + handshake_sd = mongoc_client_get_handshake_description (client, monitor_sd->id, NULL /* opts */, &error); ASSERT_OR_PRINT (handshake_sd, error); - BSON_ASSERT ( - 0 != strcmp ("Unknown", mongoc_server_description_type (handshake_sd))); + BSON_ASSERT (0 != strcmp ("Unknown", mongoc_server_description_type (handshake_sd))); mongoc_server_description_destroy (handshake_sd); mongoc_server_description_destroy (invalidated_sd); @@ -4043,37 +3737,27 @@ test_mongoc_client_get_handshake_hello_response_pooled (void) pool = test_framework_new_default_client_pool (); client = mongoc_client_pool_pop (pool); - monitor_sd = mongoc_client_select_server ( - client, false /* for writes */, NULL /* read prefs */, &error); + monitor_sd = mongoc_client_select_server (client, false /* for writes */, NULL /* read prefs */, &error); ASSERT_OR_PRINT (monitor_sd, error); - BSON_ASSERT ( - 0 != strcmp ("Unknown", mongoc_server_description_type (monitor_sd))); + BSON_ASSERT (0 != strcmp ("Unknown", mongoc_server_description_type (monitor_sd))); /* Send a ping to establish a connection. */ - ret = mongoc_client_command_simple_with_server_id (client, - "admin", - tmp_bson ("{'ping': 1}"), - NULL, - monitor_sd->id, - NULL /* reply */, - &error); + ret = mongoc_client_command_simple_with_server_id ( + client, "admin", tmp_bson ("{'ping': 1}"), NULL, monitor_sd->id, NULL /* reply */, &error); ASSERT_OR_PRINT (ret, error); /* Invalidate the server. */ _mongoc_topology_invalidate_server (client->topology, monitor_sd->id); /* Get the new invalidated server description from monitoring. */ - invalidated_sd = - mongoc_client_get_server_description (client, monitor_sd->id); + invalidated_sd = mongoc_client_get_server_description (client, monitor_sd->id); BSON_ASSERT (NULL != invalidated_sd); // Check the resulting server description. // Invalidating sets the type to Unknown. // A background monitor may have set the type to PossiblePrimary. - const char *got_description_type = - mongoc_server_description_type (invalidated_sd); - if (0 != strcmp ("Unknown", got_description_type) && - 0 != strcmp ("PossiblePrimary", got_description_type)) { + const char *got_description_type = mongoc_server_description_type (invalidated_sd); + if (0 != strcmp ("Unknown", got_description_type) && 0 != strcmp ("PossiblePrimary", got_description_type)) { test_error ("Expected server to have type 'Unknown' or " "'PossiblePrimary', got: '%s'", got_description_type); @@ -4081,11 +3765,9 @@ test_mongoc_client_get_handshake_hello_response_pooled (void) /* The previously established connection should have a valid server * description. */ - handshake_sd = mongoc_client_get_handshake_description ( - client, monitor_sd->id, NULL /* opts */, &error); + handshake_sd = mongoc_client_get_handshake_description (client, monitor_sd->id, NULL /* opts */, &error); ASSERT_OR_PRINT (handshake_sd, error); - BSON_ASSERT ( - 0 != strcmp ("Unknown", mongoc_server_description_type (handshake_sd))); + BSON_ASSERT (0 != strcmp ("Unknown", mongoc_server_description_type (handshake_sd))); mongoc_server_description_destroy (handshake_sd); mongoc_server_description_destroy (invalidated_sd); @@ -4106,11 +3788,9 @@ test_mongoc_client_get_handshake_establishes_connection_single (void) client = test_framework_new_default_client (); - handshake_sd = mongoc_client_get_handshake_description ( - client, server_id, NULL /* opts */, &error); + handshake_sd = mongoc_client_get_handshake_description (client, server_id, NULL /* opts */, &error); ASSERT_OR_PRINT (handshake_sd, error); - BSON_ASSERT ( - 0 != strcmp ("Unknown", mongoc_server_description_type (handshake_sd))); + BSON_ASSERT (0 != strcmp ("Unknown", mongoc_server_description_type (handshake_sd))); mongoc_server_description_destroy (handshake_sd); mongoc_client_destroy (client); @@ -4130,11 +3810,9 @@ test_mongoc_client_get_handshake_establishes_connection_pooled (void) /* The previously established connection should have a valid server * description. */ - handshake_sd = mongoc_client_get_handshake_description ( - client, server_id, NULL /* opts */, &error); + handshake_sd = mongoc_client_get_handshake_description (client, server_id, NULL /* opts */, &error); ASSERT_OR_PRINT (handshake_sd, error); - BSON_ASSERT ( - 0 != strcmp ("Unknown", mongoc_server_description_type (handshake_sd))); + BSON_ASSERT (0 != strcmp ("Unknown", mongoc_server_description_type (handshake_sd))); mongoc_server_description_destroy (handshake_sd); mongoc_client_pool_push (pool, client); @@ -4154,57 +3832,39 @@ test_mongoc_client_resends_handshake_on_network_error (void) server = mock_server_new (); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); mongoc_client_set_appname (client, "foo"); /* Send a "ping" command. */ - future = future_client_command_simple ( - client, "db", ping, NULL /* read_prefs */, NULL /* reply */, &error); + future = future_client_command_simple (client, "db", ping, NULL /* read_prefs */, NULL /* reply */, &error); /* The first command on the new connection is handshake. It uses the legacy * hello and includes the client.application.name. */ request = mock_server_receives_any_hello_with_match ( server, - "{'" HANDSHAKE_CMD_HELLO - "': 1, 'client': {'application': {'name': 'foo'}}}", - "{'" HANDSHAKE_CMD_LEGACY_HELLO - "': 1, 'client': {'application': {'name': 'foo'}}}"); + "{'" HANDSHAKE_CMD_HELLO "': 1, 'client': {'application': {'name': 'foo'}}}", + "{'" HANDSHAKE_CMD_LEGACY_HELLO "': 1, 'client': {'application': {'name': 'foo'}}}"); reply_to_request_simple ( - request, - tmp_str ("{'ok': 1, 'minWireVersion': %d, 'maxWireVersion': %d}", - WIRE_VERSION_MIN, - WIRE_VERSION_5_1)); + request, tmp_str ("{'ok': 1, 'minWireVersion': %d, 'maxWireVersion': %d}", WIRE_VERSION_MIN, WIRE_VERSION_5_1)); request_destroy (request); - request = mock_server_receives_msg ( - server, MONGOC_QUERY_NONE, tmp_bson ("{'ping': 1}")); + request = mock_server_receives_msg (server, MONGOC_QUERY_NONE, tmp_bson ("{'ping': 1}")); reply_to_request_with_hang_up (request); future_wait (future); future_destroy (future); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_SOCKET, - "socket error or timeout"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "socket error or timeout"); request_destroy (request); /* Send another "ping" command. */ - future = future_client_command_simple ( - client, "db", ping, NULL /* read_prefs */, NULL /* reply */, &error); + future = future_client_command_simple (client, "db", ping, NULL /* read_prefs */, NULL /* reply */, &error); /* Expect the new connection to send the full handshake. */ request = mock_server_receives_any_hello_with_match ( server, - "{'" HANDSHAKE_CMD_HELLO - "': 1, 'client': {'application': {'name': 'foo'}}}", - "{'" HANDSHAKE_CMD_LEGACY_HELLO - "': 1, 'client': {'application': {'name': 'foo'}}}"); + "{'" HANDSHAKE_CMD_HELLO "': 1, 'client': {'application': {'name': 'foo'}}}", + "{'" HANDSHAKE_CMD_LEGACY_HELLO "': 1, 'client': {'application': {'name': 'foo'}}}"); reply_to_request_simple ( - request, - tmp_str ("{'ok': 1, 'minWireVersion': %d, 'maxWireVersion': %d }", - WIRE_VERSION_MIN, - WIRE_VERSION_5_1)); + request, tmp_str ("{'ok': 1, 'minWireVersion': %d, 'maxWireVersion': %d }", WIRE_VERSION_MIN, WIRE_VERSION_5_1)); request_destroy (request); - request = mock_server_receives_msg ( - server, MONGOC_QUERY_NONE, tmp_bson ("{'ping': 1}")); + request = mock_server_receives_msg (server, MONGOC_QUERY_NONE, tmp_bson ("{'ping': 1}")); reply_to_request_with_ok_and_destroy (request); ASSERT (future_get_bool (future)); future_destroy (future); @@ -4221,14 +3881,12 @@ test_failure_to_auth (void) mongoc_uri_t *uri = mongoc_uri_new_for_host_port ("localhost", 12345); mongoc_uri_set_username (uri, "foo"); mongoc_uri_set_password (uri, "bar"); - mongoc_uri_set_option_as_bool ( - uri, MONGOC_URI_SERVERSELECTIONTRYONCE, false); + mongoc_uri_set_option_as_bool (uri, MONGOC_URI_SERVERSELECTIONTRYONCE, false); // Set a shorter serverSelectionTimeoutMS for a faster test. // serverSelectionTimeoutMS must be long enough to require a second attempt // of authentication. Experimentally: 100ms appears long enough to reproduce // leak reported in CDRIVER-4699. - mongoc_uri_set_option_as_int32 ( - uri, MONGOC_URI_SERVERSELECTIONTIMEOUTMS, 100); + mongoc_uri_set_option_as_int32 (uri, MONGOC_URI_SERVERSELECTIONTIMEOUTMS, 100); mongoc_client_t *client = mongoc_client_new_from_uri (uri); // Override minHeartbeatFrequencyMS to reduce the time between server checks. @@ -4239,12 +3897,8 @@ test_failure_to_auth (void) // failing to connect to a server before making another attempt. _mongoc_topology_bypass_cooldown (client->topology); - bool ok = mongoc_client_command_simple (client, - "admin", - tmp_bson ("{'ping': 1}"), - NULL /* read prefs */, - NULL /* reply */, - NULL /* error */); + bool ok = mongoc_client_command_simple ( + client, "admin", tmp_bson ("{'ping': 1}"), NULL /* read prefs */, NULL /* reply */, NULL /* error */); ASSERT_WITH_MSG (!ok, "expected command to fail, got success"); mongoc_client_destroy (client); mongoc_uri_destroy (uri); @@ -4254,20 +3908,14 @@ test_client_install (TestSuite *suite) { if (test_framework_getenv_bool ("MONGOC_CHECK_IPV6")) { /* try to validate ipv6 too */ - TestSuite_AddLive ( - suite, "/Client/ipv6/single", test_mongoc_client_ipv6_single); + TestSuite_AddLive (suite, "/Client/ipv6/single", test_mongoc_client_ipv6_single); /* try to validate ipv6 too */ - TestSuite_AddLive ( - suite, "/Client/ipv6/single", test_mongoc_client_ipv6_pooled); + TestSuite_AddLive (suite, "/Client/ipv6/single", test_mongoc_client_ipv6_pooled); } - TestSuite_AddFull (suite, - "/Client/authenticate", - test_mongoc_client_authenticate, - NULL, - NULL, - test_framework_skip_if_no_auth); + TestSuite_AddFull ( + suite, "/Client/authenticate", test_mongoc_client_authenticate, NULL, NULL, test_framework_skip_if_no_auth); TestSuite_AddFull (suite, "/Client/speculative_auth_failure/single", test_mongoc_client_single_speculative_auth_failure, @@ -4311,222 +3959,106 @@ test_client_install (TestSuite *suite) NULL, test_framework_skip_if_no_auth); TestSuite_AddLive (suite, "/Client/command", test_mongoc_client_command); - TestSuite_AddLive ( - suite, "/Client/command_defaults", test_mongoc_client_command_defaults); - TestSuite_AddLive ( - suite, "/Client/command_secondary", test_mongoc_client_command_secondary); - TestSuite_AddMockServerTest ( - suite, "/Client/command_w_server_id", test_client_cmd_w_server_id); - TestSuite_AddMockServerTest (suite, - "/Client/command_w_server_id/sharded", - test_client_cmd_w_server_id_sharded); - TestSuite_AddFull (suite, - "/Client/command_w_server_id/option", - test_server_id_option, - NULL, - NULL, - test_framework_skip_if_auth); - TestSuite_AddFull (suite, - "/Client/command_w_write_concern", - test_client_cmd_w_write_concern, - NULL, - NULL, - TestSuite_CheckLive); - TestSuite_AddMockServerTest ( - suite, "/Client/command/write_concern", test_client_cmd_write_concern); - TestSuite_AddMockServerTest (suite, - "/Client/command/write_concern_fam", - test_client_cmd_write_concern_fam); - TestSuite_AddMockServerTest (suite, - "/Client/command/read_prefs/simple/single", - test_command_simple_read_prefs_single); - TestSuite_AddMockServerTest (suite, - "/Client/command/read_prefs/simple/pooled", - test_command_simple_read_prefs_pooled); - TestSuite_AddMockServerTest (suite, - "/Client/command/read_prefs/single", - test_command_read_prefs_single); - TestSuite_AddMockServerTest (suite, - "/Client/command/read_prefs/pooled", - test_command_read_prefs_pooled); - TestSuite_AddLive ( - suite, "/Client/command_not_found/cursor", test_command_not_found); - TestSuite_AddLive ( - suite, "/Client/command_not_found/simple", test_command_not_found_simple); - TestSuite_AddMockServerTest (suite, - "/Client/command_with_opts/read_prefs", - test_command_with_opts_read_prefs); - TestSuite_AddMockServerTest (suite, - "/Client/command_with_opts/read_write", - test_read_write_cmd_with_opts); - TestSuite_AddMockServerTest ( - suite, "/Client/command_with_opts", test_command_with_opts); + TestSuite_AddLive (suite, "/Client/command_defaults", test_mongoc_client_command_defaults); + TestSuite_AddLive (suite, "/Client/command_secondary", test_mongoc_client_command_secondary); + TestSuite_AddMockServerTest (suite, "/Client/command_w_server_id", test_client_cmd_w_server_id); + TestSuite_AddMockServerTest (suite, "/Client/command_w_server_id/sharded", test_client_cmd_w_server_id_sharded); + TestSuite_AddFull ( + suite, "/Client/command_w_server_id/option", test_server_id_option, NULL, NULL, test_framework_skip_if_auth); + TestSuite_AddFull ( + suite, "/Client/command_w_write_concern", test_client_cmd_w_write_concern, NULL, NULL, TestSuite_CheckLive); + TestSuite_AddMockServerTest (suite, "/Client/command/write_concern", test_client_cmd_write_concern); + TestSuite_AddMockServerTest (suite, "/Client/command/write_concern_fam", test_client_cmd_write_concern_fam); TestSuite_AddMockServerTest ( - suite, "/Client/command_with_opts/op_msg", test_command_with_opts_op_msg); + suite, "/Client/command/read_prefs/simple/single", test_command_simple_read_prefs_single); TestSuite_AddMockServerTest ( - suite, "/Client/command_with_opts/read", test_read_command_with_opts); + suite, "/Client/command/read_prefs/simple/pooled", test_command_simple_read_prefs_pooled); + TestSuite_AddMockServerTest (suite, "/Client/command/read_prefs/single", test_command_read_prefs_single); + TestSuite_AddMockServerTest (suite, "/Client/command/read_prefs/pooled", test_command_read_prefs_pooled); + TestSuite_AddLive (suite, "/Client/command_not_found/cursor", test_command_not_found); + TestSuite_AddLive (suite, "/Client/command_not_found/simple", test_command_not_found_simple); + TestSuite_AddMockServerTest (suite, "/Client/command_with_opts/read_prefs", test_command_with_opts_read_prefs); + TestSuite_AddMockServerTest (suite, "/Client/command_with_opts/read_write", test_read_write_cmd_with_opts); + TestSuite_AddMockServerTest (suite, "/Client/command_with_opts", test_command_with_opts); + TestSuite_AddMockServerTest (suite, "/Client/command_with_opts/op_msg", test_command_with_opts_op_msg); + TestSuite_AddMockServerTest (suite, "/Client/command_with_opts/read", test_read_command_with_opts); TestSuite_AddLive (suite, "/Client/command/empty", test_command_empty); - TestSuite_AddMockServerTest ( - suite, "/Client/command/no_errmsg", test_command_no_errmsg); - TestSuite_AddMockServerTest ( - suite, "/Client/unavailable_seeds", test_unavailable_seeds); - TestSuite_AddMockServerTest (suite, - "/Client/rs_seeds_no_connect/single", - test_rs_seeds_no_connect_single); - TestSuite_AddMockServerTest (suite, - "/Client/rs_seeds_no_connect/pooled", - test_rs_seeds_no_connect_pooled); - TestSuite_AddMockServerTest ( - suite, "/Client/rs_seeds_connect/single", test_rs_seeds_connect_single); - TestSuite_AddMockServerTest ( - suite, "/Client/rs_seeds_connect/pooled", test_rs_seeds_connect_pooled); - TestSuite_AddMockServerTest (suite, - "/Client/rs_seeds_reconnect/single", - test_rs_seeds_reconnect_single); - TestSuite_AddMockServerTest (suite, - "/Client/rs_seeds_reconnect/pooled", - test_rs_seeds_reconnect_pooled); - TestSuite_AddMockServerTest (suite, - "/Client/mongos_seeds_no_connect/single", - test_mongos_seeds_no_connect_single); - TestSuite_AddMockServerTest (suite, - "/Client/mongos_seeds_no_connect/pooled", - test_mongos_seeds_no_connect_pooled); - TestSuite_AddMockServerTest (suite, - "/Client/mongos_seeds_connect/single", - test_mongos_seeds_connect_single); - TestSuite_AddMockServerTest (suite, - "/Client/mongos_seeds_connect/pooled", - test_mongos_seeds_connect_pooled); - TestSuite_AddMockServerTest (suite, - "/Client/mongos_seeds_reconnect/single", - test_mongos_seeds_reconnect_single); - TestSuite_AddMockServerTest (suite, - "/Client/mongos_seeds_reconnect/pooled", - test_mongos_seeds_reconnect_pooled); - TestSuite_AddFull (suite, - "/Client/recovering", - test_recovering, - NULL, - NULL, - test_framework_skip_if_slow); + TestSuite_AddMockServerTest (suite, "/Client/command/no_errmsg", test_command_no_errmsg); + TestSuite_AddMockServerTest (suite, "/Client/unavailable_seeds", test_unavailable_seeds); + TestSuite_AddMockServerTest (suite, "/Client/rs_seeds_no_connect/single", test_rs_seeds_no_connect_single); + TestSuite_AddMockServerTest (suite, "/Client/rs_seeds_no_connect/pooled", test_rs_seeds_no_connect_pooled); + TestSuite_AddMockServerTest (suite, "/Client/rs_seeds_connect/single", test_rs_seeds_connect_single); + TestSuite_AddMockServerTest (suite, "/Client/rs_seeds_connect/pooled", test_rs_seeds_connect_pooled); + TestSuite_AddMockServerTest (suite, "/Client/rs_seeds_reconnect/single", test_rs_seeds_reconnect_single); + TestSuite_AddMockServerTest (suite, "/Client/rs_seeds_reconnect/pooled", test_rs_seeds_reconnect_pooled); + TestSuite_AddMockServerTest (suite, "/Client/mongos_seeds_no_connect/single", test_mongos_seeds_no_connect_single); + TestSuite_AddMockServerTest (suite, "/Client/mongos_seeds_no_connect/pooled", test_mongos_seeds_no_connect_pooled); + TestSuite_AddMockServerTest (suite, "/Client/mongos_seeds_connect/single", test_mongos_seeds_connect_single); + TestSuite_AddMockServerTest (suite, "/Client/mongos_seeds_connect/pooled", test_mongos_seeds_connect_pooled); + TestSuite_AddMockServerTest (suite, "/Client/mongos_seeds_reconnect/single", test_mongos_seeds_reconnect_single); + TestSuite_AddMockServerTest (suite, "/Client/mongos_seeds_reconnect/pooled", test_mongos_seeds_reconnect_pooled); + TestSuite_AddFull (suite, "/Client/recovering", test_recovering, NULL, NULL, test_framework_skip_if_slow); TestSuite_AddLive (suite, "/Client/server_status", test_server_status); - TestSuite_AddMockServerTest ( - suite, "/Client/database_names", test_get_database_names); - TestSuite_AddFull (suite, - "/Client/connect/uds", - test_mongoc_client_unix_domain_socket, - NULL, - NULL, - test_framework_skip_if_no_uds); - TestSuite_AddMockServerTest ( - suite, "/Client/mismatched_me", test_mongoc_client_mismatched_me); + TestSuite_AddMockServerTest (suite, "/Client/database_names", test_get_database_names); + TestSuite_AddFull ( + suite, "/Client/connect/uds", test_mongoc_client_unix_domain_socket, NULL, NULL, test_framework_skip_if_no_uds); + TestSuite_AddMockServerTest (suite, "/Client/mismatched_me", test_mongoc_client_mismatched_me); - TestSuite_AddMockServerTest ( - suite, "/Client/handshake/pool", test_mongoc_handshake_pool); - TestSuite_Add (suite, - "/Client/application_handshake", - test_mongoc_client_application_handshake); + TestSuite_AddMockServerTest (suite, "/Client/handshake/pool", test_mongoc_handshake_pool); + TestSuite_Add (suite, "/Client/application_handshake", test_mongoc_client_application_handshake); TestSuite_AddFull (suite, "/Client/sends_handshake_single", test_client_sends_handshake_single, NULL, NULL, test_framework_skip_if_slow); - TestSuite_Add (suite, - "/Client/sends_handshake_pooled", - test_client_sends_handshake_pooled); - TestSuite_AddMockServerTest ( - suite, "/Client/appname_single_uri", test_client_appname_single_uri); - TestSuite_AddMockServerTest (suite, - "/Client/appname_single_no_uri", - test_client_appname_single_no_uri); - TestSuite_AddMockServerTest ( - suite, "/Client/appname_pooled_uri", test_client_appname_pooled_uri); - TestSuite_AddMockServerTest (suite, - "/Client/appname_pooled_no_uri", - test_client_appname_pooled_no_uri); - TestSuite_AddMockServerTest ( - suite, "/Client/wire_version", test_wire_version); + TestSuite_Add (suite, "/Client/sends_handshake_pooled", test_client_sends_handshake_pooled); + TestSuite_AddMockServerTest (suite, "/Client/appname_single_uri", test_client_appname_single_uri); + TestSuite_AddMockServerTest (suite, "/Client/appname_single_no_uri", test_client_appname_single_no_uri); + TestSuite_AddMockServerTest (suite, "/Client/appname_pooled_uri", test_client_appname_pooled_uri); + TestSuite_AddMockServerTest (suite, "/Client/appname_pooled_no_uri", test_client_appname_pooled_no_uri); + TestSuite_AddMockServerTest (suite, "/Client/wire_version", test_wire_version); #ifdef MONGOC_ENABLE_SSL TestSuite_AddLive (suite, "/Client/ssl_opts/single", test_ssl_single); TestSuite_AddLive (suite, "/Client/ssl_opts/pooled", test_ssl_pooled); TestSuite_Add (suite, "/Client/set_ssl_opts", test_set_ssl_opts); TestSuite_Add (suite, "/Client/ssl_opts_override", test_ssl_opts_override); - TestSuite_Add (suite, - "/Client/ssl_opts_padding_not_null/single", - test_ssl_opts_padding_not_null); + TestSuite_Add (suite, "/Client/ssl_opts_padding_not_null/single", test_ssl_opts_padding_not_null); TestSuite_AddLive (suite, "/Client/ssl_hang", test_client_buildinfo_hang); -#if defined(MONGOC_ENABLE_SSL_OPENSSL) || \ - defined(MONGOC_ENABLE_SSL_SECURE_TRANSPORT) - TestSuite_AddMockServerTest (suite, - "/Client/ssl_opts/copies_single", - test_ssl_client_single_copies_args); - TestSuite_AddMockServerTest (suite, - "/Client/ssl_opts/copies_pooled", - test_ssl_client_pooled_copies_args); - TestSuite_AddMockServerTest ( - suite, "/Client/ssl/reconnect/single", test_ssl_reconnect_single); - TestSuite_AddMockServerTest ( - suite, "/Client/ssl/reconnect/pooled", test_ssl_reconnect_pooled); +#if defined(MONGOC_ENABLE_SSL_OPENSSL) || defined(MONGOC_ENABLE_SSL_SECURE_TRANSPORT) + TestSuite_AddMockServerTest (suite, "/Client/ssl_opts/copies_single", test_ssl_client_single_copies_args); + TestSuite_AddMockServerTest (suite, "/Client/ssl_opts/copies_pooled", test_ssl_client_pooled_copies_args); + TestSuite_AddMockServerTest (suite, "/Client/ssl/reconnect/single", test_ssl_reconnect_single); + TestSuite_AddMockServerTest (suite, "/Client/ssl/reconnect/pooled", test_ssl_reconnect_pooled); #endif #else /* No SSL support at all */ - TestSuite_Add ( - suite, "/Client/ssl_disabled", test_mongoc_client_ssl_disabled); + TestSuite_Add (suite, "/Client/ssl_disabled", test_mongoc_client_ssl_disabled); #endif - TestSuite_AddMockServerTest (suite, - "/Client/client_reset/sessions", - test_client_reset_sessions, - test_framework_skip_if_no_crypto); - TestSuite_AddMockServerTest ( - suite, "/Client/client_reset/cursors", test_client_reset_cursors); + suite, "/Client/client_reset/sessions", test_client_reset_sessions, test_framework_skip_if_no_crypto); + + TestSuite_AddMockServerTest (suite, "/Client/client_reset/cursors", test_client_reset_cursors); + TestSuite_AddMockServerTest (suite, "/Client/client_reset/connections", test_client_reset_connections); + + TestSuite_AddLive (suite, "/Client/get_description/single", test_mongoc_client_get_description_single); + TestSuite_AddLive (suite, "/Client/get_description/pooled", test_mongoc_client_get_description_pooled); + TestSuite_AddLive (suite, "/Client/descriptions/single", test_mongoc_client_descriptions_single); + TestSuite_AddFull ( + suite, "/Client/descriptions/pooled", test_mongoc_client_descriptions_pooled, NULL, NULL, TestSuite_CheckLive); + TestSuite_AddLive (suite, "/Client/select_server/single", test_mongoc_client_select_server_single); + TestSuite_AddLive (suite, "/Client/select_server/pooled", test_mongoc_client_select_server_pooled); + TestSuite_AddLive (suite, "/Client/select_server/err/single", test_mongoc_client_select_server_error_single); + TestSuite_AddLive (suite, "/Client/select_server/err/pooled", test_mongoc_client_select_server_error_pooled); TestSuite_AddMockServerTest ( - suite, "/Client/client_reset/connections", test_client_reset_connections); - - TestSuite_AddLive (suite, - "/Client/get_description/single", - test_mongoc_client_get_description_single); - TestSuite_AddLive (suite, - "/Client/get_description/pooled", - test_mongoc_client_get_description_pooled); - TestSuite_AddLive (suite, - "/Client/descriptions/single", - test_mongoc_client_descriptions_single); - TestSuite_AddFull (suite, - "/Client/descriptions/pooled", - test_mongoc_client_descriptions_pooled, - NULL, - NULL, - TestSuite_CheckLive); - TestSuite_AddLive (suite, - "/Client/select_server/single", - test_mongoc_client_select_server_single); - TestSuite_AddLive (suite, - "/Client/select_server/pooled", - test_mongoc_client_select_server_pooled); - TestSuite_AddLive (suite, - "/Client/select_server/err/single", - test_mongoc_client_select_server_error_single); - TestSuite_AddLive (suite, - "/Client/select_server/err/pooled", - test_mongoc_client_select_server_error_pooled); - TestSuite_AddMockServerTest (suite, - "/Client/select_server/retry/succeed", - test_mongoc_client_select_server_retry_succeed); - TestSuite_AddMockServerTest (suite, - "/Client/select_server/retry/fail", - test_mongoc_client_select_server_retry_fail); - TestSuite_AddMockServerTest (suite, - "/Client/fetch_stream/retry/succeed", - test_mongoc_client_fetch_stream_retry_succeed); - TestSuite_AddMockServerTest (suite, - "/Client/fetch_stream/retry/fail", - test_mongoc_client_fetch_stream_retry_fail); + suite, "/Client/select_server/retry/succeed", test_mongoc_client_select_server_retry_succeed); + TestSuite_AddMockServerTest (suite, "/Client/select_server/retry/fail", test_mongoc_client_select_server_retry_fail); + TestSuite_AddMockServerTest ( + suite, "/Client/fetch_stream/retry/succeed", test_mongoc_client_fetch_stream_retry_succeed); + TestSuite_AddMockServerTest (suite, "/Client/fetch_stream/retry/fail", test_mongoc_client_fetch_stream_retry_fail); TestSuite_AddFull (suite, "/Client/null_error_pointer/single", test_null_error_pointer_single, @@ -4541,26 +4073,18 @@ test_client_install (TestSuite *suite) test_framework_skip_if_slow); TestSuite_Add (suite, "/Client/get_database", test_get_database); TestSuite_Add (suite, "/Client/invalid_server_id", test_invalid_server_id); - TestSuite_AddMockServerTest (suite, - "/Client/recv_network_error", - test_mongoc_client_recv_network_error); - TestSuite_AddLive (suite, - "/Client/get_handshake_hello_response/single", - test_mongoc_client_get_handshake_hello_response_single); - TestSuite_AddLive (suite, - "/Client/get_handshake_hello_response/pooled", - test_mongoc_client_get_handshake_hello_response_pooled); + TestSuite_AddMockServerTest (suite, "/Client/recv_network_error", test_mongoc_client_recv_network_error); TestSuite_AddLive ( - suite, - "/Client/get_handshake_establishes_connection/single", - test_mongoc_client_get_handshake_establishes_connection_single); + suite, "/Client/get_handshake_hello_response/single", test_mongoc_client_get_handshake_hello_response_single); TestSuite_AddLive ( - suite, - "/Client/get_handshake_establishes_connection/pooled", - test_mongoc_client_get_handshake_establishes_connection_pooled); + suite, "/Client/get_handshake_hello_response/pooled", test_mongoc_client_get_handshake_hello_response_pooled); + TestSuite_AddLive (suite, + "/Client/get_handshake_establishes_connection/single", + test_mongoc_client_get_handshake_establishes_connection_single); + TestSuite_AddLive (suite, + "/Client/get_handshake_establishes_connection/pooled", + test_mongoc_client_get_handshake_establishes_connection_pooled); TestSuite_AddMockServerTest ( - suite, - "/Client/resends_handshake_on_network_error", - test_mongoc_client_resends_handshake_on_network_error); + suite, "/Client/resends_handshake_on_network_error", test_mongoc_client_resends_handshake_on_network_error); TestSuite_Add (suite, "/Client/failure_to_auth", test_failure_to_auth); } diff --git a/src/libmongoc/tests/test-mongoc-cluster.c b/src/libmongoc/tests/test-mongoc-cluster.c index c0f7f82970..303ff4e4f8 100644 --- a/src/libmongoc/tests/test-mongoc-cluster.c +++ b/src/libmongoc/tests/test-mongoc-cluster.c @@ -25,8 +25,7 @@ server_id_for_reads (mongoc_cluster_t *cluster) mongoc_server_stream_t *server_stream; uint32_t id; - server_stream = - mongoc_cluster_stream_for_reads (cluster, NULL, NULL, NULL, NULL, &error); + server_stream = mongoc_cluster_stream_for_reads (cluster, NULL, NULL, NULL, NULL, &error); ASSERT_OR_PRINT (server_stream, error); id = server_stream->sd->id; @@ -56,8 +55,7 @@ test_get_max_bson_obj_size (void) sd = mongoc_set_get (mc_tpld_servers (tdmod.new_td), id); sd->max_bson_obj_size = max_bson_obj_size; mc_tpld_modify_commit (tdmod); - BSON_ASSERT (max_bson_obj_size == - mongoc_cluster_get_max_bson_obj_size (&client->cluster)); + BSON_ASSERT (max_bson_obj_size == mongoc_cluster_get_max_bson_obj_size (&client->cluster)); mongoc_client_destroy (client); @@ -68,8 +66,7 @@ test_get_max_bson_obj_size (void) id = server_id_for_reads (&client->cluster); node = (mongoc_cluster_node_t *) mongoc_set_get (client->cluster.nodes, id); node->handshake_sd->max_bson_obj_size = max_bson_obj_size; - BSON_ASSERT (max_bson_obj_size == - mongoc_cluster_get_max_bson_obj_size (&client->cluster)); + BSON_ASSERT (max_bson_obj_size == mongoc_cluster_get_max_bson_obj_size (&client->cluster)); mongoc_client_pool_push (pool, client); mongoc_client_pool_destroy (pool); @@ -94,8 +91,7 @@ test_get_max_msg_size (void) sd = mongoc_set_get (mc_tpld_servers (tdmod.new_td), id); sd->max_msg_size = max_msg_size; mc_tpld_modify_commit (tdmod); - BSON_ASSERT (max_msg_size == - mongoc_cluster_get_max_msg_size (&client->cluster)); + BSON_ASSERT (max_msg_size == mongoc_cluster_get_max_msg_size (&client->cluster)); mongoc_client_destroy (client); @@ -106,37 +102,30 @@ test_get_max_msg_size (void) id = server_id_for_reads (&client->cluster); node = (mongoc_cluster_node_t *) mongoc_set_get (client->cluster.nodes, id); node->handshake_sd->max_msg_size = max_msg_size; - BSON_ASSERT (max_msg_size == - mongoc_cluster_get_max_msg_size (&client->cluster)); + BSON_ASSERT (max_msg_size == mongoc_cluster_get_max_msg_size (&client->cluster)); mongoc_client_pool_push (pool, client); mongoc_client_pool_destroy (pool); } -#define ASSERT_CURSOR_ERR() \ - do { \ - BSON_ASSERT (!future_get_bool (future)); \ - BSON_ASSERT (mongoc_cursor_error (cursor, &error)); \ - ASSERT_ERROR_CONTAINS ( \ - error, \ - MONGOC_ERROR_STREAM, \ - MONGOC_ERROR_STREAM_SOCKET, \ - "Failed to read 4 bytes: socket error or timeout"); \ +#define ASSERT_CURSOR_ERR() \ + do { \ + BSON_ASSERT (!future_get_bool (future)); \ + BSON_ASSERT (mongoc_cursor_error (cursor, &error)); \ + ASSERT_ERROR_CONTAINS ( \ + error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "Failed to read 4 bytes: socket error or timeout"); \ } while (0) -#define START_QUERY(client_port_variable) \ - do { \ - cursor = mongoc_collection_find_with_opts ( \ - collection, tmp_bson ("{}"), NULL, NULL); \ - future = future_cursor_next (cursor, &doc); \ - request = mock_server_receives_msg ( \ - server, \ - MONGOC_MSG_NONE, \ - tmp_bson ("{'$db': 'test', 'find': 'test', 'filter': {}}")); \ - BSON_ASSERT (request); \ - client_port_variable = request_get_client_port (request); \ +#define START_QUERY(client_port_variable) \ + do { \ + cursor = mongoc_collection_find_with_opts (collection, tmp_bson ("{}"), NULL, NULL); \ + future = future_cursor_next (cursor, &doc); \ + request = mock_server_receives_msg ( \ + server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'test', 'find': 'test', 'filter': {}}")); \ + BSON_ASSERT (request); \ + client_port_variable = request_get_client_port (request); \ } while (0) @@ -266,22 +255,16 @@ _test_cluster_command_timeout (bool pooled) } /* server doesn't respond in time */ - future = future_client_command_simple ( - client, "db", tmp_bson ("{'foo': 1}"), NULL, NULL, &error); - request = mock_server_receives_msg ( - server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', 'foo': 1}")); + future = future_client_command_simple (client, "db", tmp_bson ("{'foo': 1}"), NULL, NULL, &error); + request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', 'foo': 1}")); client_port = request_get_client_port (request); ASSERT (!future_get_bool (future)); ASSERT_ERROR_CONTAINS ( - error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_SOCKET, - "Failed to send \"foo\" command with database \"db\""); + error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "Failed to send \"foo\" command with database \"db\""); /* a network timeout does NOT invalidate the server description */ - sd = mongoc_topology_description_server_by_id_const ( - mc_tpld_unsafe_get_const (client->topology), 1, NULL); + sd = mongoc_topology_description_server_by_id_const (mc_tpld_unsafe_get_const (client->topology), 1, NULL); BSON_ASSERT (sd->type != MONGOC_SERVER_UNKNOWN); /* late response */ @@ -289,10 +272,8 @@ _test_cluster_command_timeout (bool pooled) request_destroy (request); future_destroy (future); - future = future_client_command_simple ( - client, "db", tmp_bson ("{'baz': 1}"), NULL, &reply, &error); - request = mock_server_receives_msg ( - server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', 'baz': 1}")); + future = future_client_command_simple (client, "db", tmp_bson ("{'baz': 1}"), NULL, &reply, &error); + request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', 'baz': 1}")); ASSERT (request); /* new socket */ ASSERT_CMPUINT16 (client_port, !=, request_get_client_port (request)); @@ -350,14 +331,12 @@ _test_write_disconnect (void) server = mock_server_new (); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); /* * establish connection with an "hello" and "ping" */ - future = future_client_command_simple ( - client, "db", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); + future = future_client_command_simple (client, "db", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); request = mock_server_receives_any_hello (server); hello = bson_strdup_printf ("{'ok': 1.0," " 'isWritablePrimary': true," @@ -369,8 +348,7 @@ _test_write_disconnect (void) reply_to_request_simple (request, hello); request_destroy (request); - request = mock_server_receives_msg ( - server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', 'ping': 1}")); + request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', 'ping': 1}")); reply_to_request_simple (request, "{'ok': 1}"); ASSERT_OR_PRINT (future_get_bool (future), error); @@ -384,20 +362,17 @@ _test_write_disconnect (void) */ collection = mongoc_client_get_collection (client, "db", "collection"); future_destroy (future); - future = future_collection_insert_one ( - collection, tmp_bson ("{'_id': 1}"), NULL, NULL, &error); + future = future_collection_insert_one (collection, tmp_bson ("{'_id': 1}"), NULL, NULL, &error); ASSERT (!future_get_bool (future)); ASSERT_CMPINT (error.domain, ==, MONGOC_ERROR_STREAM); ASSERT_CMPINT (error.code, ==, MONGOC_ERROR_STREAM_SOCKET); - scanner_node = mongoc_topology_scanner_get_node (client->topology->scanner, - 1 /* server_id */); + scanner_node = mongoc_topology_scanner_get_node (client->topology->scanner, 1 /* server_id */); ASSERT (scanner_node && !scanner_node->stream); /* a hangup DOES invalidate the server description */ - sd = mongoc_topology_description_server_by_id_const ( - mc_tpld_unsafe_get_const (client->topology), 1, NULL); + sd = mongoc_topology_description_server_by_id_const (mc_tpld_unsafe_get_const (client->topology), 1, NULL); BSON_ASSERT (sd->type == MONGOC_SERVER_UNKNOWN); mongoc_collection_destroy (collection); @@ -439,8 +414,7 @@ test_cluster_time_cmd_started_cb (const mongoc_apm_command_started_t *event) return; } - test = - (cluster_time_test_t *) mongoc_apm_command_started_get_context (event); + test = (cluster_time_test_t *) mongoc_apm_command_started_get_context (event); test->calls++; bson_destroy (test->command); @@ -481,8 +455,7 @@ test_cluster_time_cmd_succeeded_cb (const mongoc_apm_command_succeeded_t *event) const uint8_t *data; reply = mongoc_apm_command_succeeded_get_reply (event); - test = - (cluster_time_test_t *) mongoc_apm_command_succeeded_get_context (event); + test = (cluster_time_test_t *) mongoc_apm_command_succeeded_get_context (event); /* Only a MongoDB 3.6+ server reports $clusterTime. Save it in "test". */ if (test_framework_clustertime_supported ()) { @@ -515,15 +488,12 @@ _test_cluster_time (bool pooled, command_fn_t command) cluster_time_test.cluster_time = NULL; callbacks = mongoc_apm_callbacks_new (); - mongoc_apm_set_command_started_cb (callbacks, - test_cluster_time_cmd_started_cb); - mongoc_apm_set_command_succeeded_cb (callbacks, - test_cluster_time_cmd_succeeded_cb); + mongoc_apm_set_command_started_cb (callbacks, test_cluster_time_cmd_started_cb); + mongoc_apm_set_command_succeeded_cb (callbacks, test_cluster_time_cmd_succeeded_cb); if (pooled) { pool = test_framework_new_default_client_pool (); - mongoc_client_pool_set_apm_callbacks ( - pool, callbacks, &cluster_time_test); + mongoc_client_pool_set_apm_callbacks (pool, callbacks, &cluster_time_test); client = mongoc_client_pool_pop (pool); /* CDRIVER-3596 - prevent client discovery of the pool interfering with * the test operations. */ @@ -558,8 +528,7 @@ _test_cluster_time (bool pooled, command_fn_t command) static bool command_simple (mongoc_client_t *client, bson_error_t *error) { - return mongoc_client_command_simple ( - client, "test", tmp_bson ("{'ping': 1}"), NULL, NULL, error); + return mongoc_client_command_simple (client, "test", tmp_bson ("{'ping': 1}"), NULL, NULL, error); } @@ -587,15 +556,7 @@ client_command (mongoc_client_t *client, bson_error_t *error) ASSERT (client); - cursor = mongoc_client_command (client, - "test", - MONGOC_QUERY_NONE, - 0, - 0, - 0, - tmp_bson ("{'ping': 1}"), - NULL, - NULL); + cursor = mongoc_client_command (client, "test", MONGOC_QUERY_NONE, 0, 0, 0, tmp_bson ("{'ping': 1}"), NULL, NULL); mongoc_cursor_next (cursor, &doc); r = !mongoc_cursor_error (cursor, error); @@ -623,8 +584,7 @@ static bool client_command_with_opts (mongoc_client_t *client, bson_error_t *error) { /* any of the with_opts command functions should work */ - return mongoc_client_read_command_with_opts ( - client, "test", tmp_bson ("{'ping': 1}"), NULL, NULL, NULL, error); + return mongoc_client_read_command_with_opts (client, "test", tmp_bson ("{'ping': 1}"), NULL, NULL, NULL, error); } @@ -654,8 +614,7 @@ aggregate (mongoc_client_t *client, bson_error_t *error) ASSERT (client); collection = mongoc_client_get_collection (client, "test", "collection"); - cursor = mongoc_collection_aggregate ( - collection, MONGOC_QUERY_NONE, tmp_bson ("{}"), NULL, NULL); + cursor = mongoc_collection_aggregate (collection, MONGOC_QUERY_NONE, tmp_bson ("{}"), NULL, NULL); mongoc_cursor_next (cursor, &doc); r = !mongoc_cursor_error (cursor, error); @@ -692,8 +651,7 @@ cursor_next (mongoc_client_t *client, bson_error_t *error) ASSERT (client); collection = get_test_collection (client, "test_cluster_time_cursor"); - cursor = mongoc_collection_find_with_opts ( - collection, tmp_bson ("{'ping': 1}"), NULL, NULL); + cursor = mongoc_collection_find_with_opts (collection, tmp_bson ("{'ping': 1}"), NULL, NULL); mongoc_cursor_next (cursor, &doc); r = !mongoc_cursor_error (cursor, error); @@ -729,8 +687,7 @@ insert (mongoc_client_t *client, bson_error_t *error) ASSERT (client); collection = get_test_collection (client, "test_cluster_time_cursor"); - r = mongoc_collection_insert_one ( - collection, tmp_bson ("{}"), NULL, NULL, error); + r = mongoc_collection_insert_one (collection, tmp_bson ("{}"), NULL, NULL, error); mongoc_collection_destroy (collection); @@ -763,15 +720,12 @@ test_cluster_command_timeout_negative (void) // fallback to a "default" value for timeouts. mongoc_uri_set_option_as_int32 (uri, MONGOC_URI_SOCKETTIMEOUTMS, -1); - mongoc_client_t *const client = - test_framework_client_new_from_uri (uri, NULL); + mongoc_client_t *const client = test_framework_client_new_from_uri (uri, NULL); test_framework_set_ssl_opts (client); // There should not be an error when validating sockettimeoutms. - ASSERT_OR_PRINT ( - mongoc_client_command_simple ( - client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, &error), - error); + ASSERT_OR_PRINT (mongoc_client_command_simple (client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, &error), + error); mongoc_client_destroy (client); mongoc_uri_destroy (uri); @@ -779,10 +733,7 @@ test_cluster_command_timeout_negative (void) static void -replies_with_cluster_time (request_t *request, - int t, - int i, - const char *docs_json) +replies_with_cluster_time (request_t *request, int t, int i, const char *docs_json) { char *quotes_replaced; bson_t doc; @@ -805,14 +756,9 @@ replies_with_cluster_time (request_t *request, } BSON_APPEND_DOCUMENT ( - &doc, - "$clusterTime", - tmp_bson ("{'clusterTime': {'$timestamp': {'t': %d, 'i': %d}}, 'x': 'y'}", - t, - i)); + &doc, "$clusterTime", tmp_bson ("{'clusterTime': {'$timestamp': {'t': %d, 'i': %d}}, 'x': 'y'}", t, i)); - reply_to_request_with_multiple_docs ( - request, MONGOC_REPLY_NONE, &doc, 1, 0 /* cursor id */); + reply_to_request_with_multiple_docs (request, MONGOC_REPLY_NONE, &doc, 1, 0 /* cursor id */); bson_destroy (&doc); request_destroy (request); @@ -820,10 +766,7 @@ replies_with_cluster_time (request_t *request, static request_t * -receives_with_cluster_time (mock_server_t *server, - uint32_t timestamp, - uint32_t increment, - bson_t *command) +receives_with_cluster_time (mock_server_t *server, uint32_t timestamp, uint32_t increment, bson_t *command) { request_t *request; const bson_t *doc; @@ -842,11 +785,7 @@ receives_with_cluster_time (mock_server_t *server, BSON_ASSERT (BSON_ITER_HOLDS_TIMESTAMP (&cluster_time)); bson_iter_timestamp (&cluster_time, &t, &i); if (t != timestamp || i != increment) { - test_error ("Expected Timestamp(%d, %d), got Timestamp(%d, %d)", - timestamp, - increment, - t, - i); + test_error ("Expected Timestamp(%d, %d), got Timestamp(%d, %d)", timestamp, increment, t, i); } return request; @@ -865,8 +804,7 @@ assert_ok (future_t *future, const bson_error_t *error) static future_t * future_ping (mongoc_client_t *client, bson_error_t *error) { - return future_client_command_simple ( - client, "test", tmp_bson ("{'ping': 1}"), NULL, NULL, error); + return future_client_command_simple (client, "test", tmp_bson ("{'ping': 1}"), NULL, NULL, error); } @@ -935,15 +873,14 @@ _test_cluster_time_comparison (bool pooled) if (pooled) { /* wait for next heartbeat, it should contain newest cluster time */ - request = mock_server_receives_any_hello_with_match ( - server, - "{'$clusterTime': " - "{'clusterTime': {'$timestamp': " - "{'t': 2, 'i': 2}}}}", + request = mock_server_receives_any_hello_with_match (server, + "{'$clusterTime': " + "{'clusterTime': {'$timestamp': " + "{'t': 2, 'i': 2}}}}", - "{'$clusterTime': " - "{'clusterTime': {'$timestamp': " - "{'t': 2, 'i': 2}}}}"); + "{'$clusterTime': " + "{'clusterTime': {'$timestamp': " + "{'t': 2, 'i': 2}}}}"); replies_with_cluster_time (request, 2, 1, hello); @@ -953,15 +890,14 @@ _test_cluster_time_comparison (bool pooled) /* trigger next heartbeat, it should contain newest cluster time */ _mongoc_usleep (750 * 1000); /* 750 ms */ future = future_ping (client, &error); - request = mock_server_receives_any_hello_with_match ( - server, - "{'$clusterTime': " - "{'clusterTime': {'$timestamp': " - "{'t': 2, 'i': 2}}}}", + request = mock_server_receives_any_hello_with_match (server, + "{'$clusterTime': " + "{'clusterTime': {'$timestamp': " + "{'t': 2, 'i': 2}}}}", - "{'$clusterTime': " - "{'clusterTime': {'$timestamp': " - "{'t': 2, 'i': 2}}}}"); + "{'$clusterTime': " + "{'clusterTime': {'$timestamp': " + "{'t': 2, 'i': 2}}}}"); replies_with_cluster_time (request, 2, 1, hello); request = receives_with_cluster_time (server, 2, 2, ping); @@ -1000,24 +936,21 @@ typedef struct { } test_error_msg_t; -test_error_msg_t errors[] = { - {"not master", true}, - {"not master or secondary", true}, - {"node is recovering", true}, - {"not master and secondaryOk=false", true}, - {"replicatedToNum called but not master anymore", true}, - {"??? node is recovering ???", true}, - {"??? not master ???", true}, - {"foo", false}, - {0}}; +test_error_msg_t errors[] = {{"not master", true}, + {"not master or secondary", true}, + {"node is recovering", true}, + {"not master and secondaryOk=false", true}, + {"replicatedToNum called but not master anymore", true}, + {"??? node is recovering ???", true}, + {"??? not master ???", true}, + {"foo", false}, + {0}}; /* a "not primary" or "node is recovering" error marks server Unknown. "not primary" and "node is recovering" need only be substrings of the error message. */ static void -_test_not_primary (bool pooled, - run_command_fn_t run_command, - cleanup_fn_t cleanup_fn) +_test_not_primary (bool pooled, run_command_fn_t run_command, cleanup_fn_t cleanup_fn) { test_error_msg_t *test_error_msg; mock_server_t *server; @@ -1035,20 +968,17 @@ _test_not_primary (bool pooled, mock_server_run (server); if (pooled) { - pool = test_framework_client_pool_new_from_uri ( - mock_server_get_uri (server), NULL); + pool = test_framework_client_pool_new_from_uri (mock_server_get_uri (server), NULL); client = mongoc_client_pool_pop (pool); } else { - client = test_framework_client_new_from_uri (mock_server_get_uri (server), - NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); } for (test_error_msg = errors; test_error_msg->errmsg; test_error_msg++) { /* * successful command results in known server type */ - future = future_client_command_simple ( - client, "test", tmp_bson (cmd), NULL, NULL, &error); + future = future_client_command_simple (client, "test", tmp_bson (cmd), NULL, NULL, &error); request = mock_server_receives_request (server); reply_to_request_with_ok_and_destroy (request); @@ -1067,8 +997,7 @@ _test_not_primary (bool pooled, future = run_command (client); request = mock_server_receives_request (server); - reply = bson_strdup_printf ("{'ok': 0, 'errmsg': '%s'}", - test_error_msg->errmsg); + reply = bson_strdup_printf ("{'ok': 0, 'errmsg': '%s'}", test_error_msg->errmsg); reply_to_request_simple (request, reply); BSON_ASSERT (!future_get_bool (future)); @@ -1101,8 +1030,7 @@ _test_not_primary (bool pooled, static future_t * future_command_simple (mongoc_client_t *client) { - return future_client_command_simple ( - client, "test", tmp_bson ("{'cmd': 1}"), NULL, NULL, NULL); + return future_client_command_simple (client, "test", tmp_bson ("{'cmd': 1}"), NULL, NULL, NULL); } @@ -1116,16 +1044,14 @@ function_command_simple_cleanup (future_t *future) static void test_not_primary_single (void) { - _test_not_primary ( - false, future_command_simple, function_command_simple_cleanup); + _test_not_primary (false, future_command_simple, function_command_simple_cleanup); } static void test_not_primary_pooled (void) { - _test_not_primary ( - true, future_command_simple, function_command_simple_cleanup); + _test_not_primary (true, future_command_simple, function_command_simple_cleanup); } @@ -1140,24 +1066,20 @@ future_command_private (mongoc_client_t *client) ASSERT (client); - server_stream = mongoc_cluster_stream_for_writes ( - &client->cluster, NULL, NULL, NULL, &error); + server_stream = mongoc_cluster_stream_for_writes (&client->cluster, NULL, NULL, NULL, &error); ASSERT_OR_PRINT (server_stream, error); - mongoc_cmd_parts_init ( - &parts, client, "test", MONGOC_QUERY_NONE, tmp_bson ("{'cmd': 1}")); + mongoc_cmd_parts_init (&parts, client, "test", MONGOC_QUERY_NONE, tmp_bson ("{'cmd': 1}")); /* mongoc_cluster_run_command_parts will call mongoc_cmd_parts_cleanup */ - return future_cluster_run_command_parts ( - &client->cluster, server_stream, &parts, NULL, NULL); + return future_cluster_run_command_parts (&client->cluster, server_stream, &parts, NULL, NULL); } static void future_command_private_cleanup (future_t *future) { - mongoc_server_stream_t *server_stream = - future_value_get_mongoc_server_stream_ptr (future_get_param (future, 1)); + mongoc_server_stream_t *server_stream = future_value_get_mongoc_server_stream_ptr (future_get_param (future, 1)); mongoc_server_stream_cleanup (server_stream); future_destroy (future); } @@ -1166,16 +1088,14 @@ future_command_private_cleanup (future_t *future) static void test_not_primary_auth_single (void) { - _test_not_primary ( - false, future_command_private, future_command_private_cleanup); + _test_not_primary (false, future_command_private, future_command_private_cleanup); } static void test_not_primary_auth_pooled (void) { - _test_not_primary ( - true, future_command_private, future_command_private_cleanup); + _test_not_primary (true, future_command_private, future_command_private_cleanup); } @@ -1207,8 +1127,7 @@ auto_hello_callback (request_t *request, void *data, bson_t *hello_response) BSON_APPEND_UTF8 (hello_response, "setName", "rs"); if (test->cluster_time) { - BSON_APPEND_DOCUMENT_BEGIN ( - hello_response, "$clusterTime", &cluster_time); + BSON_APPEND_DOCUMENT_BEGIN (hello_response, "$clusterTime", &cluster_time); BSON_APPEND_TIMESTAMP (&cluster_time, "clusterTime", 1, 1); bson_append_document_end (hello_response, &cluster_time); } @@ -1237,8 +1156,7 @@ _test_dollar_query (void *ctx) mock_server_auto_hello_callback (server, auto_hello_callback, test, NULL); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); collection = mongoc_client_get_collection (client, "db", "collection"); if (test->secondary) { read_prefs = mongoc_read_prefs_new (MONGOC_READ_SECONDARY); @@ -1246,14 +1164,7 @@ _test_dollar_query (void *ctx) read_prefs = NULL; } - cursor = mongoc_collection_find (collection, - MONGOC_QUERY_NONE, - 0, - 0, - 0, - tmp_bson (test->q), - NULL, - read_prefs); + cursor = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, 0, tmp_bson (test->q), NULL, read_prefs); future = future_cursor_next (cursor, &doc); request = mock_server_receives_msg (server, 0, tmp_bson (test->e)); @@ -1279,113 +1190,112 @@ _test_dollar_query (void *ctx) } -dollar_query_test_t tests[] = { - {"/Cluster/cluster_time/query/", - "{'a': 1}", - "{" - " 'find': 'collection', 'filter': {'a': 1}," - " '$clusterTime': {'$exists': false}" - "}", - false, - false}, - {"/Cluster/cluster_time/query/cluster_time", - "{'a': 1}", - "{" - " 'find': 'collection', 'filter': {'a': 1}," - " '$clusterTime': {'$exists': true}" - "}", - false, - true}, - {"/Cluster/cluster_time/query/secondary", - "{'a': 1}", - "{" - " 'find': 'collection', 'filter': {'a': 1}, " - " '$clusterTime': {'$exists': false}," - " '$readPreference': {'mode': 'secondary'}" - "}", - true, - false}, - {"/Cluster/cluster_time/query/cluster_time_secondary", - "{'a': 1}", - "{" - " 'find': 'collection', 'filter': {'a': 1}, " - " '$clusterTime': {'$exists': true}," - " '$readPreference': {'mode': 'secondary'}" - "}", - true, - true}, - {"/Cluster/cluster_time/dollar_query/from_user", - "{'$query': {'a': 1}}", - "{" - " 'find': 'collection', 'filter': {'a': 1}," - " '$clusterTime': {'$exists': false}" - "}", - false, - false}, - {"/Cluster/cluster_time/dollar_query/from_user/cluster_time", - "{'$query': {'a': 1}}", - "{" - " 'find': 'collection', 'filter': {'a': 1}," - " '$clusterTime': {'$exists': true}" - "}", - false, - true}, - {"/Cluster/cluster_time/dollar_query/from_user/secondary", - "{'$query': {'a': 1}}", - "{" - " 'find': 'collection', 'filter': {'a': 1}," - " '$clusterTime': {'$exists': false}," - " '$readPreference': {'mode': 'secondary'}" - "}", - true, - false}, - {"/Cluster/cluster_time/dollar_query/from_user/cluster_time_secondary", - "{'$query': {'a': 1}}", - "{" - " 'find': 'collection', 'filter': {'a': 1}," - " '$clusterTime': {'$exists': true}," - " '$readPreference': {'mode': 'secondary'}" - "}", - true, - true}, - {"/Cluster/cluster_time/dollar_orderby", - "{'$query': {'a': 1}, '$orderby': {'a': 1}}", - "{" - " 'find': 'collection', 'filter': {'a': 1}," - " 'sort': {'a': 1}" - "}", - false, - false}, - {"/Cluster/cluster_time/dollar_orderby/secondary", - "{'$query': {'a': 1}, '$orderby': {'a': 1}}", - "{" - " 'find': 'collection', 'filter': {'a': 1}," - " 'sort': {'a': 1}," - " '$clusterTime': {'$exists': false}," - " '$readPreference': {'mode': 'secondary'}" - "}", - true, - false}, - {"/Cluster/cluster_time/dollar_orderby/cluster_time", - "{'$query': {'a': 1}, '$orderby': {'a': 1}}", - "{" - " 'find': 'collection', 'filter': {'a': 1}," - " 'sort': {'a': 1}," - " '$clusterTime': {'$exists': true}" - "}", - false, - true}, - {"/Cluster/cluster_time/dollar_orderby/cluster_time_secondary", - "{'$query': {'a': 1}, '$orderby': {'a': 1}}", - "{" - " 'find': 'collection', 'filter': {'a': 1}," - " 'sort': {'a': 1}," - " '$clusterTime': {'$exists': true}," - " '$readPreference': {'mode': 'secondary'}" - "}", - true, - true}, - {NULL}}; +dollar_query_test_t tests[] = {{"/Cluster/cluster_time/query/", + "{'a': 1}", + "{" + " 'find': 'collection', 'filter': {'a': 1}," + " '$clusterTime': {'$exists': false}" + "}", + false, + false}, + {"/Cluster/cluster_time/query/cluster_time", + "{'a': 1}", + "{" + " 'find': 'collection', 'filter': {'a': 1}," + " '$clusterTime': {'$exists': true}" + "}", + false, + true}, + {"/Cluster/cluster_time/query/secondary", + "{'a': 1}", + "{" + " 'find': 'collection', 'filter': {'a': 1}, " + " '$clusterTime': {'$exists': false}," + " '$readPreference': {'mode': 'secondary'}" + "}", + true, + false}, + {"/Cluster/cluster_time/query/cluster_time_secondary", + "{'a': 1}", + "{" + " 'find': 'collection', 'filter': {'a': 1}, " + " '$clusterTime': {'$exists': true}," + " '$readPreference': {'mode': 'secondary'}" + "}", + true, + true}, + {"/Cluster/cluster_time/dollar_query/from_user", + "{'$query': {'a': 1}}", + "{" + " 'find': 'collection', 'filter': {'a': 1}," + " '$clusterTime': {'$exists': false}" + "}", + false, + false}, + {"/Cluster/cluster_time/dollar_query/from_user/cluster_time", + "{'$query': {'a': 1}}", + "{" + " 'find': 'collection', 'filter': {'a': 1}," + " '$clusterTime': {'$exists': true}" + "}", + false, + true}, + {"/Cluster/cluster_time/dollar_query/from_user/secondary", + "{'$query': {'a': 1}}", + "{" + " 'find': 'collection', 'filter': {'a': 1}," + " '$clusterTime': {'$exists': false}," + " '$readPreference': {'mode': 'secondary'}" + "}", + true, + false}, + {"/Cluster/cluster_time/dollar_query/from_user/cluster_time_secondary", + "{'$query': {'a': 1}}", + "{" + " 'find': 'collection', 'filter': {'a': 1}," + " '$clusterTime': {'$exists': true}," + " '$readPreference': {'mode': 'secondary'}" + "}", + true, + true}, + {"/Cluster/cluster_time/dollar_orderby", + "{'$query': {'a': 1}, '$orderby': {'a': 1}}", + "{" + " 'find': 'collection', 'filter': {'a': 1}," + " 'sort': {'a': 1}" + "}", + false, + false}, + {"/Cluster/cluster_time/dollar_orderby/secondary", + "{'$query': {'a': 1}, '$orderby': {'a': 1}}", + "{" + " 'find': 'collection', 'filter': {'a': 1}," + " 'sort': {'a': 1}," + " '$clusterTime': {'$exists': false}," + " '$readPreference': {'mode': 'secondary'}" + "}", + true, + false}, + {"/Cluster/cluster_time/dollar_orderby/cluster_time", + "{'$query': {'a': 1}, '$orderby': {'a': 1}}", + "{" + " 'find': 'collection', 'filter': {'a': 1}," + " 'sort': {'a': 1}," + " '$clusterTime': {'$exists': true}" + "}", + false, + true}, + {"/Cluster/cluster_time/dollar_orderby/cluster_time_secondary", + "{'$query': {'a': 1}, '$orderby': {'a': 1}}", + "{" + " 'find': 'collection', 'filter': {'a': 1}," + " 'sort': {'a': 1}," + " '$clusterTime': {'$exists': true}," + " '$readPreference': {'mode': 'secondary'}" + "}", + true, + true}, + {NULL}}; static void _test_cluster_hello_fails (bool hangup) @@ -1401,8 +1311,7 @@ _test_cluster_hello_fails (bool hangup) int autoresponder_id; mock_server = mock_server_new (); - autoresponder_id = - mock_server_auto_hello (mock_server, "{ 'isWritablePrimary': true }"); + autoresponder_id = mock_server_auto_hello (mock_server, "{ 'isWritablePrimary': true }"); mock_server_run (mock_server); uri = mongoc_uri_copy (mock_server_get_uri (mock_server)); /* increase heartbeatFrequencyMS to prevent background server selection. */ @@ -1418,8 +1327,7 @@ _test_cluster_hello_fails (bool hangup) mongoc_server_description_destroy (sd); mock_server_remove_autoresponder (mock_server, autoresponder_id); /* now create a cluster node by running a command. */ - future = future_client_command_simple ( - client, "test", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); + future = future_client_command_simple (client, "test", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); /* the client adds a cluster node, creating a stream to the server, and then * sends a hello request. */ request = mock_server_receives_any_hello (mock_server); @@ -1431,13 +1339,11 @@ _test_cluster_hello_fails (bool hangup) capture_logs (true); /* suppress "failed to buffer" warning */ reply_to_request_with_hang_up (request); BSON_ASSERT (!future_get_bool (future)); - ASSERT_ERROR_CONTAINS ( - error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "socket err"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "socket err"); } else { reply_to_request_simple (request, "{'ok': 0, 'code': 123}"); BSON_ASSERT (!future_get_bool (future)); - ASSERT_ERROR_CONTAINS ( - error, MONGOC_ERROR_SERVER, 123, "Unknown command error"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_SERVER, 123, "Unknown command error"); } request_destroy (request); @@ -1471,16 +1377,10 @@ test_cluster_command_error (void) server = mock_server_with_auto_hello (WIRE_VERSION_MIN); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); - future = future_client_command_simple (client, - "db", - tmp_bson ("{'ping': 1}"), - NULL /* opts */, - NULL /* read prefs */, - &err); - request = mock_server_receives_msg ( - server, MONGOC_QUERY_NONE, tmp_bson ("{'$db': 'db', 'ping': 1}")); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + future = future_client_command_simple ( + client, "db", tmp_bson ("{'ping': 1}"), NULL /* opts */, NULL /* read prefs */, &err); + request = mock_server_receives_msg (server, MONGOC_QUERY_NONE, tmp_bson ("{'$db': 'db', 'ping': 1}")); reply_to_request_with_hang_up (request); BSON_ASSERT (!future_get_bool (future)); future_destroy (future); @@ -1521,29 +1421,25 @@ test_advanced_cluster_time_not_sent_to_standalone (void) WIRE_VERSION_MIN, WIRE_VERSION_MAX); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); cs = mongoc_client_start_session (client, NULL, &error); ASSERT_OR_PRINT (cs, error); - mongoc_client_session_advance_cluster_time ( - cs, tmp_bson ("{'clusterTime': {'$timestamp': {'t': 1, 'i': 1}}}")); + mongoc_client_session_advance_cluster_time (cs, tmp_bson ("{'clusterTime': {'$timestamp': {'t': 1, 'i': 1}}}")); ASSERT_OR_PRINT (mongoc_client_session_append (cs, &opts, &error), error); collection = mongoc_client_get_collection (client, "db", "collection"); - cursor = mongoc_collection_find_with_opts ( - collection, tmp_bson ("{}"), &opts, NULL); + cursor = mongoc_collection_find_with_opts (collection, tmp_bson ("{}"), &opts, NULL); future = future_cursor_next (cursor, &doc); - request = mock_server_receives_msg ( - server, - 0, - tmp_bson ("{" - " 'find': 'collection', 'filter': {}," - " '$clusterTime': {'$exists': false}" - "}")); + request = mock_server_receives_msg (server, + 0, + tmp_bson ("{" + " 'find': 'collection', 'filter': {}," + " '$clusterTime': {'$exists': false}" + "}")); reply_to_op_msg_request (request, MONGOC_MSG_NONE, tmp_bson ("{'ok': 1," @@ -1590,10 +1486,7 @@ _responder (request_t *req, void *data) } static mongoc_stream_t * -_initiator_fn (const mongoc_uri_t *uri, - const mongoc_host_list_t *host, - void *user_data, - bson_error_t *error) +_initiator_fn (const mongoc_uri_t *uri, const mongoc_host_list_t *host, void *user_data, bson_error_t *error) { mongoc_client_pool_t *pool; mongoc_client_t *client; @@ -1608,14 +1501,10 @@ _initiator_fn (const mongoc_uri_t *uri, /* Hide warnings that get logged from network errors. */ capture_logs (true); - ret = - mongoc_client_command_simple (client, "db", cmd, NULL, NULL, &ss_error); + ret = mongoc_client_command_simple (client, "db", cmd, NULL, NULL, &ss_error); capture_logs (false); BSON_ASSERT (!ret); - ASSERT_ERROR_CONTAINS (ss_error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_SOCKET, - "socket error or timeout"); + ASSERT_ERROR_CONTAINS (ss_error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "socket error or timeout"); stream = mongoc_client_default_stream_initiator (uri, host, client, error); ASSERT_OR_PRINT (stream != NULL, (*error)); mongoc_client_pool_push (pool, client); @@ -1661,8 +1550,7 @@ test_hello_on_unknown (void) /* The other client marked the server as unknown after this client selected * the server and created a stream, but *before* constructing the initial * hello. This reproduces the crash reported in CDRIVER-3404. */ - ret = mongoc_client_command_simple ( - client, "db", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); + ret = mongoc_client_command_simple (client, "db", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); ASSERT_OR_PRINT (ret, error); @@ -1713,22 +1601,13 @@ _test_cmd_on_unknown_serverid (bool pooled) } /* Do the initial topology scan and selection. */ - ret = mongoc_client_command_simple (client, - "admin", - tmp_bson ("{ 'ping': 1 }"), - NULL /* read prefs */, - NULL /* reply */, - &error); + ret = mongoc_client_command_simple ( + client, "admin", tmp_bson ("{ 'ping': 1 }"), NULL /* read prefs */, NULL /* reply */, &error); ASSERT_OR_PRINT (ret, error); - ret = mongoc_client_command_simple_with_server_id (client, - "admin", - tmp_bson ("{'ping': 1}"), - NULL /* read prefs */, - 1, - NULL /* reply */, - &error); + ret = mongoc_client_command_simple_with_server_id ( + client, "admin", tmp_bson ("{'ping': 1}"), NULL /* read prefs */, 1, NULL /* reply */, &error); ASSERT_OR_PRINT (ret, error); /* Invalidate the server, giving it the server type MONGOC_SERVER_UNKNOWN */ @@ -1736,13 +1615,8 @@ _test_cmd_on_unknown_serverid (bool pooled) /* The next command is attempted directly on the unknown server and should * result in an error. */ - ret = mongoc_client_command_simple_with_server_id (client, - "admin", - tmp_bson ("{'ping': 1}"), - NULL /* read prefs */, - 1, - NULL /* reply */, - &error); + ret = mongoc_client_command_simple_with_server_id ( + client, "admin", tmp_bson ("{'ping': 1}"), NULL /* read prefs */, 1, NULL /* reply */, &error); ASSERT_OR_PRINT (ret, error); if (pooled) { @@ -1779,17 +1653,13 @@ test_cluster_stream_invalidation_single (void) client = test_framework_new_default_client (); /* Select a server to start monitoring. */ - sd = mongoc_client_select_server ( - client, true /* for writes */, NULL /* read prefs */, &error); + sd = mongoc_client_select_server (client, true /* for writes */, NULL /* read prefs */, &error); ASSERT_OR_PRINT (sd, error); /* Test "clearing the pool". This should invalidate existing server streams. */ - stream = mongoc_cluster_stream_for_writes (&client->cluster, - NULL /* session */, - NULL /* deprioritized servers */, - NULL /* reply */, - &error); + stream = mongoc_cluster_stream_for_writes ( + &client->cluster, NULL /* session */, NULL /* deprioritized servers */, NULL /* reply */, &error); ASSERT_OR_PRINT (stream, error); BSON_ASSERT (mongoc_cluster_stream_valid (&client->cluster, stream)); tdmod = mc_tpld_modify_begin (client->topology); @@ -1801,11 +1671,8 @@ test_cluster_stream_invalidation_single (void) /* Test closing the connection. This should invalidate existing server * streams. */ - stream = mongoc_cluster_stream_for_writes (&client->cluster, - NULL /* session */, - NULL /* deprioritized servers */, - NULL /* reply */, - &error); + stream = mongoc_cluster_stream_for_writes ( + &client->cluster, NULL /* session */, NULL /* deprioritized servers */, NULL /* reply */, &error); ASSERT_OR_PRINT (stream, error); BSON_ASSERT (mongoc_cluster_stream_valid (&client->cluster, stream)); mongoc_cluster_disconnect_node (&client->cluster, sd->id); @@ -1813,11 +1680,8 @@ test_cluster_stream_invalidation_single (void) mongoc_server_stream_cleanup (stream); /* Test that a new stream is considered valid. */ - stream = mongoc_cluster_stream_for_writes (&client->cluster, - NULL /* session */, - NULL /* deprioritized servers */, - NULL /* reply */, - &error); + stream = mongoc_cluster_stream_for_writes ( + &client->cluster, NULL /* session */, NULL /* deprioritized servers */, NULL /* reply */, &error); ASSERT_OR_PRINT (stream, error); BSON_ASSERT (mongoc_cluster_stream_valid (&client->cluster, stream)); mongoc_server_stream_cleanup (stream); @@ -1840,17 +1704,13 @@ test_cluster_stream_invalidation_pooled (void) pool = test_framework_new_default_client_pool (); client = mongoc_client_pool_pop (pool); /* Select a server. */ - sd = mongoc_client_select_server ( - client, true /* for writes */, NULL /* read prefs */, &error); + sd = mongoc_client_select_server (client, true /* for writes */, NULL /* read prefs */, &error); ASSERT_OR_PRINT (sd, error); /* Test "clearing the pool". This should invalidate existing server streams. */ - stream = mongoc_cluster_stream_for_writes (&client->cluster, - NULL /* session */, - NULL /* deprioritized servers */, - NULL /* reply */, - &error); + stream = mongoc_cluster_stream_for_writes ( + &client->cluster, NULL /* session */, NULL /* deprioritized servers */, NULL /* reply */, &error); ASSERT_OR_PRINT (stream, error); BSON_ASSERT (mongoc_cluster_stream_valid (&client->cluster, stream)); tdmod = mc_tpld_modify_begin (client->topology); @@ -1862,11 +1722,8 @@ test_cluster_stream_invalidation_pooled (void) /* Test closing the connection. This should invalidate existing server * streams. */ - stream = mongoc_cluster_stream_for_writes (&client->cluster, - NULL /* session */, - NULL /* deprioritized servers */, - NULL /* reply */, - &error); + stream = mongoc_cluster_stream_for_writes ( + &client->cluster, NULL /* session */, NULL /* deprioritized servers */, NULL /* reply */, &error); ASSERT_OR_PRINT (stream, error); BSON_ASSERT (mongoc_cluster_stream_valid (&client->cluster, stream)); mongoc_cluster_disconnect_node (&client->cluster, sd->id); @@ -1874,11 +1731,8 @@ test_cluster_stream_invalidation_pooled (void) mongoc_server_stream_cleanup (stream); /* Test that a new stream is considered valid. */ - stream = mongoc_cluster_stream_for_writes (&client->cluster, - NULL /* session */, - NULL /* deprioritized servers */, - NULL /* reply */, - &error); + stream = mongoc_cluster_stream_for_writes ( + &client->cluster, NULL /* session */, NULL /* deprioritized servers */, NULL /* reply */, &error); ASSERT_OR_PRINT (stream, error); BSON_ASSERT (mongoc_cluster_stream_valid (&client->cluster, stream)); mongoc_server_stream_cleanup (stream); @@ -1894,20 +1748,13 @@ test_cluster_install (TestSuite *suite) dollar_query_test_t *p = tests; while (p->name) { - TestSuite_AddFull (suite, - p->name, - _test_dollar_query, - NULL, - p, - TestSuite_CheckMockServerAllowed); + TestSuite_AddFull (suite, p->name, _test_dollar_query, NULL, p, TestSuite_CheckMockServerAllowed); p++; } - TestSuite_AddLive ( - suite, "/Cluster/test_get_max_bson_obj_size", test_get_max_bson_obj_size); - TestSuite_AddLive ( - suite, "/Cluster/test_get_max_msg_size", test_get_max_msg_size); + TestSuite_AddLive (suite, "/Cluster/test_get_max_bson_obj_size", test_get_max_bson_obj_size); + TestSuite_AddLive (suite, "/Cluster/test_get_max_msg_size", test_get_max_msg_size); TestSuite_AddFull (suite, "/Cluster/disconnect/single", test_cluster_node_disconnect_single, @@ -1920,57 +1767,29 @@ test_cluster_install (TestSuite *suite) NULL, NULL, test_framework_skip_if_slow); - TestSuite_AddMockServerTest (suite, - "/Cluster/command/timeout/single", - test_cluster_command_timeout_single); - TestSuite_AddMockServerTest (suite, - "/Cluster/command/timeout/pooled", - test_cluster_command_timeout_pooled); + TestSuite_AddMockServerTest (suite, "/Cluster/command/timeout/single", test_cluster_command_timeout_single); + TestSuite_AddMockServerTest (suite, "/Cluster/command/timeout/pooled", test_cluster_command_timeout_pooled); TestSuite_AddFull (suite, "/Cluster/write_command/disconnect", test_write_command_disconnect, NULL, NULL, test_framework_skip_if_slow); - TestSuite_AddLive (suite, - "/Cluster/cluster_time/command_simple/single", - test_cluster_time_command_simple_single); - TestSuite_AddLive (suite, - "/Cluster/cluster_time/command_simple/pooled", - test_cluster_time_command_simple_pooled); - TestSuite_AddLive (suite, - "/Cluster/cluster_time/command/single", - test_cluster_time_command_single); - TestSuite_AddLive (suite, - "/Cluster/cluster_time/command/pooled", - test_cluster_time_command_pooled); - TestSuite_AddLive (suite, - "/Cluster/cluster_time/command_with_opts/single", - test_cluster_time_command_with_opts_single); - TestSuite_AddLive (suite, - "/Cluster/cluster_time/command_with_opts/pooled", - test_cluster_time_command_with_opts_pooled); - TestSuite_AddLive (suite, - "/Cluster/cluster_time/aggregate/single", - test_cluster_time_aggregate_single); - TestSuite_AddLive (suite, - "/Cluster/cluster_time/aggregate/pooled", - test_cluster_time_aggregate_pooled); - TestSuite_AddLive (suite, - "/Cluster/cluster_time/cursor/single", - test_cluster_time_cursor_single); - TestSuite_AddLive (suite, - "/Cluster/cluster_time/cursor/pooled", - test_cluster_time_cursor_pooled); - TestSuite_AddLive (suite, - "/Cluster/cluster_time/insert/single", - test_cluster_time_insert_single); - TestSuite_AddLive (suite, - "/Cluster/cluster_time/insert/pooled", - test_cluster_time_insert_pooled); - TestSuite_AddLive (suite, - "/Cluster/command/timeout/negative", - test_cluster_command_timeout_negative); + TestSuite_AddLive (suite, "/Cluster/cluster_time/command_simple/single", test_cluster_time_command_simple_single); + TestSuite_AddLive (suite, "/Cluster/cluster_time/command_simple/pooled", test_cluster_time_command_simple_pooled); + TestSuite_AddLive (suite, "/Cluster/cluster_time/command/single", test_cluster_time_command_single); + TestSuite_AddLive (suite, "/Cluster/cluster_time/command/pooled", test_cluster_time_command_pooled); + TestSuite_AddLive ( + suite, "/Cluster/cluster_time/command_with_opts/single", test_cluster_time_command_with_opts_single); + TestSuite_AddLive ( + suite, "/Cluster/cluster_time/command_with_opts/pooled", test_cluster_time_command_with_opts_pooled); + TestSuite_AddLive (suite, "/Cluster/cluster_time/aggregate/single", test_cluster_time_aggregate_single); + TestSuite_AddLive (suite, "/Cluster/cluster_time/aggregate/pooled", test_cluster_time_aggregate_pooled); + TestSuite_AddLive (suite, "/Cluster/cluster_time/cursor/single", test_cluster_time_cursor_single); + TestSuite_AddLive (suite, "/Cluster/cluster_time/cursor/pooled", test_cluster_time_cursor_pooled); + TestSuite_AddLive (suite, "/Cluster/cluster_time/insert/single", test_cluster_time_insert_single); + TestSuite_AddLive (suite, "/Cluster/cluster_time/insert/pooled", test_cluster_time_insert_pooled); + TestSuite_AddLive (suite, "/Cluster/command/timeout/negative", test_cluster_command_timeout_negative); TestSuite_AddMockServerTest (suite, "/Cluster/cluster_time/comparison/single", test_cluster_time_comparison_single, @@ -1979,35 +1798,22 @@ test_cluster_install (TestSuite *suite) "/Cluster/cluster_time/comparison/pooled", test_cluster_time_comparison_pooled, test_framework_skip_if_slow); - TestSuite_AddMockServerTest ( - suite, - "/Cluster/cluster_time/advanced_not_sent_to_standalone", - test_advanced_cluster_time_not_sent_to_standalone, - test_framework_skip_if_no_crypto); - TestSuite_AddMockServerTest (suite, - "/Cluster/not_primary/single", - test_not_primary_single, - test_framework_skip_if_slow); TestSuite_AddMockServerTest (suite, - "/Cluster/not_primary/pooled", - test_not_primary_pooled, - test_framework_skip_if_slow); - TestSuite_AddMockServerTest (suite, - "/Cluster/not_primary_auth/single", - test_not_primary_auth_single, - test_framework_skip_if_slow); - TestSuite_AddMockServerTest (suite, - "/Cluster/not_primary_auth/pooled", - test_not_primary_auth_pooled, - test_framework_skip_if_slow); + "/Cluster/cluster_time/advanced_not_sent_to_standalone", + test_advanced_cluster_time_not_sent_to_standalone, + test_framework_skip_if_no_crypto); TestSuite_AddMockServerTest ( - suite, "/Cluster/hello_fails", test_cluster_hello_fails); + suite, "/Cluster/not_primary/single", test_not_primary_single, test_framework_skip_if_slow); TestSuite_AddMockServerTest ( - suite, "/Cluster/hello_hangup", test_cluster_hello_hangup); + suite, "/Cluster/not_primary/pooled", test_not_primary_pooled, test_framework_skip_if_slow); TestSuite_AddMockServerTest ( - suite, "/Cluster/command_error/op_msg", test_cluster_command_error); + suite, "/Cluster/not_primary_auth/single", test_not_primary_auth_single, test_framework_skip_if_slow); TestSuite_AddMockServerTest ( - suite, "/Cluster/hello_on_unknown/mock", test_hello_on_unknown); + suite, "/Cluster/not_primary_auth/pooled", test_not_primary_auth_pooled, test_framework_skip_if_slow); + TestSuite_AddMockServerTest (suite, "/Cluster/hello_fails", test_cluster_hello_fails); + TestSuite_AddMockServerTest (suite, "/Cluster/hello_hangup", test_cluster_hello_hangup); + TestSuite_AddMockServerTest (suite, "/Cluster/command_error/op_msg", test_cluster_command_error); + TestSuite_AddMockServerTest (suite, "/Cluster/hello_on_unknown/mock", test_hello_on_unknown); /* These tests exhibit some mysterious behavior after the new feature changes-- see: "https://jira.mongodb.org/browse/CDRIVER-4293". TestSuite_AddLive (suite, @@ -2017,10 +1823,6 @@ test_cluster_install (TestSuite *suite) "/Cluster/cmd_on_unknown_serverid/single", test_cmd_on_unknown_serverid_single); */ - TestSuite_AddLive (suite, - "/Cluster/stream_invalidation/single", - test_cluster_stream_invalidation_single); - TestSuite_AddLive (suite, - "/Cluster/stream_invalidation/pooled", - test_cluster_stream_invalidation_pooled); + TestSuite_AddLive (suite, "/Cluster/stream_invalidation/single", test_cluster_stream_invalidation_single); + TestSuite_AddLive (suite, "/Cluster/stream_invalidation/pooled", test_cluster_stream_invalidation_pooled); } diff --git a/src/libmongoc/tests/test-mongoc-cmd.c b/src/libmongoc/tests/test-mongoc-cmd.c index 2e8da5e73e..2e80a1fa44 100644 --- a/src/libmongoc/tests/test-mongoc-cmd.c +++ b/src/libmongoc/tests/test-mongoc-cmd.c @@ -44,8 +44,7 @@ test_client_cmd_options (void) server = mock_server_with_auto_hello (WIRE_VERSION_MAX); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); rc = mongoc_read_concern_new (); mongoc_read_concern_set_level (rc, MONGOC_READ_CONCERN_LEVEL_MAJORITY); @@ -53,18 +52,9 @@ test_client_cmd_options (void) mongoc_read_concern_append (rc, &opts); future = - future_client_command_with_opts (client, - "db", - tmp_bson ("{'ping': 1, '$db': 'db'}"), - NULL, - &opts, - NULL, - &error); + future_client_command_with_opts (client, "db", tmp_bson ("{'ping': 1, '$db': 'db'}"), NULL, &opts, NULL, &error); - request = mock_server_receives_msg ( - server, - MONGOC_QUERY_NONE, - tmp_bson ("{'readConcern': { '$exists': true }}")); + request = mock_server_receives_msg (server, MONGOC_QUERY_NONE, tmp_bson ("{'readConcern': { '$exists': true }}")); reply_to_request_simple (request, "{'ok': 1, 'n': 1}"); ASSERT_OR_PRINT (future_get_bool (future), error); @@ -82,6 +72,5 @@ test_client_cmd_options (void) void test_client_cmd_install (TestSuite *suite) { - TestSuite_AddMockServerTest ( - suite, "/Client/cmd/options", test_client_cmd_options); + TestSuite_AddMockServerTest (suite, "/Client/cmd/options", test_client_cmd_options); } diff --git a/src/libmongoc/tests/test-mongoc-collection-find-with-opts.c b/src/libmongoc/tests/test-mongoc-collection-find-with-opts.c index 6e68afef8c..a6be20cd1b 100644 --- a/src/libmongoc/tests/test-mongoc-collection-find-with-opts.c +++ b/src/libmongoc/tests/test-mongoc-collection-find-with-opts.c @@ -50,18 +50,14 @@ _test_collection_find_command (test_collection_find_with_opts_t *test_data) server = mock_server_with_auto_hello (WIRE_VERSION_MIN); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); collection = mongoc_client_get_collection (client, "db", "collection"); - cursor = mongoc_collection_find_with_opts (collection, - test_data->filter_bson, - test_data->opts_bson, - test_data->read_prefs); + cursor = mongoc_collection_find_with_opts ( + collection, test_data->filter_bson, test_data->opts_bson, test_data->read_prefs); ASSERT_OR_PRINT (!mongoc_cursor_error (cursor, &error), error); future = future_cursor_next (cursor, &doc); - request = mock_server_receives_msg ( - server, MONGOC_MSG_NONE, tmp_bson (test_data->expected_find_command)); + request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson (test_data->expected_find_command)); ASSERT (request); reply_to_request_simple (request, "{'ok': 1," @@ -98,8 +94,7 @@ test_dollar_or (void) test_collection_find_with_opts_t test_data = {0}; test_data.filter = "{'$or': [{'_id': 1}]}"; - test_data.expected_find_command = - "{'find': 'collection', 'filter': {'$or': [{'_id': 1}]}}"; + test_data.expected_find_command = "{'find': 'collection', 'filter': {'$or': [{'_id': 1}]}}"; _test_collection_find_with_opts (&test_data); } @@ -116,9 +111,8 @@ test_snapshot_dollar_or (void) test_data.filter = "{'$or': [{'_id': 1}]}"; test_data.opts = "{'snapshot': true}"; - test_data.expected_find_command = - "{'find': 'collection', 'filter': {'$or': [{'_id': 1}]}," - " 'snapshot': true}"; + test_data.expected_find_command = "{'find': 'collection', 'filter': {'$or': [{'_id': 1}]}," + " 'snapshot': true}"; _test_collection_find_with_opts (&test_data); } @@ -131,8 +125,7 @@ test_key_named_filter (void) test_collection_find_with_opts_t test_data = {0}; test_data.filter = "{'filter': 2}"; - test_data.expected_find_command = - "{'find': 'collection', 'filter': {'filter': 2}}"; + test_data.expected_find_command = "{'find': 'collection', 'filter': {'filter': 2}}"; _test_collection_find_with_opts (&test_data); } @@ -144,8 +137,7 @@ test_op_query_subdoc_named_filter (void) test_collection_find_with_opts_t test_data = {0}; test_data.filter = "{'filter': {'i': 2}}"; - test_data.expected_find_command = - "{'find': 'collection', 'filter': {'filter': {'i': 2}}}"; + test_data.expected_find_command = "{'find': 'collection', 'filter': {'filter': {'i': 2}}}"; _test_collection_find_with_opts (&test_data); } @@ -161,9 +153,8 @@ test_find_cmd_subdoc_named_filter_with_option (void) test_data.filter = "{'filter': {'i': 2}}"; test_data.opts = "{'snapshot': true}"; - test_data.expected_find_command = - "{'find': 'collection', 'filter': {'filter': {'i': 2}}, " - " 'snapshot': true}"; + test_data.expected_find_command = "{'find': 'collection', 'filter': {'filter': {'i': 2}}, " + " 'snapshot': true}"; _test_collection_find_with_opts (&test_data); } @@ -176,8 +167,7 @@ test_newoption (void) test_data.filter = "{'_id': 1}"; test_data.opts = "{'newOption': true}"; - test_data.expected_find_command = - "{'find': 'collection', 'filter': {'_id': 1}, 'newOption': true}"; + test_data.expected_find_command = "{'find': 'collection', 'filter': {'_id': 1}, 'newOption': true}"; _test_collection_find_with_opts (&test_data); } @@ -189,8 +179,7 @@ test_sort (void) test_collection_find_with_opts_t test_data = {0}; test_data.opts = "{'sort': {'_id': -1}}"; - test_data.expected_find_command = - "{'find': 'collection', 'filter': {}, 'sort': {'_id': -1}}"; + test_data.expected_find_command = "{'find': 'collection', 'filter': {}, 'sort': {'_id': -1}}"; _test_collection_find_with_opts (&test_data); } @@ -201,8 +190,7 @@ test_fields (void) test_collection_find_with_opts_t test_data = {0}; test_data.opts = "{'projection': {'_id': 0, 'b': 1}}"; - test_data.expected_find_command = - "{'find': 'collection', 'filter': {}, 'projection': {'_id': 0, 'b': 1}}"; + test_data.expected_find_command = "{'find': 'collection', 'filter': {}, 'projection': {'_id': 0, 'b': 1}}"; _test_collection_find_with_opts (&test_data); } @@ -213,10 +201,9 @@ test_slice (void) test_collection_find_with_opts_t test_data = {0}; test_data.opts = "{'projection': {'array': {'$slice': 10}}}"; - test_data.expected_find_command = - "{'find': 'collection', " - " 'filter': {}," - " 'projection': {'array': {'$slice': 10}}}"; + test_data.expected_find_command = "{'find': 'collection', " + " 'filter': {}," + " 'projection': {'array': {'$slice': 10}}}"; _test_collection_find_with_opts (&test_data); } @@ -274,8 +261,7 @@ test_index_spec_modifiers (void) opts = bson_strdup_printf ("{'%s': {'_id': 1}}", mod); /* find command options have no $-prefix: hint, min, max */ - find_command = bson_strdup_printf ( - "{'find': 'collection', 'filter': {}, '%s': {'_id': 1}}", mod); + find_command = bson_strdup_printf ("{'find': 'collection', 'filter': {}, '%s': {'_id': 1}}", mod); test_data.opts = opts; test_data.expected_find_command = find_command; @@ -293,8 +279,7 @@ test_comment (void) test_collection_find_with_opts_t test_data = {0}; test_data.opts = "{'comment': 'COMMENT'}"; - test_data.expected_find_command = - "{'find': 'collection', 'filter': {}, 'comment': 'COMMENT'}"; + test_data.expected_find_command = "{'find': 'collection', 'filter': {}, 'comment': 'COMMENT'}"; _test_collection_find_with_opts (&test_data); } @@ -305,8 +290,7 @@ test_snapshot (void) test_collection_find_with_opts_t test_data = {0}; test_data.opts = "{'snapshot': true}"; - test_data.expected_find_command = - "{'find': 'collection', 'filter': {}, 'snapshot': true}"; + test_data.expected_find_command = "{'find': 'collection', 'filter': {}, 'snapshot': true}"; _test_collection_find_with_opts (&test_data); } @@ -318,8 +302,7 @@ test_diskloc (void) test_collection_find_with_opts_t test_data = {0}; test_data.opts = "{'showRecordId': true}"; - test_data.expected_find_command = - "{'find': 'collection', 'filter': {}, 'showRecordId': true}"; + test_data.expected_find_command = "{'find': 'collection', 'filter': {}, 'showRecordId': true}"; _test_collection_find_with_opts (&test_data); } @@ -330,8 +313,7 @@ test_returnkey (void) test_collection_find_with_opts_t test_data = {0}; test_data.opts = "{'returnKey': true}"; - test_data.expected_find_command = - "{'find': 'collection', 'filter': {}, 'returnKey': true}"; + test_data.expected_find_command = "{'find': 'collection', 'filter': {}, 'returnKey': true}"; _test_collection_find_with_opts (&test_data); } @@ -343,8 +325,7 @@ test_skip (void) test_data.expected_skip = 1; test_data.opts = "{'skip': {'$numberLong': '1'}}"; - test_data.expected_find_command = - "{'find': 'collection', 'filter': {}, 'skip': {'$numberLong': '1'}}"; + test_data.expected_find_command = "{'find': 'collection', 'filter': {}, 'skip': {'$numberLong': '1'}}"; _test_collection_find_with_opts (&test_data); } @@ -356,8 +337,7 @@ test_batch_size (void) test_data.opts = "{'batchSize': {'$numberLong': '2'}}"; test_data.expected_n_return = 2; - test_data.expected_find_command = - "{'find': 'collection', 'filter': {}, 'batchSize': {'$numberLong': '2'}}"; + test_data.expected_find_command = "{'find': 'collection', 'filter': {}, 'batchSize': {'$numberLong': '2'}}"; _test_collection_find_with_opts (&test_data); } @@ -369,8 +349,7 @@ test_limit (void) test_data.opts = "{'limit': {'$numberLong': '2'}}"; test_data.expected_n_return = 2; - test_data.expected_find_command = - "{'find': 'collection', 'filter': {}, 'limit': {'$numberLong': '2'}}"; + test_data.expected_find_command = "{'find': 'collection', 'filter': {}, 'limit': {'$numberLong': '2'}}"; _test_collection_find_with_opts (&test_data); } @@ -382,9 +361,8 @@ test_singlebatch (void) test_data.opts = "{'limit': {'$numberLong': '2'}, 'singleBatch': true}"; test_data.expected_n_return = -2; - test_data.expected_find_command = - "{'find': 'collection', 'filter': {}, " - " 'singleBatch': true, 'limit': {'$numberLong': '2'}}"; + test_data.expected_find_command = "{'find': 'collection', 'filter': {}, " + " 'singleBatch': true, 'limit': {'$numberLong': '2'}}"; _test_collection_find_with_opts (&test_data); } @@ -397,8 +375,7 @@ test_singlebatch_no_limit (void) test_data.opts = "{'singleBatch': true}"; /* singleBatch doesn't affect OP_QUERY with limit 0, nToReturn is still 0 */ test_data.expected_n_return = 0; - test_data.expected_find_command = - "{'find': 'collection', 'filter': {}, 'singleBatch': true}"; + test_data.expected_find_command = "{'find': 'collection', 'filter': {}, 'singleBatch': true}"; _test_collection_find_with_opts (&test_data); } @@ -410,8 +387,7 @@ test_unrecognized_dollar_option (void) test_collection_find_with_opts_t test_data = {0}; test_data.opts = "{'dumb': 1}"; - test_data.expected_find_command = - "{'find': 'collection', 'filter': {}, 'dumb': 1}"; + test_data.expected_find_command = "{'find': 'collection', 'filter': {}, 'dumb': 1}"; _test_collection_find_with_opts (&test_data); } @@ -436,14 +412,12 @@ test_query_flags (void) {MONGOC_QUERY_OPLOG_REPLAY, "'oplogReplay': true"}, {MONGOC_QUERY_NO_CURSOR_TIMEOUT, "'noCursorTimeout': true"}, {MONGOC_QUERY_PARTIAL, "'allowPartialResults': true"}, - {MONGOC_QUERY_TAILABLE_CURSOR | MONGOC_QUERY_AWAIT_DATA, - "'tailable': true, 'awaitData': true"}, + {MONGOC_QUERY_TAILABLE_CURSOR | MONGOC_QUERY_AWAIT_DATA, "'tailable': true, 'awaitData': true"}, }; for (i = 0; i < (sizeof flags_and_frags) / (sizeof (flag_and_name_t)); i++) { opts = bson_strdup_printf ("{%s}", flags_and_frags[i].json_fragment); - find_cmd = bson_strdup_printf ("{'find': 'collection', 'filter': {}, %s}", - flags_and_frags[i].json_fragment); + find_cmd = bson_strdup_printf ("{'find': 'collection', 'filter': {}, %s}", flags_and_frags[i].json_fragment); test_data.opts = opts; test_data.expected_flags = flags_and_frags[i].flag; @@ -471,11 +445,9 @@ test_exhaust (void) server = mock_server_with_auto_hello (WIRE_VERSION_MIN); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); collection = mongoc_client_get_collection (client, "db", "collection"); - cursor = mongoc_collection_find_with_opts ( - collection, tmp_bson (NULL), tmp_bson ("{'exhaust': true}"), NULL); + cursor = mongoc_collection_find_with_opts (collection, tmp_bson (NULL), tmp_bson ("{'exhaust': true}"), NULL); future = future_cursor_next (cursor, &doc); @@ -484,13 +456,8 @@ test_exhaust (void) * fallback to existing OP_QUERY wire protocol messages." */ request = mock_server_receives_request (server); - reply_to_find_request (request, - MONGOC_QUERY_SECONDARY_OK | MONGOC_QUERY_EXHAUST, - 0, - 0, - "db.collection", - "{}", - false /* is_command */); + reply_to_find_request ( + request, MONGOC_QUERY_SECONDARY_OK | MONGOC_QUERY_EXHAUST, 0, 0, "db.collection", "{}", false /* is_command */); ASSERT (future_get_bool (future)); ASSERT_OR_PRINT (!mongoc_cursor_error (cursor, &error), error); @@ -525,21 +492,18 @@ test_getmore_cmd_await (void) */ server = mock_server_with_auto_hello (WIRE_VERSION_MIN); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); collection = mongoc_client_get_collection (client, "db", "collection"); - cursor = mongoc_collection_find_with_opts ( - collection, tmp_bson (NULL), opts, NULL); + cursor = mongoc_collection_find_with_opts (collection, tmp_bson (NULL), opts, NULL); future = future_cursor_next (cursor, &doc); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db'," - " 'find': 'collection'," - " 'filter': {}," - " 'maxTimeMS': {'$exists': false}," - " 'maxAwaitTimeMS': {'$exists': false}}")); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'db'," + " 'find': 'collection'," + " 'filter': {}," + " 'maxTimeMS': {'$exists': false}," + " 'maxAwaitTimeMS': {'$exists': false}}")); ASSERT (request); reply_to_request_simple (request, @@ -557,14 +521,13 @@ test_getmore_cmd_await (void) * "getMore" command */ future = future_cursor_next (cursor, &doc); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db'," - " 'getMore': {'$numberLong': '123'}," - " 'collection': 'collection'," - " 'maxAwaitTimeMS': {'$exists': false}," - " 'maxTimeMS': {'$numberLong': '9999'}}")); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'db'," + " 'getMore': {'$numberLong': '123'}," + " 'collection': 'collection'," + " 'maxAwaitTimeMS': {'$exists': false}," + " 'maxTimeMS': {'$numberLong': '9999'}}")); ASSERT (request); reply_to_request_simple (request, @@ -597,10 +560,8 @@ test_find_w_server_id (void) future_t *future; request_t *request; - rs = mock_rs_with_auto_hello (WIRE_VERSION_MIN /* wire version */, - true /* has primary */, - 1 /* secondary */, - 0 /* arbiters */); + rs = mock_rs_with_auto_hello ( + WIRE_VERSION_MIN /* wire version */, true /* has primary */, 1 /* secondary */, 0 /* arbiters */); mock_rs_run (rs); client = test_framework_client_new_from_uri (mock_rs_get_uri (rs), NULL); @@ -608,17 +569,15 @@ test_find_w_server_id (void) /* use serverId instead of prefs to select the secondary */ opts = tmp_bson ("{'serverId': 2}"); - cursor = mongoc_collection_find_with_opts ( - collection, tmp_bson (NULL), opts, NULL); + cursor = mongoc_collection_find_with_opts (collection, tmp_bson (NULL), opts, NULL); future = future_cursor_next (cursor, &doc); - request = mock_rs_receives_msg ( - rs, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db'," - " 'find': 'collection'," - " 'filter': {}," - " '$readPreference': {'mode': 'primaryPreferred'}}")); + request = mock_rs_receives_msg (rs, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'db'," + " 'find': 'collection'," + " 'filter': {}," + " '$readPreference': {'mode': 'primaryPreferred'}}")); ASSERT (mock_rs_request_is_to_secondary (rs, request)); reply_to_request_simple (request, @@ -650,10 +609,7 @@ test_find_cmd_w_server_id (void) request_t *request; bson_error_t error; - rs = mock_rs_with_auto_hello (WIRE_VERSION_MIN, - true /* has primary */, - 1 /* secondary */, - 0 /* arbiters */); + rs = mock_rs_with_auto_hello (WIRE_VERSION_MIN, true /* has primary */, 1 /* secondary */, 0 /* arbiters */); mock_rs_run (rs); client = test_framework_client_new_from_uri (mock_rs_get_uri (rs), NULL); @@ -661,20 +617,18 @@ test_find_cmd_w_server_id (void) /* use serverId instead of prefs to select the secondary */ opts = tmp_bson ("{'serverId': 2, 'readConcern': {'level': 'local'}}"); - cursor = mongoc_collection_find_with_opts ( - collection, tmp_bson (NULL), opts, NULL); + cursor = mongoc_collection_find_with_opts (collection, tmp_bson (NULL), opts, NULL); future = future_cursor_next (cursor, &doc); /* recognized that wire version is recent enough for readConcern */ - request = - mock_rs_receives_msg (rs, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db'," - " 'find': 'collection', " - " 'filter': {}," - " 'readConcern': {'level': 'local'}," - " 'serverId': {'$exists': false}}")); + request = mock_rs_receives_msg (rs, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'db'," + " 'find': 'collection', " + " 'filter': {}," + " 'readConcern': {'level': 'local'}," + " 'serverId': {'$exists': false}}")); ASSERT (mock_rs_request_is_to_secondary (rs, request)); reply_to_request_simple (request, @@ -711,24 +665,21 @@ test_find_w_server_id_sharded (void) server = mock_mongos_new (WIRE_VERSION_MIN); mock_server_run (server); mock_server_auto_endsessions (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); collection = mongoc_client_get_collection (client, "db", "collection"); opts = tmp_bson ("{'serverId': 1}"); - cursor = mongoc_collection_find_with_opts ( - collection, tmp_bson (NULL), opts, NULL); + cursor = mongoc_collection_find_with_opts (collection, tmp_bson (NULL), opts, NULL); future = future_cursor_next (cursor, &doc); /* Does NOT set '$readPreference', since this is a sharded topology. */ - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db'," - " 'find': 'collection'," - " 'filter': {}," - " '$readPreference': {'$exists': false}}")); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'db'," + " 'find': 'collection'," + " 'filter': {}," + " '$readPreference': {'$exists': false}}")); reply_to_request_simple (request, "{'ok': 1," @@ -763,25 +714,22 @@ test_find_cmd_w_server_id_sharded (void) server = mock_mongos_new (WIRE_VERSION_MIN); mock_server_run (server); mock_server_auto_endsessions (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); collection = mongoc_client_get_collection (client, "db", "collection"); opts = tmp_bson ("{'serverId': 1, 'readConcern': {'level': 'local'}}"); - cursor = mongoc_collection_find_with_opts ( - collection, tmp_bson (NULL), opts, NULL); + cursor = mongoc_collection_find_with_opts (collection, tmp_bson (NULL), opts, NULL); future = future_cursor_next (cursor, &doc); /* recognized that wire version is recent enough for readConcern */ - request = - mock_server_receives_msg (server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db'," - " 'find': 'collection', " - " 'filter': {}," - " 'readConcern': {'level': 'local'}," - " 'serverId': {'$exists': false}}")); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'db'," + " 'find': 'collection', " + " 'filter': {}," + " 'readConcern': {'level': 'local'}," + " 'serverId': {'$exists': false}}")); reply_to_request_simple (request, "{'ok': 1," @@ -812,26 +760,17 @@ test_server_id_option (void) client = test_framework_new_default_client (); collection = mongoc_client_get_collection (client, "db", "collection"); q = tmp_bson (NULL); - cursor = mongoc_collection_find_with_opts ( - collection, q, tmp_bson ("{'serverId': 'foo'}"), NULL); + cursor = mongoc_collection_find_with_opts (collection, q, tmp_bson ("{'serverId': 'foo'}"), NULL); - ASSERT_ERROR_CONTAINS (cursor->error, - MONGOC_ERROR_CURSOR, - MONGOC_ERROR_CURSOR_INVALID_CURSOR, - "must be an integer"); + ASSERT_ERROR_CONTAINS (cursor->error, MONGOC_ERROR_CURSOR, MONGOC_ERROR_CURSOR_INVALID_CURSOR, "must be an integer"); mongoc_cursor_destroy (cursor); - cursor = mongoc_collection_find_with_opts ( - collection, q, tmp_bson ("{'serverId': 0}"), NULL); + cursor = mongoc_collection_find_with_opts (collection, q, tmp_bson ("{'serverId': 0}"), NULL); - ASSERT_ERROR_CONTAINS (cursor->error, - MONGOC_ERROR_CURSOR, - MONGOC_ERROR_CURSOR_INVALID_CURSOR, - "must be >= 1"); + ASSERT_ERROR_CONTAINS (cursor->error, MONGOC_ERROR_CURSOR, MONGOC_ERROR_CURSOR_INVALID_CURSOR, "must be >= 1"); mongoc_cursor_destroy (cursor); - cursor = mongoc_collection_find_with_opts ( - collection, q, tmp_bson ("{'serverId': 1}"), NULL); + cursor = mongoc_collection_find_with_opts (collection, q, tmp_bson ("{'serverId': 1}"), NULL); ASSERT_OR_PRINT (!mongoc_cursor_error (cursor, &error), error); @@ -854,10 +793,7 @@ test_find_batchSize (void) // Test a cursor with an int32 batchSize. { cursor = mongoc_collection_find_with_opts ( - collection, - tmp_bson ("{}"), - tmp_bson ("{'batchSize': { '$numberInt': '1' }}"), - NULL); + collection, tmp_bson ("{}"), tmp_bson ("{'batchSize': { '$numberInt': '1' }}"), NULL); ASSERT_OR_PRINT (!mongoc_cursor_error (cursor, &error), error); @@ -877,10 +813,7 @@ test_find_batchSize (void) // Test a cursor with an int64 batchSize. { cursor = mongoc_collection_find_with_opts ( - collection, - tmp_bson ("{}"), - tmp_bson ("{'batchSize': { '$numberLong': '1' }}"), - NULL); + collection, tmp_bson ("{}"), tmp_bson ("{'batchSize': { '$numberLong': '1' }}"), NULL); ASSERT_OR_PRINT (!mongoc_cursor_error (cursor, &error), error); @@ -899,8 +832,7 @@ test_find_batchSize (void) // Test a cursor with a string batchSize. { - cursor = mongoc_collection_find_with_opts ( - collection, tmp_bson ("{}"), tmp_bson ("{'batchSize': 'foo'}"), NULL); + cursor = mongoc_collection_find_with_opts (collection, tmp_bson ("{}"), tmp_bson ("{'batchSize': 'foo'}"), NULL); ASSERT_OR_PRINT (!mongoc_cursor_error (cursor, &error), error); @@ -925,82 +857,38 @@ test_find_batchSize (void) void test_collection_find_with_opts_install (TestSuite *suite) { + TestSuite_AddMockServerTest (suite, "/Collection/find_with_opts/dollar_or", test_dollar_or); + TestSuite_AddMockServerTest (suite, "/Collection/find_with_opts/snapshot_dollar_or", test_snapshot_dollar_or); + TestSuite_AddMockServerTest (suite, "/Collection/find_with_opts/key_named_filter", test_key_named_filter); TestSuite_AddMockServerTest ( - suite, "/Collection/find_with_opts/dollar_or", test_dollar_or); - TestSuite_AddMockServerTest (suite, - "/Collection/find_with_opts/snapshot_dollar_or", - test_snapshot_dollar_or); - TestSuite_AddMockServerTest (suite, - "/Collection/find_with_opts/key_named_filter", - test_key_named_filter); - TestSuite_AddMockServerTest ( - suite, - "/Collection/find_with_opts/query/subdoc_named_filter", - test_op_query_subdoc_named_filter); - TestSuite_AddMockServerTest ( - suite, "/Collection/find_with_opts/newoption", test_newoption); - TestSuite_AddMockServerTest ( - suite, - "/Collection/find_with_opts/cmd/subdoc_named_filter", - test_find_cmd_subdoc_named_filter_with_option); - TestSuite_AddMockServerTest ( - suite, "/Collection/find_with_opts/orderby", test_sort); - TestSuite_AddMockServerTest ( - suite, "/Collection/find_with_opts/fields", test_fields); - TestSuite_AddMockServerTest ( - suite, "/Collection/find_with_opts/slice", test_slice); - TestSuite_AddMockServerTest (suite, - "/Collection/find_with_opts/modifiers/integer", - test_int_modifiers); - TestSuite_AddMockServerTest ( - suite, - "/Collection/find_with_opts/modifiers/index_spec", - test_index_spec_modifiers); - TestSuite_AddMockServerTest ( - suite, "/Collection/find_with_opts/comment", test_comment); - TestSuite_AddMockServerTest ( - suite, "/Collection/find_with_opts/modifiers/bool", test_snapshot); - TestSuite_AddMockServerTest ( - suite, "/Collection/find_with_opts/showdiskloc", test_diskloc); - TestSuite_AddMockServerTest ( - suite, "/Collection/find_with_opts/returnkey", test_returnkey); - TestSuite_AddMockServerTest ( - suite, "/Collection/find_with_opts/skip", test_skip); - TestSuite_AddMockServerTest ( - suite, "/Collection/find_with_opts/batch_size", test_batch_size); - TestSuite_AddMockServerTest ( - suite, "/Collection/find_with_opts/limit", test_limit); - TestSuite_AddMockServerTest ( - suite, "/Collection/find_with_opts/singlebatch", test_singlebatch); - TestSuite_AddMockServerTest ( - suite, - "/Collection/find_with_opts/singlebatch/no_limit", - test_singlebatch_no_limit); - TestSuite_AddMockServerTest ( - suite, - "/Collection/find_with_opts/unrecognized_dollar", - test_unrecognized_dollar_option); - TestSuite_AddMockServerTest ( - suite, "/Collection/find_with_opts/flags", test_query_flags); + suite, "/Collection/find_with_opts/query/subdoc_named_filter", test_op_query_subdoc_named_filter); + TestSuite_AddMockServerTest (suite, "/Collection/find_with_opts/newoption", test_newoption); TestSuite_AddMockServerTest ( - suite, "/Collection/find_with_opts/exhaust", test_exhaust); - TestSuite_AddMockServerTest (suite, - "/Collection/find_with_opts/await/getmore_cmd", - test_getmore_cmd_await); + suite, "/Collection/find_with_opts/cmd/subdoc_named_filter", test_find_cmd_subdoc_named_filter_with_option); + TestSuite_AddMockServerTest (suite, "/Collection/find_with_opts/orderby", test_sort); + TestSuite_AddMockServerTest (suite, "/Collection/find_with_opts/fields", test_fields); + TestSuite_AddMockServerTest (suite, "/Collection/find_with_opts/slice", test_slice); + TestSuite_AddMockServerTest (suite, "/Collection/find_with_opts/modifiers/integer", test_int_modifiers); + TestSuite_AddMockServerTest (suite, "/Collection/find_with_opts/modifiers/index_spec", test_index_spec_modifiers); + TestSuite_AddMockServerTest (suite, "/Collection/find_with_opts/comment", test_comment); + TestSuite_AddMockServerTest (suite, "/Collection/find_with_opts/modifiers/bool", test_snapshot); + TestSuite_AddMockServerTest (suite, "/Collection/find_with_opts/showdiskloc", test_diskloc); + TestSuite_AddMockServerTest (suite, "/Collection/find_with_opts/returnkey", test_returnkey); + TestSuite_AddMockServerTest (suite, "/Collection/find_with_opts/skip", test_skip); + TestSuite_AddMockServerTest (suite, "/Collection/find_with_opts/batch_size", test_batch_size); + TestSuite_AddMockServerTest (suite, "/Collection/find_with_opts/limit", test_limit); + TestSuite_AddMockServerTest (suite, "/Collection/find_with_opts/singlebatch", test_singlebatch); + TestSuite_AddMockServerTest (suite, "/Collection/find_with_opts/singlebatch/no_limit", test_singlebatch_no_limit); TestSuite_AddMockServerTest ( - suite, "/Collection/find_with_opts/server_id", test_find_w_server_id); - TestSuite_AddMockServerTest (suite, - "/Collection/find_cmd_with_opts/server_id", - test_find_cmd_w_server_id); - TestSuite_AddMockServerTest (suite, - "/Collection/find_with_opts/server_id/sharded", - test_find_w_server_id_sharded); + suite, "/Collection/find_with_opts/unrecognized_dollar", test_unrecognized_dollar_option); + TestSuite_AddMockServerTest (suite, "/Collection/find_with_opts/flags", test_query_flags); + TestSuite_AddMockServerTest (suite, "/Collection/find_with_opts/exhaust", test_exhaust); + TestSuite_AddMockServerTest (suite, "/Collection/find_with_opts/await/getmore_cmd", test_getmore_cmd_await); + TestSuite_AddMockServerTest (suite, "/Collection/find_with_opts/server_id", test_find_w_server_id); + TestSuite_AddMockServerTest (suite, "/Collection/find_cmd_with_opts/server_id", test_find_cmd_w_server_id); + TestSuite_AddMockServerTest (suite, "/Collection/find_with_opts/server_id/sharded", test_find_w_server_id_sharded); TestSuite_AddMockServerTest ( - suite, - "/Collection/find_cmd_with_opts/server_id/sharded", - test_find_cmd_w_server_id_sharded); - TestSuite_AddLive (suite, - "/Collection/find_with_opts/server_id/option", - test_server_id_option); + suite, "/Collection/find_cmd_with_opts/server_id/sharded", test_find_cmd_w_server_id_sharded); + TestSuite_AddLive (suite, "/Collection/find_with_opts/server_id/option", test_server_id_option); TestSuite_AddLive (suite, "/Collection/find/batchSize", test_find_batchSize); } diff --git a/src/libmongoc/tests/test-mongoc-collection-find.c b/src/libmongoc/tests/test-mongoc-collection-find.c index 14b39512b2..b56125cd2d 100644 --- a/src/libmongoc/tests/test-mongoc-collection-find.c +++ b/src/libmongoc/tests/test-mongoc-collection-find.c @@ -113,10 +113,7 @@ _test_collection_find_live (test_collection_find_t *test_data) database = mongoc_client_get_database (client, "test"); collection_name = gen_collection_name ("test"); collection = mongoc_database_create_collection ( - database, - collection_name, - tmp_bson ("{'capped': true, 'size': 10000}"), - &error); + database, collection_name, tmp_bson ("{'capped': true, 'size': 10000}"), &error); ASSERT_OR_PRINT (collection, error); @@ -134,8 +131,7 @@ _test_collection_find_live (test_collection_find_t *test_data) _check_cursor (cursor, test_data); drop_cmd = bson_strdup_printf ("{'drop': '%s'}", collection_name); - r = mongoc_client_command_simple ( - client, "test", tmp_bson (drop_cmd), NULL, NULL, &error); + r = mongoc_client_command_simple (client, "test", tmp_bson (drop_cmd), NULL, NULL, &error); ASSERT_OR_PRINT (r, error); bson_free (drop_cmd); @@ -150,8 +146,7 @@ _test_collection_find_live (test_collection_find_t *test_data) static request_t * _check_find_command (mock_server_t *server, test_collection_find_t *test_data) { - return mock_server_receives_msg ( - server, MONGOC_MSG_NONE, tmp_bson (test_data->expected_find_command)); + return mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson (test_data->expected_find_command)); } @@ -211,8 +206,7 @@ _test_collection_find_command (test_collection_find_t *test_data) server = mock_server_with_auto_hello (WIRE_VERSION_MIN); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); collection = mongoc_client_get_collection (client, "db", "collection"); cursor = mongoc_collection_find (collection, test_data->flags, @@ -276,8 +270,7 @@ _test_collection_find (test_collection_find_t *test_data) test_data->docs_bson = tmp_bson (test_data->docs); test_data->query_bson = tmp_bson (test_data->query_input); - test_data->fields_bson = - test_data->fields ? tmp_bson (test_data->fields) : NULL; + test_data->fields_bson = test_data->fields ? tmp_bson (test_data->fields) : NULL; test_data->expected_result_bson = tmp_bson (test_data->expected_result); test_data->n_results = bson_count_keys (test_data->expected_result_bson); @@ -300,8 +293,7 @@ test_dollar_query (void) test_collection_find_t test_data = TEST_COLLECTION_FIND_INIT; test_data.docs = "[{'_id': 1}, {'_id': 2}]"; test_data.query_input = "{'$query': {'_id': 1}}"; - test_data.expected_find_command = - "{'$db': 'db', 'find': 'collection', 'filter': {'_id': 1}}"; + test_data.expected_find_command = "{'$db': 'db', 'find': 'collection', 'filter': {'_id': 1}}"; test_data.expected_result = "[{'_id': 1}]"; _test_collection_find (&test_data); } @@ -314,10 +306,9 @@ test_dollar_or (void) test_data.docs = "[{'_id': 1}, {'_id': 2}, {'_id': 3}]"; test_data.query_input = "{'$or': [{'_id': 1}, {'_id': 3}]}"; - test_data.expected_find_command = - "{'$db': 'db'," - " 'find': 'collection'," - " 'filter': {'$or': [{'_id': 1}, {'_id': 3}]}}"; + test_data.expected_find_command = "{'$db': 'db'," + " 'find': 'collection'," + " 'filter': {'$or': [{'_id': 1}, {'_id': 3}]}}"; test_data.expected_result = "[{'_id': 1}, {'_id': 3}]"; _test_collection_find (&test_data); @@ -331,10 +322,9 @@ test_mixed_dollar_nondollar (void) test_data.docs = "[{'a': 1}, {'a': 1, 'b': 2}, {'a': 2}]"; test_data.query_input = "{'a': 1, '$or': [{'b': 1}, {'b': 2}]}"; - test_data.expected_find_command = - "{'$db': 'db'," - " 'find': 'collection'," - " 'filter': {'a': 1, '$or': [{'b': 1}, {'b': 2}]}}"; + test_data.expected_find_command = "{'$db': 'db'," + " 'find': 'collection'," + " 'filter': {'a': 1, '$or': [{'b': 1}, {'b': 2}]}}"; test_data.expected_result = "[{'a': 1, 'b': 2}]"; _test_collection_find (&test_data); @@ -348,8 +338,7 @@ test_key_named_filter (void) test_collection_find_t test_data = TEST_COLLECTION_FIND_INIT; test_data.docs = "[{'_id': 1, 'filter': 1}, {'_id': 2, 'filter': 2}]"; test_data.query_input = "{'filter': 2}"; - test_data.expected_find_command = - "{'$db': 'db', 'find': 'collection', 'filter': {'filter': 2}}"; + test_data.expected_find_command = "{'$db': 'db', 'find': 'collection', 'filter': {'filter': 2}}"; test_data.expected_result = "[{'_id': 2, 'filter': 2}]"; _test_collection_find (&test_data); } @@ -362,8 +351,7 @@ test_key_named_filter_with_dollar_query (void) test_collection_find_t test_data = TEST_COLLECTION_FIND_INIT; test_data.docs = "[{'_id': 1, 'filter': 1}, {'_id': 2, 'filter': 2}]"; test_data.query_input = "{'$query': {'filter': 2}}"; - test_data.expected_find_command = - "{'$db': 'db', 'find': 'collection', 'filter': {'filter': 2}}"; + test_data.expected_find_command = "{'$db': 'db', 'find': 'collection', 'filter': {'filter': 2}}"; test_data.expected_result = "[{'_id': 2, 'filter': 2}]"; _test_collection_find (&test_data); } @@ -374,11 +362,9 @@ static void test_subdoc_named_filter (void) { test_collection_find_t test_data = TEST_COLLECTION_FIND_INIT; - test_data.docs = - "[{'_id': 1, 'filter': {'i': 1}}, {'_id': 2, 'filter': {'i': 2}}]"; + test_data.docs = "[{'_id': 1, 'filter': {'i': 1}}, {'_id': 2, 'filter': {'i': 2}}]"; test_data.query_input = "{'filter': {'i': 2}}"; - test_data.expected_find_command = - "{'$db': 'db', 'find': 'collection', 'filter': {'filter': {'i': 2}}}"; + test_data.expected_find_command = "{'$db': 'db', 'find': 'collection', 'filter': {'filter': {'i': 2}}}"; test_data.expected_result = "[{'_id': 2, 'filter': {'i': 2}}]"; _test_collection_find (&test_data); @@ -390,11 +376,9 @@ static void test_subdoc_named_filter_with_dollar_query (void) { test_collection_find_t test_data = TEST_COLLECTION_FIND_INIT; - test_data.docs = - "[{'_id': 1, 'filter': {'i': 1}}, {'_id': 2, 'filter': {'i': 2}}]"; + test_data.docs = "[{'_id': 1, 'filter': {'i': 1}}, {'_id': 2, 'filter': {'i': 2}}]"; test_data.query_input = "{'$query': {'filter': {'i': 2}}}"; - test_data.expected_find_command = - "{'$db': 'db', 'find': 'collection', 'filter': {'filter': {'i': 2}}}"; + test_data.expected_find_command = "{'$db': 'db', 'find': 'collection', 'filter': {'filter': {'i': 2}}}"; test_data.expected_result = "[{'_id': 2, 'filter': {'i': 2}}]"; _test_collection_find (&test_data); } @@ -424,8 +408,7 @@ test_orderby (void) test_collection_find_t test_data = TEST_COLLECTION_FIND_INIT; test_data.docs = "[{'_id': 1}, {'_id': 2}]"; test_data.query_input = "{'$query': {}, '$orderby': {'_id': -1}}"; - test_data.expected_find_command = - "{'$db': 'db', 'find': 'collection', 'filter': {}, 'sort': {'_id': -1}}"; + test_data.expected_find_command = "{'$db': 'db', 'find': 'collection', 'filter': {}, 'sort': {'_id': -1}}"; test_data.expected_result = "[{'_id': 2}, {'_id': 1}]"; _test_collection_find (&test_data); } @@ -458,8 +441,7 @@ _test_int_modifier (const char *mod) query = bson_strdup_printf ("{'$query': {}, '$%s': 9999}", mod); /* find command has same modifier, without the $-prefix */ - find_command = bson_strdup_printf ( - "{'find': 'collection', 'filter': {}, '%s': 9999}", mod); + find_command = bson_strdup_printf ("{'find': 'collection', 'filter': {}, '%s': 9999}", mod); test_data.query_input = query; test_data.expected_find_command = find_command; @@ -482,8 +464,7 @@ test_comment (void) test_collection_find_t test_data = TEST_COLLECTION_FIND_INIT; test_data.docs = "[{'_id': 1}]"; test_data.query_input = "{'$query': {}, '$comment': 'hi'}"; - test_data.expected_find_command = - "{'find': 'collection', 'filter': {}, 'comment': 'hi'}"; + test_data.expected_find_command = "{'find': 'collection', 'filter': {}, 'comment': 'hi'}"; test_data.expected_result = "[{'_id': 1}]"; _test_collection_find (&test_data); } @@ -495,8 +476,7 @@ test_hint (void) test_collection_find_t test_data = TEST_COLLECTION_FIND_INIT; test_data.docs = "[{'_id': 1}]"; test_data.query_input = "{'$query': {}, '$hint': { '_id': 1 }}"; - test_data.expected_find_command = - "{'find': 'collection', 'filter': {}, 'hint': { '_id': 1 }}"; + test_data.expected_find_command = "{'find': 'collection', 'filter': {}, 'hint': { '_id': 1 }}"; test_data.expected_result = "[{'_id': 1}]"; _test_collection_find (&test_data); } @@ -508,11 +488,9 @@ test_max (void) test_collection_find_t test_data = TEST_COLLECTION_FIND_INIT; test_data.docs = "[{'_id': 1}]"; /* MongoDB 4.2 requires that max/min also use hint */ - test_data.query_input = - "{'$query': {}, '$max': {'_id': 100}, '$hint': { '_id': 1 }}"; - test_data.expected_find_command = - "{'find': 'collection', 'filter': {}, " - "'max': {'_id': 100}, 'hint': { '_id': 1 }}"; + test_data.query_input = "{'$query': {}, '$max': {'_id': 100}, '$hint': { '_id': 1 }}"; + test_data.expected_find_command = "{'find': 'collection', 'filter': {}, " + "'max': {'_id': 100}, 'hint': { '_id': 1 }}"; test_data.expected_result = "[{'_id': 1}]"; _test_collection_find (&test_data); } @@ -524,8 +502,7 @@ test_min (void) test_collection_find_t test_data = TEST_COLLECTION_FIND_INIT; test_data.docs = "[{'_id': 1}]"; /* MongoDB 4.2 requires that max/min also use hint */ - test_data.query_input = - "{'$query': {}, '$min': {'_id': 1}, '$hint': { '_id': 1 }}"; + test_data.query_input = "{'$query': {}, '$min': {'_id': 1}, '$hint': { '_id': 1 }}"; test_data.expected_find_command = "{'find': 'collection', 'filter': {}, " "'min': {'_id': 1}, 'hint': { '_id': 1 }}"; test_data.expected_result = "[{'_id': 1}]"; @@ -541,8 +518,7 @@ test_snapshot (void) test_data.max_wire_version = 6; test_data.docs = "[{'_id': 1}]"; test_data.query_input = "{'$query': {}, '$snapshot': true}"; - test_data.expected_find_command = - "{'find': 'collection', 'filter': {}, 'snapshot': true}"; + test_data.expected_find_command = "{'find': 'collection', 'filter': {}, 'snapshot': true}"; test_data.expected_result = "[{'_id': 1}]"; _test_collection_find (&test_data); } @@ -555,8 +531,7 @@ test_diskloc (void) test_collection_find_t test_data = TEST_COLLECTION_FIND_INIT; test_data.docs = "[{'_id': 1}]"; test_data.query_input = "{'$query': {}, '$showDiskLoc': true}"; - test_data.expected_find_command = - "{'find': 'collection', 'filter': {}, 'showRecordId': true}"; + test_data.expected_find_command = "{'find': 'collection', 'filter': {}, 'showRecordId': true}"; test_data.expected_result = "[{'_id': 1}]"; _test_collection_find (&test_data); } @@ -568,8 +543,7 @@ test_returnkey (void) test_collection_find_t test_data = TEST_COLLECTION_FIND_INIT; test_data.docs = "[{'_id': 1}]"; test_data.query_input = "{'$query': {}, '$returnKey': true}"; - test_data.expected_find_command = - "{'find': 'collection', 'filter': {}, 'returnKey': true}"; + test_data.expected_find_command = "{'find': 'collection', 'filter': {}, 'returnKey': true}"; test_data.expected_result = "[{}]"; _test_collection_find (&test_data); } @@ -597,8 +571,7 @@ test_batch_size (void) test_data.docs = "[{'_id': 1}]"; test_data.batch_size = 2; test_data.n_return = 2; - test_data.expected_find_command = - "{'find': 'collection', 'filter': {}, 'batchSize': {'$numberLong': '2'}}"; + test_data.expected_find_command = "{'find': 'collection', 'filter': {}, 'batchSize': {'$numberLong': '2'}}"; test_data.expected_result = "[{'_id': 1}]"; _test_collection_find (&test_data); } @@ -642,8 +615,7 @@ test_unrecognized_dollar_option (void) test_collection_find_t test_data = TEST_COLLECTION_FIND_INIT; test_data.query_input = "{'$query': {'a': 1}, '$dumb': 1}"; - test_data.expected_find_command = - "{'find': 'collection', 'filter': {'a': 1}, 'dumb': 1}"; + test_data.expected_find_command = "{'find': 'collection', 'filter': {'a': 1}, 'dumb': 1}"; test_data.do_live = false; _test_collection_find (&test_data); @@ -668,15 +640,13 @@ test_query_flags (void) {MONGOC_QUERY_OPLOG_REPLAY, "'oplogReplay': true"}, {MONGOC_QUERY_NO_CURSOR_TIMEOUT, "'noCursorTimeout': true"}, {MONGOC_QUERY_PARTIAL, "'allowPartialResults': true"}, - {MONGOC_QUERY_TAILABLE_CURSOR | MONGOC_QUERY_AWAIT_DATA, - "'tailable': true, 'awaitData': true"}, + {MONGOC_QUERY_TAILABLE_CURSOR | MONGOC_QUERY_AWAIT_DATA, "'tailable': true, 'awaitData': true"}, }; test_data.expected_result = test_data.docs = "[{'_id': 1}]"; for (i = 0; i < (sizeof flags_and_frags) / (sizeof (flag_and_name_t)); i++) { - find_cmd = bson_strdup_printf ("{'find': 'collection', 'filter': {}, %s}", - flags_and_frags[i].json_fragment); + find_cmd = bson_strdup_printf ("{'find': 'collection', 'filter': {}, %s}", flags_and_frags[i].json_fragment); test_data.flags = flags_and_frags[i].flag; test_data.expected_find_command = find_cmd; @@ -702,11 +672,9 @@ test_exhaust (void) server = mock_server_with_auto_hello (WIRE_VERSION_MIN); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); collection = mongoc_client_get_collection (client, "db", "collection"); - cursor = mongoc_collection_find ( - collection, MONGOC_QUERY_EXHAUST, 0, 0, 0, tmp_bson (NULL), NULL, NULL); + cursor = mongoc_collection_find (collection, MONGOC_QUERY_EXHAUST, 0, 0, 0, tmp_bson (NULL), NULL, NULL); future = future_cursor_next (cursor, &doc); @@ -715,13 +683,8 @@ test_exhaust (void) * fallback to existing OP_QUERY wire protocol messages." */ request = mock_server_receives_request (server); - reply_to_find_request (request, - MONGOC_QUERY_SECONDARY_OK | MONGOC_QUERY_EXHAUST, - 0, - 0, - "db.collection", - "{}", - false /* is_command */); + reply_to_find_request ( + request, MONGOC_QUERY_SECONDARY_OK | MONGOC_QUERY_EXHAUST, 0, 0, "db.collection", "{}", false /* is_command */); ASSERT (future_get_bool (future)); ASSERT_OR_PRINT (!mongoc_cursor_error (cursor, &error), error); @@ -752,25 +715,17 @@ test_getmore_batch_size (void) server = mock_server_with_auto_hello (WIRE_VERSION_MIN); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); collection = mongoc_client_get_collection (client, "db", "collection"); for (i = 0; i < sizeof (batch_sizes) / sizeof (uint32_t); i++) { - cursor = mongoc_collection_find (collection, - MONGOC_QUERY_NONE, - 0, - 0, - batch_sizes[i], - tmp_bson ("{}"), - NULL, - NULL); + cursor = + mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, batch_sizes[i], tmp_bson ("{}"), NULL, NULL); future = future_cursor_next (cursor, &doc); if (batch_sizes[i]) { - batch_size_json = - bson_strdup_printf ("{'$numberLong': '%u'}", batch_sizes[i]); + batch_size_json = bson_strdup_printf ("{'$numberLong': '%u'}", batch_sizes[i]); } else { batch_size_json = bson_strdup ("{'$exists': false}"); } @@ -826,18 +781,14 @@ test_getmore_invalid_reply (void *ctx) server = mock_server_with_auto_hello (WIRE_VERSION_MIN); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); collection = mongoc_client_get_collection (client, "db", "collection"); - cursor = mongoc_collection_find ( - collection, MONGOC_QUERY_NONE, 0, 0, 0, tmp_bson ("{}"), NULL, NULL); + cursor = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, 0, tmp_bson ("{}"), NULL, NULL); future = future_cursor_next (cursor, &doc); request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db', 'find': 'collection', 'filter': {}}")); + server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', 'find': 'collection', 'filter': {}}")); reply_to_request_simple (request, "{'ok': 1," @@ -852,12 +803,11 @@ test_getmore_invalid_reply (void *ctx) request_destroy (request); future = future_cursor_next (cursor, &doc); - request = - mock_server_receives_msg (server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db'," - " 'getMore': {'$numberLong': '123'}," - " 'collection': 'collection'}")); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'db'," + " 'getMore': {'$numberLong': '123'}," + " 'collection': 'collection'}")); /* missing "cursor" */ reply_to_request_with_ok_and_destroy (request); @@ -903,19 +853,11 @@ test_getmore_await (void) server = mock_server_with_auto_hello (WIRE_VERSION_MIN); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); collection = mongoc_client_get_collection (client, "db", "collection"); for (i = 3; i < sizeof (await_tests) / sizeof (await_test_t); i++) { - cursor = mongoc_collection_find (collection, - await_tests[i].flags, - 0, - 0, - 0, - tmp_bson ("{}"), - NULL, - NULL); + cursor = mongoc_collection_find (collection, await_tests[i].flags, 0, 0, 0, tmp_bson ("{}"), NULL, NULL); ASSERT (mongoc_cursor_more (cursor)); @@ -923,13 +865,12 @@ test_getmore_await (void) mongoc_cursor_set_max_await_time_ms (cursor, 123); future = future_cursor_next (cursor, &doc); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db'," - " 'find': 'collection'," - " 'maxTimeMS': {'$exists': false}," - " 'maxAwaitTimeMS': {'$exists': false}}")); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'db'," + " 'find': 'collection'," + " 'maxTimeMS': {'$exists': false}," + " 'maxAwaitTimeMS': {'$exists': false}}")); /* reply with cursor id 1 */ reply_to_request_simple (request, @@ -954,15 +895,14 @@ test_getmore_await (void) max_time_json = "{'$exists': false}"; } - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db'," - " 'getMore': {'$numberLong': '1'}," - " 'collection': 'collection'," - " 'maxAwaitTimeMS': {'$exists': false}," - " 'maxTimeMS': {'$numberLong': '%s'}}", - max_time_json)); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'db'," + " 'getMore': {'$numberLong': '1'}," + " 'collection': 'collection'," + " 'maxAwaitTimeMS': {'$exists': false}," + " 'maxTimeMS': {'$numberLong': '%s'}}", + max_time_json)); BSON_ASSERT (request); /* reply with cursor id 0 */ @@ -1021,34 +961,22 @@ _test_tailable_timeout (bool pooled) mongoc_collection_destroy (collection); collection = mongoc_database_create_collection ( - database, - collection_name, - tmp_bson ("{'capped': true, 'size': 10000}"), - &error); + database, collection_name, tmp_bson ("{'capped': true, 'size': 10000}"), &error); ASSERT_OR_PRINT (collection, error); - r = mongoc_collection_insert_one ( - collection, tmp_bson ("{}"), NULL, NULL, &error); + r = mongoc_collection_insert_one (collection, tmp_bson ("{}"), NULL, NULL, &error); ASSERT_OR_PRINT (r, error); client->cluster.sockettimeoutms = 100; - cursor = mongoc_collection_find (collection, - MONGOC_QUERY_TAILABLE_CURSOR | - MONGOC_QUERY_AWAIT_DATA, - 0, - 0, - 0, - tmp_bson ("{'a': 1}"), - NULL, - NULL); + cursor = mongoc_collection_find ( + collection, MONGOC_QUERY_TAILABLE_CURSOR | MONGOC_QUERY_AWAIT_DATA, 0, 0, 0, tmp_bson ("{'a': 1}"), NULL, NULL); ASSERT (!mongoc_cursor_next (cursor, &doc)); client->cluster.sockettimeoutms = 30 * 1000 * 1000; - r = mongoc_client_command_simple ( - client, "test", tmp_bson ("{'buildinfo': 1}"), NULL, &reply, &error); + r = mongoc_client_command_simple (client, "test", tmp_bson ("{'buildinfo': 1}"), NULL, &reply, &error); ASSERT_OR_PRINT (r, error); ASSERT_HAS_FIELD (&reply, "version"); @@ -1089,27 +1017,17 @@ test_tailable_timeout_pooled (void) void test_collection_find_install (TestSuite *suite) { - TestSuite_AddLive ( - suite, "/Collection/find/dollar_query", test_dollar_query); + TestSuite_AddLive (suite, "/Collection/find/dollar_query", test_dollar_query); TestSuite_AddLive (suite, "/Collection/find/dollar_or", test_dollar_or); - TestSuite_AddLive (suite, - "/Collection/find/mixed_dollar_nondollar", - test_mixed_dollar_nondollar); - TestSuite_AddLive ( - suite, "/Collection/find/key_named_filter", test_key_named_filter); - TestSuite_AddLive (suite, - "/Collection/find/key_named_filter/$query", - test_key_named_filter_with_dollar_query); - TestSuite_AddLive ( - suite, "/Collection/find/subdoc_named_filter", test_subdoc_named_filter); - TestSuite_AddLive (suite, - "/Collection/find/subdoc_named_filter/$query", - test_subdoc_named_filter_with_dollar_query); + TestSuite_AddLive (suite, "/Collection/find/mixed_dollar_nondollar", test_mixed_dollar_nondollar); + TestSuite_AddLive (suite, "/Collection/find/key_named_filter", test_key_named_filter); + TestSuite_AddLive (suite, "/Collection/find/key_named_filter/$query", test_key_named_filter_with_dollar_query); + TestSuite_AddLive (suite, "/Collection/find/subdoc_named_filter", test_subdoc_named_filter); + TestSuite_AddLive (suite, "/Collection/find/subdoc_named_filter/$query", test_subdoc_named_filter_with_dollar_query); TestSuite_AddLive (suite, "/Collection/find/newoption", test_newoption); TestSuite_AddLive (suite, "/Collection/find/orderby", test_orderby); TestSuite_AddLive (suite, "/Collection/find/fields", test_fields); - TestSuite_AddLive ( - suite, "/Collection/find/modifiers/maxtimems", test_maxtimems); + TestSuite_AddLive (suite, "/Collection/find/modifiers/maxtimems", test_maxtimems); TestSuite_AddLive (suite, "/Collection/find/comment", test_comment); TestSuite_AddLive (suite, "/Collection/find/hint", test_hint); TestSuite_AddLive (suite, "/Collection/find/max", test_max); @@ -1120,31 +1038,18 @@ test_collection_find_install (TestSuite *suite) TestSuite_AddLive (suite, "/Collection/find/skip", test_skip); TestSuite_AddLive (suite, "/Collection/find/batch_size", test_batch_size); TestSuite_AddLive (suite, "/Collection/find/limit", test_limit); - TestSuite_AddLive ( - suite, "/Collection/find/negative_limit", test_negative_limit); - TestSuite_Add ( - suite, "/Collection/find/unrecognized", test_unrecognized_dollar_option); + TestSuite_AddLive (suite, "/Collection/find/negative_limit", test_negative_limit); + TestSuite_Add (suite, "/Collection/find/unrecognized", test_unrecognized_dollar_option); TestSuite_AddLive (suite, "/Collection/find/flags", test_query_flags); - TestSuite_AddMockServerTest ( - suite, "/Collection/find/exhaust", test_exhaust); - TestSuite_AddMockServerTest ( - suite, "/Collection/getmore/batch_size", test_getmore_batch_size); - TestSuite_AddFull (suite, - "/Collection/getmore/invalid_reply", - test_getmore_invalid_reply, - NULL, - NULL, - test_framework_skip_if_slow); - TestSuite_AddMockServerTest ( - suite, "/Collection/getmore/await", test_getmore_await); - TestSuite_AddLive (suite, - "/Collection/tailable/timeout/single", - test_tailable_timeout_single); + TestSuite_AddMockServerTest (suite, "/Collection/find/exhaust", test_exhaust); + TestSuite_AddMockServerTest (suite, "/Collection/getmore/batch_size", test_getmore_batch_size); + TestSuite_AddFull ( + suite, "/Collection/getmore/invalid_reply", test_getmore_invalid_reply, NULL, NULL, test_framework_skip_if_slow); + TestSuite_AddMockServerTest (suite, "/Collection/getmore/await", test_getmore_await); + TestSuite_AddLive (suite, "/Collection/tailable/timeout/single", test_tailable_timeout_single); #ifndef MONGOC_ENABLE_SSL_SECURE_TRANSPORT #ifndef MONGOC_ENABLE_SSL_SECURE_CHANNEL - TestSuite_AddLive (suite, - "/Collection/tailable/timeout/pooled", - test_tailable_timeout_pooled); + TestSuite_AddLive (suite, "/Collection/tailable/timeout/pooled", test_tailable_timeout_pooled); #endif #endif } diff --git a/src/libmongoc/tests/test-mongoc-collection.c b/src/libmongoc/tests/test-mongoc-collection.c index 4c2ac8dc5a..3750956772 100644 --- a/src/libmongoc/tests/test-mongoc-collection.c +++ b/src/libmongoc/tests/test-mongoc-collection.c @@ -55,8 +55,7 @@ test_aggregate_w_write_concern (void *ctx) mongoc_write_concern_set_w (good_wc, 1); bson_reinit (opts); mongoc_write_concern_append (good_wc, opts); - cursor = mongoc_collection_aggregate ( - collection, MONGOC_QUERY_NONE, pipeline, opts, NULL); + cursor = mongoc_collection_aggregate (collection, MONGOC_QUERY_NONE, pipeline, opts, NULL); ASSERT (cursor); mongoc_cursor_next (cursor, &doc); @@ -67,14 +66,11 @@ test_aggregate_w_write_concern (void *ctx) bad_wc->wtimeout = -10; bson_reinit (opts); mongoc_write_concern_append_bad (bad_wc, opts); - cursor = mongoc_collection_aggregate ( - collection, MONGOC_QUERY_NONE, pipeline, opts, NULL); + cursor = mongoc_collection_aggregate (collection, MONGOC_QUERY_NONE, pipeline, opts, NULL); ASSERT (cursor); ASSERT (!mongoc_cursor_next (cursor, &doc)); - ASSERT_ERROR_CONTAINS (cursor->error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Invalid writeConcern"); + ASSERT_ERROR_CONTAINS ( + cursor->error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid writeConcern"); bad_wc->wtimeout = 0; mongoc_write_concern_destroy (good_wc); @@ -105,13 +101,11 @@ test_aggregate_inherit_collection (void) server = mock_server_with_auto_hello (WIRE_VERSION_MIN); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); collection = mongoc_client_get_collection (client, "db", "collection"); - pipeline = BCON_NEW ( - "pipeline", "[", "{", "$out", BCON_UTF8 ("collection2"), "}", "]"); + pipeline = BCON_NEW ("pipeline", "[", "{", "$out", BCON_UTF8 ("collection2"), "}", "]"); rc = mongoc_read_concern_new (); mongoc_read_concern_set_level (rc, MONGOC_READ_CONCERN_LEVEL_MAJORITY); @@ -122,19 +116,17 @@ test_aggregate_inherit_collection (void) mongoc_write_concern_append (wc, &opts); /* Uses the opts */ - cursor = mongoc_collection_aggregate ( - collection, MONGOC_QUERY_SECONDARY_OK, pipeline, &opts, NULL); + cursor = mongoc_collection_aggregate (collection, MONGOC_QUERY_SECONDARY_OK, pipeline, &opts, NULL); future = future_cursor_next (cursor, &doc); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db'," - " 'aggregate': 'collection'," - " 'pipeline': [{'$out': 'collection2'}]," - " 'cursor': {}," - " 'readConcern': {'level': 'majority'}," - " 'writeConcern': {'w': 2}}")); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'db'," + " 'aggregate': 'collection'," + " 'pipeline': [{'$out': 'collection2'}]," + " 'cursor': {}," + " 'readConcern': {'level': 'majority'}," + " 'writeConcern': {'w': 2}}")); reply_to_request_with_ok_and_destroy (request); @@ -152,19 +144,17 @@ test_aggregate_inherit_collection (void) mongoc_cursor_destroy (cursor); /* Inherits from collection */ - cursor = mongoc_collection_aggregate ( - collection, MONGOC_QUERY_SECONDARY_OK, pipeline, NULL, NULL); + cursor = mongoc_collection_aggregate (collection, MONGOC_QUERY_SECONDARY_OK, pipeline, NULL, NULL); future = future_cursor_next (cursor, &doc); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson (" {'$db': 'db'," - " 'aggregate': 'collection'," - " 'pipeline': [{'$out': 'collection2'}]," - " 'cursor': {}," - " 'readConcern': {'level': 'local'}," - " 'writeConcern': {'w': 3}}")); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson (" {'$db': 'db'," + " 'aggregate': 'collection'," + " 'pipeline': [{'$out': 'collection2'}]," + " 'cursor': {}," + " 'readConcern': {'level': 'local'}," + " 'writeConcern': {'w': 3}}")); reply_to_request_with_ok_and_destroy (request); @@ -174,19 +164,17 @@ test_aggregate_inherit_collection (void) mongoc_cursor_destroy (cursor); /* Uses the opts, not default collection level */ - cursor = mongoc_collection_aggregate ( - collection, MONGOC_QUERY_SECONDARY_OK, pipeline, &opts, NULL); + cursor = mongoc_collection_aggregate (collection, MONGOC_QUERY_SECONDARY_OK, pipeline, &opts, NULL); future = future_cursor_next (cursor, &doc); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db'," - " 'aggregate': 'collection'," - " 'pipeline': [{'$out': 'collection2'}]," - " 'cursor': {}," - " 'readConcern': {'level': 'majority'}," - " 'writeConcern': {'w': 2}}")); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'db'," + " 'aggregate': 'collection'," + " 'pipeline': [{'$out': 'collection2'}]," + " 'cursor': {}," + " 'readConcern': {'level': 'majority'}," + " 'writeConcern': {'w': 2}}")); reply_to_request_with_ok_and_destroy (request); @@ -197,22 +185,19 @@ test_aggregate_inherit_collection (void) /* Doesn't inherit write concern when not using $out */ bson_destroy (pipeline); - pipeline = BCON_NEW ( - "pipeline", "[", "{", "$in", BCON_UTF8 ("collection2"), "}", "]"); + pipeline = BCON_NEW ("pipeline", "[", "{", "$in", BCON_UTF8 ("collection2"), "}", "]"); - cursor = mongoc_collection_aggregate ( - collection, MONGOC_QUERY_SECONDARY_OK, pipeline, NULL, NULL); + cursor = mongoc_collection_aggregate (collection, MONGOC_QUERY_SECONDARY_OK, pipeline, NULL, NULL); future = future_cursor_next (cursor, &doc); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson (" {'$db': 'db'," - " 'aggregate': 'collection'," - " 'pipeline': [{'$in': 'collection2'}]," - " 'cursor': {}," - " 'readConcern': {'level': 'local'}," - " 'writeConcern': {'$exists': false}}")); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson (" {'$db': 'db'," + " 'aggregate': 'collection'," + " 'pipeline': [{'$in': 'collection2'}]," + " 'cursor': {}," + " 'readConcern': {'level': 'local'}," + " 'writeConcern': {'$exists': false}}")); reply_to_request_with_ok_and_destroy (request); ASSERT (!future_get_bool (future)); @@ -232,10 +217,7 @@ test_aggregate_inherit_collection (void) } static void -_batch_size_test (bson_t *pipeline, - bson_t *batch_size, - bool use_batch_size, - int size) +_batch_size_test (bson_t *pipeline, bson_t *batch_size, bool use_batch_size, int size) { mock_server_t *mock_server; mongoc_client_t *client; @@ -248,24 +230,17 @@ _batch_size_test (bson_t *pipeline, mock_server = mock_server_with_auto_hello (WIRE_VERSION_MAX); mock_server_run (mock_server); - client = test_framework_client_new_from_uri ( - mock_server_get_uri (mock_server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (mock_server), NULL); coll = mongoc_client_get_collection (client, "db", "coll"); - cursor = mongoc_collection_aggregate ( - coll, MONGOC_QUERY_NONE, pipeline, batch_size, NULL); + cursor = mongoc_collection_aggregate (coll, MONGOC_QUERY_NONE, pipeline, batch_size, NULL); future = future_cursor_next (cursor, &doc); if (use_batch_size) { - request = mock_server_receives_msg ( - mock_server, - 0, - tmp_bson ("{ 'cursor' : { 'batchSize' : %d } }", size)); + request = mock_server_receives_msg (mock_server, 0, tmp_bson ("{ 'cursor' : { 'batchSize' : %d } }", size)); } else { - request = mock_server_receives_msg ( - mock_server, - 0, - tmp_bson ("{ 'cursor' : { 'batchSize' : { '$exists': false } } }")); + request = + mock_server_receives_msg (mock_server, 0, tmp_bson ("{ 'cursor' : { 'batchSize' : { '$exists': false } } }")); } reply_to_request_simple (request, "{'ok': 1}"); @@ -289,8 +264,7 @@ test_aggregate_with_batch_size (void) bson_t *batch_size_one; pipeline_dollar_out = tmp_bson ("{ 'pipeline': [ { '$out' : 'coll2' } ] }"); - pipeline_dollar_merge = - tmp_bson ("{ 'pipeline': [ { '$merge' : 'coll2' } ] }"); + pipeline_dollar_merge = tmp_bson ("{ 'pipeline': [ { '$merge' : 'coll2' } ] }"); pipeline_no_terminal_key = tmp_bson ("{ 'pipeline': [ ] }"); batch_size_one = tmp_bson (" { 'batchSize': 1 } "); @@ -342,75 +316,42 @@ test_read_prefs_is_valid (void *ctx) collection = get_test_collection (client, "test_aggregate"); ASSERT (collection); - pipeline = BCON_NEW ("pipeline", - "[", - "{", - "$match", - "{", - "hello", - BCON_UTF8 ("world"), - "}", - "}", - "]"); + pipeline = BCON_NEW ("pipeline", "[", "{", "$match", "{", "hello", BCON_UTF8 ("world"), "}", "}", "]"); /* if read prefs is not valid */ read_prefs = mongoc_read_prefs_new (MONGOC_READ_PRIMARY); ASSERT (read_prefs); - mongoc_read_prefs_set_tags (read_prefs, - tmp_bson ("[{'does-not-exist': 'x'}]")); + mongoc_read_prefs_set_tags (read_prefs, tmp_bson ("[{'does-not-exist': 'x'}]")); /* mongoc_collection_aggregate */ - cursor = mongoc_collection_aggregate ( - collection, MONGOC_QUERY_NONE, pipeline, NULL, read_prefs); + cursor = mongoc_collection_aggregate (collection, MONGOC_QUERY_NONE, pipeline, NULL, read_prefs); ASSERT (cursor); ASSERT (mongoc_cursor_error (cursor, &error)); mongoc_cursor_destroy (cursor); /* mongoc_collection_command */ - cursor = mongoc_collection_command (collection, - MONGOC_QUERY_NONE, - 0, - 0, - 0, - tmp_bson ("{}"), - NULL, - read_prefs); + cursor = mongoc_collection_command (collection, MONGOC_QUERY_NONE, 0, 0, 0, tmp_bson ("{}"), NULL, read_prefs); ASSERT (cursor); ASSERT (mongoc_cursor_error (cursor, &error)); mongoc_cursor_destroy (cursor); /* mongoc_collection_command_simple */ - ASSERT (!mongoc_collection_command_simple ( - collection, tmp_bson ("{'ping': 1}"), read_prefs, &reply, &error)); + ASSERT (!mongoc_collection_command_simple (collection, tmp_bson ("{'ping': 1}"), read_prefs, &reply, &error)); bson_destroy (&reply); /* mongoc_collection_count_with_opts */ - ASSERT (mongoc_collection_count_with_opts (collection, - MONGOC_QUERY_NONE, - tmp_bson ("{}"), - 0, - 0, - NULL, - read_prefs, - &error) == -1); + ASSERT (mongoc_collection_count_with_opts ( + collection, MONGOC_QUERY_NONE, tmp_bson ("{}"), 0, 0, NULL, read_prefs, &error) == -1); /* mongoc_collection_find */ - cursor = mongoc_collection_find (collection, - MONGOC_QUERY_NONE, - 0, - 0, - 0, - tmp_bson ("{}"), - NULL, - read_prefs); + cursor = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, 0, tmp_bson ("{}"), NULL, read_prefs); ASSERT (cursor); ASSERT (mongoc_cursor_error (cursor, &error)); mongoc_cursor_destroy (cursor); /* mongoc_collection_find_with_opts */ - cursor = mongoc_collection_find_with_opts ( - collection, tmp_bson ("{}"), NULL, read_prefs); + cursor = mongoc_collection_find_with_opts (collection, tmp_bson ("{}"), NULL, read_prefs); ASSERT (cursor); ASSERT (mongoc_cursor_error (cursor, &error)); @@ -422,60 +363,36 @@ test_read_prefs_is_valid (void *ctx) ASSERT (read_prefs); /* mongoc_collection_aggregate */ - cursor = mongoc_collection_aggregate ( - collection, MONGOC_QUERY_NONE, pipeline, NULL, read_prefs); + cursor = mongoc_collection_aggregate (collection, MONGOC_QUERY_NONE, pipeline, NULL, read_prefs); ASSERT (cursor); ASSERT_OR_PRINT (!mongoc_cursor_error (cursor, &error), error); mongoc_cursor_destroy (cursor); /* mongoc_collection_command */ - cursor = mongoc_collection_command (collection, - MONGOC_QUERY_NONE, - 0, - 0, - 0, - tmp_bson ("{}"), - NULL, - read_prefs); + cursor = mongoc_collection_command (collection, MONGOC_QUERY_NONE, 0, 0, 0, tmp_bson ("{}"), NULL, read_prefs); ASSERT (cursor); ASSERT_OR_PRINT (!mongoc_cursor_error (cursor, &error), error); mongoc_cursor_destroy (cursor); /* mongoc_collection_command_simple */ - ASSERT_OR_PRINT ( - mongoc_collection_command_simple ( - collection, tmp_bson ("{'ping': 1}"), read_prefs, &reply, &error), - error); + ASSERT_OR_PRINT (mongoc_collection_command_simple (collection, tmp_bson ("{'ping': 1}"), read_prefs, &reply, &error), + error); bson_destroy (&reply); /* mongoc_collection_count_with_opts */ - ASSERT_OR_PRINT (mongoc_collection_count_with_opts (collection, - MONGOC_QUERY_NONE, - tmp_bson ("{}"), - 0, - 0, - NULL, - read_prefs, - &error) != -1, + ASSERT_OR_PRINT (mongoc_collection_count_with_opts ( + collection, MONGOC_QUERY_NONE, tmp_bson ("{}"), 0, 0, NULL, read_prefs, &error) != -1, error); /* mongoc_collection_find */ - cursor = mongoc_collection_find (collection, - MONGOC_QUERY_NONE, - 0, - 0, - 0, - tmp_bson ("{}"), - NULL, - read_prefs); + cursor = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, 0, tmp_bson ("{}"), NULL, read_prefs); ASSERT (cursor); ASSERT_OR_PRINT (!mongoc_cursor_error (cursor, &error), error); mongoc_cursor_destroy (cursor); /* mongoc_collection_find_with_opts */ - cursor = mongoc_collection_find_with_opts ( - collection, tmp_bson ("{}"), NULL, read_prefs); + cursor = mongoc_collection_find_with_opts (collection, tmp_bson ("{}"), NULL, read_prefs); ASSERT (cursor); ASSERT_OR_PRINT (!mongoc_cursor_error (cursor, &error), error); @@ -551,20 +468,14 @@ test_insert (void) bson_oid_init (&oid, context); bson_append_oid (&b, "_id", 3, &oid); bson_append_utf8 (&b, "hello", 5, "/world", 6); - ASSERT_OR_PRINT ( - mongoc_collection_insert_one (collection, &b, NULL, NULL, &error), - error); + ASSERT_OR_PRINT (mongoc_collection_insert_one (collection, &b, NULL, NULL, &error), error); bson_destroy (&b); } - r = mongoc_collection_insert_one ( - collection, tmp_bson ("{'': 1}"), NULL, NULL, &error); + r = mongoc_collection_insert_one (collection, tmp_bson ("{'': 1}"), NULL, NULL, &error); ASSERT (!r); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "invalid document"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "invalid document"); ASSERT_OR_PRINT (mongoc_collection_drop (collection, &error), error); @@ -594,8 +505,7 @@ test_insert_null (void) client = test_framework_new_default_client (); ASSERT (client); - collection = - mongoc_client_get_collection (client, "test", "test_null_insert"); + collection = mongoc_client_get_collection (client, "test", "test_null_insert"); ASSERT (collection); (void) mongoc_collection_drop (collection, &error); @@ -635,8 +545,7 @@ test_insert_null (void) bulk = mongoc_collection_create_bulk_operation_with_opts (collection, NULL); mongoc_bulk_operation_remove_one (bulk, &doc); - ret = mongoc_bulk_operation_update_one_with_opts ( - bulk, &doc, tmp_bson ("{'$set': {'x': 1}}"), NULL, &error); + ret = mongoc_bulk_operation_update_one_with_opts (bulk, &doc, tmp_bson ("{'$set': {'x': 1}}"), NULL, &error); ASSERT_OR_PRINT (ret, error); ret = mongoc_bulk_operation_execute (bulk, &reply, &error); ASSERT_OR_PRINT (ret, error); @@ -672,17 +581,14 @@ test_insert_oversize (void *ctx) collection = get_test_collection (client, "test_insert_oversize"); /* two huge strings make the doc too large */ - BSON_ASSERT (bson_append_utf8 ( - &doc, "x", 1, huge_string (client), (int) huge_string_length (client))); + BSON_ASSERT (bson_append_utf8 (&doc, "x", 1, huge_string (client), (int) huge_string_length (client))); - BSON_ASSERT (bson_append_utf8 ( - &doc, "y", 1, huge_string (client), (int) huge_string_length (client))); + BSON_ASSERT (bson_append_utf8 (&doc, "y", 1, huge_string (client), (int) huge_string_length (client))); r = mongoc_collection_insert_one (collection, &doc, NULL, NULL, &error); ASSERT (!r); - ASSERT_ERROR_CONTAINS ( - error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "too large"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "too large"); bson_destroy (&doc); mongoc_collection_destroy (collection); @@ -732,15 +638,12 @@ test_insert_many (void) bptr[i] = &b[i]; } - ASSERT_OR_PRINT ( - mongoc_collection_insert_many ( - collection, (const bson_t **) bptr, 10, NULL, &reply, &error), - error); + ASSERT_OR_PRINT (mongoc_collection_insert_many (collection, (const bson_t **) bptr, 10, NULL, &reply, &error), + error); ASSERT_CMPINT32 (bson_lookup_int32 (&reply, "insertedCount"), ==, 10); bson_destroy (&reply); - count = mongoc_collection_count_documents ( - collection, &q, NULL, NULL, NULL, &error); + count = mongoc_collection_count_documents (collection, &q, NULL, NULL, NULL, &error); ASSERT (count == 5); for (i = 8; i < 10; i++) { @@ -752,31 +655,24 @@ test_insert_many (void) bptr[i] = &b[i]; } - r = mongoc_collection_insert_many ( - collection, (const bson_t **) bptr, 10, NULL, &reply, &error); + r = mongoc_collection_insert_many (collection, (const bson_t **) bptr, 10, NULL, &reply, &error); ASSERT (!r); ASSERT (error.code == 11000); ASSERT_CMPINT32 (bson_lookup_int32 (&reply, "insertedCount"), ==, 0); bson_destroy (&reply); - count = mongoc_collection_count_documents ( - collection, &q, NULL, NULL, NULL, &error); + count = mongoc_collection_count_documents (collection, &q, NULL, NULL, NULL, &error); ASSERT (count == 5); - r = mongoc_collection_insert_many (collection, - (const bson_t **) bptr, - 10, - tmp_bson ("{'ordered': false}"), - &reply, - &error); + r = mongoc_collection_insert_many ( + collection, (const bson_t **) bptr, 10, tmp_bson ("{'ordered': false}"), &reply, &error); ASSERT (!r); ASSERT (error.code == 11000); ASSERT_CMPINT32 (bson_lookup_int32 (&reply, "insertedCount"), ==, 2); bson_destroy (&reply); - count = mongoc_collection_count_documents ( - collection, &q, NULL, NULL, NULL, &error); + count = mongoc_collection_count_documents (collection, &q, NULL, NULL, NULL, &error); ASSERT (count == 6); /* test validate */ @@ -786,12 +682,8 @@ test_insert_many (void) BSON_APPEND_INT32 (&b[i], "" /* empty key */, i); bptr[i] = &b[i]; } - r = mongoc_collection_insert_many (collection, - (const bson_t **) bptr, - 10, - tmp_bson ("{'ordered': false}"), - NULL, - &error); + r = mongoc_collection_insert_many ( + collection, (const bson_t **) bptr, 10, tmp_bson ("{'ordered': false}"), NULL, &error); ASSERT (!r); ASSERT (error.domain == MONGOC_ERROR_COMMAND); ASSERT (error.code == MONGOC_ERROR_COMMAND_INVALID_ARG); @@ -803,8 +695,7 @@ test_insert_many (void) bptr[i] = &b[i]; } - r = mongoc_collection_insert_many ( - collection, (const bson_t **) bptr, 10, NULL, NULL, &error); + r = mongoc_collection_insert_many (collection, (const bson_t **) bptr, 10, NULL, NULL, &error); ASSERT (!r); ASSERT (error.domain == MONGOC_ERROR_COMMAND); ASSERT (error.code == MONGOC_ERROR_COMMAND_INVALID_ARG); @@ -837,12 +728,7 @@ test_insert_bulk_empty (void) collection = get_test_collection (client, "test_insert_bulk_empty"); BEGIN_IGNORE_DEPRECATIONS - ASSERT (!mongoc_collection_insert_bulk (collection, - MONGOC_INSERT_NONE, - (const bson_t **) &bptr, - 0, - NULL, - &error)); + ASSERT (!mongoc_collection_insert_bulk (collection, MONGOC_INSERT_NONE, (const bson_t **) &bptr, 0, NULL, &error)); END_IGNORE_DEPRECATIONS ASSERT_CMPINT (MONGOC_ERROR_COLLECTION, ==, error.domain); @@ -934,8 +820,7 @@ test_insert_command_keys (void) server = mock_server_with_auto_hello (WIRE_VERSION_MIN); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); collection = mongoc_client_get_collection (client, "test", "test"); bulk = mongoc_collection_create_bulk_operation_with_opts (collection, NULL); @@ -946,13 +831,12 @@ test_insert_command_keys (void) } future = future_bulk_operation_execute (bulk, &reply, &error); - request = - mock_server_receives_msg (server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'test', 'insert': 'test'}"), - tmp_bson ("{'_id': 0}"), - tmp_bson ("{'_id': 1}"), - tmp_bson ("{'_id': 2}")); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'test', 'insert': 'test'}"), + tmp_bson ("{'_id': 0}"), + tmp_bson ("{'_id': 1}"), + tmp_bson ("{'_id': 2}")); reply_to_request_with_ok_and_destroy (request); @@ -1002,8 +886,7 @@ test_save (void) bson_oid_init (&oid, context); bson_append_oid (&b, "_id", 3, &oid); bson_append_utf8 (&b, "hello", 5, "/world", 5); - ASSERT_OR_PRINT (mongoc_collection_save (collection, &b, NULL, &error), - error); + ASSERT_OR_PRINT (mongoc_collection_save (collection, &b, NULL, &error), error); bson_destroy (&b); } @@ -1012,10 +895,7 @@ test_save (void) END_IGNORE_DEPRECATIONS ASSERT (!r); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "invalid document"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "invalid document"); mongoc_collection_destroy (collection); mongoc_database_destroy (database); @@ -1051,14 +931,11 @@ test_regex (void) mongoc_write_concern_append (wr, &opts); doc = BCON_NEW ("hello", "/world"); - ASSERT_OR_PRINT ( - mongoc_collection_insert_one (collection, doc, &opts, NULL, &error), - error); + ASSERT_OR_PRINT (mongoc_collection_insert_one (collection, doc, &opts, NULL, &error), error); BSON_APPEND_REGEX (&q, "hello", "^/wo", "i"); - count = mongoc_collection_count_documents ( - collection, &q, NULL, NULL, NULL, &error); + count = mongoc_collection_count_documents (collection, &q, NULL, NULL, NULL, &error); ASSERT (count > 0); ASSERT_OR_PRINT (mongoc_collection_drop (collection, &error), error); @@ -1115,12 +992,10 @@ test_decimal128 (void *ctx) } ASSERT (r); - count = mongoc_collection_count_documents ( - collection, &query, NULL, NULL, NULL, &error); + count = mongoc_collection_count_documents (collection, &query, NULL, NULL, NULL, &error); ASSERT (count > 0); - cursor = mongoc_collection_find ( - collection, MONGOC_QUERY_NONE, 0, 0, 0, &query, NULL, NULL); + cursor = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, 0, &query, NULL, NULL); ASSERT (mongoc_cursor_next (cursor, &dec)); ASSERT (bson_iter_init (&dec_iter, dec)); @@ -1129,8 +1004,7 @@ test_decimal128 (void *ctx) ASSERT (BSON_ITER_HOLDS_DECIMAL128 (&dec_iter)); bson_iter_decimal128 (&dec_iter, &read_decimal); - ASSERT (read_decimal.high == decimal128.high && - read_decimal.low == decimal128.low); + ASSERT (read_decimal.high == decimal128.high && read_decimal.low == decimal128.low); bson_destroy (doc); bson_destroy (&query); @@ -1180,9 +1054,7 @@ test_update (void) bson_append_int64 (&b, "int64", 5, 12345678); bson_append_bool (&b, "bool", 4, 1); - ASSERT_OR_PRINT ( - mongoc_collection_insert_one (collection, &b, NULL, NULL, &error), - error); + ASSERT_OR_PRINT (mongoc_collection_insert_one (collection, &b, NULL, NULL, &error), error); bson_init (&q); bson_append_oid (&q, "_id", 3, &oid); @@ -1192,9 +1064,7 @@ test_update (void) bson_append_utf8 (&set, "utf8", 4, "updated", 7); bson_append_document_end (&u, &set); - ASSERT_OR_PRINT (mongoc_collection_update ( - collection, MONGOC_UPDATE_NONE, &q, &u, NULL, &error), - error); + ASSERT_OR_PRINT (mongoc_collection_update (collection, MONGOC_UPDATE_NONE, &q, &u, NULL, &error), error); bson_destroy (&b); bson_destroy (&q); @@ -1205,8 +1075,7 @@ test_update (void) bson_init (&u); BSON_APPEND_INT32 (&u, "abcd", 1); BSON_APPEND_INT32 (&u, "$hi", 1); - r = mongoc_collection_update ( - collection, MONGOC_UPDATE_NONE, &q, &u, NULL, &error); + r = mongoc_collection_update (collection, MONGOC_UPDATE_NONE, &q, &u, NULL, &error); ASSERT (!r); ASSERT (error.domain == MONGOC_ERROR_COMMAND); ASSERT (error.code == MONGOC_ERROR_COMMAND_INVALID_ARG); @@ -1216,8 +1085,7 @@ test_update (void) bson_init (&q); bson_init (&u); BSON_APPEND_INT32 (&u, "" /* empty key */, 1); - r = mongoc_collection_update ( - collection, MONGOC_UPDATE_NONE, &q, &u, NULL, &error); + r = mongoc_collection_update (collection, MONGOC_UPDATE_NONE, &q, &u, NULL, &error); ASSERT (!r); ASSERT (error.domain == MONGOC_ERROR_COMMAND); ASSERT (error.code == MONGOC_ERROR_COMMAND_INVALID_ARG); @@ -1263,8 +1131,7 @@ test_update_pipeline (void *ctx) (i.e. {"0": value, "1": value, "2": value}) */ pipeline = tmp_bson ("{'0': {'$replaceRoot': {'newRoot': '$nums'}}," " '1': {'$addFields': {'z': 3}}}"); - res = mongoc_collection_update_one ( - collection, b, pipeline, NULL, NULL, &error); + res = mongoc_collection_update_one (collection, b, pipeline, NULL, NULL, &error); ASSERT_OR_PRINT (res, error); res = mongoc_collection_insert_one (collection, b, NULL, NULL, &error); @@ -1273,19 +1140,14 @@ test_update_pipeline (void *ctx) /* ensure that arrays sent to mongoc_collection_replace_one are not treated as pipelines */ replacement = tmp_bson ("{'0': 0, '1': 1}"); - res = mongoc_collection_replace_one ( - collection, b, replacement, NULL, NULL, &error); + res = mongoc_collection_replace_one (collection, b, replacement, NULL, NULL, &error); ASSERT_OR_PRINT (res, error); /* ensure that a pipeline with an empty document is considered invalid */ pipeline = tmp_bson ("{ '0': {} }"); - res = mongoc_collection_update_one ( - collection, b, pipeline, NULL, NULL, &error); + res = mongoc_collection_update_one (collection, b, pipeline, NULL, NULL, &error); ASSERT (!res); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Invalid key"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid key"); mongoc_collection_destroy (collection); mongoc_database_destroy (database); @@ -1312,17 +1174,13 @@ test_update_oversize (void *ctx) collection = get_test_collection (client, "test_update_oversize"); /* first test oversized selector. two huge strings make the doc too large */ - BSON_ASSERT (bson_append_utf8 ( - &huge, "x", 1, huge_string (client), (int) huge_string_length (client))); + BSON_ASSERT (bson_append_utf8 (&huge, "x", 1, huge_string (client), (int) huge_string_length (client))); - BSON_ASSERT (bson_append_utf8 ( - &huge, "y", 1, huge_string (client), (int) huge_string_length (client))); + BSON_ASSERT (bson_append_utf8 (&huge, "y", 1, huge_string (client), (int) huge_string_length (client))); - r = mongoc_collection_update ( - collection, MONGOC_UPDATE_NONE, &huge, &empty, NULL, &error); + r = mongoc_collection_update (collection, MONGOC_UPDATE_NONE, &huge, &empty, NULL, &error); ASSERT (!r); - ASSERT_ERROR_CONTAINS ( - error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "too large"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "too large"); /* test oversized update operator */ huger = bson_malloc (huger_sz + 1); @@ -1332,11 +1190,9 @@ test_update_oversize (void *ctx) BSON_ASSERT (bson_append_utf8 (&child, "x", 1, huger, (int) huger_sz)); BSON_ASSERT (bson_append_document_end (&huge_update, &child)); - r = mongoc_collection_update ( - collection, MONGOC_UPDATE_NONE, &empty, &huge_update, NULL, &error); + r = mongoc_collection_update (collection, MONGOC_UPDATE_NONE, &empty, &huge_update, NULL, &error); ASSERT (!r); - ASSERT_ERROR_CONTAINS ( - error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "too large"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "too large"); bson_free (huger); bson_destroy (&huge); @@ -1418,16 +1274,13 @@ test_remove_oversize (void *ctx) collection = get_test_collection (client, "test_remove_oversize"); /* two huge strings make the doc too large */ - BSON_ASSERT (bson_append_utf8 ( - &doc, "x", 1, huge_string (client), (int) huge_string_length (client))); + BSON_ASSERT (bson_append_utf8 (&doc, "x", 1, huge_string (client), (int) huge_string_length (client))); - BSON_ASSERT (bson_append_utf8 ( - &doc, "y", 1, huge_string (client), (int) huge_string_length (client))); + BSON_ASSERT (bson_append_utf8 (&doc, "y", 1, huge_string (client), (int) huge_string_length (client))); r = mongoc_collection_delete_many (collection, &doc, NULL, NULL, &error); ASSERT (!r); - ASSERT_ERROR_CONTAINS ( - error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "too large"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_BSON, MONGOC_ERROR_BSON_INVALID, "too large"); bson_destroy (&doc); mongoc_collection_destroy (collection); @@ -1450,8 +1303,7 @@ test_insert_w0 (void) wc = mongoc_write_concern_new (); mongoc_write_concern_set_w (wc, 0); mongoc_write_concern_append (wc, &opts); - r = mongoc_collection_insert_one ( - collection, tmp_bson ("{}"), &opts, NULL, &error); + r = mongoc_collection_insert_one (collection, tmp_bson ("{}"), &opts, NULL, &error); ASSERT_OR_PRINT (r, error); ASSERT (mongoc_collection_get_last_error (collection) == NULL); @@ -1475,12 +1327,8 @@ test_update_w0 (void) collection = get_test_collection (client, "test_update_w0"); wc = mongoc_write_concern_new (); mongoc_write_concern_set_w (wc, 0); - r = mongoc_collection_update (collection, - MONGOC_UPDATE_NONE, - tmp_bson ("{}"), - tmp_bson ("{'$set': {'x': 1}}"), - wc, - &error); + r = mongoc_collection_update ( + collection, MONGOC_UPDATE_NONE, tmp_bson ("{}"), tmp_bson ("{'$set': {'x': 1}}"), wc, &error); ASSERT_OR_PRINT (r, error); ASSERT (bson_empty (mongoc_collection_get_last_error (collection))); @@ -1506,8 +1354,7 @@ test_remove_w0 (void) wc = mongoc_write_concern_new (); mongoc_write_concern_set_w (wc, 0); mongoc_write_concern_append (wc, &opts); - r = mongoc_collection_delete_many ( - collection, tmp_bson ("{}"), &opts, &reply, &error); + r = mongoc_collection_delete_many (collection, tmp_bson ("{}"), &opts, &reply, &error); ASSERT_OR_PRINT (r, error); ASSERT (bson_empty (&reply)); @@ -1534,15 +1381,13 @@ test_insert_twice_w0 (void) wc = mongoc_write_concern_new (); mongoc_write_concern_set_w (wc, 0); mongoc_write_concern_append (wc, &opts); - r = mongoc_collection_insert_one ( - collection, tmp_bson ("{'_id': 1}"), &opts, NULL, &error); + r = mongoc_collection_insert_one (collection, tmp_bson ("{'_id': 1}"), &opts, NULL, &error); ASSERT_OR_PRINT (r, error); ASSERT (mongoc_collection_get_last_error (collection) == NULL); /* Insert same document for the second time, but we should not get * an error since we don't wait for a server response */ - r = mongoc_collection_insert_one ( - collection, tmp_bson ("{'_id': 1}"), &opts, NULL, &error); + r = mongoc_collection_insert_one (collection, tmp_bson ("{'_id': 1}"), &opts, NULL, &error); ASSERT_OR_PRINT (r, error); ASSERT (mongoc_collection_get_last_error (collection) == NULL); @@ -1585,28 +1430,20 @@ test_index (void) bson_init (&keys); bson_append_int32 (&keys, "hello", -1, 1); - ASSERT_OR_PRINT ( - mongoc_collection_create_index (collection, &keys, &opt, &error), error); + ASSERT_OR_PRINT (mongoc_collection_create_index (collection, &keys, &opt, &error), error); - ASSERT_OR_PRINT ( - mongoc_collection_create_index (collection, &keys, &opt, &error), error); + ASSERT_OR_PRINT (mongoc_collection_create_index (collection, &keys, &opt, &error), error); - ASSERT_OR_PRINT ( - mongoc_collection_drop_index (collection, "hello_1", &error), error); + ASSERT_OR_PRINT (mongoc_collection_drop_index (collection, "hello_1", &error), error); - ASSERT_OR_PRINT ( - mongoc_collection_create_index (collection, &keys, &opt, &error), error); + ASSERT_OR_PRINT (mongoc_collection_create_index (collection, &keys, &opt, &error), error); /* invalid writeConcern */ bad_wc->wtimeout = -10; bson_reinit (opts); mongoc_write_concern_append_bad (bad_wc, opts); - ASSERT (!mongoc_collection_drop_index_with_opts ( - collection, "hello_1", opts, &error)); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Invalid writeConcern"); + ASSERT (!mongoc_collection_drop_index_with_opts (collection, "hello_1", opts, &error)); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid writeConcern"); bad_wc->wtimeout = 0; error.code = 0; error.domain = 0; @@ -1615,9 +1452,7 @@ test_index (void) mongoc_write_concern_set_w (good_wc, 1); bson_reinit (opts); mongoc_write_concern_append (good_wc, opts); - ASSERT_OR_PRINT (mongoc_collection_drop_index_with_opts ( - collection, "hello_1", opts, &error), - error); + ASSERT_OR_PRINT (mongoc_collection_drop_index_with_opts (collection, "hello_1", opts, &error), error); ASSERT (!error.code); ASSERT (!error.domain); @@ -1625,13 +1460,10 @@ test_index (void) mongoc_write_concern_set_w (bad_wc, 99); if (!test_framework_is_mongos ()) { /* skip if sharded */ - ASSERT_OR_PRINT ( - mongoc_collection_create_index (collection, &keys, &opt, &error), - error); + ASSERT_OR_PRINT (mongoc_collection_create_index (collection, &keys, &opt, &error), error); bson_reinit (opts); mongoc_write_concern_append_bad (bad_wc, opts); - r = mongoc_collection_drop_index_with_opts ( - collection, "hello_1", opts, &error); + r = mongoc_collection_drop_index_with_opts (collection, "hello_1", opts, &error); ASSERT (!r); assert_wc_oob_error (&error); } @@ -1687,14 +1519,10 @@ test_index_w_write_concern (void) bad_wc->wtimeout = -10; bson_reinit (opts); mongoc_write_concern_append_bad (bad_wc, opts); - ASSERT (!mongoc_collection_create_index_with_opts ( - collection, &keys, &opt, opts, &reply, &error)); + ASSERT (!mongoc_collection_create_index_with_opts (collection, &keys, &opt, opts, &reply, &error)); bson_destroy (&reply); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Invalid writeConcern"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid writeConcern"); bad_wc->wtimeout = 0; error.code = 0; error.domain = 0; @@ -1703,8 +1531,7 @@ test_index_w_write_concern (void) mongoc_write_concern_set_w (good_wc, 1); bson_reinit (opts); mongoc_write_concern_append (good_wc, opts); - result = mongoc_collection_create_index_with_opts ( - collection, &keys, &opt, opts, &reply, &error); + result = mongoc_collection_create_index_with_opts (collection, &keys, &opt, opts, &reply, &error); ASSERT_OR_PRINT (result, error); ASSERT (!error.code); @@ -1724,8 +1551,7 @@ test_index_w_write_concern (void) mongoc_write_concern_append_bad (bad_wc, opts); /* skip this part of the test if sharded cluster */ if (!is_mongos) { - ASSERT (!mongoc_collection_create_index_with_opts ( - collection, &keys, &opt, opts, &reply, &error)); + ASSERT (!mongoc_collection_create_index_with_opts (collection, &keys, &opt, opts, &reply, &error)); assert_wc_oob_error (&error); ASSERT (!bson_empty (&reply)); @@ -1733,12 +1559,10 @@ test_index_w_write_concern (void) } /* Make sure it doesn't crash with a NULL reply or writeConcern */ - result = mongoc_collection_create_index_with_opts ( - collection, &keys, &opt, NULL, NULL, &error); + result = mongoc_collection_create_index_with_opts (collection, &keys, &opt, NULL, NULL, &error); ASSERT_OR_PRINT (result, error); - ASSERT_OR_PRINT ( - mongoc_collection_drop_index (collection, "hello_1", &error), error); + ASSERT_OR_PRINT (mongoc_collection_drop_index (collection, "hello_1", &error), error); /* Now attempt to create an invalid index which the server will reject */ bson_reinit (&keys); @@ -1749,8 +1573,7 @@ test_index_w_write_concern (void) This fails both on legacy and modern versions of the server */ BSON_APPEND_UTF8 (&keys, "abc", "hallo thar"); - result = mongoc_collection_create_index_with_opts ( - collection, &keys, &opt, NULL, &reply, &error); + result = mongoc_collection_create_index_with_opts (collection, &keys, &opt, NULL, &reply, &error); bson_destroy (&reply); ASSERT (!result); @@ -1758,8 +1581,7 @@ test_index_w_write_concern (void) memset (&error, 0, sizeof (error)); /* Try again but with reply NULL. Shouldn't crash */ - result = mongoc_collection_create_index_with_opts ( - collection, &keys, &opt, NULL, NULL, &error); + result = mongoc_collection_create_index_with_opts (collection, &keys, &opt, NULL, NULL, &error); ASSERT (!result); ASSERT (strlen (error.message) > 0); @@ -1799,15 +1621,11 @@ test_index_compound (void) bson_init (&keys); bson_append_int32 (&keys, "hello", -1, 1); bson_append_int32 (&keys, "world", -1, -1); - ASSERT_OR_PRINT ( - mongoc_collection_create_index (collection, &keys, &opt, &error), error); + ASSERT_OR_PRINT (mongoc_collection_create_index (collection, &keys, &opt, &error), error); - ASSERT_OR_PRINT ( - mongoc_collection_create_index (collection, &keys, &opt, &error), error); + ASSERT_OR_PRINT (mongoc_collection_create_index (collection, &keys, &opt, &error), error); - ASSERT_OR_PRINT ( - mongoc_collection_drop_index (collection, "hello_1_world_-1", &error), - error); + ASSERT_OR_PRINT (mongoc_collection_drop_index (collection, "hello_1_world_-1", &error), error); bson_destroy (&keys); @@ -1849,11 +1667,9 @@ test_index_geo (void *unused) /* Create a basic 2d index */ bson_init (&keys); BSON_APPEND_UTF8 (&keys, "location", "2d"); - ASSERT_OR_PRINT ( - mongoc_collection_create_index (collection, &keys, &opt, &error), error); + ASSERT_OR_PRINT (mongoc_collection_create_index (collection, &keys, &opt, &error), error); - ASSERT_OR_PRINT ( - mongoc_collection_drop_index (collection, "location_2d", &error), error); + ASSERT_OR_PRINT (mongoc_collection_drop_index (collection, "location_2d", &error), error); /* Create a 2d index with bells and whistles */ bson_destroy (&keys); @@ -1866,21 +1682,15 @@ test_index_geo (void *unused) opt.geo_options = &geo_opt; /* TODO this hack is needed for single-threaded tests */ - id = mc_tpld_servers_const (mc_tpld_unsafe_get_const (client->topology)) - ->items[0] - .id; - description = mongoc_topology_description_server_by_id_const ( - mc_tpld_unsafe_get_const (client->topology), id, &error); + id = mc_tpld_servers_const (mc_tpld_unsafe_get_const (client->topology))->items[0].id; + description = + mongoc_topology_description_server_by_id_const (mc_tpld_unsafe_get_const (client->topology), id, &error); ASSERT_OR_PRINT (description, error); if (description->max_wire_version > 0) { - ASSERT_OR_PRINT ( - mongoc_collection_create_index (collection, &keys, &opt, &error), - error); + ASSERT_OR_PRINT (mongoc_collection_create_index (collection, &keys, &opt, &error), error); - ASSERT_OR_PRINT ( - mongoc_collection_drop_index (collection, "location_2d", &error), - error); + ASSERT_OR_PRINT (mongoc_collection_drop_index (collection, "location_2d", &error), error); } /* Create a Haystack index */ @@ -1894,16 +1704,13 @@ test_index_geo (void *unused) opt.geo_options = &geo_opt; - description = mongoc_topology_description_server_by_id_const ( - mc_tpld_unsafe_get_const (client->topology), id, &error); + description = + mongoc_topology_description_server_by_id_const (mc_tpld_unsafe_get_const (client->topology), id, &error); ASSERT_OR_PRINT (description, error); if (description->max_wire_version > 0) { - ASSERT_OR_PRINT ( - mongoc_collection_create_index (collection, &keys, &opt, &error), - error); + ASSERT_OR_PRINT (mongoc_collection_create_index (collection, &keys, &opt, &error), error); - r = mongoc_collection_drop_index ( - collection, "location_geoHaystack_category_1", &error); + r = mongoc_collection_drop_index (collection, "location_geoHaystack_category_1", &error); ASSERT_OR_PRINT (r, error); } @@ -1927,9 +1734,7 @@ storage_engine (mongoc_client_t *client) char *engine = bson_strdup ("mmapv1"); BSON_APPEND_INT32 (&cmd, "getCmdLineOpts", 1); - ASSERT_OR_PRINT (mongoc_client_command_simple ( - client, "admin", &cmd, NULL, &reply, &error), - error); + ASSERT_OR_PRINT (mongoc_client_command_simple (client, "admin", &cmd, NULL, &reply, &error), error); if (bson_iter_init_find (&iter, &reply, "parsed.storage.engine")) { engine = bson_strdup (bson_iter_utf8 (&iter, NULL)); @@ -1981,8 +1786,7 @@ test_index_storage (void) opt.storage_options = (mongoc_index_opt_storage_t *) &wt_opt; - ASSERT_OR_PRINT ( - mongoc_collection_create_index (collection, &keys, &opt, &error), error); + ASSERT_OR_PRINT (mongoc_collection_create_index (collection, &keys, &opt, &error), error); cleanup: if (engine) @@ -2011,8 +1815,7 @@ test_count (void) ASSERT (collection); bson_init (&b); - count = mongoc_collection_count ( - collection, MONGOC_QUERY_NONE, &b, 0, 0, NULL, &error); + count = mongoc_collection_count (collection, MONGOC_QUERY_NONE, &b, 0, 0, NULL, &error); bson_destroy (&b); if (count == -1) { @@ -2039,20 +1842,17 @@ test_count_read_pref (void) server = mock_mongos_new (WIRE_VERSION_MIN); mock_server_run (server); mock_server_auto_endsessions (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); collection = mongoc_client_get_collection (client, "db", "collection"); prefs = mongoc_read_prefs_new (MONGOC_READ_SECONDARY); mongoc_collection_set_read_prefs (collection, prefs); - future = future_collection_count ( - collection, MONGOC_QUERY_NONE, NULL, 0, 0, NULL, &error); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db'," - " 'count': 'collection'," - " '$readPreference': {'mode': 'secondary'}}")); + future = future_collection_count (collection, MONGOC_QUERY_NONE, NULL, 0, 0, NULL, &error); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'db'," + " 'count': 'collection'," + " '$readPreference': {'mode': 'secondary'}}")); reply_to_request_simple (request, "{'ok': 1, 'n': 1}"); ASSERT_OR_PRINT (1 == future_get_int64_t (future), error); @@ -2081,21 +1881,17 @@ test_count_read_concern (void) server = mock_server_with_auto_hello (WIRE_VERSION_MIN); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); ASSERT (client); collection = mongoc_client_get_collection (client, "test", "test"); ASSERT (collection); bson_init (&b); - future = future_collection_count ( - collection, MONGOC_QUERY_NONE, &b, 0, 0, NULL, &error); + future = future_collection_count (collection, MONGOC_QUERY_NONE, &b, 0, 0, NULL, &error); bson_destroy (&b); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'test', 'count': 'test', 'query': {}}")); + request = + mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'test', 'count': 'test', 'query': {}}")); reply_to_request_simple (request, "{ 'n' : 42, 'ok' : 1 } "); count = future_get_int64_t (future); @@ -2109,16 +1905,14 @@ test_count_read_concern (void) mongoc_collection_set_read_concern (collection, rc); bson_init (&b); - future = future_collection_count ( - collection, MONGOC_QUERY_NONE, &b, 0, 0, NULL, &error); + future = future_collection_count (collection, MONGOC_QUERY_NONE, &b, 0, 0, NULL, &error); bson_destroy (&b); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'test'," - " 'count': 'test'," - " 'query': {}," - " 'readConcern': {'level': 'majority'}}")); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'test'," + " 'count': 'test'," + " 'query': {}," + " 'readConcern': {'level': 'majority'}}")); reply_to_request_simple (request, "{ 'n' : 43, 'ok' : 1 } "); count = future_get_int64_t (future); @@ -2133,16 +1927,14 @@ test_count_read_concern (void) mongoc_collection_set_read_concern (collection, rc); bson_init (&b); - future = future_collection_count ( - collection, MONGOC_QUERY_NONE, &b, 0, 0, NULL, &error); + future = future_collection_count (collection, MONGOC_QUERY_NONE, &b, 0, 0, NULL, &error); bson_destroy (&b); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'test'," - " 'count': 'test'," - " 'query': {}," - " 'readConcern': {'level': 'local'}}")); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'test'," + " 'count': 'test'," + " 'query': {}," + " 'readConcern': {'level': 'local'}}")); reply_to_request_simple (request, "{ 'n' : 44, 'ok' : 1 } "); count = future_get_int64_t (future); @@ -2157,16 +1949,14 @@ test_count_read_concern (void) mongoc_collection_set_read_concern (collection, rc); bson_init (&b); - future = future_collection_count ( - collection, MONGOC_QUERY_NONE, &b, 0, 0, NULL, &error); + future = future_collection_count (collection, MONGOC_QUERY_NONE, &b, 0, 0, NULL, &error); bson_destroy (&b); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'test'," - " 'count': 'test'," - " 'query': {}," - " 'readConcern': {'level': 'futureCompatible'}}")); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'test'," + " 'count': 'test'," + " 'query': {}," + " 'readConcern': {'level': 'futureCompatible'}}")); reply_to_request_simple (request, "{ 'n' : 45, 'ok' : 1 } "); count = future_get_int64_t (future); @@ -2181,16 +1971,14 @@ test_count_read_concern (void) mongoc_collection_set_read_concern (collection, rc); bson_init (&b); - future = future_collection_count ( - collection, MONGOC_QUERY_NONE, &b, 0, 0, NULL, &error); + future = future_collection_count (collection, MONGOC_QUERY_NONE, &b, 0, 0, NULL, &error); bson_destroy (&b); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'test'," - " 'count': 'test'," - " 'query': {}," - " 'readConcern': { '$exists': false }}")); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'test'," + " 'count': 'test'," + " 'query': {}," + " 'readConcern': { '$exists': false }}")); reply_to_request_simple (request, "{ 'n' : 46, 'ok' : 1 } "); count = future_get_int64_t (future); @@ -2204,16 +1992,14 @@ test_count_read_concern (void) mongoc_collection_set_read_concern (collection, rc); bson_init (&b); - future = future_collection_count ( - collection, MONGOC_QUERY_NONE, &b, 0, 0, NULL, &error); + future = future_collection_count (collection, MONGOC_QUERY_NONE, &b, 0, 0, NULL, &error); bson_destroy (&b); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'test'," - " 'count': 'test'," - " 'query': {}," - " 'readConcern': { '$exists': false }}")); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'test'," + " 'count': 'test'," + " 'query': {}," + " 'readConcern': { '$exists': false }}")); reply_to_request_simple (request, "{ 'n' : 47, 'ok' : 1 } "); count = future_get_int64_t (future); @@ -2266,8 +2052,7 @@ test_count_read_concern_live (void *unused) } bson_init (&b); - count = mongoc_collection_count ( - collection, MONGOC_QUERY_NONE, &b, 0, 0, NULL, &error); + count = mongoc_collection_count (collection, MONGOC_QUERY_NONE, &b, 0, 0, NULL, &error); bson_destroy (&b); ASSERT_OR_PRINT (count != -1, error); ASSERT_CMPINT64 (count, ==, 0); @@ -2278,8 +2063,7 @@ test_count_read_concern_live (void *unused) mongoc_collection_set_read_concern (collection, rc); bson_init (&b); - count = mongoc_collection_count ( - collection, MONGOC_QUERY_NONE, &b, 0, 0, NULL, &error); + count = mongoc_collection_count (collection, MONGOC_QUERY_NONE, &b, 0, 0, NULL, &error); bson_destroy (&b); ASSERT_OR_PRINT (count != -1, error); ASSERT_CMPINT64 (count, ==, 0); @@ -2291,8 +2075,7 @@ test_count_read_concern_live (void *unused) mongoc_collection_set_read_concern (collection, rc); bson_init (&b); - count = mongoc_collection_count ( - collection, MONGOC_QUERY_NONE, &b, 0, 0, NULL, &error); + count = mongoc_collection_count (collection, MONGOC_QUERY_NONE, &b, 0, 0, NULL, &error); bson_destroy (&b); ASSERT_OR_PRINT (count != -1, error); ASSERT_CMPINT64 (count, ==, 0); @@ -2304,8 +2087,7 @@ test_count_read_concern_live (void *unused) mongoc_collection_set_read_concern (collection, rc); bson_init (&b); - count = mongoc_collection_count ( - collection, MONGOC_QUERY_NONE, &b, 0, 0, NULL, &error); + count = mongoc_collection_count (collection, MONGOC_QUERY_NONE, &b, 0, 0, NULL, &error); bson_destroy (&b); ASSERT_OR_PRINT (count != -1, error); ASSERT_CMPINT64 (count, ==, 0); @@ -2321,8 +2103,7 @@ skip_unless_server_has_decimal128 (void) if (!TestSuite_CheckLive ()) { return 0; } - if (test_framework_get_server_version () >= - test_framework_str_to_version ("3.3.5")) { + if (test_framework_get_server_version () >= test_framework_str_to_version ("3.3.5")) { return 1; } return 0; @@ -2352,23 +2133,14 @@ test_count_with_opts (void) server = mock_mongos_new (WIRE_VERSION_MIN); mock_server_run (server); mock_server_auto_endsessions (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); collection = mongoc_client_get_collection (client, "db", "collection"); - future = future_collection_count_with_opts (collection, - MONGOC_QUERY_SECONDARY_OK, - NULL, - 0, - 0, - tmp_bson ("{'opt': 1}"), - NULL, - &error); + future = future_collection_count_with_opts ( + collection, MONGOC_QUERY_SECONDARY_OK, NULL, 0, 0, tmp_bson ("{'opt': 1}"), NULL, &error); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db', 'count': 'collection', 'opt': 1}")); + request = + mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', 'count': 'collection', 'opt': 1}")); reply_to_request_simple (request, "{'ok': 1, 'n': 1}"); ASSERT_OR_PRINT (1 == future_get_int64_t (future), error); @@ -2394,26 +2166,17 @@ test_count_with_collation (void) server = mock_server_with_auto_hello (WIRE_VERSION_MIN); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); collection = mongoc_client_get_collection (client, "db", "collection"); future = future_collection_count_with_opts ( - collection, - MONGOC_QUERY_SECONDARY_OK, - NULL, - 0, - 0, - tmp_bson ("{'collation': {'locale': 'en'}}"), - NULL, - &error); + collection, MONGOC_QUERY_SECONDARY_OK, NULL, 0, 0, tmp_bson ("{'collation': {'locale': 'en'}}"), NULL, &error); - request = - mock_server_receives_msg (server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db'," - " 'count': 'collection'," - " 'collation': {'locale': 'en'}}")); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'db'," + " 'count': 'collection'," + " 'collation': {'locale': 'en'}}")); reply_to_request_simple (request, "{'ok': 1, 'n': 1}"); ASSERT_OR_PRINT (1 == future_get_int64_t (future), error); request_destroy (request); @@ -2441,24 +2204,17 @@ test_count_documents (void) server = mock_server_with_auto_hello (WIRE_VERSION_MAX); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); collection = mongoc_client_get_collection (client, "db", "coll"); - future = - future_collection_count_documents (collection, - tmp_bson ("{'x': 1}"), - tmp_bson ("{'limit': 2, 'skip': 1}"), - NULL, - &reply, - &error); + future = future_collection_count_documents ( + collection, tmp_bson ("{'x': 1}"), tmp_bson ("{'limit': 2, 'skip': 1}"), NULL, &reply, &error); - request = mock_server_receives_msg ( - server, - 0, - tmp_bson ("{'aggregate': 'coll', 'pipeline': [{'$match': " - "{'x': 1}}, {'$skip': 1}, {'$limit': 2}, {'$group': " - "{'n': {'$sum': 1}}}]}")); + request = mock_server_receives_msg (server, + 0, + tmp_bson ("{'aggregate': 'coll', 'pipeline': [{'$match': " + "{'x': 1}}, {'$skip': 1}, {'$limit': 2}, {'$group': " + "{'n': {'$sum': 1}}}]}")); reply_to_request_simple (request, server_reply); ASSERT_OR_PRINT (123 == future_get_int64_t (future), error); ASSERT_MATCH (&reply, server_reply); @@ -2467,21 +2223,15 @@ test_count_documents (void) request_destroy (request); future_destroy (future); - future = - future_collection_count_documents (collection, - tmp_bson ("{}"), - tmp_bson ("{'limit': 2, 'skip': 1}"), - NULL, - &reply, - &error); + future = future_collection_count_documents ( + collection, tmp_bson ("{}"), tmp_bson ("{'limit': 2, 'skip': 1}"), NULL, &reply, &error); /* even with an empty filter, we still prepend $match */ - request = mock_server_receives_msg ( - server, - 0, - tmp_bson ("{'aggregate': 'coll', 'pipeline': [{'$match': {}}, {'$skip': " - "1}, {'$limit': 2}, {'$group': " - "{'n': {'$sum': 1}}}]}")); + request = mock_server_receives_msg (server, + 0, + tmp_bson ("{'aggregate': 'coll', 'pipeline': [{'$match': {}}, {'$skip': " + "1}, {'$limit': 2}, {'$group': " + "{'n': {'$sum': 1}}}]}")); reply_to_request_simple (request, server_reply); ASSERT_OR_PRINT (123 == future_get_int64_t (future), error); ASSERT_MATCH (&reply, server_reply); @@ -2490,18 +2240,13 @@ test_count_documents (void) future_destroy (future); // Test appending maxTimeMS. - future = future_collection_count_documents (collection, - tmp_bson ("{}"), - tmp_bson ("{'maxTimeMS': 123}"), - NULL, - &reply, - &error); + future = future_collection_count_documents ( + collection, tmp_bson ("{}"), tmp_bson ("{'maxTimeMS': 123}"), NULL, &reply, &error); - request = mock_server_receives_msg ( - server, - 0, - tmp_bson ("{'aggregate': 'coll', 'pipeline': [{'$match': {}}, {'$group': " - "{'n': {'$sum': 1}}}], 'maxTimeMS': 123}")); + request = mock_server_receives_msg (server, + 0, + tmp_bson ("{'aggregate': 'coll', 'pipeline': [{'$match': {}}, {'$group': " + "{'n': {'$sum': 1}}}], 'maxTimeMS': 123}")); reply_to_request_simple (request, server_reply); ASSERT_OR_PRINT (123 == future_get_int64_t (future), error); ASSERT_MATCH (&reply, server_reply); @@ -2529,8 +2274,7 @@ test_count_documents_live (void) collection = mongoc_client_get_collection (client, "test", "test"); ASSERT (collection); - count = mongoc_collection_count_documents ( - collection, tmp_bson ("{}"), NULL, NULL, NULL, &error); + count = mongoc_collection_count_documents (collection, tmp_bson ("{}"), NULL, NULL, NULL, &error); ASSERT_OR_PRINT (count != -1, error); @@ -2553,15 +2297,13 @@ test_estimated_document_count (void) server = mock_server_with_auto_hello (WIRE_VERSION_MAX); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); collection = mongoc_client_get_collection (client, "db", "coll"); future = future_collection_estimated_document_count ( collection, tmp_bson ("{'limit': 2, 'skip': 1}"), NULL, &reply, &error); - request = mock_server_receives_msg ( - server, 0, tmp_bson ("{'count': 'coll', 'limit': 2, 'skip': 1}")); + request = mock_server_receives_msg (server, 0, tmp_bson ("{'count': 'coll', 'limit': 2, 'skip': 1}")); reply_to_request_simple (request, server_reply); ASSERT_OR_PRINT (123 == future_get_int64_t (future), error); ASSERT_MATCH (&reply, server_reply); @@ -2569,8 +2311,8 @@ test_estimated_document_count (void) future_destroy (future); /* CDRIVER-3612: ensure that an explicit session triggers a client error */ - future = future_collection_estimated_document_count ( - collection, tmp_bson ("{'sessionId': 123}"), NULL, &reply, &error); + future = + future_collection_estimated_document_count (collection, tmp_bson ("{'sessionId': 123}"), NULL, &reply, &error); ASSERT (-1 == future_get_int64_t (future)); ASSERT_ERROR_CONTAINS (error, @@ -2601,8 +2343,7 @@ test_estimated_document_count_live (void) collection = mongoc_client_get_collection (client, "test", "test"); ASSERT (collection); - count = mongoc_collection_estimated_document_count ( - collection, NULL, NULL, NULL, &error); + count = mongoc_collection_estimated_document_count (collection, NULL, NULL, NULL, &error); ASSERT (count != -1); @@ -2639,24 +2380,17 @@ test_drop (void) ASSERT (collection); doc = BCON_NEW ("hello", "world"); - ASSERT_OR_PRINT ( - mongoc_collection_insert_one (collection, doc, NULL, NULL, &error), - error); + ASSERT_OR_PRINT (mongoc_collection_insert_one (collection, doc, NULL, NULL, &error), error); ASSERT_OR_PRINT (mongoc_collection_drop (collection, &error), error); /* invalid writeConcern */ bad_wc->wtimeout = -10; - ASSERT_OR_PRINT ( - mongoc_collection_insert_one (collection, doc, NULL, NULL, &error), - error); + ASSERT_OR_PRINT (mongoc_collection_insert_one (collection, doc, NULL, NULL, &error), error); bson_reinit (opts); mongoc_write_concern_append_bad (bad_wc, opts); ASSERT (!mongoc_collection_drop_with_opts (collection, opts, &error)); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Invalid writeConcern"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid writeConcern"); bad_wc->wtimeout = 0; error.code = 0; error.domain = 0; @@ -2665,8 +2399,7 @@ test_drop (void) mongoc_write_concern_set_w (good_wc, 1); bson_reinit (opts); mongoc_write_concern_append (good_wc, opts); - ASSERT_OR_PRINT (mongoc_collection_drop_with_opts (collection, opts, &error), - error); + ASSERT_OR_PRINT (mongoc_collection_drop_with_opts (collection, opts, &error), error); ASSERT (!error.code); ASSERT (!error.domain); @@ -2674,9 +2407,7 @@ test_drop (void) mongoc_write_concern_set_w (bad_wc, 99); if (!test_framework_is_mongos ()) { /* skip if sharded */ - ASSERT_OR_PRINT ( - mongoc_collection_insert_one (collection, doc, NULL, NULL, &error), - error); + ASSERT_OR_PRINT (mongoc_collection_insert_one (collection, doc, NULL, NULL, &error), error); bson_reinit (opts); mongoc_write_concern_append_bad (bad_wc, opts); r = mongoc_collection_drop_with_opts (collection, opts, &error); @@ -2726,18 +2457,15 @@ test_aggregate_bypass (void *context) bson_free (collname); collname = gen_collection_name ("bypass"); - options = tmp_bson ( - "{'validator': {'number': {'$gte': 5}}, 'validationAction': 'error'}"); - out_collection = - mongoc_database_create_collection (database, collname, options, &error); + options = tmp_bson ("{'validator': {'number': {'$gte': 5}}, 'validationAction': 'error'}"); + out_collection = mongoc_database_create_collection (database, collname, options, &error); ASSERT_OR_PRINT (out_collection, error); bson_free (dbname); bson_free (collname); /* Generate some example data */ - bulk = - mongoc_collection_create_bulk_operation_with_opts (data_collection, NULL); + bulk = mongoc_collection_create_bulk_operation_with_opts (data_collection, NULL); for (i = 0; i < 3; i++) { bson_t *document; @@ -2756,8 +2484,7 @@ test_aggregate_bypass (void *context) json = bson_strdup_printf ("[{'$out': '%s'}]", out_collection->collection); pipeline = tmp_bson (json); - cursor = mongoc_collection_aggregate ( - data_collection, MONGOC_QUERY_NONE, pipeline, NULL, NULL); + cursor = mongoc_collection_aggregate (data_collection, MONGOC_QUERY_NONE, pipeline, NULL, NULL); ASSERT (cursor); r = mongoc_cursor_next (cursor, &doc); ASSERT (!r); @@ -2765,8 +2492,7 @@ test_aggregate_bypass (void *context) mongoc_cursor_destroy (cursor); options = tmp_bson ("{'bypassDocumentValidation': true}"); - cursor = mongoc_collection_aggregate ( - data_collection, MONGOC_QUERY_NONE, pipeline, options, NULL); + cursor = mongoc_collection_aggregate (data_collection, MONGOC_QUERY_NONE, pipeline, options, NULL); ASSERT (cursor); ASSERT (!mongoc_cursor_error (cursor, &error)); @@ -2810,31 +2536,12 @@ test_aggregate (void) collection = get_test_collection (client, "test_aggregate"); ASSERT (collection); - pipeline = BCON_NEW ("pipeline", - "[", - "{", - "$match", - "{", - "hello", - BCON_UTF8 ("world"), - "}", - "}", - "]"); - broken_pipeline = BCON_NEW ("pipeline", - "[", - "{", - "$asdf", - "{", - "foo", - BCON_UTF8 ("bar"), - "}", - "}", - "]"); + pipeline = BCON_NEW ("pipeline", "[", "{", "$match", "{", "hello", BCON_UTF8 ("world"), "}", "}", "]"); + broken_pipeline = BCON_NEW ("pipeline", "[", "{", "$asdf", "{", "foo", BCON_UTF8 ("bar"), "}", "}", "]"); b = BCON_NEW ("hello", BCON_UTF8 ("world")); /* empty collection */ - cursor = mongoc_collection_aggregate ( - collection, MONGOC_QUERY_NONE, pipeline, NULL, NULL); + cursor = mongoc_collection_aggregate (collection, MONGOC_QUERY_NONE, pipeline, NULL, NULL); ASSERT (cursor); ASSERT (!mongoc_cursor_next (cursor, &doc)); @@ -2842,8 +2549,7 @@ test_aggregate (void) mongoc_cursor_destroy (cursor); /* empty collection */ - cursor = mongoc_collection_aggregate ( - collection, MONGOC_QUERY_NONE, pipeline, NULL, NULL); + cursor = mongoc_collection_aggregate (collection, MONGOC_QUERY_NONE, pipeline, NULL, NULL); ASSERT (cursor); r = mongoc_cursor_next (cursor, &doc); @@ -2852,14 +2558,11 @@ test_aggregate (void) mongoc_cursor_destroy (cursor); for (i = 0; i < 2; i++) { - ASSERT_OR_PRINT ( - mongoc_collection_insert_one (collection, b, NULL, NULL, &error), - error); + ASSERT_OR_PRINT (mongoc_collection_insert_one (collection, b, NULL, NULL, &error), error); } again: - cursor = mongoc_collection_aggregate ( - collection, MONGOC_QUERY_NONE, broken_pipeline, NULL, NULL); + cursor = mongoc_collection_aggregate (collection, MONGOC_QUERY_NONE, broken_pipeline, NULL, NULL); ASSERT (cursor); r = mongoc_cursor_next (cursor, &doc); @@ -2870,8 +2573,7 @@ test_aggregate (void) for (i = 0; i < 2; i++) { if (i % 2 == 0) { - cursor = mongoc_collection_aggregate ( - collection, MONGOC_QUERY_NONE, pipeline, NULL, NULL); + cursor = mongoc_collection_aggregate (collection, MONGOC_QUERY_NONE, pipeline, NULL, NULL); ASSERT (cursor); } else { bson_init (&opts); @@ -2879,8 +2581,7 @@ test_aggregate (void) BSON_APPEND_BOOL (&opts, "allowDiskUse", true); BSON_APPEND_INT32 (&opts, "batchSize", 10); - cursor = mongoc_collection_aggregate ( - collection, MONGOC_QUERY_NONE, pipeline, &opts, NULL); + cursor = mongoc_collection_aggregate (collection, MONGOC_QUERY_NONE, pipeline, &opts, NULL); ASSERT (cursor); bson_destroy (&opts); @@ -2895,8 +2596,7 @@ test_aggregate (void) ASSERT (r); ASSERT (doc); - ASSERT (bson_iter_init_find (&iter, doc, "hello") && - BSON_ITER_HOLDS_UTF8 (&iter)); + ASSERT (bson_iter_init_find (&iter, doc, "hello") && BSON_ITER_HOLDS_UTF8 (&iter)); } r = mongoc_cursor_next (cursor, &doc); @@ -2913,8 +2613,7 @@ test_aggregate (void) if (!did_alternate) { did_alternate = true; bson_destroy (pipeline); - pipeline = BCON_NEW ( - "0", "{", "$match", "{", "hello", BCON_UTF8 ("world"), "}", "}"); + pipeline = BCON_NEW ("0", "{", "$match", "{", "hello", BCON_UTF8 ("world"), "}", "}"); goto again; } @@ -2966,8 +2665,7 @@ test_aggregate_large (void) pipeline = tmp_bson ("[{'$sort': {'_id': 1}}]"); - cursor = mongoc_collection_aggregate ( - collection, MONGOC_QUERY_NONE, pipeline, NULL, NULL); + cursor = mongoc_collection_aggregate (collection, MONGOC_QUERY_NONE, pipeline, NULL, NULL); ASSERT (cursor); i = 0; @@ -3026,29 +2724,23 @@ test_aggregate_modern (void *data) server = mock_server_with_auto_hello (WIRE_VERSION_MIN); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); collection = mongoc_client_get_collection (client, "db", "collection"); - cursor = mongoc_collection_aggregate (collection, - MONGOC_QUERY_NONE, - tmp_bson ("[{'a': 1}]"), - tmp_bson (options_json (context)), - NULL); + cursor = mongoc_collection_aggregate ( + collection, MONGOC_QUERY_NONE, tmp_bson ("[{'a': 1}]"), tmp_bson (options_json (context)), NULL); ASSERT (cursor); future = future_cursor_next (cursor, &doc); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db'," - " 'aggregate': 'collection'," - " 'pipeline': [{'a': 1}]," - " 'cursor': %s %s}", - context->with_batch_size ? "{'batchSize': 11}" - : "{'$empty': true}", - context->with_options ? ", 'foo': 1" : "")); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'db'," + " 'aggregate': 'collection'," + " 'pipeline': [{'a': 1}]," + " 'cursor': %s %s}", + context->with_batch_size ? "{'batchSize': 11}" : "{'$empty': true}", + context->with_options ? ", 'foo': 1" : "")); reply_to_request_simple (request, "{'ok': 1," @@ -3066,15 +2758,14 @@ test_aggregate_modern (void *data) /* create a second batch to see if batch size is still 11 */ future = future_cursor_next (cursor, &doc); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db'," - " 'getMore': {'$numberLong': '42'}," - "'collection': 'collection'," - "'batchSize': %s}", - context->with_batch_size ? "{'$numberLong': '11'}" - : "{'$exists': false}")); + request = + mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'db'," + " 'getMore': {'$numberLong': '42'}," + "'collection': 'collection'," + "'batchSize': %s}", + context->with_batch_size ? "{'$numberLong': '11'}" : "{'$exists': false}")); reply_to_request_simple (request, "{'ok': 1," @@ -3110,10 +2801,7 @@ test_aggregate_w_server_id (void) future_t *future; request_t *request; - rs = mock_rs_with_auto_hello (WIRE_VERSION_MIN, - true /* has primary */, - 1 /* secondary */, - 0 /* arbiters */); + rs = mock_rs_with_auto_hello (WIRE_VERSION_MIN, true /* has primary */, 1 /* secondary */, 0 /* arbiters */); mock_rs_run (rs); client = test_framework_client_new_from_uri (mock_rs_get_uri (rs), NULL); @@ -3121,17 +2809,15 @@ test_aggregate_w_server_id (void) /* use serverId instead of prefs to select the secondary */ opts = tmp_bson ("{'serverId': 2}"); - cursor = mongoc_collection_aggregate ( - collection, MONGOC_QUERY_NONE, tmp_bson (NULL), opts, NULL); + cursor = mongoc_collection_aggregate (collection, MONGOC_QUERY_NONE, tmp_bson (NULL), opts, NULL); future = future_cursor_next (cursor, &doc); - request = - mock_rs_receives_msg (rs, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db'," - " 'aggregate': 'collection'," - " 'cursor': {}," - " 'serverId': {'$exists': false}}")); + request = mock_rs_receives_msg (rs, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'db'," + " 'aggregate': 'collection'," + " 'cursor': {}," + " 'serverId': {'$exists': false}}")); ASSERT (mock_rs_request_is_to_secondary (rs, request)); reply_to_request_simple (request, @@ -3165,22 +2851,19 @@ test_aggregate_w_server_id_sharded (void) server = mock_mongos_new (WIRE_VERSION_MIN); mock_server_run (server); mock_server_auto_endsessions (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); collection = mongoc_client_get_collection (client, "db", "collection"); opts = tmp_bson ("{'serverId': 1}"); - cursor = mongoc_collection_aggregate ( - collection, MONGOC_QUERY_NONE, tmp_bson (NULL), opts, NULL); + cursor = mongoc_collection_aggregate (collection, MONGOC_QUERY_NONE, tmp_bson (NULL), opts, NULL); future = future_cursor_next (cursor, &doc); - request = - mock_server_receives_msg (server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db'," - " 'aggregate': 'collection'," - " 'serverId': {'$exists': false}}")); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'db'," + " 'aggregate': 'collection'," + " 'serverId': {'$exists': false}}")); reply_to_request_simple (request, "{'ok': 1," @@ -3214,26 +2897,17 @@ test_aggregate_server_id_option (void *ctx) client = test_framework_new_default_client (); collection = mongoc_client_get_collection (client, "db", "collection"); q = tmp_bson (NULL); - cursor = mongoc_collection_aggregate ( - collection, MONGOC_QUERY_NONE, q, tmp_bson ("{'serverId': 'foo'}"), NULL); + cursor = mongoc_collection_aggregate (collection, MONGOC_QUERY_NONE, q, tmp_bson ("{'serverId': 'foo'}"), NULL); - ASSERT_ERROR_CONTAINS (cursor->error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "must be an integer"); + ASSERT_ERROR_CONTAINS (cursor->error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "must be an integer"); mongoc_cursor_destroy (cursor); - cursor = mongoc_collection_aggregate ( - collection, MONGOC_QUERY_NONE, q, tmp_bson ("{'serverId': 0}"), NULL); + cursor = mongoc_collection_aggregate (collection, MONGOC_QUERY_NONE, q, tmp_bson ("{'serverId': 0}"), NULL); - ASSERT_ERROR_CONTAINS (cursor->error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "must be >= 1"); + ASSERT_ERROR_CONTAINS (cursor->error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "must be >= 1"); mongoc_cursor_destroy (cursor); - cursor = mongoc_collection_aggregate ( - collection, MONGOC_QUERY_NONE, q, tmp_bson ("{'serverId': 1}"), NULL); + cursor = mongoc_collection_aggregate (collection, MONGOC_QUERY_NONE, q, tmp_bson ("{'serverId': 1}"), NULL); mongoc_cursor_next (cursor, &doc); ASSERT_OR_PRINT (!mongoc_cursor_error (cursor, &error), error); @@ -3266,22 +2940,18 @@ test_validate (void *ctx) collection = get_test_collection (client, "test_validate"); ASSERT (collection); - ASSERT_OR_PRINT ( - mongoc_collection_insert_one (collection, &doc, NULL, NULL, &error), - error); + ASSERT_OR_PRINT (mongoc_collection_insert_one (collection, &doc, NULL, NULL, &error), error); BSON_APPEND_BOOL (&opts, "full", true); - ASSERT_OR_PRINT ( - mongoc_collection_validate (collection, &opts, &reply, &error), error); + ASSERT_OR_PRINT (mongoc_collection_validate (collection, &opts, &reply, &error), error); BSON_ASSERT (bson_iter_init_find (&iter, &reply, "valid")); bson_destroy (&reply); /* Make sure we don't segfault when reply is NULL */ - ASSERT_OR_PRINT ( - mongoc_collection_validate (collection, &opts, NULL, &error), error); + ASSERT_OR_PRINT (mongoc_collection_validate (collection, &opts, NULL, &error), error); bson_reinit (&opts); BSON_APPEND_UTF8 (&opts, "full", "bad_value"); @@ -3344,16 +3014,11 @@ test_rename (void) database = mongoc_client_get_database (client, dbname); collection = mongoc_database_get_collection (database, "test_rename"); - ASSERT_OR_PRINT ( - mongoc_collection_insert_one (collection, &doc, NULL, NULL, &error), - error); + ASSERT_OR_PRINT (mongoc_collection_insert_one (collection, &doc, NULL, NULL, &error), error); - ASSERT_OR_PRINT (mongoc_collection_rename ( - collection, dbname, "test_rename.2", false, &error), - error); + ASSERT_OR_PRINT (mongoc_collection_rename (collection, dbname, "test_rename.2", false, &error), error); - names = - mongoc_database_get_collection_names_with_opts (database, NULL, &error); + names = mongoc_database_get_collection_names_with_opts (database, NULL, &error); ASSERT_OR_PRINT (names, error); found = false; for (name = names; *name; ++name) { @@ -3371,12 +3036,8 @@ test_rename (void) bad_wc->wtimeout = -10; bson_reinit (opts); mongoc_write_concern_append_bad (bad_wc, opts); - ASSERT (!mongoc_collection_rename_with_opts ( - collection, dbname, "test_rename.3", false, opts, &error)); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Invalid writeConcern"); + ASSERT (!mongoc_collection_rename_with_opts (collection, dbname, "test_rename.3", false, opts, &error)); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid writeConcern"); ASSERT_CMPSTR (mongoc_collection_get_name (collection), "test_rename.2"); bad_wc->wtimeout = 0; @@ -3387,8 +3048,7 @@ test_rename (void) mongoc_write_concern_set_w (good_wc, 1); bson_reinit (opts); mongoc_write_concern_append (good_wc, opts); - r = mongoc_collection_rename_with_opts ( - collection, dbname, "test_rename.3", false, opts, &error); + r = mongoc_collection_rename_with_opts (collection, dbname, "test_rename.3", false, opts, &error); ASSERT_OR_PRINT (r, error); ASSERT_CMPSTR (mongoc_collection_get_name (collection), "test_rename.3"); @@ -3401,8 +3061,7 @@ test_rename (void) if (!test_framework_is_mongos ()) { bson_reinit (opts); mongoc_write_concern_append_bad (bad_wc, opts); - r = mongoc_collection_rename_with_opts ( - collection, dbname, "test_rename.4", false, opts, &error); + r = mongoc_collection_rename_with_opts (collection, dbname, "test_rename.4", false, opts, &error); ASSERT (!r); /* check that collection name has not changed */ @@ -3441,13 +3100,10 @@ test_stats (void *unused) collection = get_test_collection (client, "test_stats"); ASSERT (collection); - ASSERT_OR_PRINT ( - mongoc_collection_insert_one (collection, &doc, NULL, NULL, &error), - error); + ASSERT_OR_PRINT (mongoc_collection_insert_one (collection, &doc, NULL, NULL, &error), error); BEGIN_IGNORE_DEPRECATIONS - ASSERT_OR_PRINT (mongoc_collection_stats (collection, NULL, &stats, &error), - error); + ASSERT_OR_PRINT (mongoc_collection_stats (collection, NULL, &stats, &error), error); END_IGNORE_DEPRECATIONS BSON_ASSERT (bson_iter_init_find (&iter, &stats, "ns")); @@ -3480,18 +3136,16 @@ test_stats_read_pref (void) server = mock_mongos_new (WIRE_VERSION_MIN); mock_server_run (server); mock_server_auto_endsessions (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); collection = mongoc_client_get_collection (client, "db", "collection"); prefs = mongoc_read_prefs_new (MONGOC_READ_SECONDARY); mongoc_collection_set_read_prefs (collection, prefs); future = future_collection_stats (collection, NULL, &stats, &error); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db'," - " 'collStats': 'collection'," - " '$readPreference': {'mode': 'secondary'}}")); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'db'," + " 'collStats': 'collection'," + " '$readPreference': {'mode': 'secondary'}}")); reply_to_request_with_ok_and_destroy (request); ASSERT_OR_PRINT (future_get_bool (future), error); @@ -3522,12 +3176,10 @@ test_find_and_modify_write_concern (void) server = mock_server_new (); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); ASSERT (client); - collection = - mongoc_client_get_collection (client, "test", "test_find_and_modify"); + collection = mongoc_client_get_collection (client, "test", "test_find_and_modify"); mock_server_auto_hello (server, "{'isWritablePrimary': true, " @@ -3549,18 +3201,17 @@ test_find_and_modify_write_concern (void) write_concern = mongoc_write_concern_new (); mongoc_write_concern_set_w (write_concern, 42); mongoc_collection_set_write_concern (collection, write_concern); - future = future_collection_find_and_modify ( - collection, &doc, NULL, update, NULL, false, false, true, &reply, &error); + future = + future_collection_find_and_modify (collection, &doc, NULL, update, NULL, false, false, true, &reply, &error); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'test'," - " 'findAndModify': 'test_find_and_modify'," - " 'query': {'superduper': 77889}," - " 'update': {'$set': {'superduper': 1234}}," - " 'new' : true," - " 'writeConcern': {'w': 42}}")); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'test'," + " 'findAndModify': 'test_find_and_modify'," + " 'query': {'superduper': 77889}," + " 'update': {'$set': {'superduper': 1234}}," + " 'new' : true," + " 'writeConcern': {'w': 42}}")); reply_to_request_simple (request, "{ 'value' : null, 'ok' : 1 }"); ASSERT_OR_PRINT (future_get_bool (future), error); @@ -3598,23 +3249,13 @@ test_find_and_modify (void) BSON_APPEND_INT32 (&doc, "superduper", 77889); - ASSERT_OR_PRINT ( - mongoc_collection_insert_one (collection, &doc, NULL, NULL, &error), - error); + ASSERT_OR_PRINT (mongoc_collection_insert_one (collection, &doc, NULL, NULL, &error), error); update = BCON_NEW ("$set", "{", "superduper", BCON_INT32 (1234), "}"); - ASSERT_OR_PRINT (mongoc_collection_find_and_modify (collection, - &doc, - NULL, - update, - NULL, - false, - false, - true, - &reply, - &error), - error); + ASSERT_OR_PRINT ( + mongoc_collection_find_and_modify (collection, &doc, NULL, update, NULL, false, false, true, &reply, &error), + error); BSON_ASSERT (bson_iter_init_find (&iter, &reply, "value")); BSON_ASSERT (BSON_ITER_HOLDS_DOCUMENT (&iter)); @@ -3673,16 +3314,13 @@ test_large_return (void *ctx) BSON_APPEND_OID (&insert_doc, "_id", &oid); BSON_APPEND_UTF8 (&insert_doc, "big", str); - ASSERT_OR_PRINT (mongoc_collection_insert_one ( - collection, &insert_doc, NULL, NULL, &error), - error); + ASSERT_OR_PRINT (mongoc_collection_insert_one (collection, &insert_doc, NULL, NULL, &error), error); bson_destroy (&insert_doc); BSON_APPEND_OID (&query, "_id", &oid); - cursor = mongoc_collection_find ( - collection, MONGOC_QUERY_NONE, 0, 0, 0, &query, NULL, NULL); + cursor = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, 0, &query, NULL, NULL); BSON_ASSERT (cursor); bson_destroy (&query); @@ -3730,13 +3368,9 @@ test_many_return (void) BSON_APPEND_OID (docs[i], "_id", &oid); } - ASSERT_OR_PRINT (mongoc_collection_insert_many (collection, - (const bson_t **) docs, - (uint32_t) N_BSONS, - NULL, - NULL, - &error), - error); + ASSERT_OR_PRINT ( + mongoc_collection_insert_many (collection, (const bson_t **) docs, (uint32_t) N_BSONS, NULL, NULL, &error), + error); cursor = mongoc_collection_find_with_opts (collection, &query, NULL, NULL); BSON_ASSERT (cursor); @@ -3759,10 +3393,8 @@ test_many_return (void) BSON_ASSERT (!mongoc_cursor_more (cursor)); /* mongoc_cursor_next after done is considered an error */ BSON_ASSERT (mongoc_cursor_error (cursor, &error)); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_CURSOR, - MONGOC_ERROR_CURSOR_INVALID_CURSOR, - "Cannot advance a completed or failed cursor"); + ASSERT_ERROR_CONTAINS ( + error, MONGOC_ERROR_CURSOR, MONGOC_ERROR_CURSOR_INVALID_CURSOR, "Cannot advance a completed or failed cursor"); mongoc_cursor_destroy (cursor); @@ -3775,30 +3407,20 @@ test_many_return (void) static bool -insert_one (mongoc_collection_t *collection, - const bson_t *doc, - const bson_t *opts, - bson_error_t *error) +insert_one (mongoc_collection_t *collection, const bson_t *doc, const bson_t *opts, bson_error_t *error) { return mongoc_collection_insert_one (collection, doc, opts, NULL, error); } static bool -insert_many (mongoc_collection_t *collection, - const bson_t *doc, - const bson_t *opts, - bson_error_t *error) +insert_many (mongoc_collection_t *collection, const bson_t *doc, const bson_t *opts, bson_error_t *error) { - return mongoc_collection_insert_many ( - collection, &doc, 1, opts, NULL, error); + return mongoc_collection_insert_many (collection, &doc, 1, opts, NULL, error); } -typedef bool (*insert_fn_t) (mongoc_collection_t *, - const bson_t *, - const bson_t *, - bson_error_t *); +typedef bool (*insert_fn_t) (mongoc_collection_t *, const bson_t *, const bson_t *, bson_error_t *); static void @@ -3813,60 +3435,33 @@ _test_insert_validate (insert_fn_t insert_fn) collection = get_test_collection (client, "test_insert_validate"); BSON_ASSERT (!insert_fn (collection, tmp_bson ("{'': 1}"), NULL, &error)); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "empty key"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "empty key"); - BSON_ASSERT (!insert_fn (collection, - tmp_bson ("{'_id': {'$a': 1}}"), - tmp_bson ("{'validate': false}"), - &error)); + BSON_ASSERT (!insert_fn (collection, tmp_bson ("{'_id': {'$a': 1}}"), tmp_bson ("{'validate': false}"), &error)); ASSERT_CMPUINT32 (error.domain, ==, (uint32_t) MONGOC_ERROR_SERVER); - BSON_ASSERT (!insert_fn (collection, - tmp_bson ("{'$': 1}"), - tmp_bson ("{'validate': 'foo'}"), - &error)); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Invalid type for option \"validate\": \"UTF8\""); + BSON_ASSERT (!insert_fn (collection, tmp_bson ("{'$': 1}"), tmp_bson ("{'validate': 'foo'}"), &error)); + ASSERT_ERROR_CONTAINS ( + error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid type for option \"validate\": \"UTF8\""); - BSON_ASSERT (insert_fn ( - collection, tmp_bson ("{'a': 1}"), tmp_bson ("{'validate': 0}"), &error)); + BSON_ASSERT (insert_fn (collection, tmp_bson ("{'a': 1}"), tmp_bson ("{'validate': 0}"), &error)); /* BSON_VALIDATE_DOT_KEYS */ - BSON_ASSERT (!insert_fn (collection, - tmp_bson ("{'a.a': 1}"), - tmp_bson ("{'validate': 4}"), - &error)); - ASSERT_ERROR_CONTAINS ( - error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "invalid document for insert: keys cannot contain \".\": \"a.a\""); - - /* {validate: true} is still prohibited */ - BSON_ASSERT (!insert_fn (collection, - tmp_bson ("{'a': 1}"), - tmp_bson ("{'validate': true}"), - &error)); + BSON_ASSERT (!insert_fn (collection, tmp_bson ("{'a.a': 1}"), tmp_bson ("{'validate': 4}"), &error)); ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, - "Invalid option \"validate\": true"); + "invalid document for insert: keys cannot contain \".\": \"a.a\""); + /* {validate: true} is still prohibited */ + BSON_ASSERT (!insert_fn (collection, tmp_bson ("{'a': 1}"), tmp_bson ("{'validate': true}"), &error)); + ASSERT_ERROR_CONTAINS ( + error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid option \"validate\": true"); - BSON_ASSERT (insert_fn (collection, - tmp_bson ("{'a.a': 1}"), - tmp_bson ("{'validate': 0}"), - &error)); - BSON_ASSERT (insert_fn (collection, - tmp_bson ("{'a': 1}"), - tmp_bson ("{'validate': 31}"), - &error)); + BSON_ASSERT (insert_fn (collection, tmp_bson ("{'a.a': 1}"), tmp_bson ("{'validate': 0}"), &error)); + + BSON_ASSERT (insert_fn (collection, tmp_bson ("{'a': 1}"), tmp_bson ("{'validate': 31}"), &error)); mongoc_collection_destroy (collection); mongoc_client_destroy (client); @@ -3878,10 +3473,8 @@ test_insert_bulk_validate (void) mongoc_client_t *client; mongoc_collection_t *collection; bson_error_t error; - const bson_t *docs_client_invalid[] = {tmp_bson ("{'a': 1}"), - tmp_bson ("{'': 2}")}; - const bson_t *docs_server_invalid[] = {tmp_bson ("{'a': 1}"), - tmp_bson ("{'_id': {'$a': 2}}")}; + const bson_t *docs_client_invalid[] = {tmp_bson ("{'a': 1}"), tmp_bson ("{'': 2}")}; + const bson_t *docs_server_invalid[] = {tmp_bson ("{'a': 1}"), tmp_bson ("{'_id': {'$a': 2}}")}; BEGIN_IGNORE_DEPRECATIONS client = test_framework_new_default_client (); @@ -3889,36 +3482,27 @@ test_insert_bulk_validate (void) collection = get_test_collection (client, "test_insert_validate"); /* Invalid documents, validation. */ + BSON_ASSERT (!mongoc_collection_insert_bulk ( + collection, MONGOC_INSERT_NONE, docs_client_invalid, 2, NULL /* write concern */, &error)); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "invalid document"); + + /* Invalid documents, no validation. */ BSON_ASSERT (!mongoc_collection_insert_bulk (collection, - MONGOC_INSERT_NONE, - docs_client_invalid, + (mongoc_insert_flags_t) MONGOC_INSERT_NO_VALIDATE, + docs_server_invalid, 2, NULL /* write concern */, &error)); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "invalid document"); - - /* Invalid documents, no validation. */ - BSON_ASSERT (!mongoc_collection_insert_bulk ( - collection, - (mongoc_insert_flags_t) MONGOC_INSERT_NO_VALIDATE, - docs_server_invalid, - 2, - NULL /* write concern */, - &error)); ASSERT_CMPUINT32 (error.domain, ==, (uint32_t) MONGOC_ERROR_SERVER); /* Valid document, validation. */ - ASSERT_OR_PRINT ( - mongoc_collection_insert_bulk (collection, - MONGOC_INSERT_NONE, - docs_client_invalid, - 1 /* don't include invalid second doc. */, - NULL /* write concern */, - &error), - error); + ASSERT_OR_PRINT (mongoc_collection_insert_bulk (collection, + MONGOC_INSERT_NONE, + docs_client_invalid, + 1 /* don't include invalid second doc. */, + NULL /* write concern */, + &error), + error); mongoc_collection_destroy (collection); mongoc_client_destroy (client); @@ -3955,32 +3539,22 @@ test_find_limit (void) server = mock_server_with_auto_hello (WIRE_VERSION_MIN); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); collection = mongoc_client_get_collection (client, "test", "test"); /* test mongoc_collection_find and mongoc_collection_find_with_opts */ - cursor = mongoc_collection_find (collection, - MONGOC_QUERY_NONE, - 0 /* skip */, - 2 /* limit */, - 0 /* batch_size */, - tmp_bson ("{}"), - NULL, - NULL); + cursor = mongoc_collection_find ( + collection, MONGOC_QUERY_NONE, 0 /* skip */, 2 /* limit */, 0 /* batch_size */, tmp_bson ("{}"), NULL, NULL); future = future_cursor_next (cursor, &doc); - request = - mock_server_receives_msg (server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'test'," - " 'find': 'test'," - " 'filter': {}," - " 'limit': {'$numberLong': '2'}}")); - - reply_to_request_simple ( - request, - "{'ok': 1, 'cursor': {'id': 0, 'ns': 'test.test', 'firstBatch': [{}]}}"); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'test'," + " 'find': 'test'," + " 'filter': {}," + " 'limit': {'$numberLong': '2'}}")); + + reply_to_request_simple (request, "{'ok': 1, 'cursor': {'id': 0, 'ns': 'test.test', 'firstBatch': [{}]}}"); BSON_ASSERT (future_get_bool (future)); future_destroy (future); @@ -3988,23 +3562,17 @@ test_find_limit (void) mongoc_cursor_destroy (cursor); cursor = mongoc_collection_find_with_opts ( - collection, - tmp_bson ("{}"), - tmp_bson ("{'limit': {'$numberLong': '2'}}"), - NULL); + collection, tmp_bson ("{}"), tmp_bson ("{'limit': {'$numberLong': '2'}}"), NULL); future = future_cursor_next (cursor, &doc); - request = - mock_server_receives_msg (server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'test'," - " 'find': 'test'," - " 'filter': {}," - " 'limit': {'$numberLong': '2'}}")); - - reply_to_request_simple ( - request, - "{'ok': 1, 'cursor': {'id': 0, 'ns': 'test.test', 'firstBatch': [{}]}}"); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'test'," + " 'find': 'test'," + " 'filter': {}," + " 'limit': {'$numberLong': '2'}}")); + + reply_to_request_simple (request, "{'ok': 1, 'cursor': {'id': 0, 'ns': 'test.test', 'firstBatch': [{}]}}"); BSON_ASSERT (future_get_bool (future)); future_destroy (future); @@ -4031,32 +3599,22 @@ test_find_batch_size (void) server = mock_server_with_auto_hello (WIRE_VERSION_MIN); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); collection = mongoc_client_get_collection (client, "test", "test"); /* test mongoc_collection_find and mongoc_collection_find_with_opts */ - cursor = mongoc_collection_find (collection, - MONGOC_QUERY_NONE, - 0 /* skip */, - 0 /* limit */, - 2 /* batch_size */, - tmp_bson ("{}"), - NULL, - NULL); + cursor = mongoc_collection_find ( + collection, MONGOC_QUERY_NONE, 0 /* skip */, 0 /* limit */, 2 /* batch_size */, tmp_bson ("{}"), NULL, NULL); future = future_cursor_next (cursor, &doc); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'test'," - " 'find': 'test'," - " 'filter': {}," - " 'batchSize': {'$numberLong': '2'}}")); - - reply_to_request_simple ( - request, - "{'ok': 1, 'cursor': {'id': 0, 'ns': 'test.test', 'firstBatch': [{}]}}"); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'test'," + " 'find': 'test'," + " 'filter': {}," + " 'batchSize': {'$numberLong': '2'}}")); + + reply_to_request_simple (request, "{'ok': 1, 'cursor': {'id': 0, 'ns': 'test.test', 'firstBatch': [{}]}}"); BSON_ASSERT (future_get_bool (future)); future_destroy (future); @@ -4064,23 +3622,17 @@ test_find_batch_size (void) mongoc_cursor_destroy (cursor); cursor = mongoc_collection_find_with_opts ( - collection, - tmp_bson ("{}"), - tmp_bson ("{'batchSize': {'$numberLong': '2'}}"), - NULL); + collection, tmp_bson ("{}"), tmp_bson ("{'batchSize': {'$numberLong': '2'}}"), NULL); future = future_cursor_next (cursor, &doc); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'test'," - " 'find': 'test'," - " 'filter': {}," - " 'batchSize': {'$numberLong': '2'}}")); - - reply_to_request_simple ( - request, - "{'ok': 1, 'cursor': {'id': 0, 'ns': 'test.test', 'firstBatch': [{}]}}"); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'test'," + " 'find': 'test'," + " 'filter': {}," + " 'batchSize': {'$numberLong': '2'}}")); + + reply_to_request_simple (request, "{'ok': 1, 'cursor': {'id': 0, 'ns': 'test.test', 'firstBatch': [{}]}}"); BSON_ASSERT (future_get_bool (future)); future_destroy (future); @@ -4109,15 +3661,7 @@ test_command_fq (void *context) cmd = tmp_bson ("{ 'dbstats': 1}"); - cursor = mongoc_client_command (client, - "sometest.$cmd", - MONGOC_QUERY_SECONDARY_OK, - 0, - -1, - 0, - cmd, - NULL, - NULL); + cursor = mongoc_client_command (client, "sometest.$cmd", MONGOC_QUERY_SECONDARY_OK, 0, -1, 0, cmd, NULL, NULL); r = mongoc_cursor_next (cursor, &doc); BSON_ASSERT (r); @@ -4190,10 +3734,8 @@ test_get_index_info (void) ASSERT (!mongoc_cursor_error (cursor, &error)); while (mongoc_cursor_next (cursor, &indexinfo)) { - if (bson_iter_init (&idx_spec_iter, indexinfo) && - bson_iter_find (&idx_spec_iter, "name") && - BSON_ITER_HOLDS_UTF8 (&idx_spec_iter) && - (cur_idx_name = bson_iter_utf8 (&idx_spec_iter, NULL))) { + if (bson_iter_init (&idx_spec_iter, indexinfo) && bson_iter_find (&idx_spec_iter, "name") && + BSON_ITER_HOLDS_UTF8 (&idx_spec_iter) && (cur_idx_name = bson_iter_utf8 (&idx_spec_iter, NULL))) { BSON_ASSERT (0 == strcmp (cur_idx_name, id_idx_name)); ++num_idxs; } else { @@ -4214,9 +3756,7 @@ test_get_index_info (void) ASSERT (strcmp (idx1_name, "raspberry_1") == 0); mongoc_index_opt_init (&opt1); opt1.background = true; - ASSERT_OR_PRINT ( - mongoc_collection_create_index (collection, &indexkey1, &opt1, &error), - error); + ASSERT_OR_PRINT (mongoc_collection_create_index (collection, &indexkey1, &opt1, &error), error); bson_destroy (&indexkey1); bson_init (&indexkey2); @@ -4225,9 +3765,7 @@ test_get_index_info (void) ASSERT (strcmp (idx2_name, "snozzberry_1") == 0); mongoc_index_opt_init (&opt2); opt2.unique = true; - ASSERT_OR_PRINT ( - mongoc_collection_create_index (collection, &indexkey2, &opt2, &error), - error); + ASSERT_OR_PRINT (mongoc_collection_create_index (collection, &indexkey2, &opt2, &error), error); bson_destroy (&indexkey2); /* @@ -4237,21 +3775,17 @@ test_get_index_info (void) ASSERT (!mongoc_cursor_error (cursor, &error)); while (mongoc_cursor_next (cursor, &indexinfo)) { - if (bson_iter_init (&idx_spec_iter, indexinfo) && - bson_iter_find (&idx_spec_iter, "name") && - BSON_ITER_HOLDS_UTF8 (&idx_spec_iter) && - (cur_idx_name = bson_iter_utf8 (&idx_spec_iter, NULL))) { + if (bson_iter_init (&idx_spec_iter, indexinfo) && bson_iter_find (&idx_spec_iter, "name") && + BSON_ITER_HOLDS_UTF8 (&idx_spec_iter) && (cur_idx_name = bson_iter_utf8 (&idx_spec_iter, NULL))) { if (0 == strcmp (cur_idx_name, idx1_name)) { /* need to use the copy of the iter since idx_spec_iter may have * gone * past the key we want */ - ASSERT (bson_iter_init_find ( - &idx_spec_iter_copy, indexinfo, "background")); + ASSERT (bson_iter_init_find (&idx_spec_iter_copy, indexinfo, "background")); ASSERT (BSON_ITER_HOLDS_BOOL (&idx_spec_iter_copy)); ASSERT (bson_iter_bool (&idx_spec_iter_copy)); } else if (0 == strcmp (cur_idx_name, idx2_name)) { - ASSERT ( - bson_iter_init_find (&idx_spec_iter_copy, indexinfo, "unique")); + ASSERT (bson_iter_init_find (&idx_spec_iter_copy, indexinfo, "unique")); ASSERT (BSON_ITER_HOLDS_BOOL (&idx_spec_iter_copy)); ASSERT (bson_iter_bool (&idx_spec_iter_copy)); } else { @@ -4319,19 +3853,15 @@ test_find_indexes_err (void) server = mock_server_with_auto_hello (WIRE_VERSION_MIN); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); mongoc_client_set_error_api (client, 2); collection = mongoc_client_get_collection (client, "db", "collection"); future = future_collection_find_indexes_with_opts (collection, NULL); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db', 'listIndexes': 'collection'}")); + request = + mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', 'listIndexes': 'collection'}")); - reply_to_request_simple (request, - "{'ok': 0, 'code': 1234567, 'errmsg': 'foo'}"); + reply_to_request_simple (request, "{'ok': 0, 'code': 1234567, 'errmsg': 'foo'}"); cursor = future_get_mongoc_cursor_ptr (future); BSON_ASSERT (mongoc_cursor_error (cursor, &error)); ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_SERVER, 1234567, "foo"); @@ -4361,13 +3891,11 @@ test_aggregate_install (TestSuite *suite) context->with_batch_size = (bool) with_batch_size; context->with_options = (bool) with_options; - name = bson_strdup_printf ( - "/Collection/aggregate/%s/%s", - context->with_batch_size ? "batch_size" : "no_batch_size", - context->with_options ? "with_options" : "no_options"); + name = bson_strdup_printf ("/Collection/aggregate/%s/%s", + context->with_batch_size ? "batch_size" : "no_batch_size", + context->with_options ? "with_options" : "no_options"); - TestSuite_AddWC ( - suite, name, test_aggregate_modern, NULL, (void *) context); + TestSuite_AddWC (suite, name, test_aggregate_modern, NULL, (void *) context); bson_free (name); } } @@ -4389,8 +3917,7 @@ test_find_read_concern (void) server = mock_server_with_auto_hello (WIRE_VERSION_MIN); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); collection = mongoc_client_get_collection (client, "test", "test"); /* No read_concern set - test find and find_with_opts */ @@ -4404,10 +3931,8 @@ test_find_read_concern (void) NULL); future = future_cursor_next (cursor, &doc); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'test', 'find': 'test', 'filter': {}}")); + request = + mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'test', 'find': 'test', 'filter': {}}")); reply_to_request_simple (request, "{'ok': 1," " 'cursor': {" @@ -4433,13 +3958,12 @@ test_find_read_concern (void) NULL); future = future_cursor_next (cursor, &doc); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'test'," - " 'find': 'test'," - " 'filter': {}," - " 'readConcern': {'level': 'local'}}")); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'test'," + " 'find': 'test'," + " 'filter': {}," + " 'readConcern': {'level': 'local'}}")); reply_to_request_simple (request, "{'ok': 1," " 'cursor': {" @@ -4466,13 +3990,12 @@ test_find_read_concern (void) NULL); future = future_cursor_next (cursor, &doc); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'test'," - " 'find': 'test'," - " 'filter': {}," - " 'readConcern': {'level': 'random'}}")); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'test'," + " 'find': 'test'," + " 'filter': {}," + " 'readConcern': {'level': 'random'}}")); reply_to_request_simple (request, "{'ok': 1," " 'cursor': {" @@ -4498,13 +4021,12 @@ test_find_read_concern (void) NULL); future = future_cursor_next (cursor, &doc); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'test'," - " 'find': 'test'," - " 'filter': {}," - " 'readConcern': {'$exists': false}}")); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'test'," + " 'find': 'test'," + " 'filter': {}," + " 'readConcern': {'$exists': false}}")); reply_to_request_simple (request, "{'ok': 1," " 'cursor': {" @@ -4531,13 +4053,12 @@ test_find_read_concern (void) NULL); future = future_cursor_next (cursor, &doc); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'test'," - " 'find': 'test'," - " 'filter': {}," - " 'readConcern': {'$exists': false}}")); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'test'," + " 'find': 'test'," + " 'filter': {}," + " 'readConcern': {'$exists': false}}")); reply_to_request_simple (request, "{'ok': 1," " 'cursor': {" @@ -4592,8 +4113,7 @@ test_getmore_read_concern_live (void *ctx) ASSERT_OR_PRINT (mongoc_bulk_operation_execute (bulk, NULL, &error), error); mongoc_bulk_operation_destroy (bulk); - cursor = mongoc_collection_find_with_opts ( - collection, tmp_bson ("{}"), NULL, NULL); + cursor = mongoc_collection_find_with_opts (collection, tmp_bson ("{}"), NULL, NULL); while (mongoc_cursor_next (cursor, &doc)) { i++; @@ -4624,16 +4144,14 @@ test_aggregate_secondary (void *ctx) client = test_framework_new_default_client (); collection = get_test_collection (client, "aggregate_secondary"); pref = mongoc_read_prefs_new (MONGOC_READ_SECONDARY); - cursor = mongoc_collection_aggregate ( - collection, MONGOC_QUERY_NONE, tmp_bson ("[]"), NULL, pref); + cursor = mongoc_collection_aggregate (collection, MONGOC_QUERY_NONE, tmp_bson ("[]"), NULL, pref); ASSERT (cursor); mongoc_cursor_next (cursor, &doc); ASSERT_OR_PRINT (!mongoc_cursor_error (cursor, &error), error); if (test_framework_is_replset ()) { - ASSERT (test_framework_server_is_secondary ( - client, mongoc_cursor_get_hint (cursor))); + ASSERT (test_framework_server_is_secondary (client, mongoc_cursor_get_hint (cursor))); } mongoc_read_prefs_destroy (pref); @@ -4659,22 +4177,19 @@ test_aggregate_secondary_sharded (void) server = mock_mongos_new (WIRE_VERSION_MIN); mock_server_run (server); mock_server_auto_endsessions (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); collection = mongoc_client_get_collection (client, "db", "collection"); pref = mongoc_read_prefs_new (MONGOC_READ_SECONDARY); - cursor = mongoc_collection_aggregate ( - collection, MONGOC_QUERY_NONE, tmp_bson ("[]"), NULL, pref); + cursor = mongoc_collection_aggregate (collection, MONGOC_QUERY_NONE, tmp_bson ("[]"), NULL, pref); ASSERT (cursor); future = future_cursor_next (cursor, &doc); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db'," - " 'aggregate': 'collection'," - " 'pipeline': []," - " '$readPreference': {'mode': 'secondary'}}")); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'db'," + " 'aggregate': 'collection'," + " 'pipeline': []," + " '$readPreference': {'mode': 'secondary'}}")); reply_to_request_simple (request, "{ 'ok':1," @@ -4710,25 +4225,22 @@ test_aggregate_read_concern (void) server = mock_server_with_auto_hello (WIRE_VERSION_MIN); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); collection = mongoc_client_get_collection (client, "db", "collection"); /* No readConcern */ - cursor = mongoc_collection_aggregate ( - collection, MONGOC_QUERY_NONE, tmp_bson ("[{'a': 1}]"), NULL, NULL); + cursor = mongoc_collection_aggregate (collection, MONGOC_QUERY_NONE, tmp_bson ("[{'a': 1}]"), NULL, NULL); ASSERT (cursor); future = future_cursor_next (cursor, &doc); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db'," - " 'aggregate': 'collection'," - " 'pipeline': [{'a': 1}]," - " 'cursor': {}," - " 'readConcern': {'$exists': false}}")); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'db'," + " 'aggregate': 'collection'," + " 'pipeline': [{'a': 1}]," + " 'cursor': {}," + " 'readConcern': {'$exists': false}}")); reply_to_request_simple (request, "{'ok': 1," @@ -4751,20 +4263,18 @@ test_aggregate_read_concern (void) rc = mongoc_read_concern_new (); mongoc_read_concern_set_level (rc, MONGOC_READ_CONCERN_LEVEL_MAJORITY); mongoc_collection_set_read_concern (collection, rc); - cursor = mongoc_collection_aggregate ( - collection, MONGOC_QUERY_NONE, tmp_bson ("[{'a': 1}]"), NULL, NULL); + cursor = mongoc_collection_aggregate (collection, MONGOC_QUERY_NONE, tmp_bson ("[{'a': 1}]"), NULL, NULL); ASSERT (cursor); future = future_cursor_next (cursor, &doc); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db'," - " 'aggregate': 'collection'," - " 'pipeline': [{'a': 1}]," - " 'cursor': {}," - " 'readConcern': {'level': 'majority'}}")); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'db'," + " 'aggregate': 'collection'," + " 'pipeline': [{'a': 1}]," + " 'cursor': {}," + " 'readConcern': {'level': 'majority'}}")); reply_to_request_simple (request, "{'ok': 1," @@ -4803,26 +4313,20 @@ test_aggregate_with_collation (void) server = mock_server_with_auto_hello (WIRE_VERSION_MIN); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); collection = mongoc_client_get_collection (client, "db", "collection"); - cursor = - mongoc_collection_aggregate (collection, - MONGOC_QUERY_NONE, - tmp_bson ("[{'a': 1}]"), - tmp_bson ("{'collation': {'locale': 'en'}}"), - NULL); + cursor = mongoc_collection_aggregate ( + collection, MONGOC_QUERY_NONE, tmp_bson ("[{'a': 1}]"), tmp_bson ("{'collation': {'locale': 'en'}}"), NULL); future = future_cursor_next (cursor, &doc); - request = - mock_server_receives_msg (server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db'," - " 'aggregate': 'collection'," - " 'pipeline': [{'a': 1}]," - " 'collation': {'locale': 'en'}}")); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'db'," + " 'aggregate': 'collection'," + " 'pipeline': [{'a': 1}]," + " 'collation': {'locale': 'en'}}")); reply_to_request_simple (request, "{'ok': 1," @@ -4861,29 +4365,25 @@ test_index_with_collation (void) server = mock_server_with_auto_hello (WIRE_VERSION_MIN); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); collection = mongoc_client_get_collection (client, "db", "collection"); bson_init (&keys); bson_append_int32 (&keys, "hello", -1, 1); mongoc_index_opt_init (&opt); - collation = - BCON_NEW ("locale", BCON_UTF8 ("en"), "strength", BCON_INT32 (2)); + collation = BCON_NEW ("locale", BCON_UTF8 ("en"), "strength", BCON_INT32 (2)); opt.collation = collation; - future = future_collection_create_index_with_opts ( - collection, &keys, &opt, NULL, &reply, &error); + future = future_collection_create_index_with_opts (collection, &keys, &opt, NULL, &reply, &error); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db'," - " 'createIndexes': 'collection'," - " 'indexes': [{" - " 'key': {'hello' : 1}," - " 'name': 'hello_1'," - " 'collation': {'locale': 'en', 'strength': 2}}]}")); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'db'," + " 'createIndexes': 'collection'," + " 'indexes': [{" + " 'key': {'hello' : 1}," + " 'name': 'hello_1'," + " 'collation': {'locale': 'en', 'strength': 2}}]}")); reply_to_request_with_ok_and_destroy (request); ASSERT (future_get_bool (future)); @@ -4907,11 +4407,9 @@ test_insert_duplicate_key (void) client = test_framework_new_default_client (); collection = get_test_collection (client, "test_insert_duplicate_key"); - mongoc_collection_insert_one ( - collection, tmp_bson ("{'_id': 1}"), NULL, NULL, NULL); + mongoc_collection_insert_one (collection, tmp_bson ("{'_id': 1}"), NULL, NULL, NULL); - ASSERT (!mongoc_collection_insert_one ( - collection, tmp_bson ("{'_id': 1}"), NULL, NULL, &error)); + ASSERT (!mongoc_collection_insert_one (collection, tmp_bson ("{'_id': 1}"), NULL, NULL, &error)); ASSERT_CMPINT (error.domain, ==, MONGOC_ERROR_COLLECTION); ASSERT_CMPINT (error.code, ==, MONGOC_ERROR_DUPLICATE_KEY); @@ -4930,17 +4428,13 @@ test_create_index_fail (void *context) BSON_UNUSED (context); - client = test_framework_client_new ( - "mongodb://example.doesntexist/?connectTimeoutMS=10", NULL); + client = test_framework_client_new ("mongodb://example.doesntexist/?connectTimeoutMS=10", NULL); collection = mongoc_client_get_collection (client, "test", "test"); - r = mongoc_collection_create_index_with_opts ( - collection, tmp_bson ("{'a': 1}"), NULL, NULL, &reply, &error); + r = mongoc_collection_create_index_with_opts (collection, tmp_bson ("{'a': 1}"), NULL, NULL, &reply, &error); ASSERT (!r); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_SERVER_SELECTION, - MONGOC_ERROR_SERVER_SELECTION_FAILURE, - "No suitable servers"); + ASSERT_ERROR_CONTAINS ( + error, MONGOC_ERROR_SERVER_SELECTION, MONGOC_ERROR_SERVER_SELECTION_FAILURE, "No suitable servers"); /* reply was initialized */ ASSERT (bson_empty (&reply)); @@ -4952,14 +4446,10 @@ test_create_index_fail (void *context) /* Tests that documents in `coll` found with `selector` all match `match` */ static void -_test_docs_in_coll_matches (mongoc_collection_t *coll, - bson_t *selector, - const char *match, - uint32_t expected_count) +_test_docs_in_coll_matches (mongoc_collection_t *coll, bson_t *selector, const char *match, uint32_t expected_count) { const bson_t *next_doc; - mongoc_cursor_t *cursor = - mongoc_collection_find_with_opts (coll, selector, NULL, NULL); + mongoc_cursor_t *cursor = mongoc_collection_find_with_opts (coll, selector, NULL, NULL); while (expected_count > 0) { ASSERT (mongoc_cursor_next (cursor, &next_doc)); if (match) { @@ -4977,8 +4467,7 @@ _test_no_docs_match (mongoc_collection_t *coll, const char *selector) bson_error_t error; int64_t ret; - ret = mongoc_collection_count_documents ( - coll, tmp_bson (selector), NULL, NULL, NULL, &error); + ret = mongoc_collection_count_documents (coll, tmp_bson (selector), NULL, NULL, NULL, &error); ASSERT_OR_PRINT (ret != -1, error); ASSERT_CMPINT64 (ret, ==, (int64_t) 0); } @@ -4996,8 +4485,7 @@ _test_crud_command_start (const mongoc_apm_command_started_t *event) const bson_t *cmd = mongoc_apm_command_started_get_command (event); const char *cmd_name = mongoc_apm_command_started_get_command_name (event); - test_crud_ctx_t *ctx = - (test_crud_ctx_t *) mongoc_apm_command_started_get_context (event); + test_crud_ctx_t *ctx = (test_crud_ctx_t *) mongoc_apm_command_started_get_context (event); if (!strcmp (cmd_name, ctx->command_under_test)) { ctx->commands_tested++; @@ -5040,11 +4528,7 @@ test_insert_one (void) ctx.expected_command = "{'insert': 'coll', 'bypassDocumentValidation': " "true, 'writeConcern': {'w': 1, 'j': false}}"; ret = mongoc_collection_insert_one ( - coll, - tmp_bson ("{'_id': 1}"), - tmp_bson ("{'bypassDocumentValidation': true}"), - &reply, - &err); + coll, tmp_bson ("{'_id': 1}"), tmp_bson ("{'bypassDocumentValidation': true}"), &reply, &err); ASSERT_OR_PRINT (ret, err); ASSERT_MATCH (&reply, "{'insertedCount': 1}"); bson_destroy (&reply); @@ -5053,11 +4537,7 @@ test_insert_one (void) /* Test maxTimeMS */ ctx.expected_command = "{'insert': 'coll', 'maxTimeMS': 9999, " " 'writeConcern': {'w': 1, 'j': false}}"; - ret = mongoc_collection_insert_one (coll, - tmp_bson ("{'_id': 2}"), - tmp_bson ("{'maxTimeMS': 9999}"), - &reply, - &err); + ret = mongoc_collection_insert_one (coll, tmp_bson ("{'_id': 2}"), tmp_bson ("{'maxTimeMS': 9999}"), &reply, &err); ASSERT_OR_PRINT (ret, err); ASSERT_MATCH (&reply, "{'insertedCount': 1}"); bson_destroy (&reply); @@ -5065,26 +4545,21 @@ test_insert_one (void) /* Test passing write concern through the options */ mongoc_write_concern_append (wc2, &opts_with_wc); - ctx.expected_command = - "{'insert': 'coll', 'writeConcern': {'w': 1, 'j': true}}"; - ret = mongoc_collection_insert_one ( - coll, tmp_bson ("{'_id': 3}"), &opts_with_wc, &reply, &err); + ctx.expected_command = "{'insert': 'coll', 'writeConcern': {'w': 1, 'j': true}}"; + ret = mongoc_collection_insert_one (coll, tmp_bson ("{'_id': 3}"), &opts_with_wc, &reply, &err); ASSERT_OR_PRINT (ret, err); ASSERT_MATCH (&reply, "{'insertedCount': 1}"); bson_destroy (&reply); _test_docs_in_coll_matches (coll, tmp_bson ("{'_id':3}"), NULL, 1); /* Test passing NULL for opts, reply, and error */ - ctx.expected_command = - "{'insert': 'coll', 'writeConcern': {'w': 1, 'j': false}}"; - ret = mongoc_collection_insert_one ( - coll, tmp_bson ("{'_id': 4}"), NULL, NULL, NULL); + ctx.expected_command = "{'insert': 'coll', 'writeConcern': {'w': 1, 'j': false}}"; + ret = mongoc_collection_insert_one (coll, tmp_bson ("{'_id': 4}"), NULL, NULL, NULL); ASSERT (ret); _test_docs_in_coll_matches (coll, tmp_bson ("{'_id': 4}"), NULL, 1); /* Duplicate key error */ - ret = mongoc_collection_insert_one ( - coll, tmp_bson ("{'_id': 4}"), NULL, &reply, &err); + ret = mongoc_collection_insert_one (coll, tmp_bson ("{'_id': 4}"), NULL, &reply, &err); ASSERT (!ret); ASSERT_CMPUINT32 (err.domain, ==, (uint32_t) MONGOC_ERROR_COLLECTION); ASSERT_MATCH (&reply, @@ -5100,14 +4575,9 @@ test_insert_one (void) ctx.expected_command = "{'insert': 'coll'," " 'writeConcern': {'w': 99, 'wtimeout': 100}}"; ret = mongoc_collection_insert_one ( - coll, - tmp_bson ("{}"), - tmp_bson ("{'writeConcern': {'w': 99, 'wtimeout': 100}}"), - &reply, - &err); + coll, tmp_bson ("{}"), tmp_bson ("{'writeConcern': {'w': 99, 'wtimeout': 100}}"), &reply, &err); ASSERT (!ret); - if (test_framework_get_server_version () >= - test_framework_str_to_version ("4.3.3")) { + if (test_framework_get_server_version () >= test_framework_str_to_version ("4.3.3")) { /* Error reporting changed in SERVER-45584 */ ASSERT_CMPUINT32 (err.domain, ==, (uint32_t) MONGOC_ERROR_QUERY); ASSERT_MATCH (&reply, @@ -5116,8 +4586,7 @@ test_insert_one (void) " 'writeConcernErrors': {'$exists': false}" "}"); } else { - ASSERT_CMPUINT32 ( - err.domain, ==, (uint32_t) MONGOC_ERROR_WRITE_CONCERN); + ASSERT_CMPUINT32 (err.domain, ==, (uint32_t) MONGOC_ERROR_WRITE_CONCERN); ASSERT_MATCH (&reply, "{'insertedCount': 1," " 'writeErrors': {'$exists': false}," @@ -5136,12 +4605,8 @@ test_insert_one (void) mongoc_client_destroy (client); } -typedef bool (*update_fn_t) (mongoc_collection_t *, - const bson_t *, - const bson_t *, - const bson_t *, - bson_t *, - bson_error_t *); +typedef bool (*update_fn_t) ( + mongoc_collection_t *, const bson_t *, const bson_t *, const bson_t *, bson_t *, bson_error_t *); /* Tests `update_one`, `update_many`, and `replace_one` */ static void @@ -5185,24 +4650,16 @@ _test_update_and_replace (bool is_replace, bool is_multi) ASSERT (!is_multi); fn = mongoc_collection_replace_one; } else { - fn = is_multi ? mongoc_collection_update_many - : mongoc_collection_update_one; + fn = is_multi ? mongoc_collection_update_many : mongoc_collection_update_one; } /* Test a simple update with bypassDocumentValidation */ ctx.expected_command = "{'update': 'coll', 'bypassDocumentValidation': " "true, 'writeConcern': {'w': 1, 'j': false}}"; - ret = mongoc_collection_insert_one ( - coll, tmp_bson ("{'_id': 1}"), &opts_with_wc, NULL, &err); + ret = mongoc_collection_insert_one (coll, tmp_bson ("{'_id': 1}"), &opts_with_wc, NULL, &err); ASSERT_OR_PRINT (ret, err); - update = - is_replace ? tmp_bson ("{'a': 1}") : tmp_bson ("{'$set': {'a': 1}}"); - ret = fn (coll, - tmp_bson ("{}"), - update, - tmp_bson ("{'bypassDocumentValidation': true}"), - &reply, - &err); + update = is_replace ? tmp_bson ("{'a': 1}") : tmp_bson ("{'$set': {'a': 1}}"); + ret = fn (coll, tmp_bson ("{}"), update, tmp_bson ("{'bypassDocumentValidation': true}"), &reply, &err); ASSERT_OR_PRINT (ret, err); ASSERT_MATCH (&reply, "{'modifiedCount': 1, 'matchedCount': 1, " @@ -5211,27 +4668,18 @@ _test_update_and_replace (bool is_replace, bool is_multi) _test_docs_in_coll_matches (coll, tmp_bson ("{'_id':1}"), "{'a': 1}", 1); /* Test passing an upsert */ - ctx.expected_command = - "{'update': 'coll', 'writeConcern': {'w': 1, 'j': false}}"; - update = is_replace ? tmp_bson ("{'b': 'TEST'}") - : tmp_bson ("{'$set': {'b': 'TEST'}}"); - ret = fn (coll, - tmp_bson ("{'_id': 2}"), - update, - tmp_bson ("{'upsert': true}"), - &reply, - &err); + ctx.expected_command = "{'update': 'coll', 'writeConcern': {'w': 1, 'j': false}}"; + update = is_replace ? tmp_bson ("{'b': 'TEST'}") : tmp_bson ("{'$set': {'b': 'TEST'}}"); + ret = fn (coll, tmp_bson ("{'_id': 2}"), update, tmp_bson ("{'upsert': true}"), &reply, &err); ASSERT_OR_PRINT (ret, err); ASSERT_MATCH (&reply, "{'modifiedCount': 0, 'matchedCount': 0, " "'upsertedId': {'$exists': true}}"); bson_destroy (&reply); - _test_docs_in_coll_matches ( - coll, tmp_bson ("{'_id':2}"), "{'b': 'TEST'}", 1); + _test_docs_in_coll_matches (coll, tmp_bson ("{'_id':2}"), "{'b': 'TEST'}", 1); /* Test collation */ - update = is_replace ? tmp_bson ("{'b': 'test'}") - : tmp_bson ("{'$set': {'b': 'test'}}"); + update = is_replace ? tmp_bson ("{'b': 'test'}") : tmp_bson ("{'$set': {'b': 'test'}}"); ret = fn (coll, tmp_bson ("{'b': 'TEST'}"), update, @@ -5243,16 +4691,12 @@ _test_update_and_replace (bool is_replace, bool is_multi) "{'modifiedCount': 1, 'matchedCount': 1, " "'upsertedId': {'$exists': false}}"); bson_destroy (&reply); - _test_docs_in_coll_matches ( - coll, tmp_bson ("{'_id':2}"), "{'b': 'test'}", 1); + _test_docs_in_coll_matches (coll, tmp_bson ("{'_id':2}"), "{'b': 'test'}", 1); /* Test passing write concern through the options */ - ctx.expected_command = - "{'update': 'coll', 'writeConcern': {'w': 1, 'j': true}}"; - update = - is_replace ? tmp_bson ("{'b': 0}") : tmp_bson ("{'$set': {'b': 0}}"); - ret = - fn (coll, tmp_bson ("{'_id': 2}"), update, &opts_with_wc2, &reply, &err); + ctx.expected_command = "{'update': 'coll', 'writeConcern': {'w': 1, 'j': true}}"; + update = is_replace ? tmp_bson ("{'b': 0}") : tmp_bson ("{'$set': {'b': 0}}"); + ret = fn (coll, tmp_bson ("{'_id': 2}"), update, &opts_with_wc2, &reply, &err); ASSERT_OR_PRINT (ret, err); ASSERT_MATCH (&reply, "{'modifiedCount': 1, 'matchedCount': 1, " @@ -5261,32 +4705,25 @@ _test_update_and_replace (bool is_replace, bool is_multi) _test_docs_in_coll_matches (coll, tmp_bson ("{'_id':2}"), "{'b': 0}", 1); /* Test passing NULL for opts, reply, and error */ - ctx.expected_command = - "{'update': 'coll', 'writeConcern': {'w': 1, 'j': false}}"; - update = - is_replace ? tmp_bson ("{'b': 1}") : tmp_bson ("{'$set': {'b': 1}}"); + ctx.expected_command = "{'update': 'coll', 'writeConcern': {'w': 1, 'j': false}}"; + update = is_replace ? tmp_bson ("{'b': 1}") : tmp_bson ("{'$set': {'b': 1}}"); ret = fn (coll, tmp_bson ("{'_id': 2}"), update, NULL, NULL, NULL); ASSERT (ret); _test_docs_in_coll_matches (coll, tmp_bson ("{'_id' :2}"), "{'b': 1}", 1); /* Test multiple matching documents */ - ret = mongoc_collection_insert_one ( - coll, tmp_bson ("{'_id': 3, 'a': 1}"), &opts_with_wc, NULL, &err); + ret = mongoc_collection_insert_one (coll, tmp_bson ("{'_id': 3, 'a': 1}"), &opts_with_wc, NULL, &err); ASSERT_OR_PRINT (ret, err); - ret = mongoc_collection_insert_one ( - coll, tmp_bson ("{'_id': 4, 'a': 1}"), &opts_with_wc, NULL, &err); + ret = mongoc_collection_insert_one (coll, tmp_bson ("{'_id': 4, 'a': 1}"), &opts_with_wc, NULL, &err); ASSERT_OR_PRINT (ret, err); - update = - is_replace ? tmp_bson ("{'a': 2}") : tmp_bson ("{'$set': {'a': 2}}"); - ret = fn ( - coll, tmp_bson ("{'_id': {'$in': [3,4]}}"), update, NULL, &reply, &err); + update = is_replace ? tmp_bson ("{'a': 2}") : tmp_bson ("{'$set': {'a': 2}}"); + ret = fn (coll, tmp_bson ("{'_id': {'$in': [3,4]}}"), update, NULL, &reply, &err); ASSERT_OR_PRINT (ret, err); if (is_multi) { ASSERT_MATCH (&reply, "{'modifiedCount': 2, 'matchedCount': 2, " "'upsertedId': {'$exists': false}}"); - _test_docs_in_coll_matches ( - coll, tmp_bson ("{'_id': {'$in': [3,4]}}"), "{'a': 2}", 2); + _test_docs_in_coll_matches (coll, tmp_bson ("{'_id': {'$in': [3,4]}}"), "{'a': 2}", 2); } else { ASSERT_MATCH (&reply, "{'modifiedCount': 1, 'matchedCount': 1, " @@ -5310,15 +4747,13 @@ _test_update_and_replace (bool is_replace, bool is_multi) if (test_framework_is_replset ()) { ret = fn (coll, tmp_bson ("{'_id': 3}"), - is_replace ? tmp_bson ("{'a': 3}") - : tmp_bson ("{'$set': {'a': 3}}"), + is_replace ? tmp_bson ("{'a': 3}") : tmp_bson ("{'$set': {'a': 3}}"), tmp_bson ("{'writeConcern': {'w': 99, 'wtimeout': 100}}"), &reply, &err); ASSERT (!ret); - if (test_framework_get_server_version () >= - test_framework_str_to_version ("4.3.3")) { + if (test_framework_get_server_version () >= test_framework_str_to_version ("4.3.3")) { /* Error reporting changed in SERVER-45584 */ ASSERT_CMPUINT32 (err.domain, ==, (uint32_t) MONGOC_ERROR_QUERY); ASSERT_MATCH (&reply, @@ -5328,8 +4763,7 @@ _test_update_and_replace (bool is_replace, bool is_multi) " 'writeConcernErrors': {'$exists': false}" "}"); } else { - ASSERT_CMPUINT32 ( - err.domain, ==, (uint32_t) MONGOC_ERROR_WRITE_CONCERN); + ASSERT_CMPUINT32 (err.domain, ==, (uint32_t) MONGOC_ERROR_WRITE_CONCERN); ASSERT_MATCH (&reply, "{'modifiedCount': 1," " 'matchedCount': 1," @@ -5343,86 +4777,55 @@ _test_update_and_replace (bool is_replace, bool is_multi) /* Test function specific behavior */ if (is_replace) { /* Test that replace really does replace */ - ret = - mongoc_collection_insert_one (coll, - tmp_bson ("{'_id': 5, 'a': 1, 'b': 2}"), - &opts_with_wc, - NULL, - &err); + ret = mongoc_collection_insert_one (coll, tmp_bson ("{'_id': 5, 'a': 1, 'b': 2}"), &opts_with_wc, NULL, &err); ASSERT_OR_PRINT (ret, err); - ret = fn (coll, - tmp_bson ("{'_id': 5}"), - tmp_bson ("{'a': 2}"), - NULL, - &reply, - &err); + ret = fn (coll, tmp_bson ("{'_id': 5}"), tmp_bson ("{'a': 2}"), NULL, &reply, &err); ASSERT_OR_PRINT (ret, err); ASSERT_MATCH (&reply, "{'modifiedCount': 1, 'matchedCount': 1, " "'upsertedId': {'$exists': false}}"); - _test_docs_in_coll_matches ( - coll, tmp_bson ("{'_id': 5}"), "{'a': 2, 'b': {'$exists': false}}", 1); + _test_docs_in_coll_matches (coll, tmp_bson ("{'_id': 5}"), "{'a': 2, 'b': {'$exists': false}}", 1); bson_destroy (&reply); /* Test that a non-replace update fails. */ - ret = fn (coll, - tmp_bson ("{}"), - tmp_bson ("{'$set': {'a': 1}}"), - NULL, - NULL, - &err); + ret = fn (coll, tmp_bson ("{}"), tmp_bson ("{'$set': {'a': 1}}"), NULL, NULL, &err); ASSERT (!ret); - ASSERT_ERROR_CONTAINS ( - err, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Invalid key '$set': replace prohibits $ operators"); + ASSERT_ERROR_CONTAINS (err, + MONGOC_ERROR_COMMAND, + MONGOC_ERROR_COMMAND_INVALID_ARG, + "Invalid key '$set': replace prohibits $ operators"); } else { /* Test update_one and update_many with arrayFilters */ ret = mongoc_collection_insert_one ( - coll, - tmp_bson ("{'_id': 6, 'a': [{'x':1},{'x':2}]}"), - &opts_with_wc, - NULL, - &err); + coll, tmp_bson ("{'_id': 6, 'a': [{'x':1},{'x':2}]}"), &opts_with_wc, NULL, &err); ASSERT_OR_PRINT (ret, err); update = tmp_bson ("{'$set': {'a.$[i].x': 3}}"); - ret = fn (coll, - tmp_bson ("{'_id': 6}"), - update, - tmp_bson ("{'arrayFilters': [{'i.x': {'$gt': 1}}]}"), - &reply, - &err); + ret = + fn (coll, tmp_bson ("{'_id': 6}"), update, tmp_bson ("{'arrayFilters': [{'i.x': {'$gt': 1}}]}"), &reply, &err); if (test_framework_max_wire_version_at_least (6)) { ASSERT_OR_PRINT (ret, err); ASSERT_MATCH (&reply, "{'modifiedCount': 1, 'matchedCount': 1, " "'upsertedId': {'$exists': false}}"); - _test_docs_in_coll_matches ( - coll, tmp_bson ("{'_id':6}"), "{'a': [{'x':1},{'x':3}]}", 1); + _test_docs_in_coll_matches (coll, tmp_bson ("{'_id':6}"), "{'a': [{'x':1},{'x':3}]}", 1); } else { BSON_ASSERT (!ret); - ASSERT_ERROR_CONTAINS ( - err, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION, - "The selected server does not support array filters"); + ASSERT_ERROR_CONTAINS (err, + MONGOC_ERROR_COMMAND, + MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION, + "The selected server does not support array filters"); } bson_destroy (&reply); /* Test update that fails */ ctx.expected_command = "{'update': 'coll'}"; - ret = - fn (coll, tmp_bson ("{}"), tmp_bson ("{'a': 1}"), NULL, &reply, &err); + ret = fn (coll, tmp_bson ("{}"), tmp_bson ("{'a': 1}"), NULL, &reply, &err); ASSERT (!ret); - ASSERT_ERROR_CONTAINS (err, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Invalid key"); + ASSERT_ERROR_CONTAINS (err, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid key"); ASSERT (bson_empty (&reply)); bson_destroy (&reply); } @@ -5460,33 +4863,23 @@ test_array_filters_validate (void) client = test_framework_new_default_client (); mongoc_client_set_error_api (client, 2); collection = get_test_collection (client, "test_array_filters_validation"); - r = mongoc_collection_update_one (collection, - tmp_bson ("{}"), - tmp_bson ("{'$set': {'x': 1}}"), - tmp_bson ("{'arrayFilters': 1}"), - NULL, - &error); + r = mongoc_collection_update_one ( + collection, tmp_bson ("{}"), tmp_bson ("{'$set': {'x': 1}}"), tmp_bson ("{'arrayFilters': 1}"), NULL, &error); BSON_ASSERT (!r); - ASSERT_ERROR_CONTAINS ( - error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Invalid field \"arrayFilters\" in opts, should contain array," - " not INT32"); - - r = mongoc_collection_update_one (collection, - tmp_bson ("{}"), - tmp_bson ("{'$set': {'x': 1}}"), - tmp_bson ("{'arrayFilters': {}}"), - NULL, - &error); + ASSERT_ERROR_CONTAINS (error, + MONGOC_ERROR_COMMAND, + MONGOC_ERROR_COMMAND_INVALID_ARG, + "Invalid field \"arrayFilters\" in opts, should contain array," + " not INT32"); + + r = mongoc_collection_update_one ( + collection, tmp_bson ("{}"), tmp_bson ("{'$set': {'x': 1}}"), tmp_bson ("{'arrayFilters': {}}"), NULL, &error); BSON_ASSERT (!r); - ASSERT_ERROR_CONTAINS ( - error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Invalid field \"arrayFilters\" in opts, should contain array," - " not DOCUMENT"); + ASSERT_ERROR_CONTAINS (error, + MONGOC_ERROR_COMMAND, + MONGOC_ERROR_COMMAND_INVALID_ARG, + "Invalid field \"arrayFilters\" in opts, should contain array," + " not DOCUMENT"); mongoc_collection_destroy (collection); mongoc_client_destroy (client); @@ -5523,60 +4916,34 @@ _test_update_validate (update_fn_t update_fn) msg = "Invalid key 'x': update only works with $ operators and pipelines"; } - BSON_ASSERT ( - !update_fn (collection, selector, invalid_update, NULL, NULL, &error)); - ASSERT_ERROR_CONTAINS ( - error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, msg); + BSON_ASSERT (!update_fn (collection, selector, invalid_update, NULL, NULL, &error)); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, msg); - r = update_fn (collection, - selector, - invalid_update, - tmp_bson ("{'validate': false}"), - NULL, - &error); + r = update_fn (collection, selector, invalid_update, tmp_bson ("{'validate': false}"), NULL, &error); /* server may or may not error */ if (!r) { ASSERT_CMPUINT32 (error.domain, ==, (uint32_t) MONGOC_ERROR_SERVER); } - BSON_ASSERT (!update_fn (collection, - selector, - invalid_update, - tmp_bson ("{'validate': 'foo'}"), - NULL, - &error)); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Invalid type for option \"validate\": \"UTF8\""); + BSON_ASSERT (!update_fn (collection, selector, invalid_update, tmp_bson ("{'validate': 'foo'}"), NULL, &error)); + ASSERT_ERROR_CONTAINS ( + error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid type for option \"validate\": \"UTF8\""); /* Set all validation flags */ - BSON_ASSERT (!update_fn (collection, - selector, - invalid_update, - tmp_bson ("{'validate': 31}"), - NULL, - &error)); + BSON_ASSERT (!update_fn (collection, selector, invalid_update, tmp_bson ("{'validate': 31}"), NULL, &error)); /* bson_validate_with_error will yield a different error message than the * standard key check in _mongoc_validate_replace */ if (update_fn == mongoc_collection_replace_one) { - msg = - "invalid argument for replace: keys cannot begin with \"$\": \"$set\""; + msg = "invalid argument for replace: keys cannot begin with \"$\": \"$set\""; } - ASSERT_ERROR_CONTAINS ( - error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, msg); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, msg); /* Check that validation passes for a valid update. */ ASSERT_OR_PRINT ( - update_fn (collection, - selector, - valid_update, - tmp_bson ("{'validate': %d}", BSON_VALIDATE_UTF8), - NULL, - &error), + update_fn (collection, selector, valid_update, tmp_bson ("{'validate': %d}", BSON_VALIDATE_UTF8), NULL, &error), error); mongoc_collection_destroy (collection); @@ -5605,17 +4972,12 @@ test_update_many_validate (void) } -typedef bool (*delete_fn_t) (mongoc_collection_t *, - const bson_t *, - const bson_t *, - bson_t *, - bson_error_t *); +typedef bool (*delete_fn_t) (mongoc_collection_t *, const bson_t *, const bson_t *, bson_t *, bson_error_t *); static void _test_delete_one_or_many (bool is_multi) { - delete_fn_t fn = - is_multi ? mongoc_collection_delete_many : mongoc_collection_delete_one; + delete_fn_t fn = is_multi ? mongoc_collection_delete_many : mongoc_collection_delete_one; bson_error_t err = {0}; bson_t reply; bson_t opts_with_wc = BSON_INITIALIZER; @@ -5645,19 +5007,14 @@ _test_delete_one_or_many (bool is_multi) mongoc_collection_drop (coll, NULL); for (i = 0; i < 3; i++) { - ret = mongoc_collection_insert_one ( - coll, tmp_bson ("{'_id': %d}", i), NULL, NULL, &err); + ret = mongoc_collection_insert_one (coll, tmp_bson ("{'_id': %d}", i), NULL, NULL, &err); ASSERT_OR_PRINT (ret, err); } /* Test maxTimeMS */ ctx.expected_command = "{'delete': 'coll', 'maxTimeMS': 9999, " " 'writeConcern': {'w': 1, 'j': false}}"; - ret = fn (coll, - tmp_bson ("{'_id': 1}"), - tmp_bson ("{'maxTimeMS': 9999}"), - &reply, - &err); + ret = fn (coll, tmp_bson ("{'_id': 1}"), tmp_bson ("{'maxTimeMS': 9999}"), &reply, &err); ASSERT_OR_PRINT (ret, err); ASSERT_MATCH (&reply, "{'deletedCount': 1}"); bson_destroy (&reply); @@ -5665,8 +5022,7 @@ _test_delete_one_or_many (bool is_multi) /* Test passing write concern through the options */ mongoc_write_concern_append (wc2, &opts_with_wc); - ctx.expected_command = - "{'delete': 'coll', 'writeConcern': {'w': 1, 'j': true}}"; + ctx.expected_command = "{'delete': 'coll', 'writeConcern': {'w': 1, 'j': true}}"; ret = fn (coll, tmp_bson ("{'_id': 2}"), &opts_with_wc, &reply, &err); ASSERT_OR_PRINT (ret, err); ASSERT_MATCH (&reply, "{'deletedCount': 1}"); @@ -5674,8 +5030,7 @@ _test_delete_one_or_many (bool is_multi) _test_no_docs_match (coll, "{'_id': 2}"); /* Test passing NULL for opts, reply, and error */ - ctx.expected_command = - "{'delete': 'coll', 'writeConcern': {'w': 1, 'j': false}}"; + ctx.expected_command = "{'delete': 'coll', 'writeConcern': {'w': 1, 'j': false}}"; ret = fn (coll, tmp_bson ("{'_id': 3}"), NULL, NULL, NULL); ASSERT (ret); _test_no_docs_match (coll, "{'_id': 3}"); @@ -5698,14 +5053,9 @@ _test_delete_one_or_many (bool is_multi) /* Write concern error */ ctx.expected_command = "{'delete': 'coll'," " 'writeConcern': {'w': 99, 'wtimeout': 100}}"; - ret = fn (coll, - tmp_bson ("{}"), - tmp_bson ("{'writeConcern': {'w': 99, 'wtimeout': 100}}"), - &reply, - &err); + ret = fn (coll, tmp_bson ("{}"), tmp_bson ("{'writeConcern': {'w': 99, 'wtimeout': 100}}"), &reply, &err); ASSERT (!ret); - if (test_framework_get_server_version () >= - test_framework_str_to_version ("4.3.3")) { + if (test_framework_get_server_version () >= test_framework_str_to_version ("4.3.3")) { /* Error reporting changed in SERVER-45584 */ ASSERT_CMPUINT32 (err.domain, ==, (uint32_t) MONGOC_ERROR_QUERY); ASSERT_MATCH (&reply, @@ -5714,8 +5064,7 @@ _test_delete_one_or_many (bool is_multi) " 'writeConcernErrors': {'$exists': false}" "}"); } else { - ASSERT_CMPUINT32 ( - err.domain, ==, (uint32_t) MONGOC_ERROR_WRITE_CONCERN); + ASSERT_CMPUINT32 (err.domain, ==, (uint32_t) MONGOC_ERROR_WRITE_CONCERN); ASSERT_MATCH (&reply, "{'deletedCount': 1," " 'writeErrors': {'$exists': false}," @@ -5728,23 +5077,17 @@ _test_delete_one_or_many (bool is_multi) /* Test deleting with collation. */ ctx.expected_command = "{'delete': 'coll'}"; - ret = mongoc_collection_insert_one ( - coll, tmp_bson ("{'_id': 1, 'x': 11}"), NULL, NULL, &err); + ret = mongoc_collection_insert_one (coll, tmp_bson ("{'_id': 1, 'x': 11}"), NULL, NULL, &err); ASSERT_OR_PRINT (ret, err); - ret = mongoc_collection_insert_one ( - coll, tmp_bson ("{'_id': 2, 'x': 'ping'}"), NULL, NULL, &err); + ret = mongoc_collection_insert_one (coll, tmp_bson ("{'_id': 2, 'x': 'ping'}"), NULL, NULL, &err); ASSERT_OR_PRINT (ret, err); - ret = mongoc_collection_insert_one ( - coll, tmp_bson ("{'_id': 3, 'x': 'pINg'}"), NULL, NULL, &err); + ret = mongoc_collection_insert_one (coll, tmp_bson ("{'_id': 3, 'x': 'pINg'}"), NULL, NULL, &err); ASSERT_OR_PRINT (ret, err); - ret = fn (coll, - tmp_bson ("{'x': 'PING'}"), - tmp_bson ("{'collation': {'locale': 'en_US', 'strength': 2 }}"), - &reply, - &err); + ret = fn ( + coll, tmp_bson ("{'x': 'PING'}"), tmp_bson ("{'collation': {'locale': 'en_US', 'strength': 2 }}"), &reply, &err); ASSERT_OR_PRINT (ret, err); if (is_multi) { @@ -5765,11 +5108,8 @@ _test_delete_one_or_many (bool is_multi) mongoc_client_destroy (client); } -typedef future_t *(*future_delete_fn_t) (mongoc_collection_t *, - const bson_t *, - const bson_t *, - bson_t *, - bson_error_t *); +typedef future_t *(*future_delete_fn_t) ( + mongoc_collection_t *, const bson_t *, const bson_t *, bson_t *, bson_error_t *); static void _test_delete_collation (bool is_multi) @@ -5780,28 +5120,21 @@ _test_delete_collation (bool is_multi) future_t *future; request_t *request; bson_error_t error; - future_delete_fn_t fn = - is_multi ? future_collection_delete_many : future_collection_delete_one; + future_delete_fn_t fn = is_multi ? future_collection_delete_many : future_collection_delete_one; server = mock_server_with_auto_hello (WIRE_VERSION_MIN); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); collection = mongoc_client_get_collection (client, "db", "collection"); - future = fn (collection, - tmp_bson ("{}"), - tmp_bson ("{'collation': {'locale': 'en'}}"), - NULL, - &error); + future = fn (collection, tmp_bson ("{}"), tmp_bson ("{'collation': {'locale': 'en'}}"), NULL, &error); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db'," - " 'delete': 'collection'}"), - tmp_bson ("{'q': {}, 'limit': %d, 'collation': {'locale': 'en'}}", - is_multi ? 0 : 1)); + request = + mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'db'," + " 'delete': 'collection'}"), + tmp_bson ("{'q': {}, 'limit': %d, 'collation': {'locale': 'en'}}", is_multi ? 0 : 1)); reply_to_request_simple (request, "{'ok': 1, 'n': 1}"); ASSERT_OR_PRINT (future_get_bool (future), error); request_destroy (request); @@ -5826,12 +5159,8 @@ test_delete_collation (void) _test_delete_collation (false); } -typedef future_t *(*future_update_fn_t) (mongoc_collection_t *, - const bson_t *, - const bson_t *, - const bson_t *, - bson_t *, - bson_error_t *); +typedef future_t *(*future_update_fn_t) ( + mongoc_collection_t *, const bson_t *, const bson_t *, const bson_t *, bson_t *, bson_error_t *); static void _test_update_or_replace_with_collation (bool is_replace, bool is_multi) { @@ -5847,29 +5176,22 @@ _test_update_or_replace_with_collation (bool is_replace, bool is_multi) BSON_ASSERT (!is_multi); fn = future_collection_replace_one; } else { - fn = is_multi ? future_collection_update_many - : future_collection_update_one; + fn = is_multi ? future_collection_update_many : future_collection_update_one; } server = mock_server_with_auto_hello (WIRE_VERSION_MIN); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); collection = mongoc_client_get_collection (client, "db", "collection"); - future = fn (collection, - tmp_bson ("{}"), - tmp_bson ("{}"), - tmp_bson ("{'collation': {'locale': 'en'}}"), - NULL, - &error); + future = + fn (collection, tmp_bson ("{}"), tmp_bson ("{}"), tmp_bson ("{'collation': {'locale': 'en'}}"), NULL, &error); request = mock_server_receives_msg ( server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', 'update': 'collection'}"), - tmp_bson ("{'q': {}, 'u': {}, 'collation': {'locale': 'en'}%s}", - is_multi ? ", 'multi': true" : "")); + tmp_bson ("{'q': {}, 'u': {}, 'collation': {'locale': 'en'}%s}", is_multi ? ", 'multi': true" : "")); reply_to_request_simple (request, "{'ok': 1, 'n': 1}"); ASSERT_OR_PRINT (future_get_bool (future), error); request_destroy (request); @@ -5904,30 +5226,21 @@ _test_update_hint (bool is_replace, bool is_multi, const char *hint) BSON_ASSERT (!is_multi); fn = future_collection_replace_one; } else { - fn = is_multi ? future_collection_update_many - : future_collection_update_one; + fn = is_multi ? future_collection_update_many : future_collection_update_one; } server = mock_server_with_auto_hello (WIRE_VERSION_MIN); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); collection = mongoc_client_get_collection (client, "db", "collection"); - future = fn (collection, - tmp_bson ("{}"), - tmp_bson ("{}"), - tmp_bson ("{'hint': %s}", hint), - NULL, - &error); + future = fn (collection, tmp_bson ("{}"), tmp_bson ("{}"), tmp_bson ("{'hint': %s}", hint), NULL, &error); request = mock_server_receives_msg ( server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', 'update': 'collection'}"), - tmp_bson ("{'q': {}, 'u': {}, 'hint': %s %s }", - hint, - is_multi ? ", 'multi': true" : "")); + tmp_bson ("{'q': {}, 'u': {}, 'hint': %s %s }", hint, is_multi ? ", 'multi': true" : "")); reply_to_request_simple (request, "{'ok': 1, 'n': 1}"); ASSERT_OR_PRINT (future_get_bool (future), error); @@ -5962,41 +5275,23 @@ test_update_hint_validate (void) client = test_framework_new_default_client (); mongoc_client_set_error_api (client, 2); collection = get_test_collection (client, "test_update_hint_validation"); - r = mongoc_collection_update_one (collection, - tmp_bson ("{}"), - tmp_bson ("{'$set': {'x': 1}}"), - tmp_bson ("{'hint': 1}"), - NULL, - &error); + r = mongoc_collection_update_one ( + collection, tmp_bson ("{}"), tmp_bson ("{'$set': {'x': 1}}"), tmp_bson ("{'hint': 1}"), NULL, &error); BSON_ASSERT (!r); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "The hint option must be a string or document"); - - r = mongoc_collection_update_many (collection, - tmp_bson ("{}"), - tmp_bson ("{'$set': {'x': 1}}"), - tmp_bson ("{'hint': 3.14}"), - NULL, - &error); + ASSERT_ERROR_CONTAINS ( + error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "The hint option must be a string or document"); + + r = mongoc_collection_update_many ( + collection, tmp_bson ("{}"), tmp_bson ("{'$set': {'x': 1}}"), tmp_bson ("{'hint': 3.14}"), NULL, &error); BSON_ASSERT (!r); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "The hint option must be a string or document"); - - r = mongoc_collection_replace_one (collection, - tmp_bson ("{}"), - tmp_bson ("{'x': 1}"), - tmp_bson ("{'hint': []}"), - NULL, - &error); + ASSERT_ERROR_CONTAINS ( + error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "The hint option must be a string or document"); + + r = mongoc_collection_replace_one ( + collection, tmp_bson ("{}"), tmp_bson ("{'x': 1}"), tmp_bson ("{'hint': []}"), NULL, &error); BSON_ASSERT (!r); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "The hint option must be a string or document"); + ASSERT_ERROR_CONTAINS ( + error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "The hint option must be a string or document"); mongoc_collection_destroy (collection); mongoc_client_destroy (client); @@ -6021,10 +5316,7 @@ test_update_multi (void) bptr[i] = tmp_bson ("{'_id': %d, 'x': 1234}", i); } - ASSERT_OR_PRINT ( - mongoc_collection_insert_many ( - collection, (const bson_t **) bptr, 10, NULL, NULL, &error), - error); + ASSERT_OR_PRINT (mongoc_collection_insert_many (collection, (const bson_t **) bptr, 10, NULL, NULL, &error), error); ASSERT_OR_PRINT (mongoc_collection_update (collection, MONGOC_UPDATE_MULTI_UPDATE, @@ -6034,10 +5326,8 @@ test_update_multi (void) &error), error); - _test_docs_in_coll_matches ( - collection, tmp_bson ("{'_id': {'$lt': 5}, 'x': 1234}"), NULL, 5); - _test_docs_in_coll_matches ( - collection, tmp_bson ("{'_id': {'$gte': 5}, 'x': 1235}"), NULL, 5); + _test_docs_in_coll_matches (collection, tmp_bson ("{'_id': {'$lt': 5}, 'x': 1234}"), NULL, 5); + _test_docs_in_coll_matches (collection, tmp_bson ("{'_id': {'$gte': 5}, 'x': 1235}"), NULL, 5); ASSERT_OR_PRINT (mongoc_collection_drop (collection, &error), error); @@ -6059,16 +5349,11 @@ test_update_upsert (void) (void) mongoc_collection_drop (collection, &error); ASSERT_OR_PRINT ( - mongoc_collection_update (collection, - MONGOC_UPDATE_UPSERT, - tmp_bson ("{'_id': 1}"), - tmp_bson ("{'$set': {'x': 1234}}"), - NULL, - &error), + mongoc_collection_update ( + collection, MONGOC_UPDATE_UPSERT, tmp_bson ("{'_id': 1}"), tmp_bson ("{'$set': {'x': 1234}}"), NULL, &error), error); - _test_docs_in_coll_matches ( - collection, tmp_bson ("{'_id': 1, 'x': 1234}"), NULL, 1); + _test_docs_in_coll_matches (collection, tmp_bson ("{'_id': 1, 'x': 1234}"), NULL, 1); ASSERT_OR_PRINT (mongoc_collection_drop (collection, &error), error); @@ -6095,26 +5380,16 @@ test_remove_multi (void) bptr[i] = tmp_bson ("{'_id': %d, 'x': 1234}", i); } + ASSERT_OR_PRINT (mongoc_collection_insert_many (collection, (const bson_t **) bptr, 10, NULL, NULL, &error), error); + ASSERT_OR_PRINT ( - mongoc_collection_insert_many ( - collection, (const bson_t **) bptr, 10, NULL, NULL, &error), + mongoc_collection_remove (collection, MONGOC_REMOVE_NONE, tmp_bson ("{'_id': {'$gte': 8}}"), NULL, &error), error); - ASSERT_OR_PRINT (mongoc_collection_remove (collection, - MONGOC_REMOVE_NONE, - tmp_bson ("{'_id': {'$gte': 8}}"), - NULL, - &error), - error); - /* mongoc_collection_delete is an alias of mongoc_collection_remove, although * its flag type differs slightly */ - ASSERT_OR_PRINT (mongoc_collection_delete (collection, - MONGOC_DELETE_NONE, - tmp_bson ("{'_id': {'$lt': 2}}"), - NULL, - &error), - error); + ASSERT_OR_PRINT ( + mongoc_collection_delete (collection, MONGOC_DELETE_NONE, tmp_bson ("{'_id': {'$lt': 2}}"), NULL, &error), error); _test_docs_in_coll_matches (collection, tmp_bson ("{'x': 1234}"), NULL, 6); @@ -6137,38 +5412,30 @@ test_fam_no_error_on_retry (void *unused) BSON_UNUSED (unused); client = test_framework_new_default_client (); - ret = mongoc_client_command_simple ( - client, - "admin", - tmp_bson ("{'configureFailPoint': 'failCommand', 'mode': {'times': 1}, " - "'data': {'failCommands': ['findAndModify'], 'errorLabels': " - "['RetryableWriteError']}}"), - NULL, - &reply, - &error); + ret = mongoc_client_command_simple (client, + "admin", + tmp_bson ("{'configureFailPoint': 'failCommand', 'mode': {'times': 1}, " + "'data': {'failCommands': ['findAndModify'], 'errorLabels': " + "['RetryableWriteError']}}"), + NULL, + &reply, + &error); if (!ret) { - test_error ("configureFailPoint error: %s reply: %s", - error.message, - tmp_json (&reply)); + test_error ("configureFailPoint error: %s reply: %s", error.message, tmp_json (&reply)); } coll = get_test_collection (client, BSON_FUNC); opts = mongoc_find_and_modify_opts_new (); - mongoc_find_and_modify_opts_set_update (opts, - tmp_bson ("{'$set': {'x': 2}}")); + mongoc_find_and_modify_opts_set_update (opts, tmp_bson ("{'$set': {'x': 2}}")); bson_destroy (&reply); - ret = mongoc_collection_find_and_modify_with_opts ( - coll, tmp_bson ("{'x': 1}"), opts, &reply, &error); + ret = mongoc_collection_find_and_modify_with_opts (coll, tmp_bson ("{'x': 1}"), opts, &reply, &error); if (!ret) { - test_error ( - "findAndModify error: %s reply: %s", error.message, tmp_json (&reply)); + test_error ("findAndModify error: %s reply: %s", error.message, tmp_json (&reply)); } - if (error.code != 0 || error.domain != 0 || - 0 != strcmp (error.message, "")) { - test_error ("error set, but findAndModify succeeded: code=%" PRIu32 - " domain=%" PRIu32 " message=%s", + if (error.code != 0 || error.domain != 0 || 0 != strcmp (error.message, "")) { + test_error ("error set, but findAndModify succeeded: code=%" PRIu32 " domain=%" PRIu32 " message=%s", error.code, error.domain, error.message); @@ -6186,20 +5453,13 @@ test_hint_is_validated_aggregate (void) bson_error_t error; mongoc_client_t *client = test_framework_new_default_client (); mongoc_client_set_error_api (client, MONGOC_ERROR_API_VERSION_2); - mongoc_collection_t *collection = - get_test_collection (client, "test_hint_is_validated_aggregate"); - mongoc_cursor_t *cursor = - mongoc_collection_aggregate (collection, - MONGOC_QUERY_NONE, - tmp_bson ("{}"), - tmp_bson ("{'hint': 1}"), - NULL /* read prefs */); + mongoc_collection_t *collection = get_test_collection (client, "test_hint_is_validated_aggregate"); + mongoc_cursor_t *cursor = mongoc_collection_aggregate ( + collection, MONGOC_QUERY_NONE, tmp_bson ("{}"), tmp_bson ("{'hint': 1}"), NULL /* read prefs */); bool has_error = mongoc_cursor_error (cursor, &error); ASSERT (has_error); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "The hint option must be a string or document"); + ASSERT_ERROR_CONTAINS ( + error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "The hint option must be a string or document"); mongoc_cursor_destroy (cursor); mongoc_collection_destroy (collection); mongoc_client_destroy (client); @@ -6211,66 +5471,52 @@ test_hint_is_validated_countDocuments (void) bson_error_t error; mongoc_client_t *client = test_framework_new_default_client (); mongoc_client_set_error_api (client, MONGOC_ERROR_API_VERSION_2); - mongoc_collection_t *collection = - get_test_collection (client, "test_hint_is_validated_countDocuments"); - int64_t got = mongoc_collection_count_documents (collection, - tmp_bson ("{}"), - tmp_bson ("{'hint': 1}"), - NULL /* read prefs */, - NULL /* reply */, - &error); + mongoc_collection_t *collection = get_test_collection (client, "test_hint_is_validated_countDocuments"); + int64_t got = mongoc_collection_count_documents ( + collection, tmp_bson ("{}"), tmp_bson ("{'hint': 1}"), NULL /* read prefs */, NULL /* reply */, &error); ASSERT_CMPINT64 (got, ==, -1); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "The hint option must be a string or document"); + ASSERT_ERROR_CONTAINS ( + error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "The hint option must be a string or document"); mongoc_collection_destroy (collection); mongoc_client_destroy (client); } -#define ASSERT_INDEX_EXISTS(keys, expect_name) \ - if (1) { \ - bool found = false; \ - mongoc_cursor_t *cursor = \ - mongoc_collection_find_indexes_with_opts (coll, NULL /* opts */); \ - const bson_t *got; \ - while (mongoc_cursor_next (cursor, &got)) { \ - bson_t got_key; \ - const char *got_name = NULL; \ - /* Results have the form: `{ v: 2, key: { x: 1 }, name: 'x_1' }` */ \ - bsonParse ( \ - *got, \ - require (keyWithType ("key", doc), storeDocRef (got_key)), \ - require (keyWithType ("name", utf8), storeStrRef (got_name))); \ - ASSERT_WITH_MSG ( \ - !bsonParseError, "got parse error: %s", bsonParseError); \ - if (bson_equal (&got_key, keys)) { \ - found = true; \ - ASSERT_CMPSTR (got_name, expect_name); \ - } \ - } \ - ASSERT_OR_PRINT (!mongoc_cursor_error (cursor, &error), error); \ - ASSERT_WITH_MSG (found, \ - "could not find expected index for keys: '%s'", \ - tmp_json (keys)); \ - mongoc_cursor_destroy (cursor); \ - } else \ +#define ASSERT_INDEX_EXISTS(keys, expect_name) \ + if (1) { \ + bool found = false; \ + mongoc_cursor_t *cursor = mongoc_collection_find_indexes_with_opts (coll, NULL /* opts */); \ + const bson_t *got; \ + while (mongoc_cursor_next (cursor, &got)) { \ + bson_t got_key; \ + const char *got_name = NULL; \ + /* Results have the form: `{ v: 2, key: { x: 1 }, name: 'x_1' }` */ \ + bsonParse (*got, \ + require (keyWithType ("key", doc), storeDocRef (got_key)), \ + require (keyWithType ("name", utf8), storeStrRef (got_name))); \ + ASSERT_WITH_MSG (!bsonParseError, "got parse error: %s", bsonParseError); \ + if (bson_equal (&got_key, keys)) { \ + found = true; \ + ASSERT_CMPSTR (got_name, expect_name); \ + } \ + } \ + ASSERT_OR_PRINT (!mongoc_cursor_error (cursor, &error), error); \ + ASSERT_WITH_MSG (found, "could not find expected index for keys: '%s'", tmp_json (keys)); \ + mongoc_cursor_destroy (cursor); \ + } else \ (void) 0 static void test_create_indexes_with_opts (void) { mongoc_client_t *client = test_framework_new_default_client (); - mongoc_collection_t *coll = - get_test_collection (client, "test_create_indexes_with_opts"); + mongoc_collection_t *coll = get_test_collection (client, "test_create_indexes_with_opts"); bson_error_t error; // Test creating an index. { const bson_t *keys = tmp_bson ("{'x': 1}"); mongoc_index_model_t *im = mongoc_index_model_new (keys, NULL); - bool ok = mongoc_collection_create_indexes_with_opts ( - coll, &im, 1, NULL /* opts */, NULL /* reply */, &error); + bool ok = mongoc_collection_create_indexes_with_opts (coll, &im, 1, NULL /* opts */, NULL /* reply */, &error); ASSERT_OR_PRINT (ok, error); mongoc_index_model_destroy (im); ASSERT_INDEX_EXISTS (keys, "x_1"); @@ -6282,10 +5528,8 @@ test_create_indexes_with_opts (void) // Test creating an index uses specified `name`. { const bson_t *keys = tmp_bson ("{'x': 1}"); - mongoc_index_model_t *im = - mongoc_index_model_new (keys, tmp_bson ("{'name': 'foobar'}")); - bool ok = mongoc_collection_create_indexes_with_opts ( - coll, &im, 1, NULL /* opts */, NULL /* reply */, &error); + mongoc_index_model_t *im = mongoc_index_model_new (keys, tmp_bson ("{'name': 'foobar'}")); + bool ok = mongoc_collection_create_indexes_with_opts (coll, &im, 1, NULL /* opts */, NULL /* reply */, &error); ASSERT_OR_PRINT (ok, error); mongoc_index_model_destroy (im); ASSERT_INDEX_EXISTS (keys, "foobar"); @@ -6300,8 +5544,7 @@ test_create_indexes_with_opts_no_retry (void *unused) { BSON_UNUSED (unused); mongoc_client_t *client = test_framework_new_default_client (); - mongoc_collection_t *coll = - get_test_collection (client, "test_create_indexes_with_opts"); + mongoc_collection_t *coll = get_test_collection (client, "test_create_indexes_with_opts"); bson_error_t error; // Configure failpoint to cause a network error. @@ -6311,15 +5554,10 @@ test_create_indexes_with_opts_no_retry (void *unused) "mode" : {"times" : 1}, "data" : {"failCommands" : ["createIndexes"], "closeConnection" : true} }); - bson_t *failpoint_cmd = - bson_new_from_json ((const uint8_t *) cmd_str, -1, &error); + bson_t *failpoint_cmd = bson_new_from_json ((const uint8_t *) cmd_str, -1, &error); ASSERT_OR_PRINT (failpoint_cmd, error); - bool ok = mongoc_client_command_simple (client, - "admin", - failpoint_cmd, - NULL /* read_prefs */, - NULL /* reply */, - &error); + bool ok = + mongoc_client_command_simple (client, "admin", failpoint_cmd, NULL /* read_prefs */, NULL /* reply */, &error); ASSERT_OR_PRINT (ok, error); bson_destroy (failpoint_cmd); } @@ -6328,13 +5566,9 @@ test_create_indexes_with_opts_no_retry (void *unused) { const bson_t *keys = tmp_bson ("{'x': 1}"); mongoc_index_model_t *im = mongoc_index_model_new (keys, NULL); - bool ok = mongoc_collection_create_indexes_with_opts ( - coll, &im, 1, NULL /* opts */, NULL /* reply */, &error); + bool ok = mongoc_collection_create_indexes_with_opts (coll, &im, 1, NULL /* opts */, NULL /* reply */, &error); ASSERT (!ok); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_SOCKET, - "Failed to send"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "Failed to send"); mongoc_index_model_destroy (im); } @@ -6350,8 +5584,7 @@ test_create_indexes_with_opts_commitQuorum_pre44 (void *unused) { BSON_UNUSED (unused); mongoc_client_t *client = test_framework_new_default_client (); - mongoc_collection_t *coll = - get_test_collection (client, "test_create_indexes_with_opts"); + mongoc_collection_t *coll = get_test_collection (client, "test_create_indexes_with_opts"); bson_error_t error; // Create index. @@ -6359,18 +5592,12 @@ test_create_indexes_with_opts_commitQuorum_pre44 (void *unused) const bson_t *keys = tmp_bson ("{'x': 1}"); mongoc_index_model_t *im = mongoc_index_model_new (keys, NULL); bool ok = mongoc_collection_create_indexes_with_opts ( - coll, - &im, - 1, - tmp_bson ("{'commitQuorum': 'majority'}"), - NULL /* reply */, - &error); + coll, &im, 1, tmp_bson ("{'commitQuorum': 'majority'}"), NULL /* reply */, &error); ASSERT (!ok); - ASSERT_ERROR_CONTAINS ( - error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION, - "The selected server does not support the commitQuorum option"); + ASSERT_ERROR_CONTAINS (error, + MONGOC_ERROR_COMMAND, + MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION, + "The selected server does not support the commitQuorum option"); mongoc_index_model_destroy (im); } @@ -6385,8 +5612,7 @@ test_create_indexes_with_opts_commitQuorum_post44 (void *unused) { BSON_UNUSED (unused); mongoc_client_t *client = test_framework_new_default_client (); - mongoc_collection_t *coll = - get_test_collection (client, "test_create_indexes_with_opts"); + mongoc_collection_t *coll = get_test_collection (client, "test_create_indexes_with_opts"); bson_error_t error; // Create index. @@ -6394,12 +5620,7 @@ test_create_indexes_with_opts_commitQuorum_post44 (void *unused) const bson_t *keys = tmp_bson ("{'x': 1}"); mongoc_index_model_t *im = mongoc_index_model_new (keys, NULL); bool ok = mongoc_collection_create_indexes_with_opts ( - coll, - &im, - 1, - tmp_bson ("{'commitQuorum': 'majority'}"), - NULL /* reply */, - &error); + coll, &im, 1, tmp_bson ("{'commitQuorum': 'majority'}"), NULL /* reply */, &error); ASSERT_OR_PRINT (ok, error); mongoc_index_model_destroy (im); ASSERT_INDEX_EXISTS (keys, "x_1"); @@ -6416,59 +5637,32 @@ test_collection_install (TestSuite *suite) { test_aggregate_install (suite); - TestSuite_AddFull (suite, - "/Collection/aggregate/write_concern", - test_aggregate_w_write_concern, - NULL, - NULL, - TestSuite_CheckLive); - TestSuite_AddFull (suite, - "/Collection/read_prefs_is_valid", - test_read_prefs_is_valid, - NULL, - NULL, - test_framework_skip_if_mongos); + TestSuite_AddFull ( + suite, "/Collection/aggregate/write_concern", test_aggregate_w_write_concern, NULL, NULL, TestSuite_CheckLive); + TestSuite_AddFull ( + suite, "/Collection/read_prefs_is_valid", test_read_prefs_is_valid, NULL, NULL, test_framework_skip_if_mongos); TestSuite_AddLive (suite, "/Collection/insert_many", test_insert_many); - TestSuite_AddLive ( - suite, "/Collection/insert_bulk_empty", test_insert_bulk_empty); + TestSuite_AddLive (suite, "/Collection/insert_bulk_empty", test_insert_bulk_empty); TestSuite_AddLive (suite, "/Collection/copy", test_copy); TestSuite_AddLive (suite, "/Collection/insert", test_insert); - TestSuite_AddLive ( - suite, "/Collection/insert/null_string", test_insert_null); - TestSuite_AddFull (suite, - "/Collection/insert/oversize", - test_insert_oversize, - NULL, - NULL, - test_framework_skip_if_slow_or_live); - TestSuite_AddMockServerTest ( - suite, "/Collection/insert/keys", test_insert_command_keys); + TestSuite_AddLive (suite, "/Collection/insert/null_string", test_insert_null); + TestSuite_AddFull ( + suite, "/Collection/insert/oversize", test_insert_oversize, NULL, NULL, test_framework_skip_if_slow_or_live); + TestSuite_AddMockServerTest (suite, "/Collection/insert/keys", test_insert_command_keys); TestSuite_AddLive (suite, "/Collection/save", test_save); TestSuite_AddLive (suite, "/Collection/insert/w0", test_insert_w0); TestSuite_AddLive (suite, "/Collection/update/w0", test_update_w0); TestSuite_AddLive (suite, "/Collection/remove/w0", test_remove_w0); - TestSuite_AddLive ( - suite, "/Collection/insert_twice/w0", test_insert_twice_w0); + TestSuite_AddLive (suite, "/Collection/insert_twice/w0", test_insert_twice_w0); TestSuite_AddLive (suite, "/Collection/index", test_index); - TestSuite_AddLive ( - suite, "/Collection/index_w_write_concern", test_index_w_write_concern); - TestSuite_AddMockServerTest ( - suite, "/Collection/index/collation", test_index_with_collation); + TestSuite_AddLive (suite, "/Collection/index_w_write_concern", test_index_w_write_concern); + TestSuite_AddMockServerTest (suite, "/Collection/index/collation", test_index_with_collation); TestSuite_AddLive (suite, "/Collection/index_compound", test_index_compound); - TestSuite_AddFull (suite, - "/Collection/index_geo", - test_index_geo, - NULL, - NULL, - test_framework_skip_if_max_wire_version_more_than_9); + TestSuite_AddFull ( + suite, "/Collection/index_geo", test_index_geo, NULL, NULL, test_framework_skip_if_max_wire_version_more_than_9); TestSuite_AddLive (suite, "/Collection/index_storage", test_index_storage); TestSuite_AddLive (suite, "/Collection/regex", test_regex); - TestSuite_AddFull (suite, - "/Collection/decimal128", - test_decimal128, - NULL, - NULL, - skip_unless_server_has_decimal128); + TestSuite_AddFull (suite, "/Collection/decimal128", test_decimal128, NULL, NULL, skip_unless_server_has_decimal128); TestSuite_AddLive (suite, "/Collection/update", test_update); TestSuite_AddFull (suite, "/Collection/update_pipeline", @@ -6478,29 +5672,17 @@ test_collection_install (TestSuite *suite) test_framework_skip_if_max_wire_version_less_than_8); TestSuite_AddLive (suite, "/Collection/update/multi", test_update_multi); TestSuite_AddLive (suite, "/Collection/update/upsert", test_update_upsert); - TestSuite_AddFull (suite, - "/Collection/update/oversize", - test_update_oversize, - NULL, - NULL, - test_framework_skip_if_slow_or_live); + TestSuite_AddFull ( + suite, "/Collection/update/oversize", test_update_oversize, NULL, NULL, test_framework_skip_if_slow_or_live); TestSuite_AddLive (suite, "/Collection/remove", test_remove); TestSuite_AddLive (suite, "/Collection/remove/multi", test_remove_multi); - TestSuite_AddFull (suite, - "/Collection/remove/oversize", - test_remove_oversize, - NULL, - NULL, - test_framework_skip_if_slow_or_live); + TestSuite_AddFull ( + suite, "/Collection/remove/oversize", test_remove_oversize, NULL, NULL, test_framework_skip_if_slow_or_live); TestSuite_AddLive (suite, "/Collection/count", test_count); - TestSuite_AddMockServerTest ( - suite, "/Collection/count_with_opts", test_count_with_opts); - TestSuite_AddMockServerTest ( - suite, "/Collection/count/read_pref", test_count_read_pref); - TestSuite_AddMockServerTest ( - suite, "/Collection/count/read_concern", test_count_read_concern); - TestSuite_AddMockServerTest ( - suite, "/Collection/count/collation", test_count_with_collation); + TestSuite_AddMockServerTest (suite, "/Collection/count_with_opts", test_count_with_opts); + TestSuite_AddMockServerTest (suite, "/Collection/count/read_pref", test_count_read_pref); + TestSuite_AddMockServerTest (suite, "/Collection/count/read_concern", test_count_read_concern); + TestSuite_AddMockServerTest (suite, "/Collection/count/collation", test_count_with_collation); TestSuite_AddFull (suite, "/Collection/count/read_concern_live", test_count_read_concern_live, @@ -6509,138 +5691,70 @@ test_collection_install (TestSuite *suite) mongod_supports_majority_read_concern); TestSuite_AddLive (suite, "/Collection/drop", test_drop); TestSuite_AddLive (suite, "/Collection/aggregate", test_aggregate); - TestSuite_AddMockServerTest (suite, - "/Collection/aggregate/inherit/collection", - test_aggregate_inherit_collection); - TestSuite_AddLive ( - suite, "/Collection/aggregate/large", test_aggregate_large); - TestSuite_AddFull (suite, - "/Collection/aggregate/secondary", - test_aggregate_secondary, - NULL, - NULL, - test_framework_skip_if_mongos); - TestSuite_AddMockServerTest (suite, - "/Collection/aggregate/secondary/sharded", - test_aggregate_secondary_sharded); - TestSuite_AddMockServerTest ( - suite, "/Collection/aggregate/read_concern", test_aggregate_read_concern); + TestSuite_AddMockServerTest (suite, "/Collection/aggregate/inherit/collection", test_aggregate_inherit_collection); + TestSuite_AddLive (suite, "/Collection/aggregate/large", test_aggregate_large); + TestSuite_AddFull ( + suite, "/Collection/aggregate/secondary", test_aggregate_secondary, NULL, NULL, test_framework_skip_if_mongos); + TestSuite_AddMockServerTest (suite, "/Collection/aggregate/secondary/sharded", test_aggregate_secondary_sharded); + TestSuite_AddMockServerTest (suite, "/Collection/aggregate/read_concern", test_aggregate_read_concern); TestSuite_AddFull (suite, "/Collection/aggregate/bypass_document_validation", test_aggregate_bypass, NULL, NULL, TestSuite_CheckLive); - TestSuite_AddMockServerTest ( - suite, "/Collection/aggregate/collation", test_aggregate_with_collation); - TestSuite_AddMockServerTest ( - suite, "/Collection/aggregate_w_server_id", test_aggregate_w_server_id); - TestSuite_AddMockServerTest (suite, - "/Collection/aggregate_w_server_id/sharded", - test_aggregate_w_server_id_sharded); + TestSuite_AddMockServerTest (suite, "/Collection/aggregate/collation", test_aggregate_with_collation); + TestSuite_AddMockServerTest (suite, "/Collection/aggregate_w_server_id", test_aggregate_w_server_id); + TestSuite_AddMockServerTest (suite, "/Collection/aggregate_w_server_id/sharded", test_aggregate_w_server_id_sharded); TestSuite_AddFull (suite, "/Collection/aggregate_w_server_id/option", test_aggregate_server_id_option, NULL, NULL, test_framework_skip_if_auth); - TestSuite_AddFull (suite, - "/Collection/validate", - test_validate, - NULL, - NULL, - test_framework_skip_if_slow_or_live); + TestSuite_AddFull (suite, "/Collection/validate", test_validate, NULL, NULL, test_framework_skip_if_slow_or_live); TestSuite_AddLive (suite, "/Collection/rename", test_rename); // The collStats command is deprecated in MongoDB 6.0 (maxWireVersion=17) and // may be removed in a future major release. - TestSuite_AddFull (suite, - "/Collection/stats", - test_stats, - NULL, - NULL, - test_framework_skip_if_max_wire_version_more_than_17); - TestSuite_AddMockServerTest ( - suite, "/Collection/stats/read_pref", test_stats_read_pref); - TestSuite_AddMockServerTest ( - suite, "/Collection/find_read_concern", test_find_read_concern); - TestSuite_AddFull (suite, - "/Collection/getmore_read_concern_live", - test_getmore_read_concern_live, - NULL, - NULL, - TestSuite_CheckLive); - TestSuite_AddLive ( - suite, "/Collection/find_and_modify", test_find_and_modify); - TestSuite_AddMockServerTest (suite, - "/Collection/find_and_modify/write_concern", - test_find_and_modify_write_concern); - TestSuite_AddFull (suite, - "/Collection/large_return", - test_large_return, - NULL, - NULL, - test_framework_skip_if_slow_or_live); + TestSuite_AddFull ( + suite, "/Collection/stats", test_stats, NULL, NULL, test_framework_skip_if_max_wire_version_more_than_17); + TestSuite_AddMockServerTest (suite, "/Collection/stats/read_pref", test_stats_read_pref); + TestSuite_AddMockServerTest (suite, "/Collection/find_read_concern", test_find_read_concern); + TestSuite_AddFull ( + suite, "/Collection/getmore_read_concern_live", test_getmore_read_concern_live, NULL, NULL, TestSuite_CheckLive); + TestSuite_AddLive (suite, "/Collection/find_and_modify", test_find_and_modify); + TestSuite_AddMockServerTest (suite, "/Collection/find_and_modify/write_concern", test_find_and_modify_write_concern); + TestSuite_AddFull ( + suite, "/Collection/large_return", test_large_return, NULL, NULL, test_framework_skip_if_slow_or_live); TestSuite_AddLive (suite, "/Collection/many_return", test_many_return); - TestSuite_AddLive ( - suite, "/Collection/insert_one_validate", test_insert_one_validate); - TestSuite_AddLive ( - suite, "/Collection/insert_many_validate", test_insert_many_validate); + TestSuite_AddLive (suite, "/Collection/insert_one_validate", test_insert_one_validate); + TestSuite_AddLive (suite, "/Collection/insert_many_validate", test_insert_many_validate); TestSuite_AddMockServerTest (suite, "/Collection/limit", test_find_limit); - TestSuite_AddMockServerTest ( - suite, "/Collection/batch_size", test_find_batch_size); - TestSuite_AddFull (suite, - "/Collection/command_fully_qualified", - test_command_fq, - NULL, - NULL, - test_framework_skip_if_mongos); + TestSuite_AddMockServerTest (suite, "/Collection/batch_size", test_find_batch_size); + TestSuite_AddFull ( + suite, "/Collection/command_fully_qualified", test_command_fq, NULL, NULL, test_framework_skip_if_mongos); TestSuite_AddLive (suite, "/Collection/get_index_info", test_get_index_info); - TestSuite_AddMockServerTest ( - suite, "/Collection/find_indexes/error", test_find_indexes_err); - TestSuite_AddLive ( - suite, "/Collection/insert/duplicate_key", test_insert_duplicate_key); - TestSuite_AddFull (suite, - "/Collection/create_index/fail", - test_create_index_fail, - NULL, - NULL, - test_framework_skip_if_offline); + TestSuite_AddMockServerTest (suite, "/Collection/find_indexes/error", test_find_indexes_err); + TestSuite_AddLive (suite, "/Collection/insert/duplicate_key", test_insert_duplicate_key); + TestSuite_AddFull ( + suite, "/Collection/create_index/fail", test_create_index_fail, NULL, NULL, test_framework_skip_if_offline); TestSuite_AddLive (suite, "/Collection/insert_one", test_insert_one); - TestSuite_AddLive ( - suite, "/Collection/update_and_replace", test_update_and_replace); - TestSuite_AddLive ( - suite, "/Collection/array_filters_validate", test_array_filters_validate); - TestSuite_AddLive ( - suite, "/Collection/replace_one_validate", test_replace_one_validate); - TestSuite_AddLive ( - suite, "/Collection/update_one_validate", test_update_one_validate); - TestSuite_AddLive ( - suite, "/Collection/update_many_validate", test_update_many_validate); - TestSuite_AddLive ( - suite, "/Collection/delete_one_or_many", test_delete_one_or_many); - TestSuite_AddMockServerTest ( - suite, "/Collection/delete/collation", test_delete_collation); - TestSuite_AddMockServerTest ( - suite, "/Collection/update/collation", test_update_collation); - TestSuite_AddMockServerTest ( - suite, "/Collection/update/hint", test_update_hint); - TestSuite_AddLive ( - suite, "/Collection/update/hint/validate", test_update_hint_validate); - TestSuite_AddMockServerTest ( - suite, "/Collection/count_documents", test_count_documents); - TestSuite_AddLive ( - suite, "/Collection/count_documents_live", test_count_documents_live); - TestSuite_AddMockServerTest (suite, - "/Collection/estimated_document_count", - test_estimated_document_count); - TestSuite_AddLive (suite, - "/Collection/estimated_document_count_live", - test_estimated_document_count_live); - TestSuite_AddLive ( - suite, "/Collection/insert_bulk_validate", test_insert_bulk_validate); - TestSuite_AddMockServerTest (suite, - "/Collection/aggregate_with_batch_size", - test_aggregate_with_batch_size); + TestSuite_AddLive (suite, "/Collection/update_and_replace", test_update_and_replace); + TestSuite_AddLive (suite, "/Collection/array_filters_validate", test_array_filters_validate); + TestSuite_AddLive (suite, "/Collection/replace_one_validate", test_replace_one_validate); + TestSuite_AddLive (suite, "/Collection/update_one_validate", test_update_one_validate); + TestSuite_AddLive (suite, "/Collection/update_many_validate", test_update_many_validate); + TestSuite_AddLive (suite, "/Collection/delete_one_or_many", test_delete_one_or_many); + TestSuite_AddMockServerTest (suite, "/Collection/delete/collation", test_delete_collation); + TestSuite_AddMockServerTest (suite, "/Collection/update/collation", test_update_collation); + TestSuite_AddMockServerTest (suite, "/Collection/update/hint", test_update_hint); + TestSuite_AddLive (suite, "/Collection/update/hint/validate", test_update_hint_validate); + TestSuite_AddMockServerTest (suite, "/Collection/count_documents", test_count_documents); + TestSuite_AddLive (suite, "/Collection/count_documents_live", test_count_documents_live); + TestSuite_AddMockServerTest (suite, "/Collection/estimated_document_count", test_estimated_document_count); + TestSuite_AddLive (suite, "/Collection/estimated_document_count_live", test_estimated_document_count_live); + TestSuite_AddLive (suite, "/Collection/insert_bulk_validate", test_insert_bulk_validate); + TestSuite_AddMockServerTest (suite, "/Collection/aggregate_with_batch_size", test_aggregate_with_batch_size); TestSuite_AddFull (suite, "/Collection/fam/no_error_on_retry", test_fam_no_error_on_retry, @@ -6648,35 +5762,27 @@ test_collection_install (TestSuite *suite) NULL, test_framework_skip_if_no_failpoint, test_framework_skip_if_max_wire_version_more_than_9); - TestSuite_AddLive (suite, - "/Collection/hint_is_validated/aggregate", - test_hint_is_validated_aggregate); - TestSuite_AddLive (suite, - "/Collection/hint_is_validated/countDocuments", - test_hint_is_validated_countDocuments); - TestSuite_AddLive (suite, - "/Collection/create_indexes_with_opts", - test_create_indexes_with_opts); - TestSuite_AddFull ( - suite, - "/Collection/create_indexes_with_opts/commitQuorum/pre44", - test_create_indexes_with_opts_commitQuorum_pre44, - NULL /* _dtor */, - NULL /* _ctx */, - // commitQuorum option is not available on standalone servers. - test_framework_skip_if_not_replset, - // Server Version 4.4 has Wire Version 9. - test_framework_skip_if_max_wire_version_more_than_8); - TestSuite_AddFull ( - suite, - "/Collection/create_indexes_with_opts/commitQuorum/post44", - test_create_indexes_with_opts_commitQuorum_post44, - NULL /* _dtor */, - NULL /* _ctx */, - // commitQuorum option is not available on standalone servers. - test_framework_skip_if_not_replset, - // Server Version 4.4 has Wire Version 9. - test_framework_skip_if_max_wire_version_less_than_9); + TestSuite_AddLive (suite, "/Collection/hint_is_validated/aggregate", test_hint_is_validated_aggregate); + TestSuite_AddLive (suite, "/Collection/hint_is_validated/countDocuments", test_hint_is_validated_countDocuments); + TestSuite_AddLive (suite, "/Collection/create_indexes_with_opts", test_create_indexes_with_opts); + TestSuite_AddFull (suite, + "/Collection/create_indexes_with_opts/commitQuorum/pre44", + test_create_indexes_with_opts_commitQuorum_pre44, + NULL /* _dtor */, + NULL /* _ctx */, + // commitQuorum option is not available on standalone servers. + test_framework_skip_if_not_replset, + // Server Version 4.4 has Wire Version 9. + test_framework_skip_if_max_wire_version_more_than_8); + TestSuite_AddFull (suite, + "/Collection/create_indexes_with_opts/commitQuorum/post44", + test_create_indexes_with_opts_commitQuorum_post44, + NULL /* _dtor */, + NULL /* _ctx */, + // commitQuorum option is not available on standalone servers. + test_framework_skip_if_not_replset, + // Server Version 4.4 has Wire Version 9. + test_framework_skip_if_max_wire_version_less_than_9); TestSuite_AddFull (suite, "/Collection/create_indexes_with_opts/no_retry", test_create_indexes_with_opts_no_retry, diff --git a/src/libmongoc/tests/test-mongoc-command-monitoring.c b/src/libmongoc/tests/test-mongoc-command-monitoring.c index 4326263d51..5b845270a2 100644 --- a/src/libmongoc/tests/test-mongoc-command-monitoring.c +++ b/src/libmongoc/tests/test-mongoc-command-monitoring.c @@ -38,15 +38,12 @@ check_operation_ids (const bson_t *events) while (bson_iter_next (&iter)) { bson_iter_bson (&iter, &event); if (!strcmp (first_key (&event), "command_started_event")) { - operation_id = - bson_lookup_int64 (&event, "command_started_event.operation_id"); + operation_id = bson_lookup_int64 (&event, "command_started_event.operation_id"); if (first_operation_id == -1) { first_operation_id = operation_id; } else if (operation_id != first_operation_id) { - test_error ( - "%s sent wrong operation_id", - bson_lookup_utf8 (&event, "command_started_event.command_name")); + test_error ("%s sent wrong operation_id", bson_lookup_utf8 (&event, "command_started_event.command_name")); } } } @@ -54,16 +51,13 @@ check_operation_ids (const bson_t *events) static bool -command_monitoring_test_run_operation (json_test_ctx_t *ctx, - const bson_t *test, - const bson_t *operation) +command_monitoring_test_run_operation (json_test_ctx_t *ctx, const bson_t *test, const bson_t *operation) { bson_t reply; bool res; /* Command Monitoring tests don't use explicit session */ - res = - json_test_operation (ctx, test, operation, ctx->collection, NULL, &reply); + res = json_test_operation (ctx, test, operation, ctx->collection, NULL, &reply); bson_destroy (&reply); @@ -104,10 +98,7 @@ static void test_all_spec_tests (TestSuite *suite) { run_unified_tests (suite, JSON_DIR, "command_monitoring/unified"); - install_json_test_suite (suite, - JSON_DIR, - "command_monitoring/legacy", - &test_command_monitoring_cb); + install_json_test_suite (suite, JSON_DIR, "command_monitoring/legacy", &test_command_monitoring_cb); } @@ -134,15 +125,12 @@ test_get_error (void) server = mock_server_with_auto_hello (WIRE_VERSION_MIN); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); callbacks = mongoc_apm_callbacks_new (); mongoc_apm_set_command_failed_cb (callbacks, test_get_error_failed_cb); mongoc_client_set_apm_callbacks (client, callbacks, (void *) &error); - future = future_client_command_simple ( - client, "db", tmp_bson ("{'foo': 1}"), NULL, NULL, NULL); - request = mock_server_receives_msg ( - server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', 'foo': 1}")); + future = future_client_command_simple (client, "db", tmp_bson ("{'foo': 1}"), NULL, NULL, NULL); + request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', 'foo': 1}")); reply_to_request_simple (request, "{'ok': 0, 'errmsg': 'foo', 'code': 42}"); ASSERT (!future_get_bool (future)); ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_QUERY, 42, "foo"); @@ -240,8 +228,7 @@ test_change_callbacks (void) ASSERT_CMPINT (incremented, ==, 200); mongoc_client_set_apm_callbacks (client, dec_callbacks, &decremented); - cursor = mongoc_collection_aggregate ( - collection, MONGOC_QUERY_NONE, tmp_bson (NULL), NULL, NULL); + cursor = mongoc_collection_aggregate (collection, MONGOC_QUERY_NONE, tmp_bson (NULL), NULL, NULL); ASSERT (mongoc_cursor_next (cursor, &b)); ASSERT_CMPINT (decremented, ==, -1); @@ -289,21 +276,13 @@ test_reset_callbacks (void) insert_200_docs (collection); mongoc_client_set_apm_callbacks (client, inc_callbacks, &incremented); - cmd = tmp_bson ("{'aggregate': '%s', 'pipeline': [], 'cursor': {}}", - collection->collection); + cmd = tmp_bson ("{'aggregate': '%s', 'pipeline': [], 'cursor': {}}", collection->collection); - sd = - mongoc_client_select_server (client, true /* for writes */, NULL, &error); + sd = mongoc_client_select_server (client, true /* for writes */, NULL, &error); ASSERT_OR_PRINT (sd, error); r = mongoc_client_read_command_with_opts ( - client, - "test", - cmd, - NULL, - tmp_bson ("{'serverId': %d}", sd->id), - &cmd_reply, - &error); + client, "test", cmd, NULL, tmp_bson ("{'serverId': %d}", sd->id), &cmd_reply, &error); ASSERT_OR_PRINT (r, error); ASSERT_CMPINT (incremented, ==, 1); @@ -355,8 +334,7 @@ _test_set_callbacks (bool pooled, bool try_pop) if (pooled) { pool = test_framework_new_default_client_pool (); - ASSERT (mongoc_client_pool_set_apm_callbacks ( - pool, callbacks, (void *) &n_calls)); + ASSERT (mongoc_client_pool_set_apm_callbacks (pool, callbacks, (void *) &n_calls)); if (try_pop) { client = mongoc_client_pool_try_pop (pool); } else { @@ -364,31 +342,25 @@ _test_set_callbacks (bool pooled, bool try_pop) } } else { client = test_framework_new_default_client (); - ASSERT (mongoc_client_set_apm_callbacks ( - client, callbacks, (void *) &n_calls)); + ASSERT (mongoc_client_set_apm_callbacks (client, callbacks, (void *) &n_calls)); } ASSERT_OR_PRINT ( - mongoc_client_read_command_with_opts ( - client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, NULL, &error), + mongoc_client_read_command_with_opts (client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, NULL, &error), error); ASSERT_CMPINT (1, ==, n_calls); capture_logs (true); if (pooled) { - ASSERT ( - !mongoc_client_pool_set_apm_callbacks (pool, NULL, (void *) &n_calls)); - ASSERT_CAPTURED_LOG ("mongoc_client_pool_set_apm_callbacks", - MONGOC_LOG_LEVEL_ERROR, - "Can only set callbacks once"); + ASSERT (!mongoc_client_pool_set_apm_callbacks (pool, NULL, (void *) &n_calls)); + ASSERT_CAPTURED_LOG ( + "mongoc_client_pool_set_apm_callbacks", MONGOC_LOG_LEVEL_ERROR, "Can only set callbacks once"); clear_captured_logs (); - ASSERT ( - !mongoc_client_set_apm_callbacks (client, NULL, (void *) &n_calls)); - ASSERT_CAPTURED_LOG ("mongoc_client_pool_set_apm_callbacks", - MONGOC_LOG_LEVEL_ERROR, - "Cannot set callbacks on a pooled client"); + ASSERT (!mongoc_client_set_apm_callbacks (client, NULL, (void *) &n_calls)); + ASSERT_CAPTURED_LOG ( + "mongoc_client_pool_set_apm_callbacks", MONGOC_LOG_LEVEL_ERROR, "Cannot set callbacks on a pooled client"); } else { /* repeated calls ok, null is ok */ ASSERT (mongoc_client_set_apm_callbacks (client, NULL, NULL)); @@ -511,11 +483,9 @@ test_op_id_failed_cb (const mongoc_apm_command_failed_t *event) } -#define REQUEST_ID(_event_type, _index) \ - _mongoc_array_index (&test._event_type##_ids, ids_t, _index).request_id +#define REQUEST_ID(_event_type, _index) _mongoc_array_index (&test._event_type##_ids, ids_t, _index).request_id -#define OP_ID(_event_type, _index) \ - _mongoc_array_index (&test._event_type##_ids, ids_t, _index).op_id +#define OP_ID(_event_type, _index) _mongoc_array_index (&test._event_type##_ids, ids_t, _index).op_id static void _test_bulk_operation_id (bool pooled, bool use_bulk_operation_new) @@ -539,13 +509,11 @@ _test_bulk_operation_id (bool pooled, bool use_bulk_operation_new) if (pooled) { pool = test_framework_new_default_client_pool (); - ASSERT (mongoc_client_pool_set_apm_callbacks ( - pool, callbacks, (void *) &test)); + ASSERT (mongoc_client_pool_set_apm_callbacks (pool, callbacks, (void *) &test)); client = mongoc_client_pool_pop (pool); } else { client = test_framework_new_default_client (); - ASSERT ( - mongoc_client_set_apm_callbacks (client, callbacks, (void *) &test)); + ASSERT (mongoc_client_set_apm_callbacks (client, callbacks, (void *) &test)); } collection = get_test_collection (client, "test_bulk_operation_id"); @@ -556,13 +524,11 @@ _test_bulk_operation_id (bool pooled, bool use_bulk_operation_new) mongoc_bulk_operation_set_collection (bulk, collection->collection); } else { bson_append_bool (&opts, "ordered", 7, false); - bulk = - mongoc_collection_create_bulk_operation_with_opts (collection, &opts); + bulk = mongoc_collection_create_bulk_operation_with_opts (collection, &opts); } mongoc_bulk_operation_insert (bulk, tmp_bson ("{'_id': 1}")); - mongoc_bulk_operation_update_one ( - bulk, tmp_bson ("{'_id': 1}"), tmp_bson ("{'$set': {'x': 1}}"), false); + mongoc_bulk_operation_update_one (bulk, tmp_bson ("{'_id': 1}"), tmp_bson ("{'$set': {'x': 1}}"), false); mongoc_bulk_operation_remove (bulk, tmp_bson ("{}")); /* ensure we monitor with bulk->operation_id, not cluster->operation_id */ @@ -665,21 +631,16 @@ _test_query_operation_id (bool pooled) mongoc_apm_set_command_failed_cb (callbacks, test_op_id_failed_cb); if (pooled) { - pool = test_framework_client_pool_new_from_uri ( - mock_server_get_uri (server), NULL); - ASSERT (mongoc_client_pool_set_apm_callbacks ( - pool, callbacks, (void *) &test)); + pool = test_framework_client_pool_new_from_uri (mock_server_get_uri (server), NULL); + ASSERT (mongoc_client_pool_set_apm_callbacks (pool, callbacks, (void *) &test)); client = mongoc_client_pool_pop (pool); } else { - client = test_framework_client_new_from_uri (mock_server_get_uri (server), - NULL); - ASSERT ( - mongoc_client_set_apm_callbacks (client, callbacks, (void *) &test)); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + ASSERT (mongoc_client_set_apm_callbacks (client, callbacks, (void *) &test)); } collection = mongoc_client_get_collection (client, "db", "collection"); - cursor = mongoc_collection_find ( - collection, MONGOC_QUERY_NONE, 0, 0, 1, tmp_bson ("{}"), NULL, NULL); + cursor = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, 1, tmp_bson ("{}"), NULL, NULL); future = future_cursor_next (cursor, &doc); request = mock_server_receives_request (server); @@ -784,8 +745,7 @@ cmd_started_cb (const mongoc_apm_command_started_t *event) { cmd_test_t *test; - if (!strcmp (mongoc_apm_command_started_get_command_name (event), - "endSessions")) { + if (!strcmp (mongoc_apm_command_started_get_command_name (event), "endSessions")) { /* the test is ending */ return; } @@ -793,13 +753,9 @@ cmd_started_cb (const mongoc_apm_command_started_t *event) test = (cmd_test_t *) mongoc_apm_command_started_get_context (event); test->started_calls++; bson_destroy (&test->cmd); - bson_strncpy (test->db, - mongoc_apm_command_started_get_database_name (event), - sizeof (test->db)); + bson_strncpy (test->db, mongoc_apm_command_started_get_database_name (event), sizeof (test->db)); bson_copy_to (mongoc_apm_command_started_get_command (event), &test->cmd); - bson_strncpy (test->cmd_name, - mongoc_apm_command_started_get_command_name (event), - sizeof (test->cmd_name)); + bson_strncpy (test->cmd_name, mongoc_apm_command_started_get_command_name (event), sizeof (test->cmd_name)); } @@ -809,15 +765,13 @@ cmd_succeeded_cb (const mongoc_apm_command_succeeded_t *event) cmd_test_t *test; int64_t duration; - if (!strcmp (mongoc_apm_command_succeeded_get_command_name (event), - "endSessions")) { + if (!strcmp (mongoc_apm_command_succeeded_get_command_name (event), "endSessions")) { return; } test = (cmd_test_t *) mongoc_apm_command_succeeded_get_context (event); test->succeeded_calls++; - ASSERT_CMPSTR (test->cmd_name, - mongoc_apm_command_succeeded_get_command_name (event)); + ASSERT_CMPSTR (test->cmd_name, mongoc_apm_command_succeeded_get_command_name (event)); duration = mongoc_apm_command_succeeded_get_duration (event); ASSERT_CMPINT64 (duration, >=, (int64_t) 0); @@ -833,8 +787,7 @@ cmd_failed_cb (const mongoc_apm_command_failed_t *event) test = (cmd_test_t *) mongoc_apm_command_failed_get_context (event); test->failed_calls++; - ASSERT_CMPSTR (test->cmd_name, - mongoc_apm_command_failed_get_command_name (event)); + ASSERT_CMPSTR (test->cmd_name, mongoc_apm_command_failed_get_command_name (event)); duration = mongoc_apm_command_failed_get_duration (event); ASSERT_CMPINT64 (duration, >=, (int64_t) 0); @@ -869,15 +822,8 @@ test_client_cmd (void) cmd_test_init (&test); client = test_framework_new_default_client (); set_cmd_test_callbacks (client, (void *) &test); - cursor = mongoc_client_command (client, - "admin", - MONGOC_QUERY_SECONDARY_OK, - 0, - 0, - 0, - tmp_bson ("{'ping': 1}"), - NULL, - NULL); + cursor = + mongoc_client_command (client, "admin", MONGOC_QUERY_SECONDARY_OK, 0, 0, 0, tmp_bson ("{'ping': 1}"), NULL, NULL); ASSERT (mongoc_cursor_next (cursor, &reply)); ASSERT_CMPSTR (test.cmd_name, "ping"); @@ -891,15 +837,8 @@ test_client_cmd (void) mongoc_cursor_destroy (cursor); cmd_test_init (&test); - cursor = mongoc_client_command (client, - "admin", - MONGOC_QUERY_SECONDARY_OK, - 0, - 0, - 0, - tmp_bson ("{'foo': 1}"), - NULL, - NULL); + cursor = + mongoc_client_command (client, "admin", MONGOC_QUERY_SECONDARY_OK, 0, 0, 0, tmp_bson ("{'foo': 1}"), NULL, NULL); ASSERT (!mongoc_cursor_next (cursor, &reply)); ASSERT_CMPSTR (test.cmd_name, "foo"); @@ -926,8 +865,7 @@ test_client_cmd_simple (void) cmd_test_init (&test); client = test_framework_new_default_client (); set_cmd_test_callbacks (client, (void *) &test); - r = mongoc_client_command_simple ( - client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); + r = mongoc_client_command_simple (client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); ASSERT_OR_PRINT (r, error); ASSERT_CMPSTR (test.cmd_name, "ping"); @@ -939,8 +877,7 @@ test_client_cmd_simple (void) cmd_test_cleanup (&test); cmd_test_init (&test); - r = mongoc_client_command_simple ( - client, "admin", tmp_bson ("{'foo': 1}"), NULL, NULL, &error); + r = mongoc_client_command_simple (client, "admin", tmp_bson ("{'foo': 1}"), NULL, NULL, &error); ASSERT (!r); ASSERT_CMPSTR (test.cmd_name, "foo"); @@ -975,8 +912,7 @@ test_client_cmd_op_ids (void) client = test_framework_new_default_client (); mongoc_client_set_apm_callbacks (client, callbacks, (void *) &test); - r = mongoc_client_command_simple ( - client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); + r = mongoc_client_command_simple (client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); ASSERT_OR_PRINT (r, error); ASSERT_CMPINT (1, ==, test.started_calls); @@ -991,8 +927,7 @@ test_client_cmd_op_ids (void) op_id_test_init (&test); /* again. test that we use a new op_id. */ - r = mongoc_client_command_simple ( - client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); + r = mongoc_client_command_simple (client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); ASSERT_OR_PRINT (r, error); ASSERT_CMPINT (1, ==, test.started_calls); @@ -1025,8 +960,7 @@ test_killcursors_deprecated (void *unused) client = test_framework_new_default_client (); /* connect */ - r = mongoc_client_command_simple ( - client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); + r = mongoc_client_command_simple (client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); ASSERT_OR_PRINT (r, error); set_cmd_test_callbacks (client, (void *) &test); @@ -1066,13 +1000,11 @@ cmd_failed_reply_test_cleanup (cmd_failed_reply_test_t *test) static void -command_failed_reply_command_failed_cb ( - const mongoc_apm_command_failed_t *event) +command_failed_reply_command_failed_cb (const mongoc_apm_command_failed_t *event) { cmd_failed_reply_test_t *test; - test = - (cmd_failed_reply_test_t *) mongoc_apm_command_failed_get_context (event); + test = (cmd_failed_reply_test_t *) mongoc_apm_command_failed_get_context (event); test->failed_calls++; bson_destroy (&test->reply); @@ -1101,16 +1033,13 @@ test_command_failed_reply_mock (void) mock_server_run (server); callbacks = mongoc_apm_callbacks_new (); - mongoc_apm_set_command_failed_cb (callbacks, - command_failed_reply_command_failed_cb); + mongoc_apm_set_command_failed_cb (callbacks, command_failed_reply_command_failed_cb); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); ASSERT (mongoc_client_set_apm_callbacks (client, callbacks, (void *) &test)); collection = mongoc_client_get_collection (client, "db", "collection"); - cursor = mongoc_collection_find ( - collection, MONGOC_QUERY_NONE, 0, 0, 1, tmp_bson ("{}"), NULL, NULL); + cursor = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, 1, tmp_bson ("{}"), NULL, NULL); future = future_cursor_next (cursor, &doc); request = mock_server_receives_request (server); @@ -1158,16 +1087,13 @@ test_command_failed_reply_hangup (void) mock_server_run (server); callbacks = mongoc_apm_callbacks_new (); - mongoc_apm_set_command_failed_cb (callbacks, - command_failed_reply_command_failed_cb); + mongoc_apm_set_command_failed_cb (callbacks, command_failed_reply_command_failed_cb); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); ASSERT (mongoc_client_set_apm_callbacks (client, callbacks, (void *) &test)); collection = mongoc_client_get_collection (client, "db", "collection"); - cursor = mongoc_collection_find ( - collection, MONGOC_QUERY_NONE, 0, 0, 1, tmp_bson ("{}"), NULL, NULL); + cursor = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, 1, tmp_bson ("{}"), NULL, NULL); future = future_cursor_next (cursor, &doc); request = mock_server_receives_request (server); @@ -1232,8 +1158,7 @@ service_id_cmd_succeeded_cb (const mongoc_apm_command_succeeded_t *event) service_id_test_t *test = mongoc_apm_command_succeeded_get_context (event); test->succeeded_calls++; - assert_service_id (test, - mongoc_apm_command_succeeded_get_service_id (event)); + assert_service_id (test, mongoc_apm_command_succeeded_get_service_id (event)); } @@ -1263,14 +1188,12 @@ _test_service_id (bool is_loadbalanced) mock_server_run (server); mock_server_auto_endsessions (server); uri = mongoc_uri_copy (mock_server_get_uri (server)); - mongoc_uri_set_option_as_bool ( - uri, MONGOC_URI_LOADBALANCED, is_loadbalanced); + mongoc_uri_set_option_as_bool (uri, MONGOC_URI_LOADBALANCED, is_loadbalanced); client = test_framework_client_new_from_uri (uri, NULL); if (is_loadbalanced) { context.has_service_id = true; - bson_oid_init_from_string (&context.expected_service_id, - "AAAAAAAAAAAAAAAAAAAAAAAA"); + bson_oid_init_from_string (&context.expected_service_id, "AAAAAAAAAAAAAAAAAAAAAAAA"); } callbacks = mongoc_apm_callbacks_new (); @@ -1280,30 +1203,22 @@ _test_service_id (bool is_loadbalanced) ASSERT (mongoc_client_set_apm_callbacks (client, callbacks, &context)); mongoc_apm_callbacks_destroy (callbacks); - future = future_client_command_simple (client, - "admin", - tmp_bson ("{'ping': 1}"), - NULL /* read prefs */, - NULL /* reply */, - &error); + future = future_client_command_simple ( + client, "admin", tmp_bson ("{'ping': 1}"), NULL /* read prefs */, NULL /* reply */, &error); if (is_loadbalanced) { - request = mock_server_receives_any_hello_with_match ( - server, "{'loadBalanced': true}", "{'loadBalanced': true}"); - reply_to_request_simple ( - request, - tmp_str ("{'ismaster': true," - " 'minWireVersion': %d," - " 'maxWireVersion': %d," - " 'msg': 'isdbgrid'," - " 'serviceId': {'$oid': 'AAAAAAAAAAAAAAAAAAAAAAAA'}}", - WIRE_VERSION_MIN, - WIRE_VERSION_5_0)); + request = mock_server_receives_any_hello_with_match (server, "{'loadBalanced': true}", "{'loadBalanced': true}"); + reply_to_request_simple (request, + tmp_str ("{'ismaster': true," + " 'minWireVersion': %d," + " 'maxWireVersion': %d," + " 'msg': 'isdbgrid'," + " 'serviceId': {'$oid': 'AAAAAAAAAAAAAAAAAAAAAAAA'}}", + WIRE_VERSION_MIN, + WIRE_VERSION_5_0)); } else { request = mock_server_receives_any_hello_with_match ( - server, - "{'loadBalanced': { '$exists': false }}", - "{'loadBalanced': { '$exists': false }}"); + server, "{'loadBalanced': { '$exists': false }}", "{'loadBalanced': { '$exists': false }}"); reply_to_request_simple (request, tmp_str ("{'ismaster': true," " 'minWireVersion': %d," @@ -1320,16 +1235,11 @@ _test_service_id (bool is_loadbalanced) ASSERT_OR_PRINT (future_get_bool (future), error); future_destroy (future); - future = future_client_command_simple (client, - "admin", - tmp_bson ("{'ping': 1}"), - NULL /* read prefs */, - NULL /* reply */, - &error); + future = future_client_command_simple ( + client, "admin", tmp_bson ("{'ping': 1}"), NULL /* read prefs */, NULL /* reply */, &error); request = mock_server_receives_msg (server, 0, tmp_bson ("{'ping': 1}")); - reply_to_request_simple (request, - "{'ok': 0, 'code': 8, 'errmsg': 'UnknownError'}"); + reply_to_request_simple (request, "{'ok': 0, 'code': 8, 'errmsg': 'UnknownError'}"); request_destroy (request); ASSERT (!future_get_bool (future)); @@ -1363,64 +1273,33 @@ void test_command_monitoring_install (TestSuite *suite) { test_all_spec_tests (suite); - TestSuite_AddMockServerTest ( - suite, "/command_monitoring/get_error", test_get_error); - TestSuite_AddLive (suite, - "/command_monitoring/set_callbacks/single", - test_set_callbacks_single); - TestSuite_AddLive (suite, - "/command_monitoring/set_callbacks/pooled", - test_set_callbacks_pooled); - TestSuite_AddLive (suite, - "/command_monitoring/set_callbacks/pooled_try_pop", - test_set_callbacks_pooled_try_pop); + TestSuite_AddMockServerTest (suite, "/command_monitoring/get_error", test_get_error); + TestSuite_AddLive (suite, "/command_monitoring/set_callbacks/single", test_set_callbacks_single); + TestSuite_AddLive (suite, "/command_monitoring/set_callbacks/pooled", test_set_callbacks_pooled); + TestSuite_AddLive (suite, "/command_monitoring/set_callbacks/pooled_try_pop", test_set_callbacks_pooled_try_pop); /* require aggregation cursor */ - TestSuite_AddLive ( - suite, "/command_monitoring/set_callbacks/change", test_change_callbacks); - TestSuite_AddLive ( - suite, "/command_monitoring/set_callbacks/reset", test_reset_callbacks); - TestSuite_AddLive (suite, - "/command_monitoring/operation_id/bulk/collection/single", - test_collection_bulk_op_single); - TestSuite_AddLive (suite, - "/command_monitoring/operation_id/bulk/collection/pooled", - test_collection_bulk_op_pooled); - TestSuite_AddLive (suite, - "/command_monitoring/operation_id/bulk/new/single", - test_bulk_op_single); - TestSuite_AddLive (suite, - "/command_monitoring/operation_id/bulk/new/pooled", - test_bulk_op_pooled); + TestSuite_AddLive (suite, "/command_monitoring/set_callbacks/change", test_change_callbacks); + TestSuite_AddLive (suite, "/command_monitoring/set_callbacks/reset", test_reset_callbacks); + TestSuite_AddLive (suite, "/command_monitoring/operation_id/bulk/collection/single", test_collection_bulk_op_single); + TestSuite_AddLive (suite, "/command_monitoring/operation_id/bulk/collection/pooled", test_collection_bulk_op_pooled); + TestSuite_AddLive (suite, "/command_monitoring/operation_id/bulk/new/single", test_bulk_op_single); + TestSuite_AddLive (suite, "/command_monitoring/operation_id/bulk/new/pooled", test_bulk_op_pooled); TestSuite_AddMockServerTest ( - suite, - "/command_monitoring/operation_id/query/single/cmd", - test_query_operation_id_single_cmd); + suite, "/command_monitoring/operation_id/query/single/cmd", test_query_operation_id_single_cmd); TestSuite_AddMockServerTest ( - suite, - "/command_monitoring/operation_id/query/pooled/cmd", - test_query_operation_id_pooled_cmd); + suite, "/command_monitoring/operation_id/query/pooled/cmd", test_query_operation_id_pooled_cmd); TestSuite_AddLive (suite, "/command_monitoring/client_cmd", test_client_cmd); - TestSuite_AddLive ( - suite, "/command_monitoring/client_cmd_simple", test_client_cmd_simple); - TestSuite_AddLive ( - suite, "/command_monitoring/client_cmd/op_ids", test_client_cmd_op_ids); + TestSuite_AddLive (suite, "/command_monitoring/client_cmd_simple", test_client_cmd_simple); + TestSuite_AddLive (suite, "/command_monitoring/client_cmd/op_ids", test_client_cmd_op_ids); TestSuite_AddFull (suite, "/command_monitoring/killcursors_deprecated", test_killcursors_deprecated, NULL /* dtor */, NULL /* ctx */, test_framework_skip_if_no_legacy_opcodes); - TestSuite_AddMockServerTest (suite, - "/command_monitoring/failed_reply_mock", - test_command_failed_reply_mock); - TestSuite_AddMockServerTest (suite, - "/command_monitoring/failed_reply_hangup", - test_command_failed_reply_hangup); - TestSuite_AddMockServerTest (suite, - "/command_monitoring/service_id/loadbalanced", - test_service_id_loadbalanced); + TestSuite_AddMockServerTest (suite, "/command_monitoring/failed_reply_mock", test_command_failed_reply_mock); + TestSuite_AddMockServerTest (suite, "/command_monitoring/failed_reply_hangup", test_command_failed_reply_hangup); + TestSuite_AddMockServerTest (suite, "/command_monitoring/service_id/loadbalanced", test_service_id_loadbalanced); TestSuite_AddMockServerTest ( - suite, - "/command_monitoring/service_id/not_loadbalanced", - test_service_id_not_loadbalanced); + suite, "/command_monitoring/service_id/not_loadbalanced", test_service_id_not_loadbalanced); } diff --git a/src/libmongoc/tests/test-mongoc-connection-uri.c b/src/libmongoc/tests/test-mongoc-connection-uri.c index b8ce775ca1..0d3fc1b247 100644 --- a/src/libmongoc/tests/test-mongoc-connection-uri.c +++ b/src/libmongoc/tests/test-mongoc-connection-uri.c @@ -43,8 +43,7 @@ bson_contains_iter (const bson_t *haystack, bson_iter_t *needle) bson_contains_iter (haystack, needle); return; case BSON_TYPE_UTF8: - ASSERT (0 == - strcmp (bson_iter_utf8 (needle, 0), bson_iter_utf8 (&iter, 0))); + ASSERT (0 == strcmp (bson_iter_utf8 (needle, 0), bson_iter_utf8 (&iter, 0))); bson_contains_iter (haystack, needle); return; case BSON_TYPE_DOUBLE: @@ -63,11 +62,7 @@ bson_contains_iter (const bson_t *haystack, bson_iter_t *needle) } static void -run_uri_test (const char *uri_string, - bool valid, - const bson_t *hosts, - const bson_t *auth, - const bson_t *options) +run_uri_test (const char *uri_string, bool valid, const bson_t *hosts, const bson_t *auth, const bson_t *options) { mongoc_uri_t *uri; bson_iter_t auth_iter; @@ -79,16 +74,13 @@ run_uri_test (const char *uri_string, /* BEGIN Exceptions to test suite */ /* some spec tests assume we allow DB names like "auth.foo" */ - if ((bson_iter_init_find (&auth_iter, auth, "db") || - bson_iter_init_find (&auth_iter, auth, "source")) && + if ((bson_iter_init_find (&auth_iter, auth, "db") || bson_iter_init_find (&auth_iter, auth, "source")) && BSON_ITER_HOLDS_UTF8 (&auth_iter)) { db = bson_iter_utf8 (&auth_iter, NULL); if (strchr (db, '.')) { BSON_ASSERT (!uri); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Invalid database name in URI"); + ASSERT_ERROR_CONTAINS ( + error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid database name in URI"); clear_captured_logs (); return; } @@ -97,15 +89,11 @@ run_uri_test (const char *uri_string, if (valid && !uri && error.domain) { /* Eager failures which the spec expects to be warnings. */ /* CDRIVER-3167 */ - if (strstr (uri_string, "=invalid") || - strstr (uri_string, "heartbeatFrequencyMS=-2") || + if (strstr (uri_string, "=invalid") || strstr (uri_string, "heartbeatFrequencyMS=-2") || strstr (uri_string, "w=-2") || strstr (uri_string, "wTimeoutMS=-2") || - strstr (uri_string, "zlibCompressionLevel=-2") || - strstr (uri_string, "zlibCompressionLevel=10") || - (!strstr (uri_string, "mongodb+srv") && - strstr (uri_string, "srvServiceName=customname")) || - strstr (uri_string, "srvMaxHosts=-1") || - strstr (uri_string, "srvMaxHosts=foo")) { + strstr (uri_string, "zlibCompressionLevel=-2") || strstr (uri_string, "zlibCompressionLevel=10") || + (!strstr (uri_string, "mongodb+srv") && strstr (uri_string, "srvServiceName=customname")) || + strstr (uri_string, "srvMaxHosts=-1") || strstr (uri_string, "srvMaxHosts=foo")) { MONGOC_WARNING ("Error parsing URI: '%s'", error.message); return; } @@ -114,22 +102,16 @@ run_uri_test (const char *uri_string, if (uri) { /* mongoc does not warn on negative timeouts when it should. */ /* CDRIVER-3167 */ - if ((mongoc_uri_get_option_as_int32 ( - uri, MONGOC_URI_CONNECTTIMEOUTMS, 0) < 0) || - (mongoc_uri_get_option_as_int32 ( - uri, MONGOC_URI_LOCALTHRESHOLDMS, 0) < 0) || - (mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_MAXIDLETIMEMS, 0) < - 0) || - (mongoc_uri_get_option_as_int32 ( - uri, MONGOC_URI_SERVERSELECTIONTIMEOUTMS, 0) < 0) || - (mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_SOCKETTIMEOUTMS, 0) < - 0)) { + if ((mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_CONNECTTIMEOUTMS, 0) < 0) || + (mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_LOCALTHRESHOLDMS, 0) < 0) || + (mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_MAXIDLETIMEMS, 0) < 0) || + (mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_SERVERSELECTIONTIMEOUTMS, 0) < 0) || + (mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_SOCKETTIMEOUTMS, 0) < 0)) { MONGOC_WARNING ("Invalid negative timeout"); } /* mongoc does not store lists the way the spec test expects. */ - if (strstr (uri_string, "compressors=") || - strstr (uri_string, "readPreferenceTags=")) { + if (strstr (uri_string, "compressors=") || strstr (uri_string, "readPreferenceTags=")) { options = NULL; } @@ -141,8 +123,7 @@ run_uri_test (const char *uri_string, #endif #ifndef MONGOC_ENABLE_COMPRESSION_ZLIB - if (strstr (uri_string, "compressors=zlib") || - strstr (uri_string, "compressors=snappy,zlib")) { + if (strstr (uri_string, "compressors=zlib") || strstr (uri_string, "compressors=snappy,zlib")) { clear_captured_logs (); } #endif @@ -162,18 +143,15 @@ run_uri_test (const char *uri_string, bson_iter_t iter; bson_iter_t host_iter; - for (bson_iter_init (&iter, hosts); - bson_iter_next (&iter) && bson_iter_recurse (&iter, &host_iter);) { + for (bson_iter_init (&iter, hosts); bson_iter_next (&iter) && bson_iter_recurse (&iter, &host_iter);) { const char *host = "localhost"; int64_t port = 27017; bool ok = false; - if (bson_iter_find (&host_iter, "host") && - BSON_ITER_HOLDS_UTF8 (&host_iter)) { + if (bson_iter_find (&host_iter, "host") && BSON_ITER_HOLDS_UTF8 (&host_iter)) { host = bson_iter_utf8 (&host_iter, NULL); } - if (bson_iter_find (&host_iter, "port") && - BSON_ITER_HOLDS_INT (&host_iter)) { + if (bson_iter_find (&host_iter, "port") && BSON_ITER_HOLDS_INT (&host_iter)) { port = bson_iter_as_int64 (&host_iter); } @@ -185,11 +163,7 @@ run_uri_test (const char *uri_string, } if (!ok) { - fprintf (stderr, - "Could not find '%s':%" PRId64 " in uri '%s'\n", - host, - port, - mongoc_uri_get_string (uri)); + fprintf (stderr, "Could not find '%s':%" PRId64 " in uri '%s'\n", host, port, mongoc_uri_get_string (uri)); BSON_ASSERT (0); } } @@ -201,18 +175,15 @@ run_uri_test (const char *uri_string, const char *password = mongoc_uri_get_password (uri); bson_iter_t iter; - if (bson_iter_init_find (&iter, auth, "username") && - BSON_ITER_HOLDS_UTF8 (&iter)) { + if (bson_iter_init_find (&iter, auth, "username") && BSON_ITER_HOLDS_UTF8 (&iter)) { ASSERT_CMPSTR (username, bson_iter_utf8 (&iter, NULL)); } - if (bson_iter_init_find (&iter, auth, "password") && - BSON_ITER_HOLDS_UTF8 (&iter)) { + if (bson_iter_init_find (&iter, auth, "password") && BSON_ITER_HOLDS_UTF8 (&iter)) { ASSERT_CMPSTR (password, bson_iter_utf8 (&iter, NULL)); } - if ((bson_iter_init_find (&iter, auth, "db") || - bson_iter_init_find (&iter, auth, "source")) && + if ((bson_iter_init_find (&iter, auth, "db") || bson_iter_init_find (&iter, auth, "source")) && BSON_ITER_HOLDS_UTF8 (&iter)) { ASSERT_CMPSTR (auth_source, bson_iter_utf8 (&iter, NULL)); } @@ -229,34 +200,29 @@ run_uri_test (const char *uri_string, rc = mongoc_uri_get_read_concern (uri); if (!mongoc_read_concern_is_default (rc)) { - BSON_APPEND_UTF8 (&uri_options, - "readconcernlevel", - mongoc_read_concern_get_level (rc)); + BSON_APPEND_UTF8 (&uri_options, "readconcernlevel", mongoc_read_concern_get_level (rc)); } - bson_copy_to_excluding_noinit ( - options, - &test_options, - "username", /* these 'auth' params may be included in 'options' */ - "password", - "source", - "mechanism", /* renamed to 'authmechanism' for consistency */ - "mechanism_properties", /* renamed to 'authmechanismproperties' for - * consistency */ - NULL); + bson_copy_to_excluding_noinit (options, + &test_options, + "username", /* these 'auth' params may be included in 'options' */ + "password", + "source", + "mechanism", /* renamed to 'authmechanism' for consistency */ + "mechanism_properties", /* renamed to 'authmechanismproperties' for + * consistency */ + NULL); if ((bson_iter_init_find (&iter, options, "mechanism") || bson_iter_init_find (&iter, options, "authmechanism")) && BSON_ITER_HOLDS_UTF8 (&iter)) { - BSON_APPEND_UTF8 ( - &test_options, "authmechanism", bson_iter_utf8 (&iter, NULL)); + BSON_APPEND_UTF8 (&test_options, "authmechanism", bson_iter_utf8 (&iter, NULL)); } if ((bson_iter_init_find (&iter, options, "mechanism_properties") || bson_iter_init_find (&iter, options, "authmechanismproperties")) && BSON_ITER_HOLDS_DOCUMENT (&iter)) { - ASSERT (bson_append_iter ( - &test_options, "authmechanismproperties", -1, &iter)); + ASSERT (bson_append_iter (&test_options, "authmechanismproperties", -1, &iter)); } bson_iter_init (&iter, &test_options); @@ -304,9 +270,7 @@ test_connection_uri_cb (bson_t *scenario) const char *description = bson_iter_utf8 (&test_case_iter, NULL); ASSERT (bson_iter_find_case (&test_case_iter, "uri")); - printf (" - %s: '%s'\n", - description, - bson_iter_utf8 (&test_case_iter, 0)); + printf (" - %s: '%s'\n", description, bson_iter_utf8 (&test_case_iter, 0)); fflush (stdout); } else { fprintf (stderr, "Couldn't find `description` field in testcase\n"); @@ -338,8 +302,7 @@ test_connection_uri_cb (bson_t *scenario) bson_iter_init (&warning_iter, &test_case); - if (bson_iter_find_descendant (&warning_iter, "warning", &descendent) && - BSON_ITER_HOLDS_BOOL (&descendent)) { + if (bson_iter_find_descendant (&warning_iter, "warning", &descendent) && BSON_ITER_HOLDS_BOOL (&descendent)) { if (bson_iter_as_bool (&descendent)) { ASSERT_CAPTURED_LOG ("mongoc_uri", MONGOC_LOG_LEVEL_WARNING, ""); } else { @@ -357,10 +320,8 @@ test_connection_uri_cb (bson_t *scenario) static void test_all_spec_tests (TestSuite *suite) { - install_json_test_suite ( - suite, JSON_DIR, "uri-options", &test_connection_uri_cb); - install_json_test_suite ( - suite, JSON_DIR, "connection_uri", &test_connection_uri_cb); + install_json_test_suite (suite, JSON_DIR, "uri-options", &test_connection_uri_cb); + install_json_test_suite (suite, JSON_DIR, "connection_uri", &test_connection_uri_cb); install_json_test_suite (suite, JSON_DIR, "auth", &test_connection_uri_cb); } diff --git a/src/libmongoc/tests/test-mongoc-counters.c b/src/libmongoc/tests/test-mongoc-counters.c index fd13cf8c82..fe535f5998 100644 --- a/src/libmongoc/tests/test-mongoc-counters.c +++ b/src/libmongoc/tests/test-mongoc-counters.c @@ -32,10 +32,8 @@ #undef COUNTER /* helper to reset a prev_* counter */ -#define RESET(ident) \ - bson_atomic_int32_exchange (&prev_##ident, \ - mongoc_counter_##ident##_count (), \ - bson_memory_order_seq_cst) +#define RESET(ident) \ + bson_atomic_int32_exchange (&prev_##ident, mongoc_counter_##ident##_count (), bson_memory_order_seq_cst) /* helper to compare and reset a prev_* counter. */ #define DIFF_AND_RESET(ident, cmp, expected) \ @@ -66,8 +64,7 @@ _client_new_disable_ss (bool use_compression) uri = test_framework_get_uri (); mongoc_uri_set_option_as_int32 (uri, MONGOC_URI_HEARTBEATFREQUENCYMS, 99999); - mongoc_uri_set_option_as_int32 ( - uri, MONGOC_URI_SOCKETCHECKINTERVALMS, 99999); + mongoc_uri_set_option_as_int32 (uri, MONGOC_URI_SOCKETCHECKINTERVALMS, 99999); if (use_compression) { char *compressors = test_framework_get_compressors (); mongoc_uri_set_option_as_utf8 (uri, MONGOC_URI_COMPRESSORS, compressors); @@ -79,10 +76,7 @@ _client_new_disable_ss (bool use_compression) ASSERT_OR_PRINT (sd, err); mongoc_server_description_destroy (sd); // Trigger authentication handshake now to avoid interfering with ping test. - ASSERT_OR_PRINT ( - mongoc_client_command_simple ( - client, "test", tmp_bson ("{'ping': 1}"), NULL, NULL, &err), - err); + ASSERT_OR_PRINT (mongoc_client_command_simple (client, "test", tmp_bson ("{'ping': 1}"), NULL, NULL, &err), err); mongoc_uri_destroy (uri); /* reset counters to exclude anything done in server selection. */ reset_all_counters (); @@ -104,8 +98,7 @@ _drop_and_populate_coll (mongoc_client_t *client) coll = mongoc_client_get_collection (client, "test", "test"); mongoc_collection_drop (coll, NULL); /* don't care if ns not found. */ for (i = 0; i < 3; i++) { - ret = - mongoc_collection_insert_one (coll, tmp_bson ("{}"), NULL, NULL, &err); + ret = mongoc_collection_insert_one (coll, tmp_bson ("{}"), NULL, NULL, &err); ASSERT_OR_PRINT (ret, err); } return coll; @@ -120,8 +113,7 @@ _ping (mongoc_client_t *client) ASSERT (client); - ret = mongoc_client_command_simple ( - client, "test", tmp_bson ("{'ping': 1}"), NULL, NULL, &err); + ret = mongoc_client_command_simple (client, "test", tmp_bson ("{'ping': 1}"), NULL, NULL, &err); ASSERT_OR_PRINT (ret, err); } @@ -147,8 +139,7 @@ test_counters_op_msg (void *ctx) DIFF_AND_RESET (op_egress_total, ==, 4); DIFF_AND_RESET (op_ingress_msg, ==, 4); DIFF_AND_RESET (op_ingress_total, ==, 4); - cursor = - mongoc_collection_find_with_opts (coll, tmp_bson ("{}"), NULL, NULL); + cursor = mongoc_collection_find_with_opts (coll, tmp_bson ("{}"), NULL, NULL); while (mongoc_cursor_next (cursor, &bson)) ; mongoc_cursor_destroy (cursor); @@ -202,8 +193,7 @@ test_counters_cursors (void) client = _client_new_disable_ss (false); coll = _drop_and_populate_coll (client); - cursor = mongoc_collection_find_with_opts ( - coll, tmp_bson ("{}"), tmp_bson ("{'batchSize': 1}"), NULL); + cursor = mongoc_collection_find_with_opts (coll, tmp_bson ("{}"), tmp_bson ("{'batchSize': 1}"), NULL); DIFF_AND_RESET (cursors_active, ==, 1); while (mongoc_cursor_next (cursor, &bson)) ; @@ -224,8 +214,7 @@ test_counters_clients (void) uri = test_framework_get_uri (); mongoc_uri_set_option_as_int32 (uri, MONGOC_URI_HEARTBEATFREQUENCYMS, 99999); - mongoc_uri_set_option_as_int32 ( - uri, MONGOC_URI_SOCKETCHECKINTERVALMS, 99999); + mongoc_uri_set_option_as_int32 (uri, MONGOC_URI_SOCKETCHECKINTERVALMS, 99999); reset_all_counters (); client = test_framework_client_new_from_uri (uri, NULL); BSON_ASSERT (client); @@ -305,8 +294,7 @@ test_counters_streams (void *ctx) mongoc_ssl_opt_t opts = *default_opts; mongoc_stream_t *ssl_buffered_stream_socket; - ssl_buffered_stream_socket = mongoc_stream_tls_new_with_hostname ( - buffered_stream_sock, NULL, &opts, 0); + ssl_buffered_stream_socket = mongoc_stream_tls_new_with_hostname (buffered_stream_sock, NULL, &opts, 0); DIFF_AND_RESET (streams_active, ==, 1); DIFF_AND_RESET (streams_disposed, ==, 0); mongoc_stream_destroy (ssl_buffered_stream_socket); @@ -322,11 +310,9 @@ test_counters_streams (void *ctx) } /* check a file stream. */ #ifdef WIN32 - file_stream = mongoc_stream_file_new_for_path ( - BINARY_DIR "/temp.dat", O_CREAT | O_WRONLY | O_TRUNC, _S_IWRITE); + file_stream = mongoc_stream_file_new_for_path (BINARY_DIR "/temp.dat", O_CREAT | O_WRONLY | O_TRUNC, _S_IWRITE); #else - file_stream = mongoc_stream_file_new_for_path ( - BINARY_DIR "/temp.dat", O_CREAT | O_WRONLY | O_TRUNC, S_IRWXU); + file_stream = mongoc_stream_file_new_for_path (BINARY_DIR "/temp.dat", O_CREAT | O_WRONLY | O_TRUNC, S_IRWXU); #endif BSON_ASSERT (file_stream); DIFF_AND_RESET (streams_active, ==, 1); @@ -337,8 +323,7 @@ test_counters_streams (void *ctx) mongoc_stream_destroy (file_stream); DIFF_AND_RESET (streams_active, ==, -1); DIFF_AND_RESET (streams_disposed, ==, 1); - file_stream = - mongoc_stream_file_new_for_path (BINARY_DIR "/temp.dat", O_RDONLY, 0); + file_stream = mongoc_stream_file_new_for_path (BINARY_DIR "/temp.dat", O_RDONLY, 0); BSON_ASSERT (file_stream); DIFF_AND_RESET (streams_active, ==, 1); DIFF_AND_RESET (streams_disposed, ==, 0); @@ -393,8 +378,7 @@ test_counters_auth (void *ctx) { char *host_and_port = test_framework_get_host_and_port (); char *uri_str = test_framework_get_uri_str (); - char *uri_str_bad = bson_strdup_printf ( - "mongodb://%s:%s@%s/", "bad_user", "bad_pass", host_and_port); + char *uri_str_bad = bson_strdup_printf ("mongodb://%s:%s@%s/", "bad_user", "bad_pass", host_and_port); mongoc_client_t *client; mongoc_uri_t *uri; bool ret; @@ -404,14 +388,12 @@ test_counters_auth (void *ctx) uri = mongoc_uri_new (uri_str); mongoc_uri_set_option_as_int32 (uri, MONGOC_URI_HEARTBEATFREQUENCYMS, 99999); - mongoc_uri_set_option_as_int32 ( - uri, MONGOC_URI_SOCKETCHECKINTERVALMS, 99999); + mongoc_uri_set_option_as_int32 (uri, MONGOC_URI_SOCKETCHECKINTERVALMS, 99999); reset_all_counters (); client = test_framework_client_new_from_uri (uri, NULL); test_framework_set_ssl_opts (client); BSON_ASSERT (client); - ret = mongoc_client_command_simple ( - client, "test", tmp_bson ("{'ping': 1}"), NULL, NULL, &err); + ret = mongoc_client_command_simple (client, "test", tmp_bson ("{'ping': 1}"), NULL, NULL, &err); ASSERT_OR_PRINT (ret, err); DIFF_AND_RESET (auth_success, ==, 1); DIFF_AND_RESET (auth_failure, ==, 0); @@ -468,10 +450,8 @@ test_counters_streams_timeout (void) sd = mongoc_client_select_server (client, true, NULL, &err); mongoc_server_description_destroy (sd); reset_all_counters (); - future = future_client_command_simple ( - client, "test", tmp_bson ("{'ping': 1}"), NULL, NULL, &err); - request = mock_server_receives_msg ( - server, MONGOC_QUERY_NONE, tmp_bson ("{'ping': 1}")); + future = future_client_command_simple (client, "test", tmp_bson ("{'ping': 1}"), NULL, NULL, &err); + request = mock_server_receives_msg (server, MONGOC_QUERY_NONE, tmp_bson ("{'ping': 1}")); _mongoc_usleep (350); request_destroy (request); ret = future_get_bool (future); @@ -525,50 +505,47 @@ rpc_op_egress_counters_reset (void) mongoc_counter_op_egress_update_reset (); } -#define ASSERT_RPC_OP_EGRESS_COUNTERS(expected, actual) \ - if (1) { \ - const rpc_op_egress_counters e = (expected); \ - const rpc_op_egress_counters a = (actual); \ - ASSERT_WITH_MSG (e.op_egress_compressed == a.op_egress_compressed, \ - "op_egress_compressed: expected %" PRId32 \ - ", got %" PRId32, \ - e.op_egress_compressed, \ - a.op_egress_compressed); \ - ASSERT_WITH_MSG (e.op_egress_delete == a.op_egress_delete, \ - "op_egress_delete: expected %" PRId32 ", got %" PRId32, \ - e.op_egress_delete, \ - a.op_egress_delete); \ - ASSERT_WITH_MSG (e.op_egress_getmore == a.op_egress_getmore, \ - "op_egress_getmore: expected %" PRId32 \ - ", got %" PRId32, \ - e.op_egress_getmore, \ - a.op_egress_getmore); \ - ASSERT_WITH_MSG (e.op_egress_insert == a.op_egress_insert, \ - "op_egress_insert: expected %" PRId32 ", got %" PRId32, \ - e.op_egress_insert, \ - a.op_egress_insert); \ - ASSERT_WITH_MSG (e.op_egress_killcursors == a.op_egress_killcursors, \ - "op_egress_killcursors: expected %" PRId32 \ - ", got %" PRId32, \ - e.op_egress_killcursors, \ - a.op_egress_killcursors); \ - ASSERT_WITH_MSG (e.op_egress_msg == a.op_egress_msg, \ - "op_egress_msg: expected %" PRId32 ", got %" PRId32, \ - e.op_egress_msg, \ - a.op_egress_msg); \ - ASSERT_WITH_MSG (e.op_egress_query == a.op_egress_query, \ - "op_egress_query: expected %" PRId32 ", got %" PRId32, \ - e.op_egress_query, \ - a.op_egress_query); \ - ASSERT_WITH_MSG (e.op_egress_total == a.op_egress_total, \ - "op_egress_total: expected %" PRId32 ", got %" PRId32, \ - e.op_egress_total, \ - a.op_egress_total); \ - ASSERT_WITH_MSG (e.op_egress_update == a.op_egress_update, \ - "op_egress_update: expected %" PRId32 ", got %" PRId32, \ - e.op_egress_update, \ - a.op_egress_update); \ - } else \ +#define ASSERT_RPC_OP_EGRESS_COUNTERS(expected, actual) \ + if (1) { \ + const rpc_op_egress_counters e = (expected); \ + const rpc_op_egress_counters a = (actual); \ + ASSERT_WITH_MSG (e.op_egress_compressed == a.op_egress_compressed, \ + "op_egress_compressed: expected %" PRId32 ", got %" PRId32, \ + e.op_egress_compressed, \ + a.op_egress_compressed); \ + ASSERT_WITH_MSG (e.op_egress_delete == a.op_egress_delete, \ + "op_egress_delete: expected %" PRId32 ", got %" PRId32, \ + e.op_egress_delete, \ + a.op_egress_delete); \ + ASSERT_WITH_MSG (e.op_egress_getmore == a.op_egress_getmore, \ + "op_egress_getmore: expected %" PRId32 ", got %" PRId32, \ + e.op_egress_getmore, \ + a.op_egress_getmore); \ + ASSERT_WITH_MSG (e.op_egress_insert == a.op_egress_insert, \ + "op_egress_insert: expected %" PRId32 ", got %" PRId32, \ + e.op_egress_insert, \ + a.op_egress_insert); \ + ASSERT_WITH_MSG (e.op_egress_killcursors == a.op_egress_killcursors, \ + "op_egress_killcursors: expected %" PRId32 ", got %" PRId32, \ + e.op_egress_killcursors, \ + a.op_egress_killcursors); \ + ASSERT_WITH_MSG (e.op_egress_msg == a.op_egress_msg, \ + "op_egress_msg: expected %" PRId32 ", got %" PRId32, \ + e.op_egress_msg, \ + a.op_egress_msg); \ + ASSERT_WITH_MSG (e.op_egress_query == a.op_egress_query, \ + "op_egress_query: expected %" PRId32 ", got %" PRId32, \ + e.op_egress_query, \ + a.op_egress_query); \ + ASSERT_WITH_MSG (e.op_egress_total == a.op_egress_total, \ + "op_egress_total: expected %" PRId32 ", got %" PRId32, \ + e.op_egress_total, \ + a.op_egress_total); \ + ASSERT_WITH_MSG (e.op_egress_update == a.op_egress_update, \ + "op_egress_update: expected %" PRId32 ", got %" PRId32, \ + e.op_egress_update, \ + a.op_egress_update); \ + } else \ (void) 0 #define ASSERT_RPC_OP_EGRESS_COUNTERS_CURRENT(expected) \ @@ -597,9 +574,7 @@ test_counters_rpc_op_egress_autoresponder (request_t *request, void *data) reply_to_request_simple (request, ar_data->hello); request_destroy (request); } else { - ASSERT_WITH_MSG (request->is_command, - "expected only handshakes and commands, but got: %s", - request->as_str); + ASSERT_WITH_MSG (request->is_command, "expected only handshakes and commands, but got: %s", request->as_str); reply_to_request_with_ok_and_destroy (request); } @@ -626,8 +601,7 @@ _test_counters_rpc_op_egress_cluster_single (bool with_op_msg) mock_server_run (server); bson_error_t error = {0}; - mongoc_client_t *const client = mongoc_client_new_from_uri_with_error ( - mock_server_get_uri (server), &error); + mongoc_client_t *const client = mongoc_client_new_from_uri_with_error (mock_server_get_uri (server), &error); ASSERT_OR_PRINT (client, error); // Stable API for Drivers spec: If an API version was declared, drivers MUST @@ -635,18 +609,15 @@ _test_counters_rpc_op_egress_cluster_single (bool with_op_msg) // afterwards. Instead, drivers MUST use the `hello` command exclusively and // use the `OP_MSG` protocol. if (with_op_msg) { - mongoc_server_api_t *const api = - mongoc_server_api_new (MONGOC_SERVER_API_V1); - ASSERT_OR_PRINT (mongoc_client_set_server_api (client, api, &error), - error); + mongoc_server_api_t *const api = mongoc_server_api_new (MONGOC_SERVER_API_V1); + ASSERT_OR_PRINT (mongoc_client_set_server_api (client, api, &error), error); mongoc_server_api_destroy (api); } ASSERT_RPC_OP_EGRESS_COUNTERS_CURRENT (zero); rpc_op_egress_counters expected = {0}; - int32_t *const handshake_counter = - with_op_msg ? &expected.op_egress_msg : &expected.op_egress_query; + int32_t *const handshake_counter = with_op_msg ? &expected.op_egress_msg : &expected.op_egress_query; { const bson_t *const command = tmp_bson ("{'ping': 1}"); @@ -654,13 +625,11 @@ _test_counters_rpc_op_egress_cluster_single (bool with_op_msg) // Trigger: // - mongoc_topology_scanner_node_setup // - mongoc_cluster_run_command_monitored - future_t *const ping = future_client_command_simple ( - client, "db", command, NULL, NULL, &error); + future_t *const ping = future_client_command_simple (client, "db", command, NULL, NULL, &error); { request_t *const request = - with_op_msg ? mock_server_receives_hello_op_msg (server) - : mock_server_receives_legacy_hello (server, NULL); + with_op_msg ? mock_server_receives_hello_op_msg (server) : mock_server_receives_legacy_hello (server, NULL); // OP_QUERY 1 / OP_MSG 1: // - by _mongoc_rpc_op_egress_inc @@ -684,8 +653,7 @@ _test_counters_rpc_op_egress_cluster_single (bool with_op_msg) } { - request_t *const request = - mock_server_receives_msg (server, MONGOC_MSG_NONE, command); + request_t *const request = mock_server_receives_msg (server, MONGOC_MSG_NONE, command); // OP_MSG 1 / OP_MSG 2: // - by _mongoc_rpc_op_egress_inc @@ -708,11 +676,9 @@ _test_counters_rpc_op_egress_cluster_single (bool with_op_msg) { int responses = 0; - server_monitor_autoresponder_data data = {.hello = hello, - .responses = &responses}; + server_monitor_autoresponder_data data = {.hello = hello, .responses = &responses}; - mock_server_autoresponds ( - server, test_counters_rpc_op_egress_autoresponder, &data, NULL); + mock_server_autoresponds (server, test_counters_rpc_op_egress_autoresponder, &data, NULL); mongoc_client_destroy (client); mock_server_destroy (server); @@ -752,8 +718,7 @@ test_counters_rpc_op_egress_cluster_legacy (void) mock_server_run (server); bson_error_t error = {0}; - mongoc_client_t *const client = mongoc_client_new_from_uri_with_error ( - mock_server_get_uri (server), &error); + mongoc_client_t *const client = mongoc_client_new_from_uri_with_error (mock_server_get_uri (server), &error); ASSERT_OR_PRINT (client, error); ASSERT_RPC_OP_EGRESS_COUNTERS_CURRENT (zero); @@ -764,12 +729,10 @@ test_counters_rpc_op_egress_cluster_legacy (void) { const bson_t *const command = tmp_bson ("{'ping': 1}"); - future_t *const ping = future_client_command_simple ( - client, "db", command, NULL, NULL, &error); + future_t *const ping = future_client_command_simple (client, "db", command, NULL, NULL, &error); { - request_t *const request = - mock_server_receives_legacy_hello (server, NULL); + request_t *const request = mock_server_receives_legacy_hello (server, NULL); // OP_QUERY 1: // - by _mongoc_rpc_op_egress_inc @@ -794,8 +757,7 @@ test_counters_rpc_op_egress_cluster_legacy (void) } { - request_t *const request = - mock_server_receives_msg (server, MONGOC_MSG_NONE, command); + request_t *const request = mock_server_receives_msg (server, MONGOC_MSG_NONE, command); // OP_MSG 1: // - by _mongoc_rpc_op_egress_inc @@ -818,8 +780,7 @@ test_counters_rpc_op_egress_cluster_legacy (void) mongoc_client_kill_cursor (client, 123); { - request_t *const request = - mock_server_receives_kill_cursors (server, 123); + request_t *const request = mock_server_receives_kill_cursors (server, 123); ASSERT_WITH_MSG (request->opcode == MONGOC_OPCODE_KILL_CURSORS, "expected OP_KILL_CURSORS request, but received: %s", @@ -843,11 +804,9 @@ test_counters_rpc_op_egress_cluster_legacy (void) { int responses = 0; - server_monitor_autoresponder_data data = {.hello = hello, - .responses = &responses}; + server_monitor_autoresponder_data data = {.hello = hello, .responses = &responses}; - mock_server_autoresponds ( - server, test_counters_rpc_op_egress_autoresponder, &data, NULL); + mock_server_autoresponds (server, test_counters_rpc_op_egress_autoresponder, &data, NULL); mongoc_client_destroy (client); mock_server_destroy (server); @@ -876,8 +835,7 @@ _test_counters_rpc_op_egress_cluster_pooled (bool with_op_msg) mock_server_run (server); bson_error_t error = {0}; - mongoc_client_pool_t *const pool = - mongoc_client_pool_new_with_error (mock_server_get_uri (server), &error); + mongoc_client_pool_t *const pool = mongoc_client_pool_new_with_error (mock_server_get_uri (server), &error); ASSERT_OR_PRINT (pool, error); // Stable API for Drivers spec: If an API version was declared, drivers MUST @@ -885,10 +843,8 @@ _test_counters_rpc_op_egress_cluster_pooled (bool with_op_msg) // afterwards. Instead, drivers MUST use the `hello` command exclusively and // use the `OP_MSG` protocol. if (with_op_msg) { - mongoc_server_api_t *const api = - mongoc_server_api_new (MONGOC_SERVER_API_V1); - ASSERT_OR_PRINT (mongoc_client_pool_set_server_api (pool, api, &error), - error); + mongoc_server_api_t *const api = mongoc_server_api_new (MONGOC_SERVER_API_V1); + ASSERT_OR_PRINT (mongoc_client_pool_set_server_api (pool, api, &error), error); mongoc_server_api_destroy (api); } @@ -898,13 +854,11 @@ _test_counters_rpc_op_egress_cluster_pooled (bool with_op_msg) mongoc_client_t *const client = mongoc_client_pool_pop (pool); rpc_op_egress_counters expected = {0}; - int32_t *const handshake_counter = - with_op_msg ? &expected.op_egress_msg : &expected.op_egress_query; + int32_t *const handshake_counter = with_op_msg ? &expected.op_egress_msg : &expected.op_egress_query; { request_t *const request = - with_op_msg ? mock_server_receives_hello_op_msg (server) - : mock_server_receives_legacy_hello (server, NULL); + with_op_msg ? mock_server_receives_hello_op_msg (server) : mock_server_receives_legacy_hello (server, NULL); // OP_QUERY 1 / OP_MSG 1: // - by _mongoc_rpc_op_egress_inc @@ -926,13 +880,11 @@ _test_counters_rpc_op_egress_cluster_pooled (bool with_op_msg) { const bson_t *const command = tmp_bson ("{'ping': 1}"); - future_t *const ping = future_client_command_simple ( - client, "db", command, NULL, NULL, &error); + future_t *const ping = future_client_command_simple (client, "db", command, NULL, NULL, &error); { request_t *const request = - with_op_msg ? mock_server_receives_hello_op_msg (server) - : mock_server_receives_legacy_hello (server, NULL); + with_op_msg ? mock_server_receives_hello_op_msg (server) : mock_server_receives_legacy_hello (server, NULL); // OP_QUERY 2 / OP_MSG 2: // - by _mongoc_rpc_op_egress_inc @@ -958,8 +910,7 @@ _test_counters_rpc_op_egress_cluster_pooled (bool with_op_msg) } { - request_t *const request = - mock_server_receives_msg (server, MONGOC_MSG_NONE, command); + request_t *const request = mock_server_receives_msg (server, MONGOC_MSG_NONE, command); // OP_MSG 1 / OP_MSG 3: // - by _mongoc_rpc_op_egress_inc @@ -982,11 +933,9 @@ _test_counters_rpc_op_egress_cluster_pooled (bool with_op_msg) { int responses = 0; - server_monitor_autoresponder_data data = {.hello = hello, - .responses = &responses}; + server_monitor_autoresponder_data data = {.hello = hello, .responses = &responses}; - mock_server_autoresponds ( - server, test_counters_rpc_op_egress_autoresponder, &data, NULL); + mock_server_autoresponds (server, test_counters_rpc_op_egress_autoresponder, &data, NULL); mongoc_client_pool_push (pool, client); mongoc_client_pool_destroy (pool); @@ -1014,18 +963,17 @@ _test_counters_rpc_op_egress_awaitable_hello (bool with_op_msg) { const rpc_op_egress_counters zero = {0}; - const char *const hello = - tmp_str ("{'ok': 1,%s" - " 'isWritablePrimary': true," - " 'topologyVersion': {" - " 'processId': {'$oid': '000000000000000000000001'}," - " 'counter': {'$numberLong': '1'}" - " }," - " 'minWireVersion': %d," - " 'maxWireVersion': %d}", - with_op_msg ? " 'helloOk': true," : "", - WIRE_VERSION_MIN, - WIRE_VERSION_MAX); + const char *const hello = tmp_str ("{'ok': 1,%s" + " 'isWritablePrimary': true," + " 'topologyVersion': {" + " 'processId': {'$oid': '000000000000000000000001'}," + " 'counter': {'$numberLong': '1'}" + " }," + " 'minWireVersion': %d," + " 'maxWireVersion': %d}", + with_op_msg ? " 'helloOk': true," : "", + WIRE_VERSION_MIN, + WIRE_VERSION_MAX); rpc_op_egress_counters_reset (); @@ -1035,8 +983,7 @@ _test_counters_rpc_op_egress_awaitable_hello (bool with_op_msg) bson_error_t error = {0}; mongoc_uri_t *const uri = mongoc_uri_copy (mock_server_get_uri (server)); - mongoc_client_pool_t *const pool = - mongoc_client_pool_new_with_error (uri, &error); + mongoc_client_pool_t *const pool = mongoc_client_pool_new_with_error (uri, &error); ASSERT_OR_PRINT (pool, error); // Stable API for Drivers spec: If an API version was declared, drivers MUST @@ -1044,10 +991,8 @@ _test_counters_rpc_op_egress_awaitable_hello (bool with_op_msg) // afterwards. Instead, drivers MUST use the `hello` command exclusively and // use the `OP_MSG` protocol. if (with_op_msg) { - mongoc_server_api_t *const api = - mongoc_server_api_new (MONGOC_SERVER_API_V1); - ASSERT_OR_PRINT (mongoc_client_pool_set_server_api (pool, api, &error), - error); + mongoc_server_api_t *const api = mongoc_server_api_new (MONGOC_SERVER_API_V1); + ASSERT_OR_PRINT (mongoc_client_pool_set_server_api (pool, api, &error), error); mongoc_server_api_destroy (api); } @@ -1068,23 +1013,16 @@ _test_counters_rpc_op_egress_awaitable_hello (bool with_op_msg) request_t *const request = mock_server_receives_request (server); if (strstr (request->as_str, "maxAwaitTimeMS")) { - ASSERT_WITH_MSG (!awaitable_hello, - "received more than one awaitable hello"); + ASSERT_WITH_MSG (!awaitable_hello, "received more than one awaitable hello"); awaitable_hello = request; } else { - const bool is_hello = - strcmp (request->command_name, HANDSHAKE_CMD_HELLO) == 0; - const bool is_legacy_hello = - strcmp (request->command_name, HANDSHAKE_CMD_LEGACY_HELLO) == 0; + const bool is_hello = strcmp (request->command_name, HANDSHAKE_CMD_HELLO) == 0; + const bool is_legacy_hello = strcmp (request->command_name, HANDSHAKE_CMD_LEGACY_HELLO) == 0; if (with_op_msg) { - ASSERT_WITH_MSG (is_hello, - "expected only OP_MSG hello requests, but got: %s", - request->as_str); + ASSERT_WITH_MSG (is_hello, "expected only OP_MSG hello requests, but got: %s", request->as_str); } else { - ASSERT_WITH_MSG (is_hello || is_legacy_hello, - "expected only hello requests, but got: %s", - request->as_str); + ASSERT_WITH_MSG (is_hello || is_legacy_hello, "expected only hello requests, but got: %s", request->as_str); } reply_to_request_simple (request, hello); @@ -1093,8 +1031,7 @@ _test_counters_rpc_op_egress_awaitable_hello (bool with_op_msg) } rpc_op_egress_counters expected = {0}; - int32_t *const handshake_counter = - with_op_msg ? &expected.op_egress_msg : &expected.op_egress_query; + int32_t *const handshake_counter = with_op_msg ? &expected.op_egress_msg : &expected.op_egress_query; // OP_QUERY 1 / OP_MSG 1: // - by _mongoc_rpc_op_egress_inc @@ -1143,13 +1080,11 @@ _test_counters_rpc_op_egress_awaitable_hello (bool with_op_msg) // Trigger: // - mongoc_cluster_run_command_private // - mongoc_cluster_run_command_monitored - future_t *const ping = future_client_command_simple ( - client, "db", command, NULL, NULL, &error); + future_t *const ping = future_client_command_simple (client, "db", command, NULL, NULL, &error); { request_t *const request = - with_op_msg ? mock_server_receives_hello_op_msg (server) - : mock_server_receives_legacy_hello (server, NULL); + with_op_msg ? mock_server_receives_hello_op_msg (server) : mock_server_receives_legacy_hello (server, NULL); // OP_QUERY 4 / OP_MSG 5: // - by _mongoc_rpc_op_egress_inc @@ -1175,8 +1110,7 @@ _test_counters_rpc_op_egress_awaitable_hello (bool with_op_msg) } { - request_t *const request = - mock_server_receives_msg (server, MONGOC_MSG_NONE, command); + request_t *const request = mock_server_receives_msg (server, MONGOC_MSG_NONE, command); // OP_MSG 2 / OP_MSG 6: // - by _mongoc_rpc_op_egress_inc @@ -1199,11 +1133,9 @@ _test_counters_rpc_op_egress_awaitable_hello (bool with_op_msg) { int responses = 0; - server_monitor_autoresponder_data data = {.hello = hello, - .responses = &responses}; + server_monitor_autoresponder_data data = {.hello = hello, .responses = &responses}; - mock_server_autoresponds ( - server, test_counters_rpc_op_egress_autoresponder, &data, NULL); + mock_server_autoresponds (server, test_counters_rpc_op_egress_autoresponder, &data, NULL); mongoc_uri_destroy (uri); mongoc_client_pool_push (pool, client); @@ -1244,8 +1176,7 @@ _test_counters_rpc_op_egress_mock_server (bool with_op_msg) mock_server_run (server); bson_error_t error = {0}; - mongoc_client_t *const client = mongoc_client_new_from_uri_with_error ( - mock_server_get_uri (server), &error); + mongoc_client_t *const client = mongoc_client_new_from_uri_with_error (mock_server_get_uri (server), &error); ASSERT_OR_PRINT (client, error); // Stable API for Drivers spec: If an API version was declared, drivers MUST @@ -1253,10 +1184,8 @@ _test_counters_rpc_op_egress_mock_server (bool with_op_msg) // afterwards. Instead, drivers MUST use the `hello` command exclusively and // use the `OP_MSG` protocol. if (with_op_msg) { - mongoc_server_api_t *const api = - mongoc_server_api_new (MONGOC_SERVER_API_V1); - ASSERT_OR_PRINT (mongoc_client_set_server_api (client, api, &error), - error); + mongoc_server_api_t *const api = mongoc_server_api_new (MONGOC_SERVER_API_V1); + ASSERT_OR_PRINT (mongoc_client_set_server_api (client, api, &error), error); mongoc_server_api_destroy (api); } @@ -1264,10 +1193,8 @@ _test_counters_rpc_op_egress_mock_server (bool with_op_msg) { const bson_t *const command = tmp_bson ("{'ping': 1}"); - future_t *const future = future_client_command_simple ( - client, "db", command, NULL, NULL, &error); - reply_to_request_with_ok_and_destroy ( - mock_server_receives_msg (server, MONGOC_MSG_NONE, command)); + future_t *const future = future_client_command_simple (client, "db", command, NULL, NULL, &error); + reply_to_request_with_ok_and_destroy (mock_server_receives_msg (server, MONGOC_MSG_NONE, command)); ASSERT_OR_PRINT (future_get_bool (future), error); future_destroy (future); } @@ -1319,13 +1246,11 @@ wait_for_background_threads (rpc_op_egress_counters expected) current = rpc_op_egress_counters_current (); } - ASSERT_WITH_MSG ( - false, - "expected %" PRId32 - " total requests by background threads, but observed %" PRId32 - " total requests", - expected.op_egress_total, - current.op_egress_total); + ASSERT_WITH_MSG (false, + "expected %" PRId32 " total requests by background threads, but observed %" PRId32 + " total requests", + expected.op_egress_total, + current.op_egress_total); } @@ -1344,8 +1269,7 @@ _test_counters_auth (bool with_op_msg, bool pooled) // supports a new argument, `speculativeAuthenticate`, provided as a BSON // document. Clients specifying this argument to hello or legacy hello will // speculatively include the first command of an authentication handshake. - const bool has_speculative_auth = test_framework_get_server_version () >= - test_framework_str_to_version ("4.4.0"); + const bool has_speculative_auth = test_framework_get_server_version () >= test_framework_str_to_version ("4.4.0"); // Used to calculate expected values of OP_COMPRESSED RPC egress counter. const int32_t has_compressors = test_framework_has_compressors (); @@ -1354,8 +1278,7 @@ _test_counters_auth (bool with_op_msg, bool pooled) // MUST NOT use the legacy hello command during the initial handshake or // afterwards. Instead, drivers MUST use the `hello` command exclusively // and use the `OP_MSG` protocol. - mongoc_server_api_t *const api = - with_op_msg ? mongoc_server_api_new (MONGOC_SERVER_API_V1) : NULL; + mongoc_server_api_t *const api = with_op_msg ? mongoc_server_api_new (MONGOC_SERVER_API_V1) : NULL; // SCRAM-SHA-1 is available since MongoDB server 3.0 and forces OP_MSG // requests for authentication steps that follow the initial connection @@ -1400,8 +1323,7 @@ _test_counters_auth (bool with_op_msg, bool pooled) // Awaitable hello is also a 4.4+ feature. if (has_speculative_auth) { rpc_op_egress_counters expected = {0}; - int32_t *const handshake_counter = - with_op_msg ? &expected.op_egress_msg : &expected.op_egress_query; + int32_t *const handshake_counter = with_op_msg ? &expected.op_egress_msg : &expected.op_egress_query; // OP_QUERY / OP_MSG (for each replset member): // - initial connection handshake by server monitor thread @@ -1446,10 +1368,7 @@ _test_counters_auth (bool with_op_msg, bool pooled) // - _cluster_run_hello (SASL step 1 if `has_speculative_auth`) // - _mongoc_cluster_auth_node (if not `has_speculative_auth`) // - mongoc_cluster_run_command_monitored - ASSERT_OR_PRINT ( - mongoc_client_command_simple ( - client, "db", tmp_bson ("{'ping': 1}"), NULL, NULL, &error), - error); + ASSERT_OR_PRINT (mongoc_client_command_simple (client, "db", tmp_bson ("{'ping': 1}"), NULL, NULL, &error), error); const int32_t auth_success = mongoc_counter_auth_success_count (); const int32_t auth_failure = mongoc_counter_auth_failure_count (); @@ -1457,14 +1376,12 @@ _test_counters_auth (bool with_op_msg, bool pooled) // Ensure we are not testing more than we intend. ASSERT_WITH_MSG (auth_success == 1 && auth_failure == 0, "expected exactly one authentication attempt to succeed, " - "but observed %" PRId32 " successes and %" PRId32 - " failures", + "but observed %" PRId32 " successes and %" PRId32 " failures", auth_success, auth_failure); rpc_op_egress_counters expected = {0}; - int32_t *const handshake_counter = - with_op_msg ? &expected.op_egress_msg : &expected.op_egress_query; + int32_t *const handshake_counter = with_op_msg ? &expected.op_egress_msg : &expected.op_egress_query; // The number of expected OP_QUERY requests depends on pooling and the // presence of the RTT monitor thread. @@ -1572,12 +1489,7 @@ test_counters_install (TestSuite *suite) TestSuite_CheckLive); TestSuite_AddLive (suite, "/counters/cursors", test_counters_cursors); TestSuite_AddLive (suite, "/counters/clients", test_counters_clients); - TestSuite_AddFull (suite, - "/counters/streams", - test_counters_streams, - NULL, - NULL, - TestSuite_CheckLive); + TestSuite_AddFull (suite, "/counters/streams", test_counters_streams, NULL, NULL, TestSuite_CheckLive); TestSuite_AddFull (suite, "/counters/auth", test_counters_auth, @@ -1586,51 +1498,34 @@ test_counters_install (TestSuite *suite) test_framework_skip_if_no_auth, test_framework_skip_if_not_single); TestSuite_AddLive (suite, "/counters/dns", test_counters_dns); - TestSuite_AddMockServerTest ( - suite, "/counters/streams_timeout", test_counters_streams_timeout); + TestSuite_AddMockServerTest (suite, "/counters/streams_timeout", test_counters_streams_timeout); TestSuite_AddMockServerTest ( - suite, - "/counters/rpc/op_egress/cluster/single/op_query", - test_counters_rpc_op_egress_cluster_single_op_query); + suite, "/counters/rpc/op_egress/cluster/single/op_query", test_counters_rpc_op_egress_cluster_single_op_query); TestSuite_AddMockServerTest ( - suite, - "/counters/rpc/op_egress/cluster/single/op_msg", - test_counters_rpc_op_egress_cluster_single_op_msg); + suite, "/counters/rpc/op_egress/cluster/single/op_msg", test_counters_rpc_op_egress_cluster_single_op_msg); - TestSuite_AddMockServerTest (suite, - "/counters/rpc/op_egress/cluster/legacy", - test_counters_rpc_op_egress_cluster_legacy); + TestSuite_AddMockServerTest ( + suite, "/counters/rpc/op_egress/cluster/legacy", test_counters_rpc_op_egress_cluster_legacy); TestSuite_AddMockServerTest ( - suite, - "/counters/rpc/op_egress/cluster/pooled/op_query", - test_counters_rpc_op_egress_cluster_pooled_op_query); + suite, "/counters/rpc/op_egress/cluster/pooled/op_query", test_counters_rpc_op_egress_cluster_pooled_op_query); TestSuite_AddMockServerTest ( - suite, - "/counters/rpc/op_egress/cluster/pooled/op_msg", - test_counters_rpc_op_egress_cluster_pooled_op_msg); + suite, "/counters/rpc/op_egress/cluster/pooled/op_msg", test_counters_rpc_op_egress_cluster_pooled_op_msg); TestSuite_AddMockServerTest ( - suite, - "/counters/rpc/op_egress/awaitable_hello/op_query", - test_counters_rpc_op_egress_awaitable_hello_op_query); + suite, "/counters/rpc/op_egress/awaitable_hello/op_query", test_counters_rpc_op_egress_awaitable_hello_op_query); TestSuite_AddMockServerTest ( - suite, - "/counters/rpc/op_egress/awaitable_hello/op_msg", - test_counters_rpc_op_egress_awaitable_hello_op_msg); + suite, "/counters/rpc/op_egress/awaitable_hello/op_msg", test_counters_rpc_op_egress_awaitable_hello_op_msg); TestSuite_AddMockServerTest ( - suite, - "/counters/rpc/op_egress/mock_server/op_query", - test_counters_rpc_op_egress_mock_server_op_query); + suite, "/counters/rpc/op_egress/mock_server/op_query", test_counters_rpc_op_egress_mock_server_op_query); - TestSuite_AddMockServerTest (suite, - "/counters/rpc/op_egress/mock_server/op_msg", - test_counters_rpc_op_egress_mock_server_op_msg); + TestSuite_AddMockServerTest ( + suite, "/counters/rpc/op_egress/mock_server/op_msg", test_counters_rpc_op_egress_mock_server_op_msg); #if defined(MONGOC_ENABLE_SSL) TestSuite_AddFull (suite, diff --git a/src/libmongoc/tests/test-mongoc-crud.c b/src/libmongoc/tests/test-mongoc-crud.c index e785feb497..c43d588735 100644 --- a/src/libmongoc/tests/test-mongoc-crud.c +++ b/src/libmongoc/tests/test-mongoc-crud.c @@ -5,15 +5,12 @@ #include "test-libmongoc.h" static bool -crud_test_operation_cb (json_test_ctx_t *ctx, - const bson_t *test, - const bson_t *operation) +crud_test_operation_cb (json_test_ctx_t *ctx, const bson_t *test, const bson_t *operation) { bson_t reply; bool res; - res = - json_test_operation (ctx, test, operation, ctx->collection, NULL, &reply); + res = json_test_operation (ctx, test, operation, ctx->collection, NULL, &reply); bson_destroy (&reply); @@ -33,19 +30,12 @@ test_crud_cb (bson_t *scenario) static void test_all_spec_tests (TestSuite *suite) { - install_json_test_suite_with_check (suite, - JSON_DIR, - "crud/legacy", - &test_crud_cb, - test_framework_skip_if_no_crypto, - TestSuite_CheckLive); + install_json_test_suite_with_check ( + suite, JSON_DIR, "crud/legacy", &test_crud_cb, test_framework_skip_if_no_crypto, TestSuite_CheckLive); /* Read/write concern spec tests use the same format. */ - install_json_test_suite_with_check (suite, - JSON_DIR, - "read_write_concern/operation", - &test_crud_cb, - TestSuite_CheckLive); + install_json_test_suite_with_check ( + suite, JSON_DIR, "read_write_concern/operation", &test_crud_cb, TestSuite_CheckLive); } static void @@ -62,22 +52,20 @@ prose_test_1 (void *ctx) client = test_framework_new_default_client (); coll = get_test_collection (client, "coll"); - ret = mongoc_client_command_simple ( - client, - "admin", - tmp_bson ("{'configureFailPoint': 'failCommand', 'mode': {'times': 1}, " - " 'data': {'failCommands': ['insert'], 'writeConcernError': {" - " 'code': 100, 'codeName': 'UnsatisfiableWriteConcern', " - " 'errmsg': 'Not enough data-bearing nodes', " - " 'errInfo': {'writeConcern': {'w': 2, 'wtimeout': 0, " - " 'provenance': 'clientSupplied'}}}}}"), - NULL, - NULL, - &error); + ret = mongoc_client_command_simple (client, + "admin", + tmp_bson ("{'configureFailPoint': 'failCommand', 'mode': {'times': 1}, " + " 'data': {'failCommands': ['insert'], 'writeConcernError': {" + " 'code': 100, 'codeName': 'UnsatisfiableWriteConcern', " + " 'errmsg': 'Not enough data-bearing nodes', " + " 'errInfo': {'writeConcern': {'w': 2, 'wtimeout': 0, " + " 'provenance': 'clientSupplied'}}}}}"), + NULL, + NULL, + &error); ASSERT_OR_PRINT (ret, error); - ret = mongoc_collection_insert_one ( - coll, tmp_bson ("{'x':1}"), NULL /* opts */, &reply, &error); + ret = mongoc_collection_insert_one (coll, tmp_bson ("{'x':1}"), NULL /* opts */, &reply, &error); ASSERT (!ret); /* libmongoc does not model WriteConcernError, so we only assert that the @@ -99,14 +87,11 @@ typedef struct { static void prose_test_2_command_succeeded (const mongoc_apm_command_succeeded_t *event) { - if (!strcmp (mongoc_apm_command_succeeded_get_command_name (event), - "insert")) { - prose_test_2_apm_ctx_t *ctx = - mongoc_apm_command_succeeded_get_context (event); + if (!strcmp (mongoc_apm_command_succeeded_get_command_name (event), "insert")) { + prose_test_2_apm_ctx_t *ctx = mongoc_apm_command_succeeded_get_context (event); ASSERT (!ctx->has_reply); ctx->has_reply = true; - bson_copy_to (mongoc_apm_command_succeeded_get_reply (event), - &ctx->reply); + bson_copy_to (mongoc_apm_command_succeeded_get_reply (event), &ctx->reply); } } @@ -132,21 +117,16 @@ prose_test_2 (void *ctx) (void) mongoc_collection_drop (coll, NULL); coll_created = mongoc_database_create_collection ( - db, - mongoc_collection_get_name (coll), - tmp_bson ("{'validator': {'x': {'$type': 'string'}}}"), - &error); + db, mongoc_collection_get_name (coll), tmp_bson ("{'validator': {'x': {'$type': 'string'}}}"), &error); ASSERT_OR_PRINT (coll_created, error); mongoc_collection_destroy (coll_created); callbacks = mongoc_apm_callbacks_new (); - mongoc_apm_set_command_succeeded_cb (callbacks, - prose_test_2_command_succeeded); + mongoc_apm_set_command_succeeded_cb (callbacks, prose_test_2_command_succeeded); mongoc_client_set_apm_callbacks (client, callbacks, (void *) &apm_ctx); mongoc_apm_callbacks_destroy (callbacks); - ret = mongoc_collection_insert_one ( - coll, tmp_bson ("{'x':1}"), NULL /* opts */, &reply, &error); + ret = mongoc_collection_insert_one (coll, tmp_bson ("{'x':1}"), NULL /* opts */, &reply, &error); ASSERT (!ret); /* Assert that the WriteError's code is DocumentValidationFailure */ diff --git a/src/libmongoc/tests/test-mongoc-cursor.c b/src/libmongoc/tests/test-mongoc-cursor.c index 6c36141bed..5902462d0c 100644 --- a/src/libmongoc/tests/test-mongoc-cursor.c +++ b/src/libmongoc/tests/test-mongoc-cursor.c @@ -12,17 +12,16 @@ #include "mongoc/mongoc-write-concern-private.h" #include "test-conveniences.h" -#define CURSOR_COMMON_SETUP \ - do { \ - bson_error_t _err; \ - bool _ret; \ - client = test_framework_new_default_client (); \ - coll = mongoc_client_get_collection (client, "test", "test"); \ - /* populate to ensure db and coll exist. */ \ - _ret = mongoc_collection_insert_one ( \ - coll, tmp_bson ("{}"), NULL, NULL, &_err); \ - ASSERT_OR_PRINT (_ret, _err); \ - ctor = (make_cursor_fn) ((TestFnCtx *) ctx)->test_fn; \ +#define CURSOR_COMMON_SETUP \ + do { \ + bson_error_t _err; \ + bool _ret; \ + client = test_framework_new_default_client (); \ + coll = mongoc_client_get_collection (client, "test", "test"); \ + /* populate to ensure db and coll exist. */ \ + _ret = mongoc_collection_insert_one (coll, tmp_bson ("{}"), NULL, NULL, &_err); \ + ASSERT_OR_PRINT (_ret, _err); \ + ctor = (make_cursor_fn) ((TestFnCtx *) ctx)->test_fn; \ } while (0) #define CURSOR_COMMON_TEARDOWN \ @@ -130,8 +129,7 @@ _test_common_clone_w_concerns (void *ctx) cursor = ctor (coll); read_concern = mongoc_read_concern_new (); ASSERT (read_concern); - mongoc_read_concern_set_level (read_concern, - MONGOC_READ_CONCERN_LEVEL_LOCAL); + mongoc_read_concern_set_level (read_concern, MONGOC_READ_CONCERN_LEVEL_LOCAL); write_concern = mongoc_write_concern_new (); ASSERT (write_concern); mongoc_write_concern_set_fsync (write_concern, true); @@ -146,25 +144,18 @@ _test_common_clone_w_concerns (void *ctx) cloned = mongoc_cursor_clone (cursor); /* test cloned read_concern. */ ASSERT (!mongoc_read_concern_is_default (cloned->read_concern)); - ASSERT_CMPSTR (mongoc_read_concern_get_level (cloned->read_concern), - MONGOC_READ_CONCERN_LEVEL_LOCAL); + ASSERT_CMPSTR (mongoc_read_concern_get_level (cloned->read_concern), MONGOC_READ_CONCERN_LEVEL_LOCAL); /* test cloned write_concern. */ ASSERT (mongoc_write_concern_get_wmajority (cloned->write_concern)); - ASSERT (mongoc_write_concern_get_wtimeout_int64 (cloned->write_concern) == - 1000); - ASSERT (mongoc_write_concern_get_w (cloned->write_concern) == - MONGOC_WRITE_CONCERN_W_MAJORITY); + ASSERT (mongoc_write_concern_get_wtimeout_int64 (cloned->write_concern) == 1000); + ASSERT (mongoc_write_concern_get_w (cloned->write_concern) == MONGOC_WRITE_CONCERN_W_MAJORITY); /* check generated bson in cloned cursor. */ - ASSERT_MATCH (_mongoc_read_concern_get_bson (cloned->read_concern), - "{'level': 'local'}"); + ASSERT_MATCH (_mongoc_read_concern_get_bson (cloned->read_concern), "{'level': 'local'}"); bson = _mongoc_write_concern_get_bson (cloned->write_concern); ASSERT (bson); - ASSERT (bson_iter_init_find (&iter, bson, "fsync") && - BSON_ITER_HOLDS_BOOL (&iter) && bson_iter_bool (&iter)); - ASSERT (bson_iter_init_find (&iter, bson, "j") && - BSON_ITER_HOLDS_BOOL (&iter) && bson_iter_bool (&iter)); - ASSERT (bson_iter_init_find (&iter, bson, "w") && - BSON_ITER_HOLDS_UTF8 (&iter)); + ASSERT (bson_iter_init_find (&iter, bson, "fsync") && BSON_ITER_HOLDS_BOOL (&iter) && bson_iter_bool (&iter)); + ASSERT (bson_iter_init_find (&iter, bson, "j") && BSON_ITER_HOLDS_BOOL (&iter) && bson_iter_bool (&iter)); + ASSERT (bson_iter_init_find (&iter, bson, "w") && BSON_ITER_HOLDS_UTF8 (&iter)); ASSERT_CMPSTR (bson_iter_utf8 (&iter, NULL), "majority"); mongoc_cursor_destroy (cursor); mongoc_cursor_destroy (cloned); @@ -199,10 +190,8 @@ _test_common_advancing_past_end (void *ctx) BSON_ASSERT (!mongoc_cursor_next (cursor, &doc)); BSON_ASSERT (mongoc_cursor_error (cursor, &err)); BSON_ASSERT (mongoc_cursor_error_document (cursor, &err, &err_doc)); - ASSERT_ERROR_CONTAINS (err, - MONGOC_ERROR_CURSOR, - MONGOC_ERROR_CURSOR_INVALID_CURSOR, - "Cannot advance a completed or failed cursor."); + ASSERT_ERROR_CONTAINS ( + err, MONGOC_ERROR_CURSOR, MONGOC_ERROR_CURSOR_INVALID_CURSOR, "Cannot advance a completed or failed cursor."); /* this is not a server error, the error document should be NULL. */ BSON_ASSERT (bson_empty (err_doc)); mongoc_cursor_destroy (cursor); @@ -217,18 +206,15 @@ typedef struct { static void -_test_common_server_hint_command_started ( - const mongoc_apm_command_started_t *event) +_test_common_server_hint_command_started (const mongoc_apm_command_started_t *event) { const mongoc_host_list_t *host = mongoc_apm_command_started_get_host (event); const char *cmd = mongoc_apm_command_started_get_command_name (event); test_common_server_hint_ctx_t *ctx; /* only check command associated with cursor priming. */ - if (strcmp (cmd, "find") == 0 || - strcasecmp (cmd, HANDSHAKE_CMD_LEGACY_HELLO) == 0 || - strcmp (cmd, "hello") == 0 || strcmp (cmd, "listDatabases") == 0) { - ctx = (test_common_server_hint_ctx_t *) - mongoc_apm_command_started_get_context (event); + if (strcmp (cmd, "find") == 0 || strcasecmp (cmd, HANDSHAKE_CMD_LEGACY_HELLO) == 0 || strcmp (cmd, "hello") == 0 || + strcmp (cmd, "listDatabases") == 0) { + ctx = (test_common_server_hint_ctx_t *) mongoc_apm_command_started_get_context (event); ASSERT_CMPSTR (host->host_and_port, ctx->expected_host_and_port); BSON_ASSERT (!ctx->called); ctx->called = true; @@ -255,8 +241,7 @@ _test_common_server_hint (void *ctx) /* set APM callbacks, and then set server hint. Make sure we target the same * host that we select. */ callbacks = mongoc_apm_callbacks_new (); - mongoc_apm_set_command_started_cb (callbacks, - _test_common_server_hint_command_started); + mongoc_apm_set_command_started_cb (callbacks, _test_common_server_hint_command_started); cursor = ctor (coll); read_prefs = mongoc_read_prefs_new (MONGOC_READ_PRIMARY); sd = mongoc_client_select_server (client, false, read_prefs, &err); @@ -415,8 +400,7 @@ _make_cmd_cursor (mongoc_collection_t *coll) static mongoc_cursor_t * _make_cmd_cursor_from_agg (mongoc_collection_t *coll) { - return mongoc_collection_aggregate ( - coll, MONGOC_QUERY_SECONDARY_OK, tmp_bson ("{}"), NULL, NULL); + return mongoc_collection_aggregate (coll, MONGOC_QUERY_SECONDARY_OK, tmp_bson ("{}"), NULL, NULL); } @@ -424,14 +408,7 @@ static mongoc_cursor_t * _make_cmd_deprecated_cursor (mongoc_collection_t *coll) { return mongoc_collection_command ( - coll, - MONGOC_QUERY_SECONDARY_OK, - 0, - 0, - 0, - tmp_bson ("{'" HANDSHAKE_CMD_LEGACY_HELLO "': 1}"), - NULL, - NULL); + coll, MONGOC_QUERY_SECONDARY_OK, 0, 0, 0, tmp_bson ("{'" HANDSHAKE_CMD_LEGACY_HELLO "': 1}"), NULL, NULL); } @@ -442,36 +419,20 @@ _make_array_cursor (mongoc_collection_t *coll) } #define TEST_CURSOR_FIND(prefix, fn) \ - TestSuite_AddFullWithTestFn ( \ - suite, prefix "/find", fn, NULL, _make_find_cursor, TestSuite_CheckLive) + TestSuite_AddFullWithTestFn (suite, prefix "/find", fn, NULL, _make_find_cursor, TestSuite_CheckLive) #define TEST_CURSOR_CMD(prefix, fn) \ - TestSuite_AddFullWithTestFn ( \ - suite, prefix "/cmd", fn, NULL, _make_cmd_cursor, TestSuite_CheckLive) - -#define TEST_CURSOR_CMD_DEPRECATED(prefix, fn) \ - TestSuite_AddFullWithTestFn (suite, \ - prefix "/cmd_deprecated", \ - fn, \ - NULL, \ - _make_cmd_deprecated_cursor, \ - TestSuite_CheckLive) - -#define TEST_CURSOR_ARRAY(prefix, fn) \ - TestSuite_AddFullWithTestFn (suite, \ - prefix "/array", \ - fn, \ - NULL, \ - _make_array_cursor, \ - TestSuite_CheckLive) - -#define TEST_CURSOR_AGG(prefix, fn) \ - TestSuite_AddFullWithTestFn (suite, \ - prefix "/agg", \ - fn, \ - NULL, \ - _make_cmd_cursor_from_agg, \ - TestSuite_CheckLive) + TestSuite_AddFullWithTestFn (suite, prefix "/cmd", fn, NULL, _make_cmd_cursor, TestSuite_CheckLive) + +#define TEST_CURSOR_CMD_DEPRECATED(prefix, fn) \ + TestSuite_AddFullWithTestFn ( \ + suite, prefix "/cmd_deprecated", fn, NULL, _make_cmd_deprecated_cursor, TestSuite_CheckLive) + +#define TEST_CURSOR_ARRAY(prefix, fn) \ + TestSuite_AddFullWithTestFn (suite, prefix "/array", fn, NULL, _make_array_cursor, TestSuite_CheckLive) + +#define TEST_CURSOR_AGG(prefix, fn) \ + TestSuite_AddFullWithTestFn (suite, prefix "/agg", fn, NULL, _make_cmd_cursor_from_agg, TestSuite_CheckLive) #define TEST_FOREACH_CURSOR(prefix, fn) \ @@ -491,10 +452,8 @@ test_common_cursor_functions_install (TestSuite *suite) /* test functionality common to all cursor implementations. */ TEST_FOREACH_CURSOR ("/Cursor/common/get_host", _test_common_get_host); TEST_FOREACH_CURSOR ("/Cursor/common/clone", _test_common_clone); - TEST_FOREACH_CURSOR ("/Cursor/common/clone_w_concerns", - _test_common_clone_w_concerns); - TEST_FOREACH_CURSOR ("/Cursor/common/advancing_past_end", - _test_common_advancing_past_end); + TEST_FOREACH_CURSOR ("/Cursor/common/clone_w_concerns", _test_common_clone_w_concerns); + TEST_FOREACH_CURSOR ("/Cursor/common/advancing_past_end", _test_common_advancing_past_end); /* an agg/cmd cursors do not support setting server id. test others. */ TEST_CURSOR_FIND ("/Cursor/common/hint", _test_common_server_hint); TEST_CURSOR_CMD_DEPRECATED ("/Cursor/common/hint", _test_common_server_hint); @@ -539,8 +498,7 @@ test_limit (void) /* test positive and negative limit */ for (i = 0; i < 2; i++) { - cursor = mongoc_collection_find ( - collection, MONGOC_QUERY_NONE, 0, 0, 0, tmp_bson ("{}"), NULL, NULL); + cursor = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, 0, tmp_bson ("{}"), NULL, NULL); ASSERT_CMPINT64 ((int64_t) 0, ==, mongoc_cursor_get_limit (cursor)); ASSERT (mongoc_cursor_set_limit (cursor, limits[i])); ASSERT_CMPINT64 (limits[i], ==, mongoc_cursor_get_limit (cursor)); @@ -558,16 +516,12 @@ test_limit (void) mongoc_cursor_destroy (cursor); if (limits[i] > 0) { - opts = - tmp_bson ("{'limit': {'$numberLong': '%" PRId64 "'}}", limits[i]); + opts = tmp_bson ("{'limit': {'$numberLong': '%" PRId64 "'}}", limits[i]); } else { - opts = tmp_bson ( - "{'singleBatch': true, 'limit': {'$numberLong': '%" PRId64 "'}}", - -limits[i]); + opts = tmp_bson ("{'singleBatch': true, 'limit': {'$numberLong': '%" PRId64 "'}}", -limits[i]); } - cursor = mongoc_collection_find_with_opts ( - collection, tmp_bson (NULL), opts, NULL); + cursor = mongoc_collection_find_with_opts (collection, tmp_bson (NULL), opts, NULL); ASSERT_CMPINT64 (limits[i], ==, mongoc_cursor_get_limit (cursor)); n_docs = 0; @@ -601,13 +555,11 @@ killcursors_succeeded (const mongoc_apm_command_succeeded_t *event) bson_iter_t iter; bson_iter_t array; - if (bson_strcasecmp (mongoc_apm_command_succeeded_get_command_name (event), - "killcursors") != 0) { + if (bson_strcasecmp (mongoc_apm_command_succeeded_get_command_name (event), "killcursors") != 0) { return; } - ctx = - (killcursors_test_t *) mongoc_apm_command_succeeded_get_context (event); + ctx = (killcursors_test_t *) mongoc_apm_command_succeeded_get_context (event); ctx->succeeded_count++; reply = mongoc_apm_command_succeeded_get_reply (event); @@ -692,37 +644,27 @@ test_kill_cursor_live (void) if (test_framework_supports_legacy_opcodes ()) { b = bson_new (); - cursor = _mongoc_cursor_find_new ( - client, collection->ns, b, NULL, NULL, NULL, NULL); + cursor = _mongoc_cursor_find_new (client, collection->ns, b, NULL, NULL, NULL, NULL); /* override the typical priming, and immediately transition to an OPQUERY * find cursor. */ cursor->impl.destroy (&cursor->impl); _mongoc_cursor_impl_find_opquery_init (cursor, b); cursor->cursor_id = ctx.cursor_id; - cursor->state = - END_OF_BATCH; /* meaning, "finished reading first batch" */ + cursor->state = END_OF_BATCH; /* meaning, "finished reading first batch" */ r = mongoc_cursor_next (cursor, &doc); ASSERT (!r); ASSERT (mongoc_cursor_error (cursor, &error)); - ASSERT_ERROR_CONTAINS ( - error, MONGOC_ERROR_CURSOR, 16, "cursor is invalid"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_CURSOR, 16, "cursor is invalid"); mongoc_cursor_destroy (cursor); } else { bson_t *cmd; - cmd = BCON_NEW ("getMore", - BCON_INT64 (ctx.cursor_id), - "collection", - mongoc_collection_get_name (collection)); - r = mongoc_client_command_simple ( - client, "test", cmd, NULL /* read prefs */, NULL /* reply */, &error); + cmd = BCON_NEW ("getMore", BCON_INT64 (ctx.cursor_id), "collection", mongoc_collection_get_name (collection)); + r = mongoc_client_command_simple (client, "test", cmd, NULL /* read prefs */, NULL /* reply */, &error); ASSERT (!r); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_QUERY, - MONGOC_SERVER_ERR_CURSOR_NOT_FOUND, - "not found"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_QUERY, MONGOC_SERVER_ERR_CURSOR_NOT_FOUND, "not found"); bson_destroy (cmd); } @@ -760,8 +702,7 @@ _test_kill_cursors (bool pooled) mock_rs_run (rs); if (pooled) { - pool = - test_framework_client_pool_new_from_uri (mock_rs_get_uri (rs), NULL); + pool = test_framework_client_pool_new_from_uri (mock_rs_get_uri (rs), NULL); client = mongoc_client_pool_pop (pool); } else { client = test_framework_client_new_from_uri (mock_rs_get_uri (rs), NULL); @@ -770,8 +711,7 @@ _test_kill_cursors (bool pooled) collection = mongoc_client_get_collection (client, "db", "collection"); prefs = mongoc_read_prefs_new (MONGOC_READ_SECONDARY); - cursor = mongoc_collection_find ( - collection, MONGOC_QUERY_NONE, 0, 0, 0, q, NULL, prefs); + cursor = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, 0, q, NULL, prefs); future = future_cursor_next (cursor, &doc); request = mock_rs_receives_request (rs); @@ -794,12 +734,11 @@ _test_kill_cursors (bool pooled) future_destroy (future); future = future_cursor_destroy (cursor); - kill_cursors = - mock_rs_receives_msg (rs, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db'," - " 'killCursors': 'collection'," - " 'cursors': [{'$numberLong': '123'}]}")); + kill_cursors = mock_rs_receives_msg (rs, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'db'," + " 'killCursors': 'collection'," + " 'cursors': [{'$numberLong': '123'}]}")); /* mock server framework can't test "cursors" array, CDRIVER-994 */ ASSERT (BCON_EXTRACT ((bson_t *) request_get_doc (kill_cursors, 0), @@ -816,9 +755,7 @@ _test_kill_cursors (bool pooled) reply_to_request_simple (request, "{'ok': 1}"); /* OP_KILLCURSORS was sent to the right secondary */ - ASSERT_CMPINT (request_get_server_port (kill_cursors), - ==, - request_get_server_port (request)); + ASSERT_CMPINT (request_get_server_port (kill_cursors), ==, request_get_server_port (request)); BSON_ASSERT (future_wait (future)); @@ -876,15 +813,13 @@ _test_client_kill_cursor (bool has_primary) read_prefs = mongoc_read_prefs_new (MONGOC_READ_SECONDARY); /* make client open a connection - it won't open one to kill a cursor */ - future = future_client_command_simple ( - client, "admin", tmp_bson ("{'foo': 1}"), read_prefs, NULL, &error); + future = future_client_command_simple (client, "admin", tmp_bson ("{'foo': 1}"), read_prefs, NULL, &error); - request = mock_rs_receives_msg ( - rs, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'admin'," - " '$readPreference': {'mode': 'secondary'}," - " 'foo': 1}")); + request = mock_rs_receives_msg (rs, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'admin'," + " '$readPreference': {'mode': 'secondary'}," + " 'foo': 1}")); reply_to_request_simple (request, "{'ok': 1}"); ASSERT_OR_PRINT (future_get_bool (future), error); @@ -948,8 +883,7 @@ count_docs (mongoc_cursor_t *cursor) static void -_test_cursor_new_from_command (const char *cmd_json, - const char *collection_name) +_test_cursor_new_from_command (const char *cmd_json, const char *collection_name) { mongoc_client_t *client; mongoc_collection_t *collection; @@ -963,8 +897,7 @@ _test_cursor_new_from_command (const char *cmd_json, client = test_framework_new_default_client (); collection = mongoc_client_get_collection (client, "test", collection_name); - mongoc_collection_delete_many ( - collection, tmp_bson ("{}"), NULL, NULL, NULL); + mongoc_collection_delete_many (collection, tmp_bson ("{}"), NULL, NULL, NULL); bulk = mongoc_collection_create_bulk_operation_with_opts (collection, NULL); mongoc_bulk_operation_insert (bulk, tmp_bson ("{'_id': 'a'}")); @@ -972,15 +905,13 @@ _test_cursor_new_from_command (const char *cmd_json, r = (0 != mongoc_bulk_operation_execute (bulk, NULL, &error)); ASSERT_OR_PRINT (r, error); - sd = mongoc_topology_select ( - client->topology, MONGOC_SS_READ, NULL, NULL, &error); + sd = mongoc_topology_select (client->topology, MONGOC_SS_READ, NULL, NULL, &error); ASSERT_OR_PRINT (sd, error); server_id = sd->id; - mongoc_client_command_simple_with_server_id ( - client, "test", tmp_bson (cmd_json), NULL, server_id, &reply, &error); - cmd_cursor = mongoc_cursor_new_from_command_reply_with_opts ( - client, &reply, tmp_bson ("{'serverId': %d}", server_id)); + mongoc_client_command_simple_with_server_id (client, "test", tmp_bson (cmd_json), NULL, server_id, &reply, &error); + cmd_cursor = + mongoc_cursor_new_from_command_reply_with_opts (client, &reply, tmp_bson ("{'serverId': %d}", server_id)); ASSERT_OR_PRINT (!mongoc_cursor_error (cmd_cursor, &error), error); ASSERT_CMPUINT32 (server_id, ==, mongoc_cursor_get_hint (cmd_cursor)); ASSERT_CMPINT (count_docs (cmd_cursor), ==, 2); @@ -1002,13 +933,10 @@ test_cursor_empty_collection (void) mongoc_cursor_t *cursor; client = test_framework_new_default_client (); - collection = mongoc_client_get_collection ( - client, "test", "test_cursor_empty_collection"); - mongoc_collection_delete_many ( - collection, tmp_bson ("{}"), NULL, NULL, NULL); + collection = mongoc_client_get_collection (client, "test", "test_cursor_empty_collection"); + mongoc_collection_delete_many (collection, tmp_bson ("{}"), NULL, NULL, NULL); - cursor = mongoc_collection_find_with_opts ( - collection, tmp_bson ("{}"), NULL, NULL); + cursor = mongoc_collection_find_with_opts (collection, tmp_bson ("{}"), NULL, NULL); ASSERT (cursor); ASSERT (!mongoc_cursor_error (cursor, &error)); @@ -1028,20 +956,18 @@ test_cursor_empty_collection (void) static void test_cursor_new_from_aggregate (void) { - _test_cursor_new_from_command ( - "{'aggregate': 'test_cursor_new_from_aggregate'," - " 'pipeline': [], 'cursor': {}}", - "test_cursor_new_from_aggregate"); + _test_cursor_new_from_command ("{'aggregate': 'test_cursor_new_from_aggregate'," + " 'pipeline': [], 'cursor': {}}", + "test_cursor_new_from_aggregate"); } static void test_cursor_new_from_aggregate_no_initial (void) { - _test_cursor_new_from_command ( - "{'aggregate': 'test_cursor_new_from_aggregate_no_initial'," - " 'pipeline': [], 'cursor': {'batchSize': 0}}", - "test_cursor_new_from_aggregate_no_initial"); + _test_cursor_new_from_command ("{'aggregate': 'test_cursor_new_from_aggregate_no_initial'," + " 'pipeline': [], 'cursor': {'batchSize': 0}}", + "test_cursor_new_from_aggregate_no_initial"); } @@ -1050,8 +976,7 @@ test_cursor_new_from_find (void *ctx) { BSON_UNUSED (ctx); - _test_cursor_new_from_command ("{'find': 'test_cursor_new_from_find'}", - "test_cursor_new_from_find"); + _test_cursor_new_from_command ("{'find': 'test_cursor_new_from_find'}", "test_cursor_new_from_find"); } @@ -1060,9 +985,8 @@ test_cursor_new_from_find_batches (void *ctx) { BSON_UNUSED (ctx); - _test_cursor_new_from_command ( - "{'find': 'test_cursor_new_from_find_batches', 'batchSize': 1}", - "test_cursor_new_from_find_batches"); + _test_cursor_new_from_command ("{'find': 'test_cursor_new_from_find_batches', 'batchSize': 1}", + "test_cursor_new_from_find_batches"); } @@ -1079,10 +1003,8 @@ test_cursor_new_invalid (void) cursor = mongoc_cursor_new_from_command_reply_with_opts (client, &b, NULL); ASSERT (cursor); ASSERT (mongoc_cursor_error (cursor, &error)); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_CURSOR, - MONGOC_ERROR_CURSOR_INVALID_CURSOR, - "Couldn't parse cursor document"); + ASSERT_ERROR_CONTAINS ( + error, MONGOC_ERROR_CURSOR, MONGOC_ERROR_CURSOR_INVALID_CURSOR, "Couldn't parse cursor document"); ASSERT (mongoc_cursor_error_document (cursor, &error, &error_doc)); ASSERT (bson_empty (error_doc)); @@ -1106,49 +1028,46 @@ test_cursor_new_tailable_await (void) server = mock_server_with_auto_hello (WIRE_VERSION_MIN); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); // Select a server to get the server_id. // mongoc_cursor_new_from_command_reply_with_opts expects to receive a // serverId when creating an open cursor (non-zero cursor.id) uint32_t server_id; { - mongoc_server_description_t *sd = mongoc_client_select_server ( - client, false /* for_writes */, NULL /* prefs */, &error); + mongoc_server_description_t *sd = + mongoc_client_select_server (client, false /* for_writes */, NULL /* prefs */, &error); ASSERT_OR_PRINT (sd, error); server_id = mongoc_server_description_id (sd); mongoc_server_description_destroy (sd); } - cursor = mongoc_cursor_new_from_command_reply_with_opts ( - client, - bson_copy (tmp_bson ("{'ok': 1," - " 'cursor': {" - " 'id': {'$numberLong': '123'}," - " 'ns': 'db.collection'," - " 'firstBatch': []" - " }," - " 'tailable': true," - " 'awaitData': true," - " 'maxAwaitTimeMS': 100" - "}")), - tmp_bson ("{'tailable': true," - " 'awaitData': true," - " 'maxAwaitTimeMS': 100," - " 'serverId': %" PRIu32 "}", - server_id)); + cursor = mongoc_cursor_new_from_command_reply_with_opts (client, + bson_copy (tmp_bson ("{'ok': 1," + " 'cursor': {" + " 'id': {'$numberLong': '123'}," + " 'ns': 'db.collection'," + " 'firstBatch': []" + " }," + " 'tailable': true," + " 'awaitData': true," + " 'maxAwaitTimeMS': 100" + "}")), + tmp_bson ("{'tailable': true," + " 'awaitData': true," + " 'maxAwaitTimeMS': 100," + " 'serverId': %" PRIu32 "}", + server_id)); ASSERT_OR_PRINT (!mongoc_cursor_error (cursor, &error), error); future = future_cursor_next (cursor, &doc); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db'," - " 'getMore': {'$numberLong': '123'}," - " 'collection': 'collection'," - " 'maxTimeMS': {'$numberLong': '100'}}")); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'db'," + " 'getMore': {'$numberLong': '123'}," + " 'collection': 'collection'," + " 'maxTimeMS': {'$numberLong': '100'}}")); reply_to_op_msg_request (request, MONGOC_MSG_NONE, @@ -1185,16 +1104,15 @@ test_cursor_int64_t_maxtimems (void) server = mock_server_with_auto_hello (WIRE_VERSION_MIN); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); // Select a server to get the server_id. // mongoc_cursor_new_from_command_reply_with_opts expects to receive a // serverId when creating an open cursor (non-zero cursor.id) uint32_t server_id; { - mongoc_server_description_t *sd = mongoc_client_select_server ( - client, false /* for_writes */, NULL /* prefs */, &error); + mongoc_server_description_t *sd = + mongoc_client_select_server (client, false /* for_writes */, NULL /* prefs */, &error); ASSERT_OR_PRINT (sd, error); server_id = mongoc_server_description_id (sd); mongoc_server_description_destroy (sd); @@ -1203,35 +1121,31 @@ test_cursor_int64_t_maxtimems (void) max_await_time_ms = tmp_bson (NULL); bson_append_bool (max_await_time_ms, "tailable", 8, true); bson_append_bool (max_await_time_ms, "awaitData", 9, true); - bson_append_int64 (max_await_time_ms, - MONGOC_CURSOR_MAX_AWAIT_TIME_MS, - MONGOC_CURSOR_MAX_AWAIT_TIME_MS_LEN, - ms_int64); + bson_append_int64 ( + max_await_time_ms, MONGOC_CURSOR_MAX_AWAIT_TIME_MS, MONGOC_CURSOR_MAX_AWAIT_TIME_MS_LEN, ms_int64); ASSERT (bson_in_range_int32_t_unsigned (server_id)); BSON_APPEND_INT32 (max_await_time_ms, "serverId", (uint32_t) server_id); - cursor = mongoc_cursor_new_from_command_reply_with_opts ( - client, - bson_copy (tmp_bson ("{'ok': 1," - " 'cursor': {" - " 'id': {'$numberLong': '123'}," - " 'ns': 'db.collection'," - " 'firstBatch': []" - " }" - "}")), - max_await_time_ms); + cursor = mongoc_cursor_new_from_command_reply_with_opts (client, + bson_copy (tmp_bson ("{'ok': 1," + " 'cursor': {" + " 'id': {'$numberLong': '123'}," + " 'ns': 'db.collection'," + " 'firstBatch': []" + " }" + "}")), + max_await_time_ms); ASSERT_OR_PRINT (!mongoc_cursor_error (cursor, &error), error); future = future_cursor_next (cursor, &doc); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db'," - " 'getMore': {'$numberLong': '123'}," - " 'collection': 'collection'," - " 'maxTimeMS': {'$numberLong': '%" PRIu64 "'}}", - ms_int64)); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'db'," + " 'getMore': {'$numberLong': '123'}," + " 'collection': 'collection'," + " 'maxTimeMS': {'$numberLong': '%" PRIu64 "'}}", + ms_int64)); reply_to_op_msg_request (request, @@ -1265,21 +1179,19 @@ test_cursor_new_ignores_fields (void) server = mock_server_with_auto_hello (WIRE_VERSION_MIN); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); - cursor = mongoc_cursor_new_from_command_reply_with_opts ( - client, - bson_copy (tmp_bson ("{'ok': 1," - " 'cursor': {" - " 'id': 0," - " 'ns': 'test.foo'," - " 'firstBatch': []" - " }," - " 'operationTime' : {}," - " '$clusterTime': {}," - " '$gleStats': {}" - "}")), - tmp_bson ("{'batchSize': 10}")); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + cursor = mongoc_cursor_new_from_command_reply_with_opts (client, + bson_copy (tmp_bson ("{'ok': 1," + " 'cursor': {" + " 'id': 0," + " 'ns': 'test.foo'," + " 'firstBatch': []" + " }," + " 'operationTime' : {}," + " '$clusterTime': {}," + " '$gleStats': {}" + "}")), + tmp_bson ("{'batchSize': 10}")); ASSERT_OR_PRINT (!mongoc_cursor_error (cursor, &error), error); ASSERT_MATCH (&cursor->opts, "{'batchSize': 10}"); @@ -1304,15 +1216,11 @@ test_cursor_new_invalid_filter (void) client = test_framework_new_default_client (); collection = mongoc_client_get_collection (client, "test", "test"); - cursor = mongoc_collection_find_with_opts ( - collection, tmp_bson ("{'': 1}"), NULL, NULL); + cursor = mongoc_collection_find_with_opts (collection, tmp_bson ("{'': 1}"), NULL, NULL); ASSERT (cursor); ASSERT (mongoc_cursor_error (cursor, &error)); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_CURSOR, - MONGOC_ERROR_CURSOR_INVALID_CURSOR, - "Invalid filter: empty key"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_CURSOR, MONGOC_ERROR_CURSOR_INVALID_CURSOR, "Invalid filter: empty key"); ASSERT (mongoc_cursor_error_document (cursor, &error, &error_doc)); ASSERT (bson_empty (error_doc)); @@ -1335,29 +1243,22 @@ test_cursor_new_invalid_opts (void) client = test_framework_new_default_client (); collection = mongoc_client_get_collection (client, "test", "test"); - cursor = mongoc_collection_find_with_opts ( - collection, tmp_bson (NULL), tmp_bson ("{'projection': {'': 1}}"), NULL); + cursor = mongoc_collection_find_with_opts (collection, tmp_bson (NULL), tmp_bson ("{'projection': {'': 1}}"), NULL); ASSERT (cursor); ASSERT (mongoc_cursor_error (cursor, &error)); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_CURSOR, - MONGOC_ERROR_CURSOR_INVALID_CURSOR, - "Invalid opts: empty key"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_CURSOR, MONGOC_ERROR_CURSOR_INVALID_CURSOR, "Invalid opts: empty key"); ASSERT (mongoc_cursor_error_document (cursor, &error, &error_doc)); ASSERT (bson_empty (error_doc)); mongoc_cursor_destroy (cursor); - cursor = mongoc_collection_find_with_opts ( - collection, tmp_bson (NULL), tmp_bson ("{'$invalid': 1}"), NULL); + cursor = mongoc_collection_find_with_opts (collection, tmp_bson (NULL), tmp_bson ("{'$invalid': 1}"), NULL); ASSERT (cursor); ASSERT (mongoc_cursor_error (cursor, &error)); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_CURSOR, - MONGOC_ERROR_CURSOR_INVALID_CURSOR, - "Cannot use $-modifiers in opts: \"$invalid\""); + ASSERT_ERROR_CONTAINS ( + error, MONGOC_ERROR_CURSOR, MONGOC_ERROR_CURSOR_INVALID_CURSOR, "Cannot use $-modifiers in opts: \"$invalid\""); ASSERT (mongoc_cursor_error_document (cursor, &error, &error_doc)); ASSERT (bson_empty (error_doc)); @@ -1385,22 +1286,19 @@ test_cursor_new_static (void) " 'ns': 'test.foo'," " 'firstBatch': [{'x': 1}, {'x': 2}]}}"); - ASSERT (bson_init_static ( - &bson_static, bson_get_data (bson_alloced), bson_alloced->len)); + ASSERT (bson_init_static (&bson_static, bson_get_data (bson_alloced), bson_alloced->len)); /* test heap-allocated bson */ client = test_framework_new_default_client (); bson_copied = bson_copy (bson_alloced); - cursor = mongoc_cursor_new_from_command_reply_with_opts ( - client, bson_copied, NULL); + cursor = mongoc_cursor_new_from_command_reply_with_opts (client, bson_copied, NULL); ASSERT (cursor); ASSERT (!mongoc_cursor_error (cursor, &error)); mongoc_cursor_destroy (cursor); /* test static bson */ - cursor = mongoc_cursor_new_from_command_reply_with_opts ( - client, &bson_static, NULL); + cursor = mongoc_cursor_new_from_command_reply_with_opts (client, &bson_static, NULL); ASSERT (cursor); ASSERT (!mongoc_cursor_error (cursor, &error)); @@ -1418,23 +1316,18 @@ test_cursor_hint_errors (void) client = test_framework_new_default_client (); collection = mongoc_client_get_collection (client, "db", "collection"); - cursor = mongoc_collection_find ( - collection, MONGOC_QUERY_NONE, 0, 0, 0, tmp_bson ("{}"), NULL, NULL); + cursor = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, 0, tmp_bson ("{}"), NULL, NULL); capture_logs (true); ASSERT (!mongoc_cursor_set_hint (cursor, 0)); - ASSERT_CAPTURED_LOG ("mongoc_cursor_set_hint", - MONGOC_LOG_LEVEL_ERROR, - "cannot set server_id to 0"); + ASSERT_CAPTURED_LOG ("mongoc_cursor_set_hint", MONGOC_LOG_LEVEL_ERROR, "cannot set server_id to 0"); capture_logs (true); /* clear logs */ ASSERT (mongoc_cursor_set_hint (cursor, 123)); ASSERT_CMPUINT32 ((uint32_t) 123, ==, mongoc_cursor_get_hint (cursor)); ASSERT_NO_CAPTURED_LOGS ("mongoc_cursor_set_hint"); ASSERT (!mongoc_cursor_set_hint (cursor, 42)); - ASSERT_CAPTURED_LOG ("mongoc_cursor_set_hint", - MONGOC_LOG_LEVEL_ERROR, - "server_id already set"); + ASSERT_CAPTURED_LOG ("mongoc_cursor_set_hint", MONGOC_LOG_LEVEL_ERROR, "server_id already set"); /* last set_hint had no effect */ ASSERT_CMPUINT32 ((uint32_t) 123, ==, mongoc_cursor_get_hint (cursor)); @@ -1456,8 +1349,7 @@ server_id_for_read_mode (mongoc_client_t *client, mongoc_read_mode_t read_mode) uint32_t server_id; prefs = mongoc_read_prefs_new (read_mode); - sd = mongoc_topology_select ( - client->topology, MONGOC_SS_READ, prefs, NULL, &error); + sd = mongoc_topology_select (client->topology, MONGOC_SS_READ, prefs, NULL, &error); ASSERT_OR_PRINT (sd, error); server_id = sd->id; @@ -1488,8 +1380,7 @@ _test_cursor_hint (bool pooled, bool use_primary) mock_rs_run (rs); if (pooled) { - pool = - test_framework_client_pool_new_from_uri (mock_rs_get_uri (rs), NULL); + pool = test_framework_client_pool_new_from_uri (mock_rs_get_uri (rs), NULL); client = mongoc_client_pool_pop (pool); } else { client = test_framework_client_new_from_uri (mock_rs_get_uri (rs), NULL); @@ -1497,8 +1388,7 @@ _test_cursor_hint (bool pooled, bool use_primary) collection = mongoc_client_get_collection (client, "test", "test"); - cursor = mongoc_collection_find ( - collection, MONGOC_QUERY_NONE, 0, 0, 0, q, NULL, NULL); + cursor = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, 0, q, NULL, NULL); ASSERT_CMPUINT32 ((uint32_t) 0, ==, mongoc_cursor_get_hint (cursor)); if (use_primary) { @@ -1511,10 +1401,8 @@ _test_cursor_hint (bool pooled, bool use_primary) ASSERT_CMPUINT32 (server_id, ==, mongoc_cursor_get_hint (cursor)); future = future_cursor_next (cursor, &doc); - request = mock_rs_receives_msg ( - rs, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'test', 'find': 'test', 'filter': {'a': 1}}")); + request = + mock_rs_receives_msg (rs, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'test', 'find': 'test', 'filter': {'a': 1}}")); if (use_primary) { BSON_ASSERT (mock_rs_request_is_to_primary (rs, request)); @@ -1608,14 +1496,12 @@ test_cursor_hint_mongos (void) server = mock_mongos_new (WIRE_VERSION_MIN); mock_server_run (server); mock_server_auto_endsessions (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); collection = mongoc_client_get_collection (client, "test", "test"); for (i = 0; i < sizeof (modes) / sizeof (mongoc_read_mode_t); i++) { prefs = mongoc_read_prefs_new (modes[i]); - cursor = mongoc_collection_find ( - collection, MONGOC_QUERY_NONE, 0, 0, 0, tmp_bson (NULL), NULL, prefs); + cursor = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, 0, tmp_bson (NULL), NULL, prefs); ASSERT_CMPUINT32 ((uint32_t) 0, ==, mongoc_cursor_get_hint (cursor)); ASSERT (mongoc_cursor_set_hint (cursor, 1)); @@ -1623,10 +1509,8 @@ test_cursor_hint_mongos (void) future = future_cursor_next (cursor, &doc); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'test', 'find': 'test', 'filter': {}}")); + request = + mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'test', 'find': 'test', 'filter': {}}")); reply_to_request_simple (request, "{'ok':1," @@ -1663,14 +1547,12 @@ test_cursor_hint_mongos_cmd (void) server = mock_mongos_new (WIRE_VERSION_MIN); mock_server_run (server); mock_server_auto_endsessions (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); collection = mongoc_client_get_collection (client, "test", "test"); for (i = 0; i < sizeof (modes) / sizeof (mongoc_read_mode_t); i++) { prefs = mongoc_read_prefs_new (modes[i]); - cursor = mongoc_collection_find ( - collection, MONGOC_QUERY_NONE, 0, 0, 0, tmp_bson (NULL), NULL, prefs); + cursor = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, 0, tmp_bson (NULL), NULL, prefs); ASSERT_CMPUINT32 ((uint32_t) 0, ==, mongoc_cursor_get_hint (cursor)); ASSERT (mongoc_cursor_set_hint (cursor, 1)); @@ -1678,8 +1560,7 @@ test_cursor_hint_mongos_cmd (void) future = future_cursor_next (cursor, &doc); - request = mock_server_receives_msg ( - server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'test', 'find': 'test'}")); + request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'test', 'find': 'test'}")); reply_to_request_simple (request, "{'ok': 1," @@ -1725,8 +1606,7 @@ _test_cursor_hint_no_warmup (bool pooled) } collection = get_test_collection (client, "test_cursor_hint_no_warmup"); - cursor = mongoc_collection_find ( - collection, MONGOC_QUERY_NONE, 0, 0, 0, q, NULL, NULL); + cursor = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, 0, q, NULL, NULL); /* no chance for topology scan, no server selection */ ASSERT (mongoc_cursor_set_hint (cursor, 1)); @@ -1780,28 +1660,17 @@ test_tailable_alive (void) mongoc_collection_destroy (collection); collection = mongoc_database_create_collection ( - database, - collection_name, - tmp_bson ("{'capped': true, 'size': 10000}"), - &error); + database, collection_name, tmp_bson ("{'capped': true, 'size': 10000}"), &error); ASSERT_OR_PRINT (collection, error); - r = mongoc_collection_insert_one ( - collection, tmp_bson ("{}"), NULL, NULL, &error); + r = mongoc_collection_insert_one (collection, tmp_bson ("{}"), NULL, NULL, &error); ASSERT_OR_PRINT (r, error); /* test mongoc_collection_find and mongoc_collection_find_with_opts */ - cursor = mongoc_collection_find (collection, - MONGOC_QUERY_TAILABLE_CURSOR | - MONGOC_QUERY_AWAIT_DATA, - 0, - 0, - 0, - tmp_bson (NULL), - NULL, - NULL); + cursor = mongoc_collection_find ( + collection, MONGOC_QUERY_TAILABLE_CURSOR | MONGOC_QUERY_AWAIT_DATA, 0, 0, 0, tmp_bson (NULL), NULL, NULL); ASSERT (mongoc_cursor_more (cursor)); ASSERT (mongoc_cursor_next (cursor, &doc)); @@ -1817,10 +1686,7 @@ test_tailable_alive (void) mongoc_cursor_destroy (cursor); cursor = mongoc_collection_find_with_opts ( - collection, - tmp_bson (NULL), - tmp_bson ("{'tailable': true, 'awaitData': true}"), - NULL); + collection, tmp_bson (NULL), tmp_bson ("{'tailable': true, 'awaitData': true}"), NULL); ASSERT (mongoc_cursor_more (cursor)); ASSERT (mongoc_cursor_next (cursor, &doc)); @@ -1847,10 +1713,7 @@ typedef struct { static void -_make_reply_batch (bson_string_t *reply, - uint32_t n_docs, - bool first_batch, - bool finished) +_make_reply_batch (bson_string_t *reply, uint32_t n_docs, bool first_batch, bool finished) { uint32_t j; @@ -1875,9 +1738,7 @@ _make_reply_batch (bson_string_t *reply, static void -_test_cursor_n_return_find_cmd (mongoc_cursor_t *cursor, - mock_server_t *server, - cursor_n_return_test *test) +_test_cursor_n_return_find_cmd (mongoc_cursor_t *cursor, mock_server_t *server, cursor_n_return_test *test) { bson_t find_cmd = BSON_INITIALIZER; bson_t getmore_cmd = BSON_INITIALIZER; @@ -1905,8 +1766,7 @@ _test_cursor_n_return_find_cmd (mongoc_cursor_t *cursor, } future = future_cursor_next (cursor, &doc); - request = mock_server_receives_msg ( - server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db'}")); + request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db'}")); assert_match_bson (request_get_doc (request, 0), &find_cmd, true); @@ -1927,28 +1787,21 @@ _test_cursor_n_return_find_cmd (mongoc_cursor_t *cursor, for (reply_no = 1; reply_no < 3; reply_no++) { /* expect getMore command, send reply_length[reply_no] docs to client */ future = future_cursor_next (cursor, &doc); - request = mock_server_receives_msg ( - server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db'}")); + request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db'}")); bson_reinit (&getmore_cmd); BSON_APPEND_INT64 (&getmore_cmd, "getMore", 123); if (test->expected_n_return[reply_no] && test->batch_size) { - BSON_APPEND_INT64 (&getmore_cmd, - "batchSize", - BSON_ABS (test->expected_n_return[reply_no])); + BSON_APPEND_INT64 (&getmore_cmd, "batchSize", BSON_ABS (test->expected_n_return[reply_no])); } else { - BSON_APPEND_DOCUMENT ( - &getmore_cmd, "batchSize", tmp_bson ("{'$exists': false}")); + BSON_APPEND_DOCUMENT (&getmore_cmd, "batchSize", tmp_bson ("{'$exists': false}")); } assert_match_bson (request_get_doc (request, 0), &getmore_cmd, true); reply = bson_string_new (NULL); cursor_finished = (reply_no == 2); - _make_reply_batch (reply, - (uint32_t) test->reply_length[reply_no], - false, - cursor_finished); + _make_reply_batch (reply, (uint32_t) test->reply_length[reply_no], false, cursor_finished); reply_to_request_simple (request, reply->str); bson_string_free (reply, true); @@ -2026,8 +1879,7 @@ _test_cursor_n_return (bool find_with_opts) mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); collection = mongoc_client_get_collection (client, "db", "coll"); for (i = 0; i < sizeof (tests) / sizeof (cursor_n_return_test); i++) { @@ -2051,8 +1903,7 @@ _test_cursor_n_return (bool find_with_opts) BSON_APPEND_INT64 (&opts, "batchSize", test->batch_size); } - cursor = mongoc_collection_find_with_opts ( - collection, tmp_bson (NULL), &opts, NULL); + cursor = mongoc_collection_find_with_opts (collection, tmp_bson (NULL), &opts, NULL); } else { cursor = mongoc_collection_find (collection, MONGOC_QUERY_NONE, @@ -2107,20 +1958,15 @@ test_empty_final_batch_live (void) mongoc_client_set_error_api (client, 2); collection = get_test_collection (client, "test_empty_final_batch_live"); - mongoc_collection_delete_many ( - collection, tmp_bson ("{}"), NULL, NULL, NULL); + mongoc_collection_delete_many (collection, tmp_bson ("{}"), NULL, NULL, NULL); for (i = 0; i < 3; i++) { - r = mongoc_collection_insert_one ( - collection, tmp_bson ("{}"), NULL, NULL, &error); + r = mongoc_collection_insert_one (collection, tmp_bson ("{}"), NULL, NULL, &error); ASSERT_OR_PRINT (r, error); } - cursor = mongoc_collection_find_with_opts ( - collection, - tmp_bson ("{}"), - tmp_bson ("{'limit': 3, 'batchSize': 3}"), - NULL); + cursor = + mongoc_collection_find_with_opts (collection, tmp_bson ("{}"), tmp_bson ("{'limit': 3, 'batchSize': 3}"), NULL); for (i = 0; i < 3; i++) { ASSERT (mongoc_cursor_next (cursor, &doc)); @@ -2150,21 +1996,16 @@ test_empty_final_batch (void) server = mock_server_with_auto_hello (WIRE_VERSION_MIN); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); collection = mongoc_client_get_collection (client, "db", "coll"); - cursor = mongoc_collection_find_with_opts ( - collection, - tmp_bson ("{}"), - tmp_bson ("{'limit': 1, 'batchSize': 1}"), - NULL); + cursor = + mongoc_collection_find_with_opts (collection, tmp_bson ("{}"), tmp_bson ("{'limit': 1, 'batchSize': 1}"), NULL); /* * one document in first batch */ future = future_cursor_next (cursor, &doc); - request = mock_server_receives_msg ( - server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db'}")); + request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db'}")); reply_to_op_msg_request (request, MONGOC_MSG_NONE, @@ -2182,8 +2023,7 @@ test_empty_final_batch (void) * empty batch with nonzero cursor id */ future = future_cursor_next (cursor, &doc); - request = mock_server_receives_msg ( - server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db'}")); + request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db'}")); reply_to_op_msg_request (request, MONGOC_MSG_NONE, @@ -2202,13 +2042,9 @@ test_empty_final_batch (void) * final batch, empty with zero cursor id */ future = future_cursor_next (cursor, &doc); - request = mock_server_receives_msg ( - server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db'}")); + request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db'}")); - ASSERT_CMPINT64 ( - bson_lookup_int64 (request_get_doc (request, 0), "batchSize"), - ==, - (int64_t) 1); + ASSERT_CMPINT64 (bson_lookup_int64 (request_get_doc (request, 0), "batchSize"), ==, (int64_t) 1); reply_to_op_msg_request (request, MONGOC_MSG_NONE, @@ -2243,15 +2079,13 @@ test_error_document_query (void) client = test_framework_new_default_client (); mongoc_client_set_error_api (client, 2); collection = get_test_collection (client, "test_error_document_query"); - cursor = mongoc_collection_find_with_opts ( - collection, tmp_bson ("{'x': {'$badOperator': 1}}"), NULL, NULL); + cursor = mongoc_collection_find_with_opts (collection, tmp_bson ("{'x': {'$badOperator': 1}}"), NULL, NULL); ASSERT (!mongoc_cursor_next (cursor, &doc)); ASSERT (mongoc_cursor_error_document (cursor, &error, &error_doc)); ASSERT_CMPUINT32 (error.domain, ==, MONGOC_ERROR_SERVER); ASSERT_CONTAINS (error.message, "$badOperator"); - ASSERT_CMPINT32 ( - bson_lookup_int32 (error_doc, "code"), ==, (int32_t) error.code); + ASSERT_CMPINT32 (bson_lookup_int32 (error_doc, "code"), ==, (int32_t) error.code); mongoc_cursor_destroy (cursor); mongoc_collection_destroy (collection); @@ -2285,8 +2119,7 @@ test_error_document_command (void) ASSERT_CMPUINT32 (error.domain, ==, MONGOC_ERROR_SERVER); ASSERT_CONTAINS (error.message, "no such"); - ASSERT_CMPINT32 ( - bson_lookup_int32 (error_doc, "code"), ==, (int32_t) error.code); + ASSERT_CMPINT32 (bson_lookup_int32 (error_doc, "code"), ==, (int32_t) error.code); mongoc_cursor_destroy (cursor); mongoc_client_destroy (client); @@ -2311,14 +2144,12 @@ test_error_document_getmore (void) mongoc_collection_drop (collection, NULL); for (i = 0; i < 10; i++) { - r = mongoc_collection_insert_one ( - collection, tmp_bson ("{'i': %d}", i), NULL, NULL, &error); + r = mongoc_collection_insert_one (collection, tmp_bson ("{'i': %d}", i), NULL, NULL, &error); ASSERT_OR_PRINT (r, error); } - cursor = mongoc_collection_find_with_opts ( - collection, tmp_bson ("{}"), tmp_bson ("{'batchSize': 2}"), NULL); + cursor = mongoc_collection_find_with_opts (collection, tmp_bson ("{}"), tmp_bson ("{'batchSize': 2}"), NULL); ASSERT (mongoc_cursor_next (cursor, &doc)); @@ -2331,15 +2162,11 @@ test_error_document_getmore (void) /* results vary by server version */ if (error.domain == MONGOC_ERROR_CURSOR) { /* MongoDB 3.0 and older */ - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_CURSOR, - MONGOC_ERROR_CURSOR_INVALID_CURSOR, - "cursor is invalid"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_CURSOR, MONGOC_ERROR_CURSOR_INVALID_CURSOR, "cursor is invalid"); } else { /* MongoDB 3.2+ */ ASSERT_CMPUINT32 (error.domain, ==, MONGOC_ERROR_SERVER); - ASSERT_CMPINT32 ( - bson_lookup_int32 (error_doc, "code"), ==, (int32_t) error.code); + ASSERT_CMPINT32 (bson_lookup_int32 (error_doc, "code"), ==, (int32_t) error.code); } mongoc_cursor_destroy (cursor); @@ -2360,20 +2187,11 @@ test_find_error_is_alive (void) const bson_t *bson; client = test_framework_new_default_client (); coll = mongoc_client_get_collection (client, "test", "test"); - cursor = - mongoc_collection_find (coll, - MONGOC_QUERY_NONE, - 0, - 0, - 0, - tmp_bson ("{'$query': {}, 'non_dollar': {}}"), - NULL, - NULL); + cursor = mongoc_collection_find ( + coll, MONGOC_QUERY_NONE, 0, 0, 0, tmp_bson ("{'$query': {}, 'non_dollar': {}}"), NULL, NULL); BSON_ASSERT (mongoc_cursor_error (cursor, &err)); - ASSERT_ERROR_CONTAINS (err, - MONGOC_ERROR_CURSOR, - MONGOC_ERROR_CURSOR_INVALID_CURSOR, - "Cannot mix $query with non-dollar field"); + ASSERT_ERROR_CONTAINS ( + err, MONGOC_ERROR_CURSOR, MONGOC_ERROR_CURSOR_INVALID_CURSOR, "Cannot mix $query with non-dollar field"); BSON_ASSERT (!mongoc_cursor_is_alive (cursor)); BSON_ASSERT (!mongoc_cursor_more (cursor)); BSON_ASSERT (!mongoc_cursor_next (cursor, &bson)); @@ -2390,14 +2208,11 @@ typedef struct _started_event_t { static void command_started (const mongoc_apm_command_started_t *event) { - mongoc_array_t *events = - (mongoc_array_t *) mongoc_apm_command_started_get_context (event); + mongoc_array_t *events = (mongoc_array_t *) mongoc_apm_command_started_get_context (event); started_event_t *started_event = bson_malloc0 (sizeof (started_event_t)); - started_event->command = - bson_copy (mongoc_apm_command_started_get_command (event)); - started_event->command_name = - bson_strdup (mongoc_apm_command_started_get_command_name (event)); + started_event->command = bson_copy (mongoc_apm_command_started_get_command (event)); + started_event->command_name = bson_strdup (mongoc_apm_command_started_get_command_name (event)); _mongoc_array_append_val (events, started_event); } @@ -2405,8 +2220,7 @@ static void clear_started_events (mongoc_array_t *events) { for (size_t i = 0; i < events->len; i++) { - started_event_t *started_event = - _mongoc_array_index (events, started_event_t *, i); + started_event_t *started_event = _mongoc_array_index (events, started_event_t *, i); bson_destroy (started_event->command); bson_free (started_event->command_name); bson_free (started_event); @@ -2430,8 +2244,7 @@ decimal128_iter_eq (bson_iter_t *iter, int64_t val) } void -test_cursor_batchsize_override (bson_t *findopts, - void (*assert_eq) (bson_iter_t *, int64_t)) +test_cursor_batchsize_override (bson_t *findopts, void (*assert_eq) (bson_iter_t *, int64_t)) { mongoc_client_t *client; mongoc_apm_callbacks_t *cbs; @@ -2451,14 +2264,10 @@ test_cursor_batchsize_override (bson_t *findopts, // Ignore "ns not found" error on drop. mongoc_collection_drop (coll, NULL); - ASSERT_OR_PRINT ( - mongoc_collection_insert_one ( - coll, to_insert, NULL /* opts */, NULL /* reply */, &error), - error); - ASSERT_OR_PRINT ( - mongoc_collection_insert_one ( - coll, to_insert, NULL /* opts */, NULL /* reply */, &error), - error); + ASSERT_OR_PRINT (mongoc_collection_insert_one (coll, to_insert, NULL /* opts */, NULL /* reply */, &error), + error); + ASSERT_OR_PRINT (mongoc_collection_insert_one (coll, to_insert, NULL /* opts */, NULL /* reply */, &error), + error); bson_destroy (to_insert); } @@ -2468,8 +2277,7 @@ test_cursor_batchsize_override (bson_t *findopts, { const bson_t *got; bson_t *filter = bson_new (); - mongoc_cursor_t *cursor = mongoc_collection_find_with_opts ( - coll, filter, findopts, NULL /* read_prefs */); + mongoc_cursor_t *cursor = mongoc_collection_find_with_opts (coll, filter, findopts, NULL /* read_prefs */); /* Attempt to overwrite the 'batchSize' with 2. */ mongoc_cursor_set_batch_size (cursor, 2); /* Assert no command started events. The cursor does not send 'find' until @@ -2488,8 +2296,7 @@ test_cursor_batchsize_override (bson_t *findopts, started_event_t *started_event; bson_iter_t iter; /* Expect first event is find. */ - started_event = - _mongoc_array_index (&started_events, started_event_t *, 0); + started_event = _mongoc_array_index (&started_events, started_event_t *, 0); ASSERT_CMPSTR (started_event->command_name, "find"); /* Expect the batchSize sent to be 2. */ ASSERT (bson_iter_init_find (&iter, started_event->command, "batchSize")); @@ -2557,16 +2364,14 @@ test_cursor_batchsize_override_range_warning (void) /* Create a cursor and attempt to override outside int32 range. */ { bson_t *filter = bson_new (); - mongoc_cursor_t *cursor = mongoc_collection_find_with_opts ( - coll, filter, findopts, NULL /* read_prefs */); + mongoc_cursor_t *cursor = mongoc_collection_find_with_opts (coll, filter, findopts, NULL /* read_prefs */); capture_logs (true); /* Attempt to overwrite the 'batchSize' with uint32_max. */ mongoc_cursor_set_batch_size (cursor, UINT32_MAX); - ASSERT_CAPTURED_LOG ( - "mongoc_cursor_set_batch_size", - MONGOC_LOG_LEVEL_WARNING, - "unable to overwrite stored int32 batchSize with out-of-range value"); + ASSERT_CAPTURED_LOG ("mongoc_cursor_set_batch_size", + MONGOC_LOG_LEVEL_WARNING, + "unable to overwrite stored int32 batchSize with out-of-range value"); mongoc_cursor_destroy (cursor); bson_destroy (findopts); @@ -2598,17 +2403,9 @@ test_open_cursor_from_reply (void) // Insert two documents. { - ok = mongoc_collection_insert_one (coll, - tmp_bson ("{'_id': 0}"), - NULL /* opts */, - NULL /* reply */, - &error); + ok = mongoc_collection_insert_one (coll, tmp_bson ("{'_id': 0}"), NULL /* opts */, NULL /* reply */, &error); ASSERT_OR_PRINT (ok, error); - ok = mongoc_collection_insert_one (coll, - tmp_bson ("{'_id': 1}"), - NULL /* opts */, - NULL /* reply */, - &error); + ok = mongoc_collection_insert_one (coll, tmp_bson ("{'_id': 1}"), NULL /* opts */, NULL /* reply */, &error); ASSERT_OR_PRINT (ok, error); } @@ -2618,10 +2415,8 @@ test_open_cursor_from_reply (void) bson_t reply; // Use a smaller batchSize than the number of documents. The smaller // batchSize will result in the cursor being left open on the server. - bson_t *cmd = tmp_bson ("{'find': '%s', 'batchSize': 1}", - mongoc_collection_get_name (coll)); - ok = mongoc_collection_command_simple ( - coll, cmd, NULL /* read_prefs */, &reply, &error); + bson_t *cmd = tmp_bson ("{'find': '%s', 'batchSize': 1}", mongoc_collection_get_name (coll)); + ok = mongoc_collection_command_simple (coll, cmd, NULL /* read_prefs */, &reply, &error); ASSERT_OR_PRINT (ok, error); // Assert that the cursor has a non-zero cursorId. A non-zero cursorId @@ -2636,15 +2431,12 @@ test_open_cursor_from_reply (void) // `reply` is destroyed by // `mongoc_cursor_new_from_command_reply_with_opts`. - cursor = mongoc_cursor_new_from_command_reply_with_opts ( - client, &reply, NULL /* opts */); + cursor = mongoc_cursor_new_from_command_reply_with_opts (client, &reply, NULL /* opts */); // Expect an error to be returned. ASSERT (mongoc_cursor_error (cursor, &error)); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_CURSOR, - MONGOC_ERROR_CURSOR_INVALID_CURSOR, - "Expected `serverId` option"); + ASSERT_ERROR_CONTAINS ( + error, MONGOC_ERROR_CURSOR, MONGOC_ERROR_CURSOR_INVALID_CURSOR, "Expected `serverId` option"); mongoc_cursor_destroy (cursor); } @@ -2654,8 +2446,8 @@ test_open_cursor_from_reply (void) // Get a serverID. uint32_t server_id; { - mongoc_server_description_t *sd = mongoc_client_select_server ( - client, true /* for_writes */, NULL /* read prefs */, &error); + mongoc_server_description_t *sd = + mongoc_client_select_server (client, true /* for_writes */, NULL /* read prefs */, &error); ASSERT_OR_PRINT (sd, error); server_id = mongoc_server_description_id (sd); mongoc_server_description_destroy (sd); @@ -2664,16 +2456,9 @@ test_open_cursor_from_reply (void) bson_t reply; // Use a smaller batchSize than the number of documents. The smaller // batchSize will result in the cursor being left open on the server. - bson_t *cmd = - tmp_bson ("{'find': '%s', 'batchSize': 1, 'sort': {'_id': 1}}", - mongoc_collection_get_name (coll)); + bson_t *cmd = tmp_bson ("{'find': '%s', 'batchSize': 1, 'sort': {'_id': 1}}", mongoc_collection_get_name (coll)); ok = mongoc_collection_command_with_opts ( - coll, - cmd, - NULL /* read_prefs */, - tmp_bson ("{'serverId': %" PRIu32 "}", server_id), - &reply, - &error); + coll, cmd, NULL /* read_prefs */, tmp_bson ("{'serverId': %" PRIu32 "}", server_id), &reply, &error); ASSERT_OR_PRINT (ok, error); // Assert that the cursor has a non-zero cursorId. A non-zero cursorId @@ -2713,8 +2498,8 @@ test_open_cursor_from_reply (void) // Get a serverID. uint32_t server_id; { - mongoc_server_description_t *sd = mongoc_client_select_server ( - client, true /* for_writes */, NULL /* read prefs */, &error); + mongoc_server_description_t *sd = + mongoc_client_select_server (client, true /* for_writes */, NULL /* read prefs */, &error); ASSERT_OR_PRINT (sd, error); server_id = mongoc_server_description_id (sd); mongoc_server_description_destroy (sd); @@ -2723,15 +2508,9 @@ test_open_cursor_from_reply (void) bson_t reply; // Use a smaller batchSize than the number of documents. The smaller // batchSize will result in the cursor being left open on the server. - bson_t *cmd = tmp_bson ("{'find': '%s', 'batchSize': 1}", - mongoc_collection_get_name (coll)); + bson_t *cmd = tmp_bson ("{'find': '%s', 'batchSize': 1}", mongoc_collection_get_name (coll)); ok = mongoc_collection_command_with_opts ( - coll, - cmd, - NULL /* read_prefs */, - tmp_bson ("{'serverId': %" PRIu32 "}", server_id), - &reply, - &error); + coll, cmd, NULL /* read_prefs */, tmp_bson ("{'serverId': %" PRIu32 "}", server_id), &reply, &error); ASSERT_OR_PRINT (ok, error); // Assert that the cursor has a non-zero cursorId. A non-zero cursorId @@ -2766,97 +2545,46 @@ test_cursor_install (TestSuite *suite) "" "/Cursor/kill/live", test_kill_cursor_live); + TestSuite_AddMockServerTest (suite, "/Cursor/kill/single", test_kill_cursors_single); + TestSuite_AddMockServerTest (suite, "/Cursor/kill/pooled", test_kill_cursors_pooled); + TestSuite_AddMockServerTest (suite, "/Cursor/client_kill_cursor/with_primary", test_client_kill_cursor_with_primary); TestSuite_AddMockServerTest ( - suite, "/Cursor/kill/single", test_kill_cursors_single); - TestSuite_AddMockServerTest ( - suite, "/Cursor/kill/pooled", test_kill_cursors_pooled); - TestSuite_AddMockServerTest (suite, - "/Cursor/client_kill_cursor/with_primary", - test_client_kill_cursor_with_primary); - TestSuite_AddMockServerTest (suite, - "/Cursor/client_kill_cursor/without_primary", - test_client_kill_cursor_without_primary); - TestSuite_AddLive ( - suite, "/Cursor/empty_collection", test_cursor_empty_collection); - TestSuite_AddLive ( - suite, "/Cursor/new_from_agg", test_cursor_new_from_aggregate); - TestSuite_AddLive (suite, - "/Cursor/new_from_agg_no_initial", - test_cursor_new_from_aggregate_no_initial); - TestSuite_AddFull (suite, - "/Cursor/new_from_find", - test_cursor_new_from_find, - NULL, - NULL, - TestSuite_CheckLive); - TestSuite_AddFull (suite, - "/Cursor/new_from_find_batches", - test_cursor_new_from_find_batches, - NULL, - NULL, - TestSuite_CheckLive); + suite, "/Cursor/client_kill_cursor/without_primary", test_client_kill_cursor_without_primary); + TestSuite_AddLive (suite, "/Cursor/empty_collection", test_cursor_empty_collection); + TestSuite_AddLive (suite, "/Cursor/new_from_agg", test_cursor_new_from_aggregate); + TestSuite_AddLive (suite, "/Cursor/new_from_agg_no_initial", test_cursor_new_from_aggregate_no_initial); + TestSuite_AddFull (suite, "/Cursor/new_from_find", test_cursor_new_from_find, NULL, NULL, TestSuite_CheckLive); + TestSuite_AddFull ( + suite, "/Cursor/new_from_find_batches", test_cursor_new_from_find_batches, NULL, NULL, TestSuite_CheckLive); TestSuite_AddLive (suite, "/Cursor/new_invalid", test_cursor_new_invalid); - TestSuite_AddMockServerTest ( - suite, "/Cursor/new_tailable_await", test_cursor_new_tailable_await); - TestSuite_AddMockServerTest ( - suite, "/Cursor/int64_t_maxtimems", test_cursor_int64_t_maxtimems); - TestSuite_AddMockServerTest ( - suite, "/Cursor/new_ignores_fields", test_cursor_new_ignores_fields); - TestSuite_AddLive ( - suite, "/Cursor/new_invalid_filter", test_cursor_new_invalid_filter); - TestSuite_AddLive ( - suite, "/Cursor/new_invalid_opts", test_cursor_new_invalid_opts); + TestSuite_AddMockServerTest (suite, "/Cursor/new_tailable_await", test_cursor_new_tailable_await); + TestSuite_AddMockServerTest (suite, "/Cursor/int64_t_maxtimems", test_cursor_int64_t_maxtimems); + TestSuite_AddMockServerTest (suite, "/Cursor/new_ignores_fields", test_cursor_new_ignores_fields); + TestSuite_AddLive (suite, "/Cursor/new_invalid_filter", test_cursor_new_invalid_filter); + TestSuite_AddLive (suite, "/Cursor/new_invalid_opts", test_cursor_new_invalid_opts); TestSuite_AddLive (suite, "/Cursor/new_static", test_cursor_new_static); TestSuite_AddLive (suite, "/Cursor/hint/errors", test_cursor_hint_errors); - TestSuite_AddMockServerTest ( - suite, "/Cursor/hint/single/secondary", test_hint_single_secondary); - TestSuite_AddMockServerTest ( - suite, "/Cursor/hint/single/primary", test_hint_single_primary); - TestSuite_AddMockServerTest ( - suite, "/Cursor/hint/pooled/secondary", test_hint_pooled_secondary); - TestSuite_AddMockServerTest ( - suite, "/Cursor/hint/pooled/primary", test_hint_pooled_primary); - TestSuite_AddMockServerTest ( - suite, "/Cursor/hint/mongos", test_cursor_hint_mongos); - TestSuite_AddMockServerTest ( - suite, "/Cursor/hint/mongos/cmd", test_cursor_hint_mongos_cmd); - TestSuite_AddLive ( - suite, "/Cursor/hint/no_warmup/single", test_hint_no_warmup_single); - TestSuite_AddLive ( - suite, "/Cursor/hint/no_warmup/pooled", test_hint_no_warmup_pooled); + TestSuite_AddMockServerTest (suite, "/Cursor/hint/single/secondary", test_hint_single_secondary); + TestSuite_AddMockServerTest (suite, "/Cursor/hint/single/primary", test_hint_single_primary); + TestSuite_AddMockServerTest (suite, "/Cursor/hint/pooled/secondary", test_hint_pooled_secondary); + TestSuite_AddMockServerTest (suite, "/Cursor/hint/pooled/primary", test_hint_pooled_primary); + TestSuite_AddMockServerTest (suite, "/Cursor/hint/mongos", test_cursor_hint_mongos); + TestSuite_AddMockServerTest (suite, "/Cursor/hint/mongos/cmd", test_cursor_hint_mongos_cmd); + TestSuite_AddLive (suite, "/Cursor/hint/no_warmup/single", test_hint_no_warmup_single); + TestSuite_AddLive (suite, "/Cursor/hint/no_warmup/pooled", test_hint_no_warmup_pooled); TestSuite_AddLive (suite, "/Cursor/tailable/alive", test_tailable_alive); - TestSuite_AddMockServerTest ( - suite, "/Cursor/n_return/find_cmd", test_n_return_find_cmd); - TestSuite_AddMockServerTest (suite, - "/Cursor/n_return/find_cmd/with_opts", - test_n_return_find_cmd_with_opts); - TestSuite_AddLive ( - suite, "/Cursor/empty_final_batch_live", test_empty_final_batch_live); - TestSuite_AddMockServerTest ( - suite, "/Cursor/empty_final_batch", test_empty_final_batch); - TestSuite_AddLive ( - suite, "/Cursor/error_document/query", test_error_document_query); - TestSuite_AddLive ( - suite, "/Cursor/error_document/getmore", test_error_document_getmore); - TestSuite_AddLive ( - suite, "/Cursor/error_document/command", test_error_document_command); - TestSuite_AddLive ( - suite, "/Cursor/find_error/is_alive", test_find_error_is_alive); - TestSuite_AddLive (suite, - "/Cursor/batchsize_override_int32", - test_cursor_batchsize_override_int32); - TestSuite_AddLive (suite, - "/Cursor/batchsize_override_int64", - test_cursor_batchsize_override_int64); - TestSuite_AddLive (suite, - "/Cursor/batchsize_override_double", - test_cursor_batchsize_override_double); - TestSuite_AddLive (suite, - "/Cursor/batchsize_override_decimal128", - test_cursor_batchsize_override_decimal128); - TestSuite_AddLive (suite, - "/Cursor/batchsize_override_range_warning", - test_cursor_batchsize_override_range_warning); - TestSuite_AddLive ( - suite, "/Cursor/open_cursor_from_reply", test_open_cursor_from_reply); + TestSuite_AddMockServerTest (suite, "/Cursor/n_return/find_cmd", test_n_return_find_cmd); + TestSuite_AddMockServerTest (suite, "/Cursor/n_return/find_cmd/with_opts", test_n_return_find_cmd_with_opts); + TestSuite_AddLive (suite, "/Cursor/empty_final_batch_live", test_empty_final_batch_live); + TestSuite_AddMockServerTest (suite, "/Cursor/empty_final_batch", test_empty_final_batch); + TestSuite_AddLive (suite, "/Cursor/error_document/query", test_error_document_query); + TestSuite_AddLive (suite, "/Cursor/error_document/getmore", test_error_document_getmore); + TestSuite_AddLive (suite, "/Cursor/error_document/command", test_error_document_command); + TestSuite_AddLive (suite, "/Cursor/find_error/is_alive", test_find_error_is_alive); + TestSuite_AddLive (suite, "/Cursor/batchsize_override_int32", test_cursor_batchsize_override_int32); + TestSuite_AddLive (suite, "/Cursor/batchsize_override_int64", test_cursor_batchsize_override_int64); + TestSuite_AddLive (suite, "/Cursor/batchsize_override_double", test_cursor_batchsize_override_double); + TestSuite_AddLive (suite, "/Cursor/batchsize_override_decimal128", test_cursor_batchsize_override_decimal128); + TestSuite_AddLive (suite, "/Cursor/batchsize_override_range_warning", test_cursor_batchsize_override_range_warning); + TestSuite_AddLive (suite, "/Cursor/open_cursor_from_reply", test_open_cursor_from_reply); } diff --git a/src/libmongoc/tests/test-mongoc-cyrus.c b/src/libmongoc/tests/test-mongoc-cyrus.c index 3d5c67aebb..cc5c42ed64 100644 --- a/src/libmongoc/tests/test-mongoc-cyrus.c +++ b/src/libmongoc/tests/test-mongoc-cyrus.c @@ -28,9 +28,8 @@ test_sasl_properties (void) mongoc_uri_t *uri; mongoc_cyrus_t sasl; - uri = mongoc_uri_new ( - "mongodb://user@host/?authMechanism=GSSAPI&" - "authMechanismProperties=SERVICE_NAME:sn,CANONICALIZE_HOST_NAME:TrUe"); + uri = mongoc_uri_new ("mongodb://user@host/?authMechanism=GSSAPI&" + "authMechanismProperties=SERVICE_NAME:sn,CANONICALIZE_HOST_NAME:TrUe"); BSON_ASSERT (uri); memset (&sasl, 0, sizeof sasl); @@ -43,15 +42,13 @@ test_sasl_properties (void) capture_logs (true); /* authMechanismProperties take precedence */ - uri = mongoc_uri_new ( - "mongodb://user@host/?authMechanism=GSSAPI&" - "canonicalizeHostname=true&gssapiServiceName=blah&" - "authMechanismProperties=SERVICE_NAME:sn,CANONICALIZE_HOST_NAME:False"); + uri = mongoc_uri_new ("mongodb://user@host/?authMechanism=GSSAPI&" + "canonicalizeHostname=true&gssapiServiceName=blah&" + "authMechanismProperties=SERVICE_NAME:sn,CANONICALIZE_HOST_NAME:False"); - ASSERT_CAPTURED_LOG ( - "authMechanismProperties should overwrite gssapiServiceName", - MONGOC_LOG_LEVEL_WARNING, - "Overwriting previously provided value for 'authmechanismproperties'"); + ASSERT_CAPTURED_LOG ("authMechanismProperties should overwrite gssapiServiceName", + MONGOC_LOG_LEVEL_WARNING, + "Overwriting previously provided value for 'authmechanismproperties'"); _mongoc_cyrus_destroy (&sasl); memset (&sasl, 0, sizeof sasl); @@ -76,12 +73,10 @@ test_sasl_canonicalize_hostname (void *ctx) BSON_UNUSED (ctx); client = test_framework_new_default_client (); - ss = mongoc_cluster_stream_for_reads ( - &client->cluster, NULL, NULL, NULL, NULL, &error); + ss = mongoc_cluster_stream_for_reads (&client->cluster, NULL, NULL, NULL, NULL, &error); ASSERT_OR_PRINT (ss, error); - BSON_ASSERT (_mongoc_sasl_get_canonicalized_name ( - ss->stream, real_name, sizeof real_name)); + BSON_ASSERT (_mongoc_sasl_get_canonicalized_name (ss->stream, real_name, sizeof real_name)); ASSERT_CMPSIZE_T (strlen (real_name), >, (size_t) 0); diff --git a/src/libmongoc/tests/test-mongoc-database.c b/src/libmongoc/tests/test-mongoc-database.c index 51797a11c9..466c053a22 100644 --- a/src/libmongoc/tests/test-mongoc-database.c +++ b/src/libmongoc/tests/test-mongoc-database.c @@ -33,22 +33,10 @@ test_aggregate_inherit_database (void) server = mock_server_with_auto_hello (WIRE_VERSION_MAX); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); database = mongoc_client_get_database (client, "admin"); - pipeline = BCON_NEW ("pipeline", - "[", - "{", - "$currentOp", - "{", - "}", - "}", - "{", - "$out", - BCON_UTF8 ("ops"), - "}", - "]"); + pipeline = BCON_NEW ("pipeline", "[", "{", "$currentOp", "{", "}", "}", "{", "$out", BCON_UTF8 ("ops"), "}", "]"); rc = mongoc_read_concern_new (); mongoc_read_concern_set_level (rc, MONGOC_READ_CONCERN_LEVEL_MAJORITY); @@ -62,16 +50,15 @@ test_aggregate_inherit_database (void) cursor = mongoc_database_aggregate (database, pipeline, &opts, NULL); future = future_cursor_next (cursor, &doc); - request = mock_server_receives_msg ( - server, - MONGOC_QUERY_NONE, - tmp_bson ("{ 'aggregate' : 1," - " 'pipeline' : [ { '$currentOp': { } }, { '$out' : 'ops' } ]," - " 'cursor' : { }," - " '$db' : 'admin'," - " '$readPreference' : { '$exists': false }," - " 'readConcern' : { 'level' : 'majority' }," - " 'writeConcern' : { 'w' : 2 } }")); + request = mock_server_receives_msg (server, + MONGOC_QUERY_NONE, + tmp_bson ("{ 'aggregate' : 1," + " 'pipeline' : [ { '$currentOp': { } }, { '$out' : 'ops' } ]," + " 'cursor' : { }," + " '$db' : 'admin'," + " '$readPreference' : { '$exists': false }," + " 'readConcern' : { 'level' : 'majority' }," + " 'writeConcern' : { 'w' : 2 } }")); reply_to_request_simple (request, "{'ok': 1}"); @@ -93,16 +80,15 @@ test_aggregate_inherit_database (void) cursor = mongoc_database_aggregate (database, pipeline, NULL, NULL); future = future_cursor_next (cursor, &doc); - request = mock_server_receives_msg ( - server, - MONGOC_QUERY_NONE, - tmp_bson ("{ 'aggregate' : 1," - " 'pipeline' : [ { '$currentOp': { } }, { '$out' : 'ops' } ]," - " 'cursor' : { }," - " '$db' : 'admin'," - " '$readPreference' : { '$exists': false }," - " 'readConcern' : { 'level' : 'local' }," - " 'writeConcern' : { 'w' : 3 } }")); + request = mock_server_receives_msg (server, + MONGOC_QUERY_NONE, + tmp_bson ("{ 'aggregate' : 1," + " 'pipeline' : [ { '$currentOp': { } }, { '$out' : 'ops' } ]," + " 'cursor' : { }," + " '$db' : 'admin'," + " '$readPreference' : { '$exists': false }," + " 'readConcern' : { 'level' : 'local' }," + " 'writeConcern' : { 'w' : 3 } }")); reply_to_request_simple (request, "{'ok': 1}"); @@ -116,16 +102,15 @@ test_aggregate_inherit_database (void) cursor = mongoc_database_aggregate (database, pipeline, &opts, NULL); future = future_cursor_next (cursor, &doc); - request = mock_server_receives_msg ( - server, - MONGOC_QUERY_NONE, - tmp_bson ("{ 'aggregate' : 1," - " 'pipeline' : [ { '$currentOp': { } }, { '$out' : 'ops' } ]," - " 'cursor' : { }," - " '$db' : 'admin'," - " '$readPreference' : { '$exists': false }," - " 'readConcern' : { 'level' : 'majority' }," - " 'writeConcern' : { 'w' : 2 } }")); + request = mock_server_receives_msg (server, + MONGOC_QUERY_NONE, + tmp_bson ("{ 'aggregate' : 1," + " 'pipeline' : [ { '$currentOp': { } }, { '$out' : 'ops' } ]," + " 'cursor' : { }," + " '$db' : 'admin'," + " '$readPreference' : { '$exists': false }," + " 'readConcern' : { 'level' : 'majority' }," + " 'writeConcern' : { 'w' : 2 } }")); reply_to_request_simple (request, "{'ok': 1}"); @@ -142,16 +127,15 @@ test_aggregate_inherit_database (void) cursor = mongoc_database_aggregate (database, pipeline, NULL, NULL); future = future_cursor_next (cursor, &doc); - request = mock_server_receives_msg ( - server, - MONGOC_QUERY_NONE, - tmp_bson ("{ 'aggregate' : 1," - " 'pipeline' : [ { '$currentOp': { } } ]," - " 'cursor' : { }," - " '$db' : 'admin'," - " '$readPreference' : { '$exists': false }," - " 'readConcern' : { 'level' : 'local' }," - " 'writeConcern' : { '$exists' : false } }")); + request = mock_server_receives_msg (server, + MONGOC_QUERY_NONE, + tmp_bson ("{ 'aggregate' : 1," + " 'pipeline' : [ { '$currentOp': { } } ]," + " 'cursor' : { }," + " '$db' : 'admin'," + " '$readPreference' : { '$exists': false }," + " 'readConcern' : { 'level' : 'local' }," + " 'writeConcern' : { '$exists' : false } }")); reply_to_request_simple (request, "{'ok': 1}"); ASSERT (!future_get_bool (future)); @@ -207,12 +191,8 @@ test_create_with_write_concern (void *ctx) bad_wc->wtimeout = -10; bson_reinit (opts); mongoc_write_concern_append_bad (bad_wc, opts); - collection = - mongoc_database_create_collection (database, name, opts, &error); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Invalid writeConcern"); + collection = mongoc_database_create_collection (database, name, opts, &error); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid writeConcern"); ASSERT (!collection); bad_wc->wtimeout = 0; error.code = 0; @@ -222,8 +202,7 @@ test_create_with_write_concern (void *ctx) mongoc_write_concern_set_w (good_wc, 1); bson_reinit (opts); mongoc_write_concern_append (good_wc, opts); - collection = - mongoc_database_create_collection (database, name, opts, &error); + collection = mongoc_database_create_collection (database, name, opts, &error); ASSERT_OR_PRINT (collection, error); ASSERT (!error.code); ASSERT (!error.domain); @@ -237,8 +216,7 @@ test_create_with_write_concern (void *ctx) if (!test_framework_is_mongos ()) { /* skip if sharded */ bson_reinit (opts); mongoc_write_concern_append_bad (bad_wc, opts); - collection = - mongoc_database_create_collection (database, name, opts, &error); + collection = mongoc_database_create_collection (database, name, opts, &error); ASSERT (!collection); assert_wc_oob_error (&error); @@ -303,8 +281,7 @@ test_has_collection (void) bson_oid_init (&oid, NULL); bson_append_oid (&b, "_id", 3, &oid); bson_append_utf8 (&b, "hello", 5, "world", 5); - ASSERT_OR_PRINT ( - mongoc_collection_insert_one (collection, &b, NULL, NULL, &error), error); + ASSERT_OR_PRINT (mongoc_collection_insert_one (collection, &b, NULL, NULL, &error), error); bson_destroy (&b); r = mongoc_database_has_collection (database, name, &error); @@ -340,8 +317,7 @@ test_command (void) */ bson_append_int32 (&cmd, "ping", 4, 1); - cursor = mongoc_database_command ( - database, MONGOC_QUERY_NONE, 0, 1, 0, &cmd, NULL, NULL); + cursor = mongoc_database_command (database, MONGOC_QUERY_NONE, 0, 1, 0, &cmd, NULL, NULL); BSON_ASSERT (cursor); r = mongoc_cursor_next (cursor, &doc); @@ -395,12 +371,10 @@ _test_db_command_read_prefs (bool simple, bool pooled) mock_server_auto_endsessions (server); if (pooled) { - pool = test_framework_client_pool_new_from_uri ( - mock_server_get_uri (server), NULL); + pool = test_framework_client_pool_new_from_uri (mock_server_get_uri (server), NULL); client = mongoc_client_pool_pop (pool); } else { - client = test_framework_client_new_from_uri (mock_server_get_uri (server), - NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); } db = mongoc_client_get_database (client, "db"); @@ -412,8 +386,7 @@ _test_db_command_read_prefs (bool simple, bool pooled) /* simple, without read preference */ future = future_database_command_simple (db, cmd, NULL, NULL, &error); - request = mock_server_receives_msg ( - server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', 'foo': 1}")); + request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', 'foo': 1}")); reply_to_request_simple (request, "{'ok': 1}"); ASSERT_OR_PRINT (future_get_bool (future), error); @@ -421,26 +394,22 @@ _test_db_command_read_prefs (bool simple, bool pooled) request_destroy (request); /* with read preference */ - future = - future_database_command_simple (db, cmd, secondary_pref, NULL, &error); - - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db'," - " 'foo': 1," - " '$readPreference': {'mode': 'secondary'}}")); + future = future_database_command_simple (db, cmd, secondary_pref, NULL, &error); + + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'db'," + " 'foo': 1," + " '$readPreference': {'mode': 'secondary'}}")); reply_to_request_simple (request, "{'ok': 1}"); ASSERT_OR_PRINT (future_get_bool (future), error); future_destroy (future); request_destroy (request); } else { /* not simple, no read preference */ - cursor = mongoc_database_command ( - db, MONGOC_QUERY_NONE, 0, 0, 0, cmd, NULL, NULL); + cursor = mongoc_database_command (db, MONGOC_QUERY_NONE, 0, 0, 0, cmd, NULL, NULL); future = future_cursor_next (cursor, &reply); - request = mock_server_receives_msg ( - server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', 'foo': 1}")); + request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', 'foo': 1}")); reply_to_request_simple (request, "{'ok': 1}"); ASSERT (future_get_bool (future)); @@ -449,15 +418,13 @@ _test_db_command_read_prefs (bool simple, bool pooled) mongoc_cursor_destroy (cursor); /* with read preference */ - cursor = mongoc_database_command ( - db, MONGOC_QUERY_NONE, 0, 0, 0, cmd, NULL, secondary_pref); + cursor = mongoc_database_command (db, MONGOC_QUERY_NONE, 0, 0, 0, cmd, NULL, secondary_pref); future = future_cursor_next (cursor, &reply); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db'," - " 'foo': 1," - " '$readPreference': {'mode': 'secondary'}}")); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'db'," + " 'foo': 1," + " '$readPreference': {'mode': 'secondary'}}")); reply_to_request_simple (request, "{'ok': 1}"); ASSERT (future_get_bool (future)); @@ -535,8 +502,7 @@ test_drop (void) /* MongoDB 3.2+ must create at least one replicated database before * dropDatabase will check writeConcern, see SERVER-25601 */ collection = mongoc_database_get_collection (database, "collection"); - r = mongoc_collection_insert_one ( - collection, tmp_bson ("{}"), NULL, NULL, &error); + r = mongoc_collection_insert_one (collection, tmp_bson ("{}"), NULL, NULL, &error); ASSERT_OR_PRINT (r, error); @@ -553,10 +519,7 @@ test_drop (void) bson_reinit (opts); mongoc_write_concern_append_bad (bad_wc, opts); ASSERT (!mongoc_database_drop_with_opts (database, opts, &error)); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Invalid writeConcern"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid writeConcern"); bad_wc->wtimeout = 0; error.code = 0; error.domain = 0; @@ -566,8 +529,7 @@ test_drop (void) bson_reinit (opts); mongoc_write_concern_append (good_wc, opts); - ASSERT_OR_PRINT (mongoc_database_drop_with_opts (database, opts, &error), - error); + ASSERT_OR_PRINT (mongoc_database_drop_with_opts (database, opts, &error), error); BSON_ASSERT (!error.code); BSON_ASSERT (!error.domain); @@ -629,9 +591,7 @@ test_create_collection (void) name = gen_collection_name ("create_collection"); - ASSERT_OR_PRINT (collection = mongoc_database_create_collection ( - database, name, &options, &error), - error); + ASSERT_OR_PRINT (collection = mongoc_database_create_collection (database, name, &options, &error), error); bson_destroy (&options); bson_free (name); @@ -681,13 +641,11 @@ test_get_collection_info (void) noopts_name = gen_collection_name ("noopts"); - collection = mongoc_database_create_collection ( - database, capped_name, &capped_options, &error); + collection = mongoc_database_create_collection (database, capped_name, &capped_options, &error); ASSERT_OR_PRINT (collection, error); mongoc_collection_destroy (collection); - collection = mongoc_database_create_collection ( - database, noopts_name, &noopts_options, &error); + collection = mongoc_database_create_collection (database, noopts_name, &noopts_options, &error); ASSERT_OR_PRINT (collection, error); mongoc_collection_destroy (collection); @@ -706,9 +664,7 @@ test_get_collection_info (void) BSON_ASSERT (!error.code); while (mongoc_cursor_next (cursor, &doc)) { - if (bson_iter_init (&col_iter, doc) && - bson_iter_find (&col_iter, "name") && - BSON_ITER_HOLDS_UTF8 (&col_iter) && + if (bson_iter_init (&col_iter, doc) && bson_iter_find (&col_iter, "name") && BSON_ITER_HOLDS_UTF8 (&col_iter) && (name = bson_iter_utf8 (&col_iter, NULL))) { ++num_infos; BSON_ASSERT (0 == strcmp (name, noopts_name)); @@ -756,13 +712,11 @@ test_get_collection_info_regex (void) database = mongoc_client_get_database (client, dbname); mongoc_database_drop_with_opts (database, NULL, NULL); - collection = - mongoc_database_create_collection (database, "abbbc", NULL, &error); + collection = mongoc_database_create_collection (database, "abbbc", NULL, &error); ASSERT_OR_PRINT (collection, error); mongoc_collection_destroy (collection); - collection = - mongoc_database_create_collection (database, "foo", NULL, &error); + collection = mongoc_database_create_collection (database, "foo", NULL, &error); ASSERT_OR_PRINT (collection, error); BSON_APPEND_REGEX (&name_filter, "name", "ab+c", NULL); @@ -812,13 +766,11 @@ test_get_collection_info_with_opts_regex (void) database = mongoc_client_get_database (client, dbname); mongoc_database_drop_with_opts (database, NULL, NULL); - collection = - mongoc_database_create_collection (database, "abbbc", NULL, &error); + collection = mongoc_database_create_collection (database, "abbbc", NULL, &error); ASSERT_OR_PRINT (collection, error); mongoc_collection_destroy (collection); - collection = - mongoc_database_create_collection (database, "foo", NULL, &error); + collection = mongoc_database_create_collection (database, "foo", NULL, &error); ASSERT_OR_PRINT (collection, error); BSON_APPEND_DOCUMENT_BEGIN (&opts, "filter", &name_filter); @@ -859,16 +811,12 @@ _test_get_collection_info_getmore (void) server = mock_server_with_auto_hello (WIRE_VERSION_MIN); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); database = mongoc_client_get_database (client, "db"); - future = - future_database_get_collection_names_with_opts (database, NULL, NULL); + future = future_database_get_collection_names_with_opts (database, NULL, NULL); request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db', 'listCollections': 1, 'nameOnly': true}")); + server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', 'listCollections': 1, 'nameOnly': true}")); reply_to_request_simple (request, "{'ok': 1," @@ -877,12 +825,11 @@ _test_get_collection_info_getmore (void) " 'ns': 'db.$cmd.listCollections'," " 'firstBatch': [{'name': 'a'}]}}"); request_destroy (request); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db'," - " 'getMore': {'$numberLong': '123'}," - " 'collection': '$cmd.listCollections'}")); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'db'," + " 'getMore': {'$numberLong': '123'}," + " 'collection': '$cmd.listCollections'}")); reply_to_request_simple (request, "{'ok': 1," @@ -988,28 +935,23 @@ test_get_collection_names (void) name4 = gen_collection_name ("name4"); name5 = gen_collection_name ("name5"); - collection = - mongoc_database_create_collection (database, name1, &options, &error); + collection = mongoc_database_create_collection (database, name1, &options, &error); BSON_ASSERT (collection); mongoc_collection_destroy (collection); - collection = - mongoc_database_create_collection (database, name2, &options, &error); + collection = mongoc_database_create_collection (database, name2, &options, &error); BSON_ASSERT (collection); mongoc_collection_destroy (collection); - collection = - mongoc_database_create_collection (database, name3, &options, &error); + collection = mongoc_database_create_collection (database, name3, &options, &error); BSON_ASSERT (collection); mongoc_collection_destroy (collection); - collection = - mongoc_database_create_collection (database, name4, &options, &error); + collection = mongoc_database_create_collection (database, name4, &options, &error); BSON_ASSERT (collection); mongoc_collection_destroy (collection); - collection = - mongoc_database_create_collection (database, name5, &options, &error); + collection = mongoc_database_create_collection (database, name5, &options, &error); BSON_ASSERT (collection); mongoc_collection_destroy (collection); @@ -1019,11 +961,9 @@ test_get_collection_names (void) /* ensure that if users happen to pass nameOnly in opts we don't * append it again and cause a "duplicate field" server error */ if (explicit_nameonly) { - names = mongoc_database_get_collection_names_with_opts ( - database, tmp_bson ("{'nameOnly': true}"), &error); + names = mongoc_database_get_collection_names_with_opts (database, tmp_bson ("{'nameOnly': true}"), &error); } else { - names = mongoc_database_get_collection_names_with_opts ( - database, NULL, &error); + names = mongoc_database_get_collection_names_with_opts (database, NULL, &error); } BSON_ASSERT (!error.domain); BSON_ASSERT (!error.code); @@ -1032,12 +972,10 @@ test_get_collection_names (void) /* 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)) { + 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))) { + } else if (0 == strncmp (curname, system_prefix, strlen (system_prefix))) { /* Collections prefixed with 'system.' are system collections */ } else { BSON_ASSERT (false); @@ -1092,12 +1030,9 @@ test_get_collection_names_error (void) client = test_framework_client_new_from_uri (uri, NULL); database = mongoc_client_get_database (client, "test"); - future = - future_database_get_collection_names_with_opts (database, NULL, &error); + future = future_database_get_collection_names_with_opts (database, NULL, &error); request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'test', 'listCollections': 1, 'nameOnly': true}")); + server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'test', 'listCollections': 1, 'nameOnly': true}")); reply_to_request_with_hang_up (request); names = future_get_char_ptr_ptr (future); BSON_ASSERT (!names); @@ -1117,8 +1052,7 @@ static void test_get_default_database (void) { /* default database is "db_name" */ - mongoc_client_t *client = - test_framework_client_new ("mongodb://host/db_name", NULL); + mongoc_client_t *client = test_framework_client_new ("mongodb://host/db_name", NULL); mongoc_database_t *db = mongoc_client_get_default_database (client); BSON_ASSERT (!strcmp ("db_name", mongoc_database_get_name (db))); @@ -1138,50 +1072,26 @@ test_get_default_database (void) void test_database_install (TestSuite *suite) { - TestSuite_AddMockServerTest (suite, - "/Database/aggregate/inherit/database", - test_aggregate_inherit_database); - TestSuite_AddFull (suite, - "/Database/create_with_write_concern", - test_create_with_write_concern, - NULL, - NULL, - TestSuite_CheckLive); + TestSuite_AddMockServerTest (suite, "/Database/aggregate/inherit/database", test_aggregate_inherit_database); + TestSuite_AddFull ( + suite, "/Database/create_with_write_concern", test_create_with_write_concern, NULL, NULL, TestSuite_CheckLive); TestSuite_AddLive (suite, "/Database/copy", test_copy); TestSuite_AddLive (suite, "/Database/has_collection", test_has_collection); TestSuite_AddLive (suite, "/Database/command", test_command); - TestSuite_AddMockServerTest (suite, - "/Database/command/read_prefs/simple/single", - test_db_command_simple_read_prefs_single); - TestSuite_AddMockServerTest (suite, - "/Database/command/read_prefs/simple/pooled", - test_db_command_simple_read_prefs_pooled); - TestSuite_AddMockServerTest (suite, - "/Database/command/read_prefs/single", - test_db_command_read_prefs_single); - TestSuite_AddMockServerTest (suite, - "/Database/command/read_prefs/pooled", - test_db_command_read_prefs_pooled); + TestSuite_AddMockServerTest ( + suite, "/Database/command/read_prefs/simple/single", test_db_command_simple_read_prefs_single); + TestSuite_AddMockServerTest ( + suite, "/Database/command/read_prefs/simple/pooled", test_db_command_simple_read_prefs_pooled); + TestSuite_AddMockServerTest (suite, "/Database/command/read_prefs/single", test_db_command_read_prefs_single); + TestSuite_AddMockServerTest (suite, "/Database/command/read_prefs/pooled", test_db_command_read_prefs_pooled); TestSuite_AddLive (suite, "/Database/drop", test_drop); - TestSuite_AddLive ( - suite, "/Database/create_collection", test_create_collection); - TestSuite_AddLive ( - suite, "/Database/get_collection_info", test_get_collection_info); - TestSuite_AddLive (suite, - "/Database/get_collection_info_regex", - test_get_collection_info_regex); - TestSuite_AddLive (suite, - "/Database/get_collection_info_with_opts_regex", - test_get_collection_info_with_opts_regex); - TestSuite_AddMockServerTest (suite, - "/Database/get_collection/getmore_cmd", - test_get_collection_info_getmore_cmd); + TestSuite_AddLive (suite, "/Database/create_collection", test_create_collection); + TestSuite_AddLive (suite, "/Database/get_collection_info", test_get_collection_info); + TestSuite_AddLive (suite, "/Database/get_collection_info_regex", test_get_collection_info_regex); + TestSuite_AddLive (suite, "/Database/get_collection_info_with_opts_regex", test_get_collection_info_with_opts_regex); + TestSuite_AddMockServerTest (suite, "/Database/get_collection/getmore_cmd", test_get_collection_info_getmore_cmd); TestSuite_AddLive (suite, "/Database/get_collection", test_get_collection); - TestSuite_AddLive ( - suite, "/Database/get_collection_names", test_get_collection_names); - TestSuite_AddMockServerTest (suite, - "/Database/get_collection_names_error", - test_get_collection_names_error); - TestSuite_Add ( - suite, "/Database/get_default_database", test_get_default_database); + TestSuite_AddLive (suite, "/Database/get_collection_names", test_get_collection_names); + TestSuite_AddMockServerTest (suite, "/Database/get_collection_names_error", test_get_collection_names_error); + TestSuite_Add (suite, "/Database/get_default_database", test_get_default_database); } diff --git a/src/libmongoc/tests/test-mongoc-dns.c b/src/libmongoc/tests/test-mongoc-dns.c index 7820b85926..3a55eb1ae7 100644 --- a/src/libmongoc/tests/test-mongoc-dns.c +++ b/src/libmongoc/tests/test-mongoc-dns.c @@ -42,10 +42,8 @@ _assert_options_match (const bson_t *test, mongoc_uri_t *uri) while (bson_iter_next (&test_opts_iter)) { opt_name = bson_iter_key (&test_opts_iter); opt_name_canon = mongoc_uri_canonicalize_option (opt_name); - opts_or_creds = !bson_strcasecmp (opt_name, "authSource") ? creds_from_uri - : opts_from_uri; - if (!bson_iter_init_find_case ( - &uri_opts_iter, opts_or_creds, opt_name_canon)) { + opts_or_creds = !bson_strcasecmp (opt_name, "authSource") ? creds_from_uri : opts_from_uri; + if (!bson_iter_init_find_case (&uri_opts_iter, opts_or_creds, opt_name_canon)) { test_error ("URI options incorrectly set from TXT record: " "no option named \"%s\"\n" "expected: %s\n" @@ -94,8 +92,7 @@ topology_changed (const mongoc_apm_topology_changed_t *event) _mongoc_host_list_destroy_all (ctx->hosts); ctx->hosts = NULL; for (i = 0; i < n; i++) { - ctx->hosts = _mongoc_host_list_push ( - sds[i]->host.host, sds[i]->host.port, AF_UNSPEC, ctx->hosts); + ctx->hosts = _mongoc_host_list_push (sds[i]->host.host, sds[i]->host.port, AF_UNSPEC, ctx->hosts); } bson_mutex_unlock (&ctx->mutex); @@ -186,10 +183,9 @@ typedef struct { const char *reason; } skipped_dns_test_t; -skipped_dns_test_t SKIPPED_DNS_TESTS[] = { - {"mongodb+srv://test5.test.build.10gen.cc/?authSource=otherDB", - "C driver requires username present if any auth fields are present"}, - {0}}; +skipped_dns_test_t SKIPPED_DNS_TESTS[] = {{"mongodb+srv://test5.test.build.10gen.cc/?authSource=otherDB", + "C driver requires username present if any auth fields are present"}, + {0}}; static bool is_test_skipped (const char *uri_str) @@ -198,8 +194,7 @@ is_test_skipped (const char *uri_str) for (skip = SKIPPED_DNS_TESTS; skip->uri_str != NULL; skip++) { if (!strcmp (skip->uri_str, uri_str)) { - MONGOC_DEBUG ( - "Skipping test of URI: %s Reason: %s", skip->uri_str, skip->reason); + MONGOC_DEBUG ("Skipping test of URI: %s Reason: %s", skip->uri_str, skip->reason); return true; } } @@ -225,9 +220,8 @@ _test_dns_maybe_pooled (bson_t *test, bool pooled) const char *uri_str; if (!test_framework_get_ssl ()) { - test_error ( - "Must configure an SSL replica set and set MONGOC_TEST_SSL=on " - "and other ssl options to test DNS"); + test_error ("Must configure an SSL replica set and set MONGOC_TEST_SSL=on " + "and other ssl options to test DNS"); } uri_str = bson_lookup_utf8 (test, "uri"); @@ -276,9 +270,7 @@ _test_dns_maybe_pooled (bson_t *test, bool pooled) /* before we set SSL on so that we can connect to the test replica set, * assert that the URI has SSL on by default, and SSL off if "ssl=false" * is in the URI string */ - BSON_ASSERT ( - mongoc_uri_get_tls (_mongoc_client_pool_get_topology (pool)->uri) == - expect_ssl); + BSON_ASSERT (mongoc_uri_get_tls (_mongoc_client_pool_get_topology (pool)->uri) == expect_ssl); #ifdef MONGOC_ENABLE_SSL mongoc_client_pool_set_ssl_opts (pool, &ssl_opts); #else @@ -317,13 +309,9 @@ _test_dns_maybe_pooled (bson_t *test, bool pooled) if (n_hosts > 0 && !expect_error) { WAIT_UNTIL (_host_list_matches (test, &ctx)); } else { - r = mongoc_client_command_simple ( - client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); + r = mongoc_client_command_simple (client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); BSON_ASSERT (!r); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_SERVER_SELECTION, - MONGOC_ERROR_SERVER_SELECTION_FAILURE, - ""); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_SERVER_SELECTION, MONGOC_ERROR_SERVER_SELECTION_FAILURE, ""); } } else if (NULL == mongoc_uri_get_username (uri)) { /* Skip single-threaded tests containing auth credentials. Monitoring @@ -331,18 +319,13 @@ _test_dns_maybe_pooled (bson_t *test, bool pooled) * not correspond to the test users. TODO (CDRIVER-4046): unskip these * tests. */ if (n_hosts > 0 && !expect_error) { - r = mongoc_client_command_simple ( - client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); + r = mongoc_client_command_simple (client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); ASSERT_OR_PRINT (r, error); WAIT_UNTIL (_host_list_matches (test, &ctx)); } else { - r = mongoc_client_command_simple ( - client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); + r = mongoc_client_command_simple (client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); BSON_ASSERT (!r); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_SERVER_SELECTION, - MONGOC_ERROR_SERVER_SELECTION_FAILURE, - ""); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_SERVER_SELECTION, MONGOC_ERROR_SERVER_SELECTION_FAILURE, ""); } } @@ -353,16 +336,12 @@ _test_dns_maybe_pooled (bson_t *test, bool pooled) _assert_options_match (test, client->topology->uri); /* the client has a copy of the topology's URI, assert they're the same */ - ASSERT (bson_equal (mongoc_uri_get_options (client->uri), - mongoc_uri_get_options (client->topology->uri))); - ASSERT (bson_equal (mongoc_uri_get_credentials (client->uri), - mongoc_uri_get_credentials (client->topology->uri))); + ASSERT (bson_equal (mongoc_uri_get_options (client->uri), mongoc_uri_get_options (client->topology->uri))); + ASSERT (bson_equal (mongoc_uri_get_credentials (client->uri), mongoc_uri_get_credentials (client->topology->uri))); if (!mongoc_uri_get_hosts (client->uri)) { ASSERT (!mongoc_uri_get_hosts (client->topology->uri)); } else { - _mongoc_host_list_compare_one ( - mongoc_uri_get_hosts (client->uri), - mongoc_uri_get_hosts (client->topology->uri)); + _mongoc_host_list_compare_one (mongoc_uri_get_hosts (client->uri), mongoc_uri_get_hosts (client->topology->uri)); } if (pooled) { @@ -415,31 +394,28 @@ test_dns_check_srv_polling (void) static void test_all_spec_tests (TestSuite *suite) { - install_json_test_suite_with_check ( - suite, - JSON_DIR, - "initial_dns_seedlist_discovery/replica-set", - test_dns, - test_dns_check_replset, - test_framework_skip_if_no_crypto); - - install_json_test_suite_with_check ( - suite, - JSON_DIR, - "initial_dns_seedlist_discovery/load-balanced", - test_dns, - test_dns_check_loadbalanced, - test_framework_skip_if_no_crypto); - - install_json_test_suite_with_check ( - suite, - JSON_DIR, - "initial_dns_seedlist_discovery/sharded", - test_dns, - /* Topology of load-balancer tests satisfy topology requirements of - * sharded tests, even though a load balancer is not required. */ - test_dns_check_loadbalanced, - test_framework_skip_if_no_crypto); + install_json_test_suite_with_check (suite, + JSON_DIR, + "initial_dns_seedlist_discovery/replica-set", + test_dns, + test_dns_check_replset, + test_framework_skip_if_no_crypto); + + install_json_test_suite_with_check (suite, + JSON_DIR, + "initial_dns_seedlist_discovery/load-balanced", + test_dns, + test_dns_check_loadbalanced, + test_framework_skip_if_no_crypto); + + install_json_test_suite_with_check (suite, + JSON_DIR, + "initial_dns_seedlist_discovery/sharded", + test_dns, + /* Topology of load-balancer tests satisfy topology requirements of + * sharded tests, even though a load balancer is not required. */ + test_dns_check_loadbalanced, + test_framework_skip_if_no_crypto); } extern bool @@ -497,8 +473,7 @@ dump_topology_description (const mongoc_topology_description_t *td) } static void -check_topology_description (mongoc_topology_description_t *td, - mongoc_host_list_t *hosts) +check_topology_description (mongoc_topology_description_t *td, mongoc_host_list_t *hosts) { size_t nhosts = 0u; mongoc_host_list_t *host; @@ -510,14 +485,12 @@ check_topology_description (mongoc_topology_description_t *td, /* Check that "host" is already in the topology description by upserting * it, and ensuring that the number of servers remains constant. */ const size_t server_count = servers->items_len; - BSON_ASSERT (mongoc_topology_description_add_server ( - td, host->host_and_port, NULL)); + BSON_ASSERT (mongoc_topology_description_add_server (td, host->host_and_port, NULL)); if (server_count != servers->items_len) { dump_topology_description (td); dump_hosts (hosts); - test_error ("topology description did not have host: %s", - host->host_and_port); + test_error ("topology description did not have host: %s", host->host_and_port); } } @@ -555,8 +528,7 @@ test_srv_polling_mocked (void *unused) /* Add an extra host. */ hosts = MAKE_HOSTS ("x.test.com", "a.test.com", "y.test.com", "b.test.com"); - expected = - MAKE_HOSTS ("x.test.com", "a.test.com", "y.test.com", "b.test.com"); + expected = MAKE_HOSTS ("x.test.com", "a.test.com", "y.test.com", "b.test.com"); ret = mongoc_topology_apply_scanned_srv_hosts (uri, &td, hosts, &error); ASSERT_OR_PRINT (ret, error); check_topology_description (&td, expected); @@ -590,10 +562,8 @@ test_srv_polling_mocked (void *unused) expected = MAKE_HOSTS ("x.test.com", "y.test.com"); ret = mongoc_topology_apply_scanned_srv_hosts (uri, &td, NULL, &error); BSON_ASSERT (!ret); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_NAME_RESOLUTION, - "SRV response did not contain any valid hosts"); + ASSERT_ERROR_CONTAINS ( + error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_NAME_RESOLUTION, "SRV response did not contain any valid hosts"); check_topology_description (&td, expected); _mongoc_host_list_destroy_all (expected); ASSERT_CAPTURED_LOG ("topology", MONGOC_LOG_LEVEL_ERROR, "Invalid host"); @@ -604,10 +574,8 @@ test_srv_polling_mocked (void *unused) expected = MAKE_HOSTS ("x.test.com", "y.test.com"); ret = mongoc_topology_apply_scanned_srv_hosts (uri, &td, NULL, &error); BSON_ASSERT (!ret); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_NAME_RESOLUTION, - "SRV response did not contain any valid hosts"); + ASSERT_ERROR_CONTAINS ( + error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_NAME_RESOLUTION, "SRV response did not contain any valid hosts"); check_topology_description (&td, expected); _mongoc_host_list_destroy_all (expected); _mongoc_host_list_destroy_all (hosts); @@ -632,11 +600,7 @@ test_small_initial_buffer (void *unused) memset (&rr_data, 0, sizeof (rr_data)); ASSERT_OR_PRINT ( - _mongoc_client_get_rr ("_mongodb._tcp.test1.test.build.10gen.cc", - rr_type, - &rr_data, - small_buffer_size, - &error), + _mongoc_client_get_rr ("_mongodb._tcp.test1.test.build.10gen.cc", rr_type, &rr_data, small_buffer_size, &error), error); ASSERT_CMPINT (rr_data.count, ==, 2); bson_free (rr_data.txt_record_opts); @@ -668,8 +632,7 @@ _prose_test_ping (mongoc_client_t *client) ASSERT (client); - if (!mongoc_client_command_simple ( - client, "admin", cmd, NULL, NULL, &error)) { + if (!mongoc_client_command_simple (client, "admin", cmd, NULL, NULL, &error)) { test_error ("ping failed: %s", error.message); } @@ -680,8 +643,7 @@ _prose_test_ping (mongoc_client_t *client) #define RESCAN_INTERVAL_MS 500 static void * -_prose_test_init_resource_single (const mongoc_uri_t *uri, - _mongoc_rr_resolver_fn fn) +_prose_test_init_resource_single (const mongoc_uri_t *uri, _mongoc_rr_resolver_fn fn) { mongoc_client_t *client; mongoc_topology_t *topology; @@ -693,8 +655,7 @@ _prose_test_init_resource_single (const mongoc_uri_t *uri, topology = client->topology; _mongoc_topology_set_rr_resolver (topology, fn); - _mongoc_topology_set_srv_polling_rescan_interval_ms (topology, - RESCAN_INTERVAL_MS); + _mongoc_topology_set_srv_polling_rescan_interval_ms (topology, RESCAN_INTERVAL_MS); #if defined(MONGOC_ENABLE_SSL) { @@ -708,8 +669,7 @@ _prose_test_init_resource_single (const mongoc_uri_t *uri, } static void * -_prose_test_init_resource_pooled (const mongoc_uri_t *uri, - _mongoc_rr_resolver_fn fn) +_prose_test_init_resource_pooled (const mongoc_uri_t *uri, _mongoc_rr_resolver_fn fn) { mongoc_client_pool_t *pool; mongoc_topology_t *topology; @@ -721,8 +681,7 @@ _prose_test_init_resource_pooled (const mongoc_uri_t *uri, topology = _mongoc_client_pool_get_topology (pool); _mongoc_topology_set_rr_resolver (topology, fn); - _mongoc_topology_set_srv_polling_rescan_interval_ms (topology, - RESCAN_INTERVAL_MS); + _mongoc_topology_set_srv_polling_rescan_interval_ms (topology, RESCAN_INTERVAL_MS); #if defined(MONGOC_ENABLE_SSL) { @@ -789,8 +748,7 @@ _prose_test_update_srv_single (void *resource) _mongoc_usleep (2000 * RESCAN_INTERVAL_MS); /* Avoid ping given `loadBalanced=true`; see prose test 9. */ - if (!mongoc_uri_get_option_as_bool ( - client->uri, MONGOC_URI_LOADBALANCED, false)) { + if (!mongoc_uri_get_option_as_bool (client->uri, MONGOC_URI_LOADBALANCED, false)) { _prose_test_ping (client); } } @@ -811,19 +769,17 @@ typedef struct { void (*update_srv) (void *); } _prose_test_fns_t; -static const _prose_test_fns_t _prose_test_single_fns = { - _prose_test_init_resource_single, - _prose_test_free_resource_single, - _prose_test_get_client_single, - _prose_test_release_client_single, - _prose_test_update_srv_single}; +static const _prose_test_fns_t _prose_test_single_fns = {_prose_test_init_resource_single, + _prose_test_free_resource_single, + _prose_test_get_client_single, + _prose_test_release_client_single, + _prose_test_update_srv_single}; -static const _prose_test_fns_t _prose_test_pooled_fns = { - _prose_test_init_resource_pooled, - _prose_test_free_resource_pooled, - _prose_test_get_client_pooled, - _prose_test_release_client_pooled, - _prose_test_update_srv_pooled}; +static const _prose_test_fns_t _prose_test_pooled_fns = {_prose_test_init_resource_pooled, + _prose_test_free_resource_pooled, + _prose_test_get_client_pooled, + _prose_test_release_client_pooled, + _prose_test_update_srv_pooled}; static void _prose_test_9 (const _prose_test_fns_t *fns) @@ -833,12 +789,10 @@ _prose_test_9 (const _prose_test_fns_t *fns) BSON_ASSERT_PARAM (fns); { - mongoc_uri_t *const uri = - mongoc_uri_new ("mongodb+srv://test3.test.build.10gen.cc"); + mongoc_uri_t *const uri = mongoc_uri_new ("mongodb+srv://test3.test.build.10gen.cc"); mongoc_uri_set_option_as_bool (uri, MONGOC_URI_LOADBALANCED, true); - mongoc_uri_set_option_as_int32 ( - uri, MONGOC_URI_HEARTBEATFREQUENCYMS, RESCAN_INTERVAL_MS); + mongoc_uri_set_option_as_int32 (uri, MONGOC_URI_HEARTBEATFREQUENCYMS, RESCAN_INTERVAL_MS); resource = fns->init_resource (uri, _mock_rr_resolver_prose_test_9); @@ -846,8 +800,7 @@ _prose_test_9 (const _prose_test_fns_t *fns) } { - mongoc_host_list_t *const expected = - MAKE_HOSTS ("localhost.test.build.10gen.cc:27017"); + mongoc_host_list_t *const expected = MAKE_HOSTS ("localhost.test.build.10gen.cc:27017"); mongoc_client_t *const client = fns->get_client (resource); { @@ -863,8 +816,7 @@ _prose_test_9 (const _prose_test_fns_t *fns) fns->update_srv (resource); { - mongoc_host_list_t *const expected = - MAKE_HOSTS ("localhost.test.build.10gen.cc:27017"); + mongoc_host_list_t *const expected = MAKE_HOSTS ("localhost.test.build.10gen.cc:27017"); mongoc_client_t *const client = fns->get_client (resource); { @@ -934,12 +886,10 @@ _prose_test_10 (const _prose_test_fns_t *fns) BSON_ASSERT_PARAM (fns); { - mongoc_uri_t *const uri = - mongoc_uri_new ("mongodb+srv://test1.test.build.10gen.cc"); + mongoc_uri_t *const uri = mongoc_uri_new ("mongodb+srv://test1.test.build.10gen.cc"); mongoc_uri_set_option_as_int32 (uri, MONGOC_URI_SRVMAXHOSTS, 0); - mongoc_uri_set_option_as_int32 ( - uri, MONGOC_URI_HEARTBEATFREQUENCYMS, RESCAN_INTERVAL_MS); + mongoc_uri_set_option_as_int32 (uri, MONGOC_URI_HEARTBEATFREQUENCYMS, RESCAN_INTERVAL_MS); resource = fns->init_resource (uri, _mock_rr_resolver_prose_test_10); @@ -948,8 +898,7 @@ _prose_test_10 (const _prose_test_fns_t *fns) { mongoc_host_list_t *const expected = - MAKE_HOSTS ("localhost.test.build.10gen.cc:27017", - "localhost.test.build.10gen.cc:27018"); + MAKE_HOSTS ("localhost.test.build.10gen.cc:27017", "localhost.test.build.10gen.cc:27018"); mongoc_client_t *const client = fns->get_client (resource); { @@ -965,10 +914,9 @@ _prose_test_10 (const _prose_test_fns_t *fns) fns->update_srv (resource); { - mongoc_host_list_t *const expected = - MAKE_HOSTS ("localhost.test.build.10gen.cc:27017", - "localhost.test.build.10gen.cc:27019", - "localhost.test.build.10gen.cc:27020"); + mongoc_host_list_t *const expected = MAKE_HOSTS ("localhost.test.build.10gen.cc:27017", + "localhost.test.build.10gen.cc:27019", + "localhost.test.build.10gen.cc:27020"); mongoc_client_t *const client = fns->get_client (resource); { @@ -1017,8 +965,7 @@ _mock_rr_resolver_prose_test_11 (const char *service, const size_t count = _mongoc_host_list_length (rr_data->hosts); BSON_ASSERT (bson_in_range_unsigned (uint32_t, count)); - rr_data->hosts = MAKE_HOSTS ("localhost.test.build.10gen.cc:27019", - "localhost.test.build.10gen.cc:27020"); + rr_data->hosts = MAKE_HOSTS ("localhost.test.build.10gen.cc:27019", "localhost.test.build.10gen.cc:27020"); rr_data->count = (uint32_t) count; rr_data->min_ttl = 0u; rr_data->txt_record_opts = NULL; @@ -1037,12 +984,10 @@ _prose_test_11 (const _prose_test_fns_t *fns) BSON_ASSERT_PARAM (fns); { - mongoc_uri_t *const uri = - mongoc_uri_new ("mongodb+srv://test1.test.build.10gen.cc"); + mongoc_uri_t *const uri = mongoc_uri_new ("mongodb+srv://test1.test.build.10gen.cc"); mongoc_uri_set_option_as_int32 (uri, MONGOC_URI_SRVMAXHOSTS, 2); - mongoc_uri_set_option_as_int32 ( - uri, MONGOC_URI_HEARTBEATFREQUENCYMS, RESCAN_INTERVAL_MS); + mongoc_uri_set_option_as_int32 (uri, MONGOC_URI_HEARTBEATFREQUENCYMS, RESCAN_INTERVAL_MS); resource = fns->init_resource (uri, _mock_rr_resolver_prose_test_11); @@ -1051,8 +996,7 @@ _prose_test_11 (const _prose_test_fns_t *fns) { mongoc_host_list_t *const expected = - MAKE_HOSTS ("localhost.test.build.10gen.cc:27017", - "localhost.test.build.10gen.cc:27018"); + MAKE_HOSTS ("localhost.test.build.10gen.cc:27017", "localhost.test.build.10gen.cc:27018"); mongoc_client_t *const client = fns->get_client (resource); { @@ -1069,8 +1013,7 @@ _prose_test_11 (const _prose_test_fns_t *fns) { mongoc_host_list_t *const expected = - MAKE_HOSTS ("localhost.test.build.10gen.cc:27019", - "localhost.test.build.10gen.cc:27020"); + MAKE_HOSTS ("localhost.test.build.10gen.cc:27019", "localhost.test.build.10gen.cc:27020"); mongoc_client_t *const client = fns->get_client (resource); { @@ -1173,12 +1116,10 @@ _prose_test_12 (const _prose_test_fns_t *fns) BSON_ASSERT_PARAM (fns); { - mongoc_uri_t *const uri = - mongoc_uri_new ("mongodb+srv://test1.test.build.10gen.cc"); + mongoc_uri_t *const uri = mongoc_uri_new ("mongodb+srv://test1.test.build.10gen.cc"); mongoc_uri_set_option_as_int32 (uri, MONGOC_URI_SRVMAXHOSTS, 2); - mongoc_uri_set_option_as_int32 ( - uri, MONGOC_URI_HEARTBEATFREQUENCYMS, RESCAN_INTERVAL_MS); + mongoc_uri_set_option_as_int32 (uri, MONGOC_URI_HEARTBEATFREQUENCYMS, RESCAN_INTERVAL_MS); resource = fns->init_resource (uri, _mock_rr_resolver_prose_test_12); @@ -1187,8 +1128,7 @@ _prose_test_12 (const _prose_test_fns_t *fns) { mongoc_host_list_t *const expected = - MAKE_HOSTS ("localhost.test.build.10gen.cc:27017", - "localhost.test.build.10gen.cc:27018"); + MAKE_HOSTS ("localhost.test.build.10gen.cc:27017", "localhost.test.build.10gen.cc:27018"); mongoc_client_t *const client = fns->get_client (resource); { @@ -1217,15 +1157,11 @@ _prose_test_12 (const _prose_test_fns_t *fns) mc_tpld_modify_drop (tdmod); } + ASSERT_WITH_MSG (ctx.num_existing > 0u, "hosts that have not changed must be left alone and unchanged"); ASSERT_WITH_MSG ( - ctx.num_existing > 0u, - "hosts that have not changed must be left alone and unchanged"); - ASSERT_WITH_MSG (ctx.num_existing == 1u, - "only a single host should have remained, but found %zu", - ctx.num_existing); + ctx.num_existing == 1u, "only a single host should have remained, but found %zu", ctx.num_existing); - ASSERT_WITH_MSG (ctx.num_new_valid == 1u, - "exactly one valid new hosts should have been added"); + ASSERT_WITH_MSG (ctx.num_new_valid == 1u, "exactly one valid new hosts should have been added"); fns->release_client (resource, client); } @@ -1253,12 +1189,8 @@ void test_dns_install (TestSuite *suite) { test_all_spec_tests (suite); - TestSuite_AddFull (suite, - "/initial_dns_seedlist_discovery/srv_polling/mocked", - test_srv_polling_mocked, - NULL, - NULL, - NULL); + TestSuite_AddFull ( + suite, "/initial_dns_seedlist_discovery/srv_polling/mocked", test_srv_polling_mocked, NULL, NULL, NULL); TestSuite_AddFull (suite, "/initial_dns_seedlist_discovery/small_initial_buffer", test_small_initial_buffer, @@ -1270,67 +1202,59 @@ test_dns_install (TestSuite *suite) * of the SRV polling tests, since they are defined in the "Polling SRV * Records for mongos Discovery" spec, not the "Initial DNS Seedlist * Discovery" spec. */ - TestSuite_AddFull ( - suite, - "/initial_dns_seedlist_discovery/srv_polling/prose_test_9/single", - prose_test_9_single, - NULL, - NULL, - test_dns_check_srv_polling); + TestSuite_AddFull (suite, + "/initial_dns_seedlist_discovery/srv_polling/prose_test_9/single", + prose_test_9_single, + NULL, + NULL, + test_dns_check_srv_polling); - TestSuite_AddFull ( - suite, - "/initial_dns_seedlist_discovery/srv_polling/prose_test_9/pooled", - prose_test_9_pooled, - NULL, - NULL, - test_dns_check_srv_polling); + TestSuite_AddFull (suite, + "/initial_dns_seedlist_discovery/srv_polling/prose_test_9/pooled", + prose_test_9_pooled, + NULL, + NULL, + test_dns_check_srv_polling); - TestSuite_AddFull ( - suite, - "/initial_dns_seedlist_discovery/srv_polling/prose_test_10/single", - prose_test_10_single, - NULL, - NULL, - test_dns_check_srv_polling); + TestSuite_AddFull (suite, + "/initial_dns_seedlist_discovery/srv_polling/prose_test_10/single", + prose_test_10_single, + NULL, + NULL, + test_dns_check_srv_polling); - TestSuite_AddFull ( - suite, - "/initial_dns_seedlist_discovery/srv_polling/prose_test_10/pooled", - prose_test_10_pooled, - NULL, - NULL, - test_dns_check_srv_polling); + TestSuite_AddFull (suite, + "/initial_dns_seedlist_discovery/srv_polling/prose_test_10/pooled", + prose_test_10_pooled, + NULL, + NULL, + test_dns_check_srv_polling); - TestSuite_AddFull ( - suite, - "/initial_dns_seedlist_discovery/srv_polling/prose_test_11/single", - prose_test_11_single, - NULL, - NULL, - test_dns_check_srv_polling); + TestSuite_AddFull (suite, + "/initial_dns_seedlist_discovery/srv_polling/prose_test_11/single", + prose_test_11_single, + NULL, + NULL, + test_dns_check_srv_polling); - TestSuite_AddFull ( - suite, - "/initial_dns_seedlist_discovery/srv_polling/prose_test_11/pooled", - prose_test_11_pooled, - NULL, - NULL, - test_dns_check_srv_polling); + TestSuite_AddFull (suite, + "/initial_dns_seedlist_discovery/srv_polling/prose_test_11/pooled", + prose_test_11_pooled, + NULL, + NULL, + test_dns_check_srv_polling); - TestSuite_AddFull ( - suite, - "/initial_dns_seedlist_discovery/srv_polling/prose_test_12/single", - prose_test_12_single, - NULL, - NULL, - test_dns_check_srv_polling); + TestSuite_AddFull (suite, + "/initial_dns_seedlist_discovery/srv_polling/prose_test_12/single", + prose_test_12_single, + NULL, + NULL, + test_dns_check_srv_polling); - TestSuite_AddFull ( - suite, - "/initial_dns_seedlist_discovery/srv_polling/prose_test_12/pooled", - prose_test_12_pooled, - NULL, - NULL, - test_dns_check_srv_polling); + TestSuite_AddFull (suite, + "/initial_dns_seedlist_discovery/srv_polling/prose_test_12/pooled", + prose_test_12_pooled, + NULL, + NULL, + test_dns_check_srv_polling); } diff --git a/src/libmongoc/tests/test-mongoc-error.c b/src/libmongoc/tests/test-mongoc-error.c index 032b7e413f..9c90175306 100644 --- a/src/libmongoc/tests/test-mongoc-error.c +++ b/src/libmongoc/tests/test-mongoc-error.c @@ -25,9 +25,7 @@ test_set_error_api_single (void) for (i = 0; i < sizeof (unsupported_versions) / sizeof (int32_t); i++) { ASSERT (!mongoc_client_set_error_api (client, unsupported_versions[i])); - ASSERT_CAPTURED_LOG ("mongoc_client_set_error_api", - MONGOC_LOG_LEVEL_ERROR, - "Unsupported Error API Version"); + ASSERT_CAPTURED_LOG ("mongoc_client_set_error_api", MONGOC_LOG_LEVEL_ERROR, "Unsupported Error API Version"); } mongoc_client_destroy (client); @@ -46,18 +44,14 @@ test_set_error_api_pooled (void) pool = test_framework_new_default_client_pool (); for (i = 0; i < sizeof (unsupported_versions) / sizeof (int32_t); i++) { - ASSERT ( - !mongoc_client_pool_set_error_api (pool, unsupported_versions[i])); - ASSERT_CAPTURED_LOG ("mongoc_client_pool_set_error_api", - MONGOC_LOG_LEVEL_ERROR, - "Unsupported Error API Version"); + ASSERT (!mongoc_client_pool_set_error_api (pool, unsupported_versions[i])); + ASSERT_CAPTURED_LOG ("mongoc_client_pool_set_error_api", MONGOC_LOG_LEVEL_ERROR, "Unsupported Error API Version"); } client = mongoc_client_pool_pop (pool); ASSERT (!mongoc_client_set_error_api (client, 1)); - ASSERT_CAPTURED_LOG ("mongoc_client_set_error_api", - MONGOC_LOG_LEVEL_ERROR, - "Cannot set Error API Version on a pooled client"); + ASSERT_CAPTURED_LOG ( + "mongoc_client_set_error_api", MONGOC_LOG_LEVEL_ERROR, "Cannot set Error API Version on a pooled client"); mongoc_client_pool_push (pool, client); mongoc_client_pool_destroy (pool); @@ -76,17 +70,14 @@ _test_command_error (int32_t error_api_version) server = mock_server_with_auto_hello (WIRE_VERSION_MIN); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); if (error_api_version != 0) { BSON_ASSERT (mongoc_client_set_error_api (client, error_api_version)); } - future = future_client_command_simple ( - client, "db", tmp_bson ("{'foo': 1}"), NULL, &reply, &error); - request = mock_server_receives_msg ( - server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', 'foo': 1}")); + future = future_client_command_simple (client, "db", tmp_bson ("{'foo': 1}"), NULL, &reply, &error); + request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', 'foo': 1}")); reply_to_request_simple (request, "{'ok': 0, 'code': 42, 'errmsg': 'foo'}"); ASSERT (!future_get_bool (future)); @@ -139,18 +130,14 @@ test_state_change_helper (uint32_t domain, bool expect_error) { bson_error_t error; mongoc_server_err_t not_primary_codes[] = { - MONGOC_SERVER_ERR_NOTPRIMARY, - MONGOC_SERVER_ERR_NOTPRIMARYNOSECONDARYOK, - MONGOC_SERVER_ERR_LEGACYNOTPRIMARY}; - mongoc_server_err_t node_is_recovering_codes[] = { - MONGOC_SERVER_ERR_INTERRUPTEDATSHUTDOWN, - MONGOC_SERVER_ERR_INTERRUPTEDDUETOREPLSTATECHANGE, - MONGOC_SERVER_ERR_NOTPRIMARYORSECONDARY, - MONGOC_SERVER_ERR_PRIMARYSTEPPEDDOWN, - MONGOC_SERVER_ERR_SHUTDOWNINPROGRESS}; - mongoc_server_err_t shutdown_codes[] = { - MONGOC_SERVER_ERR_INTERRUPTEDATSHUTDOWN, - MONGOC_SERVER_ERR_SHUTDOWNINPROGRESS}; + MONGOC_SERVER_ERR_NOTPRIMARY, MONGOC_SERVER_ERR_NOTPRIMARYNOSECONDARYOK, MONGOC_SERVER_ERR_LEGACYNOTPRIMARY}; + mongoc_server_err_t node_is_recovering_codes[] = {MONGOC_SERVER_ERR_INTERRUPTEDATSHUTDOWN, + MONGOC_SERVER_ERR_INTERRUPTEDDUETOREPLSTATECHANGE, + MONGOC_SERVER_ERR_NOTPRIMARYORSECONDARY, + MONGOC_SERVER_ERR_PRIMARYSTEPPEDDOWN, + MONGOC_SERVER_ERR_SHUTDOWNINPROGRESS}; + mongoc_server_err_t shutdown_codes[] = {MONGOC_SERVER_ERR_INTERRUPTEDATSHUTDOWN, + MONGOC_SERVER_ERR_SHUTDOWNINPROGRESS}; int i; MONGOC_DEBUG ("Checking domain = %d", domain); @@ -158,24 +145,20 @@ test_state_change_helper (uint32_t domain, bool expect_error) memset (&error, 0, sizeof (bson_error_t)); error.domain = domain; - for (i = 0; i < sizeof (not_primary_codes) / sizeof (mongoc_server_err_t); - i++) { + for (i = 0; i < sizeof (not_primary_codes) / sizeof (mongoc_server_err_t); i++) { error.code = not_primary_codes[i]; BSON_ASSERT (expect_error == _mongoc_error_is_not_primary (&error)); BSON_ASSERT (!_mongoc_error_is_recovering (&error)); BSON_ASSERT (!_mongoc_error_is_shutdown (&error)); BSON_ASSERT (expect_error == _mongoc_error_is_state_change (&error)); } - for (i = 0; - i < sizeof (node_is_recovering_codes) / sizeof (mongoc_server_err_t); - i++) { + for (i = 0; i < sizeof (node_is_recovering_codes) / sizeof (mongoc_server_err_t); i++) { error.code = node_is_recovering_codes[i]; BSON_ASSERT (!_mongoc_error_is_not_primary (&error)); BSON_ASSERT (expect_error == _mongoc_error_is_recovering (&error)); BSON_ASSERT (expect_error == _mongoc_error_is_state_change (&error)); } - for (i = 0; i < sizeof (shutdown_codes) / sizeof (mongoc_server_err_t); - i++) { + for (i = 0; i < sizeof (shutdown_codes) / sizeof (mongoc_server_err_t); i++) { error.code = shutdown_codes[i]; BSON_ASSERT (!_mongoc_error_is_not_primary (&error)); /* Shutdown errors are a subset of recovering errors. */ @@ -192,15 +175,13 @@ test_state_change_helper (uint32_t domain, bool expect_error) BSON_ASSERT (!_mongoc_error_is_shutdown (&error)); BSON_ASSERT (expect_error == _mongoc_error_is_state_change (&error)); - bson_strncpy ( - error.message, "... node is recovering ...", sizeof (error.message)); + bson_strncpy (error.message, "... node is recovering ...", sizeof (error.message)); BSON_ASSERT (!_mongoc_error_is_not_primary (&error)); BSON_ASSERT (expect_error == _mongoc_error_is_recovering (&error)); BSON_ASSERT (!_mongoc_error_is_shutdown (&error)); BSON_ASSERT (expect_error == _mongoc_error_is_state_change (&error)); - bson_strncpy ( - error.message, "... not master or secondary ...", sizeof (error.message)); + bson_strncpy (error.message, "... not master or secondary ...", sizeof (error.message)); BSON_ASSERT (!_mongoc_error_is_not_primary (&error)); BSON_ASSERT (expect_error == _mongoc_error_is_recovering (&error)); BSON_ASSERT (!_mongoc_error_is_shutdown (&error)); @@ -213,15 +194,13 @@ test_state_change_helper (uint32_t domain, bool expect_error) BSON_ASSERT (!_mongoc_error_is_shutdown (&error)); BSON_ASSERT (!_mongoc_error_is_state_change (&error)); - bson_strncpy ( - error.message, "... node is recovering ...", sizeof (error.message)); + bson_strncpy (error.message, "... node is recovering ...", sizeof (error.message)); BSON_ASSERT (!_mongoc_error_is_not_primary (&error)); BSON_ASSERT (!_mongoc_error_is_recovering (&error)); BSON_ASSERT (!_mongoc_error_is_shutdown (&error)); BSON_ASSERT (!_mongoc_error_is_state_change (&error)); - bson_strncpy ( - error.message, "... not master or secondary ...", sizeof (error.message)); + bson_strncpy (error.message, "... not master or secondary ...", sizeof (error.message)); BSON_ASSERT (!_mongoc_error_is_not_primary (&error)); BSON_ASSERT (!_mongoc_error_is_recovering (&error)); BSON_ASSERT (!_mongoc_error_is_shutdown (&error)); @@ -239,16 +218,11 @@ test_state_change (void) void test_error_install (TestSuite *suite) { - TestSuite_AddLive ( - suite, "/Error/set_api/single", test_set_error_api_single); - TestSuite_AddLive ( - suite, "/Error/set_api/pooled", test_set_error_api_pooled); - TestSuite_AddMockServerTest ( - suite, "/Error/command/default", test_command_error_default); - TestSuite_AddMockServerTest ( - suite, "/Error/command/v1", test_command_error_v1); - TestSuite_AddMockServerTest ( - suite, "/Error/command/v2", test_command_error_v2); + TestSuite_AddLive (suite, "/Error/set_api/single", test_set_error_api_single); + TestSuite_AddLive (suite, "/Error/set_api/pooled", test_set_error_api_pooled); + TestSuite_AddMockServerTest (suite, "/Error/command/default", test_command_error_default); + TestSuite_AddMockServerTest (suite, "/Error/command/v1", test_command_error_v1); + TestSuite_AddMockServerTest (suite, "/Error/command/v2", test_command_error_v2); TestSuite_Add (suite, "/Error/has_label", test_has_label); TestSuite_Add (suite, "/Error/state_change", test_state_change); } diff --git a/src/libmongoc/tests/test-mongoc-exhaust.c b/src/libmongoc/tests/test-mongoc-exhaust.c index 27f3bea2e9..eda1138a31 100644 --- a/src/libmongoc/tests/test-mongoc-exhaust.c +++ b/src/libmongoc/tests/test-mongoc-exhaust.c @@ -78,8 +78,7 @@ get_generation (mongoc_client_t *client, mongoc_cursor_t *cursor) server_id = mongoc_cursor_get_hint (cursor); - sd = mongoc_topology_description_server_by_id_const ( - td.ptr, server_id, &error); + sd = mongoc_topology_description_server_by_id_const (td.ptr, server_id, &error); ASSERT_OR_PRINT (sd, error); generation = mc_tpl_sd_get_generation (sd, &kZeroServiceId); mc_tpld_drop_ref (&td); @@ -99,8 +98,7 @@ get_connection_count (mongoc_client_t *client) ASSERT (client); BSON_APPEND_INT32 (&cmd, "serverStatus", 1); - res = mongoc_client_command_simple ( - client, "admin", &cmd, NULL, &reply, &error); + res = mongoc_client_command_simple (client, "admin", &cmd, NULL, &reply, &error); ASSERT_OR_PRINT (res, error); conns = bson_lookup_int32 (&reply, "connections.totalCreated"); @@ -165,23 +163,16 @@ test_exhaust_cursor (bool pooled) } BEGIN_IGNORE_DEPRECATIONS - ASSERT_OR_PRINT (mongoc_collection_insert_bulk (collection, - MONGOC_INSERT_NONE, - (const bson_t **) bptr, - 10, - wr, - &error), - error); + ASSERT_OR_PRINT ( + mongoc_collection_insert_bulk (collection, MONGOC_INSERT_NONE, (const bson_t **) bptr, 10, wr, &error), error); END_IGNORE_DEPRECATIONS } /* create a couple of cursors */ { - cursor = mongoc_collection_find ( - collection, MONGOC_QUERY_EXHAUST, 0, 0, 5, &q, NULL, NULL); + cursor = mongoc_collection_find (collection, MONGOC_QUERY_EXHAUST, 0, 0, 5, &q, NULL, NULL); - cursor2 = mongoc_collection_find ( - collection, MONGOC_QUERY_NONE, 0, 0, 0, &q, NULL, NULL); + cursor2 = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, 0, &q, NULL, NULL); } /* Read from the exhaust cursor, ensure that we're in exhaust where we @@ -213,8 +204,7 @@ test_exhaust_cursor (bool pooled) * (putting the client into exhaust), breaks a mid-stream read from a * regular cursor */ { - cursor = mongoc_collection_find ( - collection, MONGOC_QUERY_EXHAUST, 0, 0, 5, &q, NULL, NULL); + cursor = mongoc_collection_find (collection, MONGOC_QUERY_EXHAUST, 0, 0, 5, &q, NULL, NULL); r = mongoc_cursor_next (cursor2, &doc); if (!r) { @@ -226,8 +216,7 @@ test_exhaust_cursor (bool pooled) /* The pool was not cleared. */ ASSERT_CMPINT64 (generation1, ==, get_generation (client, cursor2)); /* But a new connection was made. */ - ASSERT_CMPINT32 ( - connection_count1 + 1, ==, get_connection_count (audit_client)); + ASSERT_CMPINT32 (connection_count1 + 1, ==, get_connection_count (audit_client)); for (i = 0; i < 5; i++) { r = mongoc_cursor_next (cursor2, &doc); @@ -260,12 +249,7 @@ test_exhaust_cursor (bool pooled) /* make sure writes fail as well */ { BEGIN_IGNORE_DEPRECATIONS - r = mongoc_collection_insert_bulk (collection, - MONGOC_INSERT_NONE, - (const bson_t **) bptr, - 10, - wr, - &error); + r = mongoc_collection_insert_bulk (collection, MONGOC_INSERT_NONE, (const bson_t **) bptr, 10, wr, &error); END_IGNORE_DEPRECATIONS BSON_ASSERT (!r); @@ -281,12 +265,10 @@ test_exhaust_cursor (bool pooled) * 4. make sure we can read the cursor we made during the exhaust */ { - cursor2 = mongoc_collection_find ( - collection, MONGOC_QUERY_NONE, 0, 0, 0, &q, NULL, NULL); + cursor2 = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, 0, &q, NULL, NULL); server_id = cursor->server_id; - stream = - (mongoc_stream_t *) mongoc_set_get (client->cluster.nodes, server_id); + stream = (mongoc_stream_t *) mongoc_set_get (client->cluster.nodes, server_id); while (cursor->in_exhaust && (r = mongoc_cursor_next (cursor, &doc))) ; @@ -295,8 +277,7 @@ test_exhaust_cursor (bool pooled) mongoc_cursor_destroy (cursor); - BSON_ASSERT (stream == (mongoc_stream_t *) mongoc_set_get ( - client->cluster.nodes, server_id)); + BSON_ASSERT (stream == (mongoc_stream_t *) mongoc_set_get (client->cluster.nodes, server_id)); r = mongoc_cursor_next (cursor2, &doc); BSON_ASSERT (r); @@ -329,8 +310,7 @@ test_exhaust_cursor_works (void *context) BSON_UNUSED (context); bson_error_t error; mongoc_client_t *client = test_framework_new_default_client (); - mongoc_collection_t *coll = - mongoc_client_get_collection (client, "db", "coll"); + mongoc_collection_t *coll = mongoc_client_get_collection (client, "db", "coll"); // Drop collection to remove prior test data. mongoc_collection_drop (coll, NULL /* ignore error */); @@ -338,33 +318,23 @@ test_exhaust_cursor_works (void *context) // Insert enough documents to require more than one batch. // With OP_MSG, a cursor only becomes exhaust after the first getMore. for (int i = 0; i < 5; i++) { - bool ok = mongoc_collection_insert_one (coll, - tmp_bson ("{'i': %d}", i), - NULL /* opts */, - NULL /* reply */, - &error); + bool ok = + mongoc_collection_insert_one (coll, tmp_bson ("{'i': %d}", i), NULL /* opts */, NULL /* reply */, &error); ASSERT_OR_PRINT (ok, error); } mongoc_cursor_t *cursor = mongoc_collection_find_with_opts ( - coll, - tmp_bson ("{}"), - tmp_bson ("{'exhaust': true, 'batchSize': 2}"), - NULL /* read_prefs */); + coll, tmp_bson ("{}"), tmp_bson ("{'exhaust': true, 'batchSize': 2}"), NULL /* read_prefs */); const bson_t *result; while (mongoc_cursor_next (cursor, &result)) ; // Expect an error if exhaust cursors are not supported. - const bool sharded = _mongoc_topology_get_type (cursor->client->topology) == - MONGOC_TOPOLOGY_SHARDED; + const bool sharded = _mongoc_topology_get_type (cursor->client->topology) == MONGOC_TOPOLOGY_SHARDED; int64_t wire_version; test_framework_get_max_wire_version (&wire_version); if (sharded && wire_version < WIRE_VERSION_MONGOS_EXHAUST) { ASSERT (mongoc_cursor_error (cursor, &error)); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_CURSOR, - MONGOC_ERROR_CURSOR_INVALID_CURSOR, - "exhaust cursors require"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_CURSOR, MONGOC_ERROR_CURSOR_INVALID_CURSOR, "exhaust cursors require"); } else { // Expect no error. ASSERT_OR_PRINT (!mongoc_cursor_error (cursor, &error), error); @@ -422,8 +392,7 @@ test_exhaust_cursor_multi_batch (void *context) server_id = mongoc_bulk_operation_execute (bulk, NULL, &error); ASSERT_OR_PRINT (server_id, error); - cursor = mongoc_collection_find ( - collection, MONGOC_QUERY_EXHAUST, 0, 0, 10, tmp_bson ("{}"), NULL, NULL); + cursor = mongoc_collection_find (collection, MONGOC_QUERY_EXHAUST, 0, 0, 10, tmp_bson ("{}"), NULL, NULL); i = 0; while (mongoc_cursor_next (cursor, &cursor_doc)) { @@ -448,13 +417,11 @@ test_cursor_server_hint_with_exhaust (void *unused) BSON_UNUSED (unused); bson_error_t error; mongoc_client_t *client = test_framework_new_default_client (); - mongoc_collection_t *coll = - get_test_collection (client, "cursor_server_hint_with_exhaust"); - mongoc_cursor_t *cursor = mongoc_collection_find_with_opts ( - coll, - tmp_bson ("{}"), - tmp_bson ("{'exhaust': true}"), /* opts */ - NULL /* read_prefs */); + mongoc_collection_t *coll = get_test_collection (client, "cursor_server_hint_with_exhaust"); + mongoc_cursor_t *cursor = mongoc_collection_find_with_opts (coll, + tmp_bson ("{}"), + tmp_bson ("{'exhaust': true}"), /* opts */ + NULL /* read_prefs */); // Set a bogus server ID. mongoc_cursor_set_hint (cursor, 123); @@ -465,10 +432,8 @@ test_cursor_server_hint_with_exhaust (void *unused) ; // Expect an error due to the bogus server ID. ASSERT (mongoc_cursor_error (cursor, &error)); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Could not find server with id: 123"); + ASSERT_ERROR_CONTAINS ( + error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Could not find server with id: 123"); mongoc_cursor_destroy (cursor); mongoc_collection_destroy (coll); @@ -484,18 +449,10 @@ test_cursor_set_max_await_time_ms (void) const bson_t *bson; client = test_framework_new_default_client (); - collection = - get_test_collection (client, "test_cursor_set_max_await_time_ms"); - - cursor = mongoc_collection_find (collection, - MONGOC_QUERY_TAILABLE_CURSOR | - MONGOC_QUERY_AWAIT_DATA, - 0, - 0, - 0, - tmp_bson ("{}"), - NULL, - NULL); + collection = get_test_collection (client, "test_cursor_set_max_await_time_ms"); + + cursor = mongoc_collection_find ( + collection, MONGOC_QUERY_TAILABLE_CURSOR | MONGOC_QUERY_AWAIT_DATA, 0, 0, 0, tmp_bson ("{}"), NULL, NULL); ASSERT_CMPINT (0, ==, mongoc_cursor_get_max_await_time_ms (cursor)); mongoc_cursor_set_max_await_time_ms (cursor, 123); @@ -527,19 +484,12 @@ _request_error (request_t *request, exhaust_error_type_t error_type) if (error_type == NETWORK_ERROR) { reply_to_request_with_reset (request); } else { - reply_to_request (request, - MONGOC_REPLY_QUERY_FAILURE, - 123, - 0, - 0, - "{'$err': 'uh oh', 'code': 4321}"); + reply_to_request (request, MONGOC_REPLY_QUERY_FAILURE, 123, 0, 0, "{'$err': 'uh oh', 'code': 4321}"); } } static void -_check_error (mongoc_client_t *client, - mongoc_cursor_t *cursor, - exhaust_error_type_t error_type) +_check_error (mongoc_client_t *client, mongoc_cursor_t *cursor, exhaust_error_type_t error_type) { uint32_t server_id; bson_error_t error; @@ -551,36 +501,22 @@ _check_error (mongoc_client_t *client, ASSERT (mongoc_cursor_error (cursor, &error)); if (error_type == NETWORK_ERROR) { - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_SOCKET, - "socket error or timeout"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "socket error or timeout"); /* socket was discarded */ - ASSERT (!mongoc_cluster_stream_for_server (&client->cluster, - server_id, - false /* don't reconnect */, - NULL, - NULL, - &error)); - - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_SOCKET, - "socket error or timeout"); + ASSERT (!mongoc_cluster_stream_for_server ( + &client->cluster, server_id, false /* don't reconnect */, NULL, NULL, &error)); + + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "socket error or timeout"); } else { /* query failure */ - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_QUERY, - 4321 /* error from mock server */, - "uh oh" /* message from mock server */); + ASSERT_ERROR_CONTAINS ( + error, MONGOC_ERROR_QUERY, 4321 /* error from mock server */, "uh oh" /* message from mock server */); } } static void -_mock_test_exhaust (bool pooled, - exhaust_error_when_t error_when, - exhaust_error_type_t error_type) +_mock_test_exhaust (bool pooled, exhaust_error_when_t error_when, exhaust_error_type_t error_type) { mock_server_t *server; mongoc_client_pool_t *pool = NULL; @@ -597,27 +533,18 @@ _mock_test_exhaust (bool pooled, mock_server_run (server); if (pooled) { - pool = test_framework_client_pool_new_from_uri ( - mock_server_get_uri (server), NULL); + pool = test_framework_client_pool_new_from_uri (mock_server_get_uri (server), NULL); client = mongoc_client_pool_pop (pool); } else { - client = test_framework_client_new_from_uri (mock_server_get_uri (server), - NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); } collection = mongoc_client_get_collection (client, "db", "test"); - cursor = mongoc_collection_find ( - collection, MONGOC_QUERY_EXHAUST, 0, 0, 0, tmp_bson ("{}"), NULL, NULL); + cursor = mongoc_collection_find (collection, MONGOC_QUERY_EXHAUST, 0, 0, 0, tmp_bson ("{}"), NULL, NULL); future = future_cursor_next (cursor, &doc); - request = mock_server_receives_query (server, - "db.test", - MONGOC_QUERY_SECONDARY_OK | - MONGOC_QUERY_EXHAUST, - 0, - 0, - "{}", - NULL); + request = mock_server_receives_query ( + server, "db.test", MONGOC_QUERY_SECONDARY_OK | MONGOC_QUERY_EXHAUST, 0, 0, "{}", NULL); if (error_when == SECOND_BATCH) { /* initial query succeeds, gets a doc and cursor id of 123 */ @@ -727,8 +654,7 @@ test_exhaust_in_child (void) to_insert = BCON_NEW ("x", BCON_INT32 (1)); bulk = mongoc_collection_create_bulk_operation (coll, false, NULL /* wc */); for (i = 0; i < 1001; i++) { - ret = mongoc_bulk_operation_insert_with_opts ( - bulk, to_insert, NULL /* opts */, &error); + ret = mongoc_bulk_operation_insert_with_opts (bulk, to_insert, NULL /* opts */, &error); ASSERT_OR_PRINT (ret, error); } ret = mongoc_bulk_operation_execute (bulk, NULL /* reply */, &error); @@ -736,10 +662,8 @@ test_exhaust_in_child (void) mongoc_bulk_operation_destroy (bulk); /* create an exhaust cursor. */ - cursor = mongoc_collection_find_with_opts (coll, - tmp_bson ("{}"), - tmp_bson ("{'exhaust': true }"), - NULL /* read prefs */); + cursor = + mongoc_collection_find_with_opts (coll, tmp_bson ("{}"), tmp_bson ("{'exhaust': true }"), NULL /* read prefs */); BSON_ASSERT (mongoc_cursor_next (cursor, &doc)); BSON_ASSERT (client->in_exhaust); server_id = mongoc_cursor_get_hint (cursor); @@ -756,13 +680,8 @@ test_exhaust_in_child (void) /* A command directly on that server should still work (it should open a * new socket). */ ping = BCON_NEW ("ping", BCON_INT32 (1)); - ret = mongoc_client_command_simple_with_server_id (client, - "admin", - ping, - NULL /* read prefs */, - server_id, - NULL /* reply */, - &error); + ret = mongoc_client_command_simple_with_server_id ( + client, "admin", ping, NULL /* read prefs */, server_id, NULL /* reply */, &error); ASSERT_OR_PRINT (ret, error); mongoc_collection_destroy (coll); mongoc_client_destroy (client); @@ -789,33 +708,13 @@ test_exhaust_in_child (void) void test_exhaust_install (TestSuite *suite) { - TestSuite_AddFull (suite, - "/Client/exhaust_cursor/works", - test_exhaust_cursor_works, - NULL, - NULL, - skip_if_no_exhaust); - TestSuite_AddFull (suite, - "/Client/exhaust_cursor/single", - test_exhaust_cursor_single, - NULL, - NULL, - skip_if_no_exhaust); - TestSuite_AddFull (suite, - "/Client/exhaust_cursor/pool", - test_exhaust_cursor_pool, - NULL, - NULL, - skip_if_no_exhaust); - TestSuite_AddFull (suite, - "/Client/exhaust_cursor/batches", - test_exhaust_cursor_multi_batch, - NULL, - NULL, - skip_if_no_exhaust); - TestSuite_AddLive (suite, - "/Client/set_max_await_time_ms", - test_cursor_set_max_await_time_ms); + TestSuite_AddFull (suite, "/Client/exhaust_cursor/works", test_exhaust_cursor_works, NULL, NULL, skip_if_no_exhaust); + TestSuite_AddFull ( + suite, "/Client/exhaust_cursor/single", test_exhaust_cursor_single, NULL, NULL, skip_if_no_exhaust); + TestSuite_AddFull (suite, "/Client/exhaust_cursor/pool", test_exhaust_cursor_pool, NULL, NULL, skip_if_no_exhaust); + TestSuite_AddFull ( + suite, "/Client/exhaust_cursor/batches", test_exhaust_cursor_multi_batch, NULL, NULL, skip_if_no_exhaust); + TestSuite_AddLive (suite, "/Client/set_max_await_time_ms", test_cursor_set_max_await_time_ms); TestSuite_AddFull (suite, "/Client/exhaust_cursor/server_hint", test_cursor_server_hint_with_exhaust, @@ -823,43 +722,26 @@ test_exhaust_install (TestSuite *suite) NULL, skip_if_no_exhaust); TestSuite_AddMockServerTest ( - suite, - "/Client/exhaust_cursor/err/network/1st_batch/single", - test_exhaust_network_err_1st_batch_single); + suite, "/Client/exhaust_cursor/err/network/1st_batch/single", test_exhaust_network_err_1st_batch_single); TestSuite_AddMockServerTest ( - suite, - "/Client/exhaust_cursor/err/network/1st_batch/pooled", - test_exhaust_network_err_1st_batch_pooled); + suite, "/Client/exhaust_cursor/err/network/1st_batch/pooled", test_exhaust_network_err_1st_batch_pooled); TestSuite_AddMockServerTest ( - suite, - "/Client/exhaust_cursor/err/server/1st_batch/single", - test_exhaust_server_err_1st_batch_single); + suite, "/Client/exhaust_cursor/err/server/1st_batch/single", test_exhaust_server_err_1st_batch_single); TestSuite_AddMockServerTest ( - suite, - "/Client/exhaust_cursor/err/server/1st_batch/pooled", - test_exhaust_server_err_1st_batch_pooled); + suite, "/Client/exhaust_cursor/err/server/1st_batch/pooled", test_exhaust_server_err_1st_batch_pooled); TestSuite_AddMockServerTest ( - suite, - "/Client/exhaust_cursor/err/network/2nd_batch/single", - test_exhaust_network_err_2nd_batch_single); + suite, "/Client/exhaust_cursor/err/network/2nd_batch/single", test_exhaust_network_err_2nd_batch_single); TestSuite_AddMockServerTest ( - suite, - "/Client/exhaust_cursor/err/network/2nd_batch/pooled", - test_exhaust_network_err_2nd_batch_pooled); + suite, "/Client/exhaust_cursor/err/network/2nd_batch/pooled", test_exhaust_network_err_2nd_batch_pooled); TestSuite_AddMockServerTest ( - suite, - "/Client/exhaust_cursor/err/server/2nd_batch/single", - test_exhaust_server_err_2nd_batch_single); + suite, "/Client/exhaust_cursor/err/server/2nd_batch/single", test_exhaust_server_err_2nd_batch_single); TestSuite_AddMockServerTest ( - suite, - "/Client/exhaust_cursor/err/server/2nd_batch/pooled", - test_exhaust_server_err_2nd_batch_pooled); + suite, "/Client/exhaust_cursor/err/server/2nd_batch/pooled", test_exhaust_server_err_2nd_batch_pooled); #ifndef _WIN32 /* Skip on Windows, since "fork" is not available and this test is not * particularly platform dependent. */ if (!TestSuite_NoFork (suite)) { - TestSuite_AddLive ( - suite, "/Client/exhaust_cursor/after_reset", test_exhaust_in_child); + TestSuite_AddLive (suite, "/Client/exhaust_cursor/after_reset", test_exhaust_in_child); } #endif /* _WIN32 */ } diff --git a/src/libmongoc/tests/test-mongoc-find-and-modify.c b/src/libmongoc/tests/test-mongoc-find-and-modify.c index 6486473e48..c84ed2a1b7 100644 --- a/src/libmongoc/tests/test-mongoc-find-and-modify.c +++ b/src/libmongoc/tests/test-mongoc-find-and-modify.c @@ -52,12 +52,10 @@ test_find_and_modify_bypass (bool bypass) server = mock_server_new (); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); ASSERT (client); - collection = - mongoc_client_get_collection (client, "test", "test_find_and_modify"); + collection = mongoc_client_get_collection (client, "test", "test_find_and_modify"); auto_hello (server, WIRE_VERSION_MIN, /* max_wire_version */ @@ -71,35 +69,29 @@ test_find_and_modify_bypass (bool bypass) opts = mongoc_find_and_modify_opts_new (); mongoc_find_and_modify_opts_set_bypass_document_validation (opts, bypass); - BSON_ASSERT ( - bypass == - mongoc_find_and_modify_opts_get_bypass_document_validation (opts)); + BSON_ASSERT (bypass == mongoc_find_and_modify_opts_get_bypass_document_validation (opts)); mongoc_find_and_modify_opts_set_update (opts, update); - mongoc_find_and_modify_opts_set_flags (opts, - MONGOC_FIND_AND_MODIFY_RETURN_NEW); + mongoc_find_and_modify_opts_set_flags (opts, MONGOC_FIND_AND_MODIFY_RETURN_NEW); - future = future_collection_find_and_modify_with_opts ( - collection, &doc, opts, &reply, &error); + future = future_collection_find_and_modify_with_opts (collection, &doc, opts, &reply, &error); if (bypass) { - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'test'," - " 'findAndModify': 'test_find_and_modify'," - " 'query': {'superduper': 77889}," - " 'update': {'$set': {'superduper': 1234}}," - " 'new': true," - " 'bypassDocumentValidation': true}")); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'test'," + " 'findAndModify': 'test_find_and_modify'," + " 'query': {'superduper': 77889}," + " 'update': {'$set': {'superduper': 1234}}," + " 'new': true," + " 'bypassDocumentValidation': true}")); } else { - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'test'," - " 'findAndModify': 'test_find_and_modify', " - "'query': {'superduper': 77889}," - "'update': {'$set': {'superduper': 1234}}," - "'new': true }")); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'test'," + " 'findAndModify': 'test_find_and_modify', " + "'query': {'superduper': 77889}," + "'update': {'$set': {'superduper': 1234}}," + "'new': true }")); } reply_to_request_simple (request, "{ 'value' : null, 'ok' : 1 }"); @@ -148,12 +140,10 @@ test_find_and_modify_write_concern (void) server = mock_server_new (); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); ASSERT (client); - collection = - mongoc_client_get_collection (client, "test", "test_find_and_modify"); + collection = mongoc_client_get_collection (client, "test", "test_find_and_modify"); auto_hello (server, WIRE_VERSION_MIN, /* max_wire_version */ @@ -170,21 +160,18 @@ test_find_and_modify_write_concern (void) opts = mongoc_find_and_modify_opts_new (); mongoc_collection_set_write_concern (collection, write_concern); mongoc_find_and_modify_opts_set_update (opts, update); - mongoc_find_and_modify_opts_set_flags (opts, - MONGOC_FIND_AND_MODIFY_RETURN_NEW); - - future = future_collection_find_and_modify_with_opts ( - collection, &doc, opts, &reply, &error); - - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'test'," - " 'findAndModify': 'test_find_and_modify', " - " 'query': {'superduper': 77889 }," - " 'update': {'$set': {'superduper': 1234}}," - " 'new': true," - " 'writeConcern': {'w': 42}}")); + mongoc_find_and_modify_opts_set_flags (opts, MONGOC_FIND_AND_MODIFY_RETURN_NEW); + + future = future_collection_find_and_modify_with_opts (collection, &doc, opts, &reply, &error); + + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'test'," + " 'findAndModify': 'test_find_and_modify', " + " 'query': {'superduper': 77889 }," + " 'update': {'$set': {'superduper': 1234}}," + " 'new': true," + " 'writeConcern': {'w': 42}}")); reply_to_request_simple (request, "{ 'value' : null, 'ok' : 1 }"); ASSERT_OR_PRINT (future_get_bool (future), error); @@ -230,8 +217,7 @@ test_find_and_modify_write_concern_failure (void *context) 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)); + 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"), "}"); @@ -241,15 +227,12 @@ test_find_and_modify_write_concern_failure (void *context) 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); + 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); + 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:"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_WRITE_CONCERN, 100, "Write Concern error:"); bson_destroy (&reply); bson_destroy (update); @@ -283,9 +266,7 @@ test_find_and_modify (void) BSON_APPEND_INT32 (&doc, "superduper", 77889); - ASSERT_OR_PRINT ( - mongoc_collection_insert_one (collection, &doc, NULL, NULL, &error), - error); + ASSERT_OR_PRINT (mongoc_collection_insert_one (collection, &doc, NULL, NULL, &error), error); update = BCON_NEW ("$set", "{", "superduper", BCON_INT32 (1234), "}"); @@ -294,8 +275,7 @@ test_find_and_modify (void) mongoc_find_and_modify_opts_get_update (opts, &tmp); assert_match_bson (&tmp, update, false); bson_destroy (&tmp); - mongoc_find_and_modify_opts_set_fields (opts, - tmp_bson ("{'superduper': 1}")); + mongoc_find_and_modify_opts_set_fields (opts, tmp_bson ("{'superduper': 1}")); mongoc_find_and_modify_opts_get_fields (opts, &tmp); assert_match_bson (&tmp, tmp_bson ("{'superduper': 1}"), false); bson_destroy (&tmp); @@ -303,14 +283,10 @@ test_find_and_modify (void) mongoc_find_and_modify_opts_get_sort (opts, &tmp); assert_match_bson (&tmp, tmp_bson ("{'superduper': 1}"), false); bson_destroy (&tmp); - mongoc_find_and_modify_opts_set_flags (opts, - MONGOC_FIND_AND_MODIFY_RETURN_NEW); - BSON_ASSERT (MONGOC_FIND_AND_MODIFY_RETURN_NEW == - mongoc_find_and_modify_opts_get_flags (opts)); + mongoc_find_and_modify_opts_set_flags (opts, MONGOC_FIND_AND_MODIFY_RETURN_NEW); + BSON_ASSERT (MONGOC_FIND_AND_MODIFY_RETURN_NEW == mongoc_find_and_modify_opts_get_flags (opts)); - ASSERT_OR_PRINT (mongoc_collection_find_and_modify_with_opts ( - collection, &doc, opts, &reply, &error), - error); + ASSERT_OR_PRINT (mongoc_collection_find_and_modify_with_opts (collection, &doc, opts, &reply, &error), error); BSON_ASSERT (bson_iter_init_find (&iter, &reply, "value")); BSON_ASSERT (BSON_ITER_HOLDS_DOCUMENT (&iter)); @@ -353,29 +329,24 @@ test_find_and_modify_opts (void) server = mock_server_with_auto_hello (WIRE_VERSION_MIN); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); collection = mongoc_client_get_collection (client, "db", "collection"); opts = mongoc_find_and_modify_opts_new (); BSON_ASSERT (mongoc_find_and_modify_opts_set_max_time_ms (opts, 42)); - ASSERT_CMPUINT32 ( - 42, ==, mongoc_find_and_modify_opts_get_max_time_ms (opts)); - BSON_ASSERT ( - mongoc_find_and_modify_opts_append (opts, tmp_bson ("{'foo': 1}"))); + ASSERT_CMPUINT32 (42, ==, mongoc_find_and_modify_opts_get_max_time_ms (opts)); + BSON_ASSERT (mongoc_find_and_modify_opts_append (opts, tmp_bson ("{'foo': 1}"))); mongoc_find_and_modify_opts_get_extra (opts, &extra); assert_match_bson (&extra, tmp_bson ("{'foo': 1}"), false); bson_destroy (&extra); - future = future_collection_find_and_modify_with_opts ( - collection, tmp_bson ("{}"), opts, NULL, &error); - request = - mock_server_receives_msg (server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db'," - " 'findAndModify': 'collection'," - " 'maxTimeMS': 42," - " 'foo': 1}")); + future = future_collection_find_and_modify_with_opts (collection, tmp_bson ("{}"), opts, NULL, &error); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'db'," + " 'findAndModify': 'collection'," + " 'maxTimeMS': 42," + " 'foo': 1}")); reply_to_request_with_ok_and_destroy (request); ASSERT_OR_PRINT (future_get_bool (future), error); @@ -409,8 +380,7 @@ test_find_and_modify_opts_write_concern (void) server = mock_server_with_auto_hello (WIRE_VERSION_MIN); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); collection = mongoc_client_get_collection (client, "db", "collection"); opts = mongoc_find_and_modify_opts_new (); @@ -418,30 +388,26 @@ test_find_and_modify_opts_write_concern (void) BSON_ASSERT (mongoc_find_and_modify_opts_append (opts, &extra)); bson_destroy (&extra); - future = future_collection_find_and_modify_with_opts ( - collection, tmp_bson ("{}"), opts, NULL, &error); - request = - mock_server_receives_msg (server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db'," - " 'findAndModify': 'collection'," - " 'writeConcern': {'w': 2}}")); + future = future_collection_find_and_modify_with_opts (collection, tmp_bson ("{}"), opts, NULL, &error); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'db'," + " 'findAndModify': 'collection'," + " 'writeConcern': {'w': 2}}")); reply_to_request_with_ok_and_destroy (request); ASSERT_OR_PRINT (future_get_bool (future), error); future_destroy (future); /* opts overrides collection */ mongoc_collection_set_write_concern (collection, w3); - future = future_collection_find_and_modify_with_opts ( - collection, tmp_bson ("{}"), opts, NULL, &error); + future = future_collection_find_and_modify_with_opts (collection, tmp_bson ("{}"), opts, NULL, &error); /* still w: 2 */ - request = - mock_server_receives_msg (server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db'," - " 'findAndModify': 'collection'," - " 'writeConcern': {'w': 2}}")); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'db'," + " 'findAndModify': 'collection'," + " 'writeConcern': {'w': 2}}")); reply_to_request_with_ok_and_destroy (request); ASSERT_OR_PRINT (future_get_bool (future), error); future_destroy (future); @@ -470,30 +436,21 @@ test_find_and_modify_collation (void) server = mock_server_with_auto_hello (WIRE_VERSION_MIN); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); collection = mongoc_client_get_collection (client, "db", "collection"); - collation = BCON_NEW ("collation", - "{", - "locale", - BCON_UTF8 ("en_US"), - "caseFirst", - BCON_UTF8 ("lower"), - "}"); + collation = BCON_NEW ("collation", "{", "locale", BCON_UTF8 ("en_US"), "caseFirst", BCON_UTF8 ("lower"), "}"); opts = mongoc_find_and_modify_opts_new (); BSON_ASSERT (mongoc_find_and_modify_opts_append (opts, collation)); - future = future_collection_find_and_modify_with_opts ( - collection, tmp_bson ("{}"), opts, NULL, &error); + future = future_collection_find_and_modify_with_opts (collection, tmp_bson ("{}"), opts, NULL, &error); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db'," - " 'findAndModify': 'collection'," - " 'collation': {'locale': 'en_US', 'caseFirst': 'lower'}}")); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'db'," + " 'findAndModify': 'collection'," + " 'collation': {'locale': 'en_US', 'caseFirst': 'lower'}}")); reply_to_request_with_ok_and_destroy (request); ASSERT_OR_PRINT (future_get_bool (future), error); future_destroy (future); @@ -523,23 +480,19 @@ test_find_and_modify_hint (void) opts = mongoc_find_and_modify_opts_new (); mongoc_find_and_modify_opts_append (opts, tmp_bson ("{'hint': 'abc'}")); mongoc_find_and_modify_opts_set_update (opts, tmp_bson ("{}")); - ret = mongoc_collection_find_and_modify_with_opts ( - coll, tmp_bson ("{}"), opts, NULL /* reply */, &error); - if (test_framework_max_wire_version_at_least ( - WIRE_VERSION_FIND_AND_MODIFY_HINT)) { + ret = mongoc_collection_find_and_modify_with_opts (coll, tmp_bson ("{}"), opts, NULL /* reply */, &error); + if (test_framework_max_wire_version_at_least (WIRE_VERSION_FIND_AND_MODIFY_HINT)) { ASSERT_OR_PRINT (ret, error); - } else if (test_framework_max_wire_version_at_least ( - WIRE_VERSION_FIND_AND_MODIFY_HINT_SERVER_SIDE_ERROR)) { + } else if (test_framework_max_wire_version_at_least (WIRE_VERSION_FIND_AND_MODIFY_HINT_SERVER_SIDE_ERROR)) { BSON_ASSERT (!ret); BSON_ASSERT (error.domain == MONGOC_ERROR_SERVER); /* server error. */ } else { BSON_ASSERT (!ret); - ASSERT_ERROR_CONTAINS ( - error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION, - "The selected server does not support hint for findAndModify"); + ASSERT_ERROR_CONTAINS (error, + MONGOC_ERROR_COMMAND, + MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION, + "The selected server does not support hint for findAndModify"); } mongoc_find_and_modify_opts_destroy (opts); @@ -550,31 +503,21 @@ test_find_and_modify_hint (void) void test_find_and_modify_install (TestSuite *suite) { - TestSuite_AddLive ( - suite, "/find_and_modify/find_and_modify", test_find_and_modify); - TestSuite_AddMockServerTest (suite, - "/find_and_modify/find_and_modify/bypass/true", - test_find_and_modify_bypass_true); - TestSuite_AddMockServerTest (suite, - "/find_and_modify/find_and_modify/bypass/false", - test_find_and_modify_bypass_false); + TestSuite_AddLive (suite, "/find_and_modify/find_and_modify", test_find_and_modify); + TestSuite_AddMockServerTest ( + suite, "/find_and_modify/find_and_modify/bypass/true", test_find_and_modify_bypass_true); TestSuite_AddMockServerTest ( - suite, - "/find_and_modify/find_and_modify/write_concern", - test_find_and_modify_write_concern); + suite, "/find_and_modify/find_and_modify/bypass/false", test_find_and_modify_bypass_false); + TestSuite_AddMockServerTest ( + suite, "/find_and_modify/find_and_modify/write_concern", test_find_and_modify_write_concern); TestSuite_AddFull (suite, "/find_and_modify/find_and_modify/write_concern_failure", test_find_and_modify_write_concern_failure, NULL, NULL, test_framework_skip_if_not_replset); - TestSuite_AddMockServerTest ( - suite, "/find_and_modify/opts", test_find_and_modify_opts); - TestSuite_AddMockServerTest (suite, - "/find_and_modify/opts/write_concern", - test_find_and_modify_opts_write_concern); - TestSuite_AddMockServerTest ( - suite, "/find_and_modify/collation", test_find_and_modify_collation); - TestSuite_AddLive ( - suite, "/find_and_modify/hint", test_find_and_modify_hint); + TestSuite_AddMockServerTest (suite, "/find_and_modify/opts", test_find_and_modify_opts); + TestSuite_AddMockServerTest (suite, "/find_and_modify/opts/write_concern", test_find_and_modify_opts_write_concern); + TestSuite_AddMockServerTest (suite, "/find_and_modify/collation", test_find_and_modify_collation); + TestSuite_AddLive (suite, "/find_and_modify/hint", test_find_and_modify_hint); } diff --git a/src/libmongoc/tests/test-mongoc-gridfs-bucket.c b/src/libmongoc/tests/test-mongoc-gridfs-bucket.c index 1ee5a32468..14f240bcd8 100644 --- a/src/libmongoc/tests/test-mongoc-gridfs-bucket.c +++ b/src/libmongoc/tests/test-mongoc-gridfs-bucket.c @@ -41,8 +41,7 @@ test_create_bucket (void) /* read concern */ read_concern = mongoc_read_concern_new (); - mongoc_read_concern_set_level (read_concern, - MONGOC_READ_CONCERN_LEVEL_LOCAL); + mongoc_read_concern_set_level (read_concern, MONGOC_READ_CONCERN_LEVEL_LOCAL); mongoc_read_concern_append (read_concern, opts); /* other opts */ @@ -89,18 +88,13 @@ _get_index_count (mongoc_collection_t *collection) /* Util that downloads a file content into the given buffer. Returns num bytes * read. */ static size_t -_download_file_into_buf (mongoc_gridfs_bucket_t *bucket, - const bson_value_t *file_id, - char *buf, - size_t len) +_download_file_into_buf (mongoc_gridfs_bucket_t *bucket, const bson_value_t *file_id, char *buf, size_t len) { bson_error_t error; size_t nread; - mongoc_stream_t *down = - mongoc_gridfs_bucket_open_download_stream (bucket, file_id, &error); + mongoc_stream_t *down = mongoc_gridfs_bucket_open_download_stream (bucket, file_id, &error); ASSERT_OR_PRINT (down, error); - nread = - mongoc_stream_read (down, buf, len, 1 /* min read */, 0 /* No timeout */); + nread = mongoc_stream_read (down, buf, len, 1 /* min read */, 0 /* No timeout */); mongoc_stream_destroy (down); ASSERT (nread > 0); return nread; @@ -108,18 +102,13 @@ _download_file_into_buf (mongoc_gridfs_bucket_t *bucket, /* Util for uploading a file with the given string as content */ static void -_upload_file_from_str (mongoc_gridfs_bucket_t *bucket, - const char *filename, - const char *content, - const bson_t *opts, - bson_value_t *file_id) +_upload_file_from_str ( + mongoc_gridfs_bucket_t *bucket, const char *filename, const char *content, const bson_t *opts, bson_value_t *file_id) { bson_error_t error; - mongoc_stream_t *const up = mongoc_gridfs_bucket_open_upload_stream ( - bucket, filename, opts, file_id, &error); + mongoc_stream_t *const up = mongoc_gridfs_bucket_open_upload_stream (bucket, filename, opts, file_id, &error); ASSERT_OR_PRINT (up, error); - const size_t nwritten = - mongoc_stream_write (up, (void *) content, strlen (content), 0); + const size_t nwritten = mongoc_stream_write (up, (void *) content, strlen (content), 0); ASSERT_CMPSIZE_T (nwritten, ==, strlen (content)); mongoc_stream_destroy (up); } @@ -154,9 +143,7 @@ _test_upload_and_download (bson_t *create_index_cmd) if (create_index_cmd) { bson_error_t error; - ASSERT_OR_PRINT (mongoc_database_write_command_with_opts ( - db, create_index_cmd, NULL, NULL, &error), - error); + ASSERT_OR_PRINT (mongoc_database_write_command_with_opts (db, create_index_cmd, NULL, NULL, &error), error); } opts = bson_new (); @@ -187,38 +174,32 @@ test_upload_and_download (void) _test_upload_and_download (NULL); /* Test files index with float and same options */ - _test_upload_and_download ( - tmp_bson ("{'createIndexes': '%s'," - " 'indexes': [{'key': {'filename': 1.0, 'uploadDate': 1}, " - "'name': 'filename_1_uploadDate_1'}]}", - "fs.files")); + _test_upload_and_download (tmp_bson ("{'createIndexes': '%s'," + " 'indexes': [{'key': {'filename': 1.0, 'uploadDate': 1}, " + "'name': 'filename_1_uploadDate_1'}]}", + "fs.files")); /* Files index with float and different options */ - _test_upload_and_download ( - tmp_bson ("{'createIndexes': '%s'," - " 'indexes': [{'key': {'filename': 1.0, 'uploadDate': 1}, " - "'name': 'different_name'}]}", - "fs.files")); + _test_upload_and_download (tmp_bson ("{'createIndexes': '%s'," + " 'indexes': [{'key': {'filename': 1.0, 'uploadDate': 1}, " + "'name': 'different_name'}]}", + "fs.files")); /* Chunks index with float and same options */ - _test_upload_and_download ( - tmp_bson ("{'createIndexes': '%s'," - " 'indexes': [{'key': {'files_id': 1.0, 'n': 1}, 'name': " - "'files_id_1_n_1', 'unique': true}]}", - "fs.chunks")); + _test_upload_and_download (tmp_bson ("{'createIndexes': '%s'," + " 'indexes': [{'key': {'files_id': 1.0, 'n': 1}, 'name': " + "'files_id_1_n_1', 'unique': true}]}", + "fs.chunks")); /* Chunks index with float and different options */ - _test_upload_and_download ( - tmp_bson ("{'createIndexes': '%s'," - " 'indexes': [{'key': {'files_id': 1.0, 'n': 1}, 'name': " - "'different_name', 'unique': true}]}", - "fs.chunks")); + _test_upload_and_download (tmp_bson ("{'createIndexes': '%s'," + " 'indexes': [{'key': {'files_id': 1.0, 'n': 1}, 'name': " + "'different_name', 'unique': true}]}", + "fs.chunks")); } bool -hex_to_bytes (const char *hex_str, - size_t *size /* OUT */, - uint8_t **bytes /* OUT */) +hex_to_bytes (const char *hex_str, size_t *size /* OUT */, uint8_t **bytes /* OUT */) { size_t len; uint8_t *result; @@ -276,9 +257,8 @@ convert_hex_to_binary (bson_t *doc) value = bson_iter_value (&iter); if (strcmp (key, "data") == 0) { - hex_doc = - bson_new_from_data (bson_iter_value (&iter)->value.v_doc.data, - bson_iter_value (&iter)->value.v_doc.data_len); + hex_doc = bson_new_from_data (bson_iter_value (&iter)->value.v_doc.data, + bson_iter_value (&iter)->value.v_doc.data_len); ASSERT (bson_iter_init_find (&inner, hex_doc, "$hex")); @@ -286,21 +266,17 @@ convert_hex_to_binary (bson_t *doc) r = hex_to_bytes (str, &hex_len, &hex_bytes); if (r) { - BSON_APPEND_BINARY ( - result, key, BSON_SUBTYPE_BINARY, hex_bytes, (uint32_t) hex_len); + BSON_APPEND_BINARY (result, key, BSON_SUBTYPE_BINARY, hex_bytes, (uint32_t) hex_len); bson_free (hex_bytes); } else { - BSON_APPEND_BINARY ( - result, key, BSON_SUBTYPE_BINARY, (const uint8_t *) str, 0); + BSON_APPEND_BINARY (result, key, BSON_SUBTYPE_BINARY, (const uint8_t *) str, 0); } bson_destroy (hex_doc); - } else if (value->value_type == BSON_TYPE_DOCUMENT || - value->value_type == BSON_TYPE_ARRAY) { - sub_doc = - bson_new_from_data (bson_iter_value (&iter)->value.v_doc.data, - bson_iter_value (&iter)->value.v_doc.data_len); + } else if (value->value_type == BSON_TYPE_DOCUMENT || value->value_type == BSON_TYPE_ARRAY) { + sub_doc = bson_new_from_data (bson_iter_value (&iter)->value.v_doc.data, + bson_iter_value (&iter)->value.v_doc.data_len); sub_doc_result = convert_hex_to_binary (sub_doc); bson_destroy (sub_doc); @@ -349,18 +325,15 @@ setup_gridfs_collections (mongoc_database_t *db, bson_t *data) if (bson_iter_init_find (&iter, data, "files")) { bson_t *docs = - bson_new_from_data (bson_iter_value (&iter)->value.v_doc.data, - bson_iter_value (&iter)->value.v_doc.data_len); + bson_new_from_data (bson_iter_value (&iter)->value.v_doc.data, bson_iter_value (&iter)->value.v_doc.data_len); bson_iter_init (&inner, docs); while (bson_iter_next (&inner)) { - bson_t *doc = - bson_new_from_data (bson_iter_value (&inner)->value.v_doc.data, - bson_iter_value (&inner)->value.v_doc.data_len); + bson_t *doc = bson_new_from_data (bson_iter_value (&inner)->value.v_doc.data, + bson_iter_value (&inner)->value.v_doc.data_len); r = mongoc_collection_insert_one (files, doc, NULL, NULL, NULL); ASSERT (r); - r = mongoc_collection_insert_one ( - expected_files, doc, NULL, NULL, NULL); + r = mongoc_collection_insert_one (expected_files, doc, NULL, NULL, NULL); ASSERT (r); bson_destroy (doc); } @@ -370,19 +343,16 @@ setup_gridfs_collections (mongoc_database_t *db, bson_t *data) if (bson_iter_init_find (&iter, data, "chunks")) { bson_t *docs = - bson_new_from_data (bson_iter_value (&iter)->value.v_doc.data, - bson_iter_value (&iter)->value.v_doc.data_len); + bson_new_from_data (bson_iter_value (&iter)->value.v_doc.data, bson_iter_value (&iter)->value.v_doc.data_len); bson_iter_init (&inner, docs); while (bson_iter_next (&inner)) { - bson_t *doc = - bson_new_from_data (bson_iter_value (&inner)->value.v_doc.data, - bson_iter_value (&inner)->value.v_doc.data_len); + bson_t *doc = bson_new_from_data (bson_iter_value (&inner)->value.v_doc.data, + bson_iter_value (&inner)->value.v_doc.data_len); bson_t *chunk = convert_hex_to_binary (doc); r = mongoc_collection_insert_one (chunks, chunk, NULL, NULL, NULL); ASSERT (r); - r = mongoc_collection_insert_one ( - expected_chunks, chunk, NULL, NULL, NULL); + r = mongoc_collection_insert_one (expected_chunks, chunk, NULL, NULL, NULL); ASSERT (r); bson_destroy (doc); bson_destroy (chunk); @@ -407,15 +377,13 @@ gridfs_spec_run_commands (mongoc_database_t *db, bson_t *commands) bool r; ASSERT (bson_iter_init_find (&iter, commands, "data")); - data = bson_new_from_data (bson_iter_value (&iter)->value.v_doc.data, - bson_iter_value (&iter)->value.v_doc.data_len); + data = bson_new_from_data (bson_iter_value (&iter)->value.v_doc.data, bson_iter_value (&iter)->value.v_doc.data_len); bson_iter_init (&iter, data); while (bson_iter_next (&iter)) { command = - bson_new_from_data (bson_iter_value (&iter)->value.v_doc.data, - bson_iter_value (&iter)->value.v_doc.data_len); + bson_new_from_data (bson_iter_value (&iter)->value.v_doc.data, bson_iter_value (&iter)->value.v_doc.data_len); hex_command = convert_hex_to_binary (command); @@ -458,11 +426,9 @@ gridfs_replace_result (bson_t *doc, bson_value_t *replacement) BSON_APPEND_VALUE (result, key, value); } - } else if (value->value_type == BSON_TYPE_DOCUMENT || - value->value_type == BSON_TYPE_ARRAY) { - sub_doc = - bson_new_from_data (bson_iter_value (&iter)->value.v_doc.data, - bson_iter_value (&iter)->value.v_doc.data_len); + } else if (value->value_type == BSON_TYPE_DOCUMENT || value->value_type == BSON_TYPE_ARRAY) { + sub_doc = bson_new_from_data (bson_iter_value (&iter)->value.v_doc.data, + bson_iter_value (&iter)->value.v_doc.data_len); sub_doc_result = gridfs_replace_result (sub_doc, replacement); bson_destroy (sub_doc); @@ -507,33 +473,27 @@ gridfs_compare_collections (mongoc_database_t *db) bson_init (&filter); /* Compare files collections */ - actual_cursor = - mongoc_collection_find_with_opts (files, &filter, NULL, NULL); - expected_cursor = - mongoc_collection_find_with_opts (expected_files, &filter, NULL, NULL); + actual_cursor = mongoc_collection_find_with_opts (files, &filter, NULL, NULL); + expected_cursor = mongoc_collection_find_with_opts (expected_files, &filter, NULL, NULL); while (mongoc_cursor_next (expected_cursor, &expected_doc)) { ASSERT (mongoc_cursor_next (actual_cursor, &actual_doc)); ASSERT (bson_iter_init_find (&actual_iter, actual_doc, "_id")); ASSERT (bson_iter_init_find (&expected_iter, expected_doc, "_id")); - ASSERT (bson_oid_compare (bson_iter_oid (&actual_iter), - bson_iter_oid (&expected_iter)) == 0); + ASSERT (bson_oid_compare (bson_iter_oid (&actual_iter), bson_iter_oid (&expected_iter)) == 0); ASSERT (bson_iter_init_find (&actual_iter, actual_doc, "length")); ASSERT (bson_iter_init_find (&expected_iter, expected_doc, "length")); - ASSERT (bson_iter_as_int64 (&actual_iter) == - bson_iter_as_int64 (&expected_iter)); + ASSERT (bson_iter_as_int64 (&actual_iter) == bson_iter_as_int64 (&expected_iter)); ASSERT (bson_iter_init_find (&actual_iter, actual_doc, "chunkSize")); ASSERT (bson_iter_init_find (&expected_iter, expected_doc, "chunkSize")); - ASSERT (bson_iter_int32 (&actual_iter) == - bson_iter_int32 (&expected_iter)); + ASSERT (bson_iter_int32 (&actual_iter) == bson_iter_int32 (&expected_iter)); ASSERT (bson_iter_init_find (&actual_iter, actual_doc, "filename")); ASSERT (bson_iter_init_find (&expected_iter, expected_doc, "filename")); - ASSERT (strcmp (bson_iter_utf8 (&actual_iter, NULL), - bson_iter_utf8 (&expected_iter, NULL)) == 0); + ASSERT (strcmp (bson_iter_utf8 (&actual_iter, NULL), bson_iter_utf8 (&expected_iter, NULL)) == 0); } /* Make sure the actual doesn't have extra docs */ @@ -544,10 +504,8 @@ gridfs_compare_collections (mongoc_database_t *db) /* Compare chunks collections */ - actual_cursor = - mongoc_collection_find_with_opts (chunks, &filter, NULL, NULL); - expected_cursor = - mongoc_collection_find_with_opts (expected_chunks, &filter, NULL, NULL); + actual_cursor = mongoc_collection_find_with_opts (chunks, &filter, NULL, NULL); + expected_cursor = mongoc_collection_find_with_opts (expected_chunks, &filter, NULL, NULL); while (mongoc_cursor_next (expected_cursor, &expected_doc)) { @@ -555,13 +513,11 @@ gridfs_compare_collections (mongoc_database_t *db) ASSERT (bson_iter_init_find (&actual_iter, actual_doc, "files_id")); ASSERT (bson_iter_init_find (&expected_iter, expected_doc, "files_id")); - ASSERT (bson_oid_compare (bson_iter_oid (&actual_iter), - bson_iter_oid (&expected_iter)) == 0); + ASSERT (bson_oid_compare (bson_iter_oid (&actual_iter), bson_iter_oid (&expected_iter)) == 0); ASSERT (bson_iter_init_find (&actual_iter, actual_doc, "n")); ASSERT (bson_iter_init_find (&expected_iter, expected_doc, "n")); - ASSERT (bson_iter_int32 (&actual_iter) == - bson_iter_int32 (&expected_iter)); + ASSERT (bson_iter_int32 (&actual_iter) == bson_iter_int32 (&expected_iter)); ASSERT (bson_iter_init_find (&actual_iter, actual_doc, "data")); ASSERT (bson_iter_init_find (&expected_iter, expected_doc, "data")); @@ -585,10 +541,7 @@ gridfs_compare_collections (mongoc_database_t *db) } void -gridfs_spec_delete_operation (mongoc_database_t *db, - mongoc_gridfs_bucket_t *bucket, - bson_t *act, - bson_t *assert) +gridfs_spec_delete_operation (mongoc_database_t *db, mongoc_gridfs_bucket_t *bucket, bson_t *act, bson_t *assert) { bson_iter_t iter; bson_t *arguments; @@ -597,8 +550,7 @@ gridfs_spec_delete_operation (mongoc_database_t *db, ASSERT (bson_iter_init_find (&iter, act, "arguments")); arguments = - bson_new_from_data (bson_iter_value (&iter)->value.v_doc.data, - bson_iter_value (&iter)->value.v_doc.data_len); + bson_new_from_data (bson_iter_value (&iter)->value.v_doc.data, bson_iter_value (&iter)->value.v_doc.data_len); ASSERT (bson_iter_init_find (&iter, arguments, "id")); value = bson_iter_value (&iter); @@ -617,10 +569,7 @@ gridfs_spec_delete_operation (mongoc_database_t *db, } void -gridfs_spec_download_operation (mongoc_database_t *db, - mongoc_gridfs_bucket_t *bucket, - bson_t *act, - bson_t *assert) +gridfs_spec_download_operation (mongoc_database_t *db, mongoc_gridfs_bucket_t *bucket, bson_t *act, bson_t *assert) { bson_iter_t iter; bson_t *arguments; @@ -640,8 +589,7 @@ gridfs_spec_download_operation (mongoc_database_t *db, ASSERT (bson_iter_init_find (&iter, act, "arguments")); arguments = - bson_new_from_data (bson_iter_value (&iter)->value.v_doc.data, - bson_iter_value (&iter)->value.v_doc.data_len); + bson_new_from_data (bson_iter_value (&iter)->value.v_doc.data, bson_iter_value (&iter)->value.v_doc.data_len); if (bson_iter_init_find (&iter, assert, "error")) { expected_error = bson_iter_utf8 (&iter, NULL); @@ -663,8 +611,7 @@ gridfs_spec_download_operation (mongoc_database_t *db, ret = mongoc_stream_read (stream, buf, 100, 0, 0); - if (strcmp (expected_error, "ChunkIsMissing") == 0 || - strcmp (expected_error, "ChunkIsWrongSize") == 0) { + if (strcmp (expected_error, "ChunkIsMissing") == 0 || strcmp (expected_error, "ChunkIsWrongSize") == 0) { ASSERT (ret < 0); r = mongoc_gridfs_bucket_stream_error (stream, &error); ASSERT (r); @@ -677,8 +624,8 @@ gridfs_spec_download_operation (mongoc_database_t *db, mongoc_stream_close (stream); ASSERT (bson_iter_init_find (&iter, assert, "result")); - hex_doc = bson_new_from_data (bson_iter_value (&iter)->value.v_doc.data, - bson_iter_value (&iter)->value.v_doc.data_len); + hex_doc = + bson_new_from_data (bson_iter_value (&iter)->value.v_doc.data, bson_iter_value (&iter)->value.v_doc.data_len); ASSERT (bson_iter_init_find (&iter, hex_doc, "$hex")); str = bson_iter_utf8 (&iter, NULL); @@ -717,10 +664,7 @@ gridfs_spec_download_by_name_operation (mongoc_database_t *db, } void -gridfs_spec_upload_operation (mongoc_database_t *db, - mongoc_gridfs_bucket_t *bucket, - bson_t *act, - bson_t *assert) +gridfs_spec_upload_operation (mongoc_database_t *db, mongoc_gridfs_bucket_t *bucket, bson_t *act, bson_t *assert) { bson_iter_t iter; bson_t *arguments; @@ -738,15 +682,14 @@ gridfs_spec_upload_operation (mongoc_database_t *db, ASSERT (bson_iter_init_find (&iter, act, "arguments")); arguments = - bson_new_from_data (bson_iter_value (&iter)->value.v_doc.data, - bson_iter_value (&iter)->value.v_doc.data_len); + bson_new_from_data (bson_iter_value (&iter)->value.v_doc.data, bson_iter_value (&iter)->value.v_doc.data_len); ASSERT (bson_iter_init_find (&iter, arguments, "filename")); filename = bson_iter_utf8 (&iter, NULL); ASSERT (bson_iter_init_find (&iter, arguments, "source")); - hex_doc = bson_new_from_data (bson_iter_value (&iter)->value.v_doc.data, - bson_iter_value (&iter)->value.v_doc.data_len); + hex_doc = + bson_new_from_data (bson_iter_value (&iter)->value.v_doc.data, bson_iter_value (&iter)->value.v_doc.data_len); ASSERT (bson_iter_init_find (&iter, hex_doc, "$hex")); str = bson_iter_utf8 (&iter, NULL); @@ -758,11 +701,10 @@ gridfs_spec_upload_operation (mongoc_database_t *db, } ASSERT (bson_iter_init_find (&iter, arguments, "options")); - options = bson_new_from_data (bson_iter_value (&iter)->value.v_doc.data, - bson_iter_value (&iter)->value.v_doc.data_len); + options = + bson_new_from_data (bson_iter_value (&iter)->value.v_doc.data, bson_iter_value (&iter)->value.v_doc.data_len); - stream = mongoc_gridfs_bucket_open_upload_stream ( - bucket, filename, options, &file_id, NULL); + stream = mongoc_gridfs_bucket_open_upload_stream (bucket, filename, options, &file_id, NULL); ASSERT (stream); @@ -783,9 +725,7 @@ gridfs_spec_upload_operation (mongoc_database_t *db, bson_destroy (arguments); } void -run_gridfs_spec_test (mongoc_database_t *db, - mongoc_gridfs_bucket_t *bucket, - bson_t *test) +run_gridfs_spec_test (mongoc_database_t *db, mongoc_gridfs_bucket_t *bucket, bson_t *test) { bson_iter_t iter; bson_iter_t inner; @@ -795,17 +735,15 @@ run_gridfs_spec_test (mongoc_database_t *db, const char *operation; ASSERT (bson_iter_init_find (&iter, test, "act")); - act = bson_new_from_data (bson_iter_value (&iter)->value.v_doc.data, - bson_iter_value (&iter)->value.v_doc.data_len); + act = bson_new_from_data (bson_iter_value (&iter)->value.v_doc.data, bson_iter_value (&iter)->value.v_doc.data_len); ASSERT (bson_iter_init_find (&iter, test, "assert")); - assert = bson_new_from_data (bson_iter_value (&iter)->value.v_doc.data, - bson_iter_value (&iter)->value.v_doc.data_len); + assert = + bson_new_from_data (bson_iter_value (&iter)->value.v_doc.data, bson_iter_value (&iter)->value.v_doc.data_len); if (bson_iter_init_find (&iter, test, "arrange")) { arrange = - bson_new_from_data (bson_iter_value (&iter)->value.v_doc.data, - bson_iter_value (&iter)->value.v_doc.data_len); + bson_new_from_data (bson_iter_value (&iter)->value.v_doc.data, bson_iter_value (&iter)->value.v_doc.data_len); gridfs_spec_run_commands (db, arrange); bson_destroy (arrange); } @@ -851,8 +789,8 @@ test_gridfs_cb (bson_t *scenario) /* Insert the data */ if (bson_iter_init_find (&iter, scenario, "data")) { - data = bson_new_from_data (bson_iter_value (&iter)->value.v_doc.data, - bson_iter_value (&iter)->value.v_doc.data_len); + data = + bson_new_from_data (bson_iter_value (&iter)->value.v_doc.data, bson_iter_value (&iter)->value.v_doc.data_len); setup_gridfs_collections (db, data); bson_destroy (data); } @@ -860,14 +798,12 @@ test_gridfs_cb (bson_t *scenario) /* Run the tests */ if (bson_iter_init_find (&iter, scenario, "tests")) { tests = - bson_new_from_data (bson_iter_value (&iter)->value.v_doc.data, - bson_iter_value (&iter)->value.v_doc.data_len); + bson_new_from_data (bson_iter_value (&iter)->value.v_doc.data, bson_iter_value (&iter)->value.v_doc.data_len); bson_iter_init (&inner, tests); while (bson_iter_next (&inner)) { - test = - bson_new_from_data (bson_iter_value (&inner)->value.v_doc.data, - bson_iter_value (&inner)->value.v_doc.data_len); + test = bson_new_from_data (bson_iter_value (&inner)->value.v_doc.data, + bson_iter_value (&inner)->value.v_doc.data_len); run_gridfs_spec_test (db, gridfs, test); bson_destroy (test); } @@ -904,17 +840,14 @@ test_upload_error (void *ctx) client = test_framework_new_default_client (); db = mongoc_client_get_database (client, dbname); gridfs = mongoc_gridfs_bucket_new (db, NULL, NULL, NULL); - source = mongoc_stream_file_new_for_path ( - BSON_BINARY_DIR "/test1.bson", O_RDONLY, 0); + source = mongoc_stream_file_new_for_path (BSON_BINARY_DIR "/test1.bson", O_RDONLY, 0); BSON_ASSERT (source); - r = mongoc_gridfs_bucket_upload_from_stream ( - gridfs, "test1", source, NULL /* opts */, NULL /* file id */, &error); + r = mongoc_gridfs_bucket_upload_from_stream (gridfs, "test1", source, NULL /* opts */, NULL /* file id */, &error); ASSERT_OR_PRINT (r, error); /* create a read-only user */ (void) mongoc_database_remove_user (db, "fake_user", NULL); - r = mongoc_database_add_user ( - db, "fake_user", "password", tmp_bson ("{'0': 'read'}"), NULL, &error); + r = mongoc_database_add_user (db, "fake_user", "password", tmp_bson ("{'0': 'read'}"), NULL, &error); ASSERT_OR_PRINT (r, error); mongoc_stream_close (source); @@ -931,15 +864,12 @@ test_upload_error (void *ctx) test_framework_set_ssl_opts (client); mongoc_uri_destroy (uri); - source = mongoc_stream_file_new_for_path ( - BSON_BINARY_DIR "/test1.bson", O_RDONLY, 0); + source = mongoc_stream_file_new_for_path (BSON_BINARY_DIR "/test1.bson", O_RDONLY, 0); BSON_ASSERT (source); db = mongoc_client_get_database (client, dbname); gridfs = mongoc_gridfs_bucket_new (db, NULL, NULL, NULL); - mongoc_gridfs_bucket_upload_from_stream ( - gridfs, "test1", source, NULL /* opts */, NULL /* file id */, &error); - ASSERT_ERROR_CONTAINS ( - error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_AUTHENTICATE, ""); + mongoc_gridfs_bucket_upload_from_stream (gridfs, "test1", source, NULL /* opts */, NULL /* file id */, &error); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_AUTHENTICATE, ""); mongoc_stream_close (source); mongoc_stream_destroy (source); @@ -974,10 +904,8 @@ test_find_w_session (void *ctx) ASSERT_OR_PRINT (r, error); cursor = mongoc_gridfs_bucket_find (gridfs, tmp_bson ("{}"), &opts); BSON_ASSERT (mongoc_cursor_error (cursor, &error)); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_CURSOR, - MONGOC_ERROR_CURSOR_INVALID_CURSOR, - "Cannot pass sessionId as an option"); + ASSERT_ERROR_CONTAINS ( + error, MONGOC_ERROR_CURSOR, MONGOC_ERROR_CURSOR_INVALID_CURSOR, "Cannot pass sessionId as an option"); bson_destroy (&opts); mongoc_cursor_destroy (cursor); mongoc_gridfs_bucket_destroy (gridfs); @@ -993,8 +921,7 @@ test_find (void *ctx) mongoc_client_t *const client = test_framework_new_default_client (); char *const dbname = gen_collection_name ("test_find"); mongoc_database_t *const db = mongoc_client_get_database (client, dbname); - mongoc_gridfs_bucket_t *const gridfs = - mongoc_gridfs_bucket_new (db, NULL, NULL, NULL); + mongoc_gridfs_bucket_t *const gridfs = mongoc_gridfs_bucket_new (db, NULL, NULL, NULL); mongoc_cursor_t *cursor; bson_error_t error = {0}; bson_t const *found; @@ -1002,31 +929,14 @@ test_find (void *ctx) char buffer[256] = {0}; bool ok; bson_value_t const *found_id; - const bson_t *const find_opts = - tmp_bson ("{'limit': 1, 'skip': 2, 'sort': {'metadata.testOrder': -1}}"); + const bson_t *const find_opts = tmp_bson ("{'limit': 1, 'skip': 2, 'sort': {'metadata.testOrder': -1}}"); BSON_UNUSED (ctx); - _upload_file_from_str (gridfs, - "file1", - "First file", - tmp_bson ("{'metadata': {'testOrder': 1}}"), - NULL); - _upload_file_from_str (gridfs, - "file2", - "Second file", - tmp_bson ("{'metadata': {'testOrder': 2}}"), - NULL); - _upload_file_from_str (gridfs, - "file3", - "Third file", - tmp_bson ("{'metadata': {'testOrder': 3}}"), - NULL); - _upload_file_from_str (gridfs, - "file4", - "Fourth file", - tmp_bson ("{'metadata': {'testOrder': 4}}"), - NULL); + _upload_file_from_str (gridfs, "file1", "First file", tmp_bson ("{'metadata': {'testOrder': 1}}"), NULL); + _upload_file_from_str (gridfs, "file2", "Second file", tmp_bson ("{'metadata': {'testOrder': 2}}"), NULL); + _upload_file_from_str (gridfs, "file3", "Third file", tmp_bson ("{'metadata': {'testOrder': 3}}"), NULL); + _upload_file_from_str (gridfs, "file4", "Fourth file", tmp_bson ("{'metadata': {'testOrder': 4}}"), NULL); cursor = mongoc_gridfs_bucket_find (gridfs, tmp_bson ("{}"), find_opts); ASSERT_OR_PRINT (!mongoc_cursor_error (cursor, &error), error); @@ -1070,35 +980,23 @@ test_gridfs_bucket_opts (void) ASSERT_OR_PRINT (gridfs, error); ASSERT_CMPSTR (gridfs->bucket_name, "fs"); ASSERT_CMPINT32 (gridfs->chunk_size, ==, 255 * 1024); - BSON_ASSERT (!mongoc_read_concern_get_level ( - mongoc_collection_get_read_concern (gridfs->chunks))); - BSON_ASSERT (!mongoc_read_concern_get_level ( - mongoc_collection_get_read_concern (gridfs->files))); - ASSERT_CMPINT (mongoc_write_concern_get_w ( - mongoc_collection_get_write_concern (gridfs->chunks)), + BSON_ASSERT (!mongoc_read_concern_get_level (mongoc_collection_get_read_concern (gridfs->chunks))); + BSON_ASSERT (!mongoc_read_concern_get_level (mongoc_collection_get_read_concern (gridfs->files))); + ASSERT_CMPINT (mongoc_write_concern_get_w (mongoc_collection_get_write_concern (gridfs->chunks)), ==, MONGOC_WRITE_CONCERN_W_DEFAULT); - ASSERT_CMPINT (mongoc_write_concern_get_w ( - mongoc_collection_get_write_concern (gridfs->files)), + ASSERT_CMPINT (mongoc_write_concern_get_w (mongoc_collection_get_write_concern (gridfs->files)), ==, MONGOC_WRITE_CONCERN_W_DEFAULT); mongoc_gridfs_bucket_destroy (gridfs); /* check out-of-range chunk sizes */ - gridfs = mongoc_gridfs_bucket_new ( - db, tmp_bson ("{'chunkSizeBytes': -1}"), NULL, &error); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "should be greater than 0"); + gridfs = mongoc_gridfs_bucket_new (db, tmp_bson ("{'chunkSizeBytes': -1}"), NULL, &error); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "should be greater than 0"); mongoc_gridfs_bucket_destroy (gridfs); - gridfs = mongoc_gridfs_bucket_new ( - db, tmp_bson ("{'chunkSizeBytes': 2147483648}"), NULL, &error); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "out of range"); + gridfs = mongoc_gridfs_bucket_new (db, tmp_bson ("{'chunkSizeBytes': 2147483648}"), NULL, &error); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "out of range"); mongoc_gridfs_bucket_destroy (gridfs); rc = mongoc_read_concern_new (); @@ -1113,18 +1011,14 @@ test_gridfs_bucket_opts (void) ASSERT_OR_PRINT (gridfs, error); ASSERT_CMPSTR (gridfs->bucket_name, "abc"); ASSERT_CMPINT32 (gridfs->chunk_size, ==, 123); - ASSERT_CMPSTR (mongoc_read_concern_get_level ( - mongoc_collection_get_read_concern (gridfs->chunks)), + ASSERT_CMPSTR (mongoc_read_concern_get_level (mongoc_collection_get_read_concern (gridfs->chunks)), MONGOC_READ_CONCERN_LEVEL_AVAILABLE); - ASSERT_CMPSTR (mongoc_read_concern_get_level ( - mongoc_collection_get_read_concern (gridfs->files)), + ASSERT_CMPSTR (mongoc_read_concern_get_level (mongoc_collection_get_read_concern (gridfs->files)), MONGOC_READ_CONCERN_LEVEL_AVAILABLE); - ASSERT_CMPINT (mongoc_write_concern_get_w ( - mongoc_collection_get_write_concern (gridfs->chunks)), + ASSERT_CMPINT (mongoc_write_concern_get_w (mongoc_collection_get_write_concern (gridfs->chunks)), ==, MONGOC_WRITE_CONCERN_W_UNACKNOWLEDGED); - ASSERT_CMPINT (mongoc_write_concern_get_w ( - mongoc_collection_get_write_concern (gridfs->files)), + ASSERT_CMPINT (mongoc_write_concern_get_w (mongoc_collection_get_write_concern (gridfs->files)), ==, MONGOC_WRITE_CONCERN_W_UNACKNOWLEDGED); mongoc_read_concern_destroy (rc); @@ -1137,10 +1031,7 @@ test_gridfs_bucket_opts (void) memset (bucket_name, 'a', 128 - strlen ("chunks")); opts = BCON_NEW ("bucketName", bucket_name); gridfs = mongoc_gridfs_bucket_new (db, opts, NULL, &error); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "must have fewer"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "must have fewer"); bson_destroy (opts); mongoc_gridfs_bucket_destroy (gridfs); @@ -1162,14 +1053,8 @@ test_gridfs_bucket_install (TestSuite *suite) { test_all_spec_tests (suite); TestSuite_AddLive (suite, "/gridfs/create_bucket", test_create_bucket); - TestSuite_AddLive ( - suite, "/gridfs/upload_and_download", test_upload_and_download); - TestSuite_AddFull (suite, - "/gridfs/upload_error", - test_upload_error, - NULL, - NULL, - test_framework_skip_if_no_auth); + TestSuite_AddLive (suite, "/gridfs/upload_and_download", test_upload_and_download); + TestSuite_AddFull (suite, "/gridfs/upload_error", test_upload_error, NULL, NULL, test_framework_skip_if_no_auth); TestSuite_AddFull (suite, "/gridfs/find_w_session", test_find_w_session, diff --git a/src/libmongoc/tests/test-mongoc-gridfs.c b/src/libmongoc/tests/test-mongoc-gridfs.c index 5193c6f469..3446a8e981 100644 --- a/src/libmongoc/tests/test-mongoc-gridfs.c +++ b/src/libmongoc/tests/test-mongoc-gridfs.c @@ -78,9 +78,7 @@ _check_index (mongoc_collection_t *collection, const char *index_json) static mongoc_gridfs_t * -_get_gridfs (mock_server_t *server, - mongoc_client_t *client, - mongoc_query_flags_t flags) +_get_gridfs (mock_server_t *server, mongoc_client_t *client, mongoc_query_flags_t flags) { future_t *future; bson_error_t error; @@ -92,37 +90,25 @@ _get_gridfs (mock_server_t *server, /* gridfs ensures two indexes */ future = future_client_get_gridfs (client, "db", NULL, &error); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db', 'listIndexes': 'fs.chunks'}")); - reply_to_request_simple ( - request, - "{ 'ok' : 0, 'errmsg' : 'ns does not exist: db.fs.chunks', 'code' : 26, " - "'codeName' : 'NamespaceNotFound' }"); + request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', 'listIndexes': 'fs.chunks'}")); + reply_to_request_simple (request, + "{ 'ok' : 0, 'errmsg' : 'ns does not exist: db.fs.chunks', 'code' : 26, " + "'codeName' : 'NamespaceNotFound' }"); request_destroy (request); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db', 'createIndexes': 'fs.chunks'}")); + request = + mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', 'createIndexes': 'fs.chunks'}")); reply_to_request_with_ok_and_destroy (request); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db', 'listIndexes': 'fs.files'}")); - reply_to_request_simple ( - request, - "{ 'ok' : 0, 'errmsg' : 'ns does not exist: db.fs.files', 'code' : 26, " - "'codeName' : 'NamespaceNotFound' }"); + request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', 'listIndexes': 'fs.files'}")); + reply_to_request_simple (request, + "{ 'ok' : 0, 'errmsg' : 'ns does not exist: db.fs.files', 'code' : 26, " + "'codeName' : 'NamespaceNotFound' }"); request_destroy (request); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db', 'createIndexes': 'fs.files'}")); + request = + mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', 'createIndexes': 'fs.files'}")); reply_to_request_with_ok_and_destroy (request); @@ -159,17 +145,14 @@ _test_create (bson_t *create_index_cmd) db = mongoc_client_get_database (client, "test"); - r = mongoc_database_write_command_with_opts ( - db, create_index_cmd, NULL, NULL, &error); + r = mongoc_database_write_command_with_opts (db, create_index_cmd, NULL, NULL, &error); ASSERT_OR_PRINT (r, error); mongoc_database_destroy (db); } - ASSERT_OR_PRINT ( - (gridfs = mongoc_client_get_gridfs (client, "test", "foo", &error)), - error); + ASSERT_OR_PRINT ((gridfs = mongoc_client_get_gridfs (client, "test", "foo", &error)), error); file = mongoc_gridfs_create_file (gridfs, NULL); @@ -196,11 +179,10 @@ test_create (void) _test_create (NULL); /* Test files index with float and same options */ - _test_create ( - tmp_bson ("{'createIndexes': '%s'," - " 'indexes': [{'key': {'filename': 1.0, 'uploadDate': 1}, " - "'name': 'filename_1_uploadDate_1'}]}", - "foo.files")); + _test_create (tmp_bson ("{'createIndexes': '%s'," + " 'indexes': [{'key': {'filename': 1.0, 'uploadDate': 1}, " + "'name': 'filename_1_uploadDate_1'}]}", + "foo.files")); /* Files index with float and different options */ _test_create (tmp_bson ("{'createIndexes': '%s'," @@ -235,8 +217,7 @@ test_remove (void) client = test_framework_new_default_client (); ASSERT (client); - ASSERT_OR_PRINT ( - gridfs = mongoc_client_get_gridfs (client, "test", "foo", &error), error); + ASSERT_OR_PRINT (gridfs = mongoc_client_get_gridfs (client, "test", "foo", &error), error); mongoc_gridfs_drop (gridfs, &error); @@ -319,8 +300,7 @@ test_list (void) while ((file = mongoc_gridfs_file_list_next (list))) { bson_snprintf (buf, sizeof buf, "file.%d", i++); - ASSERT_CMPINT ( - strcmp (mongoc_gridfs_file_get_filename (file), buf), ==, 0); + ASSERT_CMPINT (strcmp (mongoc_gridfs_file_get_filename (file), buf), ==, 0); mongoc_gridfs_file_destroy (file); } @@ -329,20 +309,15 @@ test_list (void) bson_init (&query); bson_append_utf8 (&query, "filename", -1, "file.1", -1); - ASSERT_OR_PRINT (file = mongoc_gridfs_find_one (gridfs, &query, &error), - error); + ASSERT_OR_PRINT (file = mongoc_gridfs_find_one (gridfs, &query, &error), error); bson_destroy (&query); - ASSERT_CMPINT ( - strcmp (mongoc_gridfs_file_get_filename (file), "file.1"), ==, 0); + ASSERT_CMPINT (strcmp (mongoc_gridfs_file_get_filename (file), "file.1"), ==, 0); mongoc_gridfs_file_destroy (file); - ASSERT_OR_PRINT ( - file = mongoc_gridfs_find_one_by_filename (gridfs, "file.1", &error), - error); + ASSERT_OR_PRINT (file = mongoc_gridfs_find_one_by_filename (gridfs, "file.1", &error), error); - ASSERT_CMPINT ( - strcmp (mongoc_gridfs_file_get_filename (file), "file.1"), ==, 0); + ASSERT_CMPINT (strcmp (mongoc_gridfs_file_get_filename (file), "file.1"), ==, 0); mongoc_gridfs_file_destroy (file); drop_collections (gridfs, &error); @@ -368,9 +343,7 @@ test_find_with_opts (void) prep_files (gridfs); list = mongoc_gridfs_find_with_opts ( - gridfs, - tmp_bson ("{'filename': {'$ne': 'file.1'}}"), - tmp_bson ("{'sort': {'filename': -1}}")); + gridfs, tmp_bson ("{'filename': {'$ne': 'file.1'}}"), tmp_bson ("{'sort': {'filename': -1}}")); file = mongoc_gridfs_file_list_next (list); ASSERT (file); @@ -387,23 +360,20 @@ test_find_with_opts (void) ASSERT (!mongoc_gridfs_file_list_error (list, &error)); mongoc_gridfs_file_list_destroy (list); - file = mongoc_gridfs_find_one_with_opts ( - gridfs, tmp_bson (NULL), tmp_bson ("{'sort': {'filename': -1}}"), &error); + file = mongoc_gridfs_find_one_with_opts (gridfs, tmp_bson (NULL), tmp_bson ("{'sort': {'filename': -1}}"), &error); ASSERT_OR_PRINT (file, error); /* file.2 is first, according to sort order */ ASSERT_CMPSTR ("file.2", mongoc_gridfs_file_get_filename (file)); mongoc_gridfs_file_destroy (file); - file = mongoc_gridfs_find_one_with_opts ( - gridfs, tmp_bson ("{'x': {'$bad_operator': 1}}"), NULL, &error); + file = mongoc_gridfs_find_one_with_opts (gridfs, tmp_bson ("{'x': {'$bad_operator': 1}}"), NULL, &error); ASSERT (!file); ASSERT_CMPINT (error.domain, ==, MONGOC_ERROR_SERVER); /* ensure "error" is cleared if we successfully find no file */ - file = mongoc_gridfs_find_one_with_opts ( - gridfs, tmp_bson ("{'x': 'doesntexist'}"), NULL, &error); + file = mongoc_gridfs_find_one_with_opts (gridfs, tmp_bson ("{'x': 'doesntexist'}"), NULL, &error); ASSERT (!file); ASSERT_CMPINT (error.domain, ==, 0); @@ -430,29 +400,23 @@ test_find_one_with_opts_limit (void) server = mock_server_with_auto_hello (WIRE_VERSION_MIN); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); mongoc_client_set_error_api (client, 2); gridfs = _get_gridfs (server, client, MONGOC_QUERY_SECONDARY_OK); - future = - future_gridfs_find_one_with_opts (gridfs, tmp_bson ("{}"), NULL, &error); + future = future_gridfs_find_one_with_opts (gridfs, tmp_bson ("{}"), NULL, &error); request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db', 'find': 'fs.files', 'filter': {}, 'limit': 1}")); - - reply_to_op_msg_request ( - request, - MONGOC_MSG_NONE, - tmp_bson ( - "{'ok': 1," - " 'cursor': {" - " 'id': {'$numberLong': '0'}," - " 'ns': 'db.fs.files'," - " 'firstBatch': [{'_id': 1, 'length': 1, 'chunkSize': 1}]}}")); + server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', 'find': 'fs.files', 'filter': {}, 'limit': 1}")); + + reply_to_op_msg_request (request, + MONGOC_MSG_NONE, + tmp_bson ("{'ok': 1," + " 'cursor': {" + " 'id': {'$numberLong': '0'}," + " 'ns': 'db.fs.files'," + " 'firstBatch': [{'_id': 1, 'length': 1, 'chunkSize': 1}]}}")); file = future_get_mongoc_gridfs_file_ptr (future); ASSERT (file); @@ -461,23 +425,18 @@ test_find_one_with_opts_limit (void) future_destroy (future); request_destroy (request); - future = future_gridfs_find_one_with_opts ( - gridfs, tmp_bson ("{}"), tmp_bson ("{'limit': 2}"), &error); + future = future_gridfs_find_one_with_opts (gridfs, tmp_bson ("{}"), tmp_bson ("{'limit': 2}"), &error); request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db', 'find': 'fs.files', 'filter': {}, 'limit': 1}")); - - reply_to_op_msg_request ( - request, - MONGOC_MSG_NONE, - tmp_bson ( - "{'ok': 1," - " 'cursor': {" - " 'id': {'$numberLong': '0'}," - " 'ns': 'db.fs.files'," - " 'firstBatch': [{'_id': 1, 'length': 1, 'chunkSize': 1}]}}")); + server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', 'find': 'fs.files', 'filter': {}, 'limit': 1}")); + + reply_to_op_msg_request (request, + MONGOC_MSG_NONE, + tmp_bson ("{'ok': 1," + " 'cursor': {" + " 'id': {'$numberLong': '0'}," + " 'ns': 'db.fs.files'," + " 'firstBatch': [{'_id': 1, 'length': 1, 'chunkSize': 1}]}}")); file = future_get_mongoc_gridfs_file_ptr (future); ASSERT (file); @@ -532,8 +491,7 @@ test_properties (void) "chunkSize", BCON_INT32 (100)); - ASSERT (mongoc_collection_insert_one ( - mongoc_gridfs_get_files (gridfs), doc_in, NULL, NULL, NULL)); + ASSERT (mongoc_collection_insert_one (mongoc_gridfs_get_files (gridfs), doc_in, NULL, NULL, NULL)); list = mongoc_gridfs_find (gridfs, &query); file = mongoc_gridfs_file_list_next (list); @@ -544,11 +502,8 @@ test_properties (void) ASSERT_CMPSTR ("md5", mongoc_gridfs_file_get_md5 (file)); ASSERT_CMPSTR ("filename", mongoc_gridfs_file_get_filename (file)); ASSERT_CMPSTR ("content_type", mongoc_gridfs_file_get_content_type (file)); - ASSERT (BCON_EXTRACT ((bson_t *) mongoc_gridfs_file_get_aliases (file), - "0", - BCONE_UTF8 (alias0), - "1", - BCONE_UTF8 (alias1))); + ASSERT (BCON_EXTRACT ( + (bson_t *) mongoc_gridfs_file_get_aliases (file), "0", BCONE_UTF8 (alias0), "1", BCONE_UTF8 (alias1))); ASSERT_CMPSTR ("alias0", alias0); ASSERT_CMPSTR ("alias1", alias1); @@ -579,14 +534,12 @@ test_create_from_stream (void) client = test_framework_new_default_client (); ASSERT (client); - ASSERT_OR_PRINT ((gridfs = get_test_gridfs (client, "from_stream", &error)), - error); + ASSERT_OR_PRINT ((gridfs = get_test_gridfs (client, "from_stream", &error)), error); mongoc_gridfs_drop (gridfs, &error); start = _mongoc_get_real_time_ms (); - stream = - mongoc_stream_file_new_for_path (BINARY_DIR "/gridfs.dat", O_RDONLY, 0); + stream = mongoc_stream_file_new_for_path (BINARY_DIR "/gridfs.dat", O_RDONLY, 0); ASSERT_OR_PRINT_ERRNO (stream, errno); ASSERT (stream); @@ -627,8 +580,7 @@ test_seek (void) mongoc_gridfs_drop (gridfs, &error); - stream = mongoc_stream_file_new_for_path ( - BINARY_DIR "/gridfs-large.dat", O_RDONLY, 0); + stream = mongoc_stream_file_new_for_path (BINARY_DIR "/gridfs-large.dat", O_RDONLY, 0); file = mongoc_gridfs_create_file_from_stream (gridfs, stream, NULL); ASSERT (file); @@ -637,14 +589,11 @@ test_seek (void) ASSERT_CMPINT (mongoc_gridfs_file_seek (file, 0, SEEK_SET), ==, 0); ASSERT_CMPUINT64 (mongoc_gridfs_file_tell (file), ==, (uint64_t) 0); - ASSERT_CMPINT ( - mongoc_gridfs_file_seek (file, file->chunk_size + 1, SEEK_CUR), ==, 0); - ASSERT_CMPINT64 ( - mongoc_gridfs_file_tell (file), ==, (uint64_t) (file->chunk_size + 1)); + ASSERT_CMPINT (mongoc_gridfs_file_seek (file, file->chunk_size + 1, SEEK_CUR), ==, 0); + ASSERT_CMPINT64 (mongoc_gridfs_file_tell (file), ==, (uint64_t) (file->chunk_size + 1)); ASSERT_CMPINT (mongoc_gridfs_file_seek (file, 0, SEEK_END), ==, 0); - ASSERT_CMPINT64 ( - mongoc_gridfs_file_tell (file), ==, mongoc_gridfs_file_get_length (file)); + ASSERT_CMPINT64 (mongoc_gridfs_file_tell (file), ==, mongoc_gridfs_file_get_length (file)); mongoc_gridfs_file_destroy (file); @@ -682,8 +631,7 @@ test_read (void) mongoc_gridfs_drop (gridfs, &error); - stream = mongoc_stream_file_new_for_path ( - BINARY_DIR "/gridfs-large.dat", O_RDONLY, 0); + stream = mongoc_stream_file_new_for_path (BINARY_DIR "/gridfs-large.dat", O_RDONLY, 0); file = mongoc_gridfs_create_file_from_stream (gridfs, stream, NULL); ASSERT (file); @@ -701,13 +649,11 @@ test_read (void) ASSERT_MEMCMP (iov[0].iov_base, "acon ipsum", 10); ASSERT_MEMCMP (iov[1].iov_base, " dolor sit", 10); - ASSERT_CMPINT ( - mongoc_gridfs_file_seek (file, file->chunk_size - 1, SEEK_SET), ==, 0); + ASSERT_CMPINT (mongoc_gridfs_file_seek (file, file->chunk_size - 1, SEEK_SET), ==, 0); r = mongoc_gridfs_file_readv (file, iov, 2, 20, 0); ASSERT_CMPSSIZE_T (r, ==, twenty); - ASSERT_CMPINT64 ( - mongoc_gridfs_file_tell (file), ==, (uint64_t) (file->chunk_size + 19)); + ASSERT_CMPINT64 (mongoc_gridfs_file_tell (file), ==, (uint64_t) (file->chunk_size + 19)); ASSERT_MEMCMP (iov[0].iov_base, "turducken ", 10); ASSERT_MEMCMP (iov[1].iov_base, "spare ribs", 10); @@ -737,12 +683,8 @@ _check_chunk_count (mongoc_gridfs_t *gridfs, int64_t len, int64_t chunk_size) /* division, rounding up */ expected_chunks = (len + chunk_size - 1) / chunk_size; - cnt = mongoc_collection_count_documents (mongoc_gridfs_get_chunks (gridfs), - tmp_bson (NULL), - NULL, - NULL, - NULL, - &error); + cnt = + mongoc_collection_count_documents (mongoc_gridfs_get_chunks (gridfs), tmp_bson (NULL), NULL, NULL, NULL, &error); ASSERT_CMPINT64 (expected_chunks, ==, cnt); } @@ -797,10 +739,8 @@ _test_write (bool at_boundary) ASSERT_CMPSSIZE_T (r, ==, len); ASSERT_CMPINT (memcmp (buf3, "foo bar baz", len), ==, 0); - ASSERT_CMPINT ( - mongoc_gridfs_file_seek (file, file->chunk_size, SEEK_SET), ==, 0); - ASSERT_CMPUINT64 ( - mongoc_gridfs_file_tell (file), ==, (uint64_t) (file->chunk_size)); + ASSERT_CMPINT (mongoc_gridfs_file_seek (file, file->chunk_size, SEEK_SET), ==, 0); + ASSERT_CMPUINT64 (mongoc_gridfs_file_tell (file), ==, (uint64_t) (file->chunk_size)); r = mongoc_gridfs_file_writev (file, iov + 1, 1, 0); ASSERT_CMPSSIZE_T (r, ==, iov[1].iov_len); @@ -832,9 +772,7 @@ _test_write (bool at_boundary) /* expect file to be like "fo bazr baz\0\0\0\0\0\0foo bar baz" */ bson_snprintf (expected, strlen ("fo bazr baz") + 1, "fo bazr baz"); - bson_snprintf (expected + strlen ("fo bazr baz") + seek_len, - strlen ("foo bar baz") + 1, - "foo bar baz"); + bson_snprintf (expected + strlen ("fo bazr baz") + seek_len, strlen ("foo bar baz") + 1, "foo bar baz"); BSON_ASSERT (memcmp (buf3, expected, (size_t) (2 * len + seek_len)) == 0); BSON_ASSERT (mongoc_gridfs_file_save (file)); @@ -880,8 +818,7 @@ test_write_past_end (void) const uint64_t delta = 35u; const uint32_t chunk_sz = 10u; /* division, rounding up */ - const uint64_t expected_chunks = - ((delta + len) + (chunk_sz - 1u)) / chunk_sz; + const uint64_t expected_chunks = ((delta + len) + (chunk_sz - 1u)) / chunk_sz; int64_t cnt; iov[0].iov_base = buf; @@ -906,8 +843,7 @@ test_write_past_end (void) ASSERT (bson_in_range_signed (size_t, r)); ASSERT_CMPSIZE_T ((size_t) r, ==, len); - ASSERT_CMPINT ( - mongoc_gridfs_file_seek (file, (int64_t) delta, SEEK_SET), ==, 0); + ASSERT_CMPINT (mongoc_gridfs_file_seek (file, (int64_t) delta, SEEK_SET), ==, 0); ASSERT_CMPUINT64 (mongoc_gridfs_file_tell (file), ==, delta); r = mongoc_gridfs_file_writev (file, iov, 1, 0); @@ -915,12 +851,8 @@ test_write_past_end (void) ASSERT_CMPSIZE_T ((size_t) r, ==, len); mongoc_gridfs_file_save (file); - cnt = mongoc_collection_count_documents (mongoc_gridfs_get_chunks (gridfs), - tmp_bson (NULL), - NULL, - NULL, - NULL, - &error); + cnt = + mongoc_collection_count_documents (mongoc_gridfs_get_chunks (gridfs), tmp_bson (NULL), NULL, NULL, NULL, &error); ASSERT_OR_PRINT (cnt != -1, error); ASSERT (bson_cmp_equal_us (expected_chunks, cnt)); @@ -963,8 +895,7 @@ test_empty (void) ASSERT_OR_PRINT (gridfs = get_test_gridfs (client, "empty", &error), error); - stream = - mongoc_stream_file_new_for_path (BINARY_DIR "/empty.dat", O_RDONLY, 0); + stream = mongoc_stream_file_new_for_path (BINARY_DIR "/empty.dat", O_RDONLY, 0); ASSERT_OR_PRINT_ERRNO (stream, errno); file = mongoc_gridfs_create_file_from_stream (gridfs, stream, NULL); @@ -1021,8 +952,7 @@ test_stream (void) mongoc_gridfs_drop (gridfs, &error); - in_stream = - mongoc_stream_file_new_for_path (BINARY_DIR "/gridfs.dat", O_RDONLY, 0); + in_stream = mongoc_stream_file_new_for_path (BINARY_DIR "/gridfs.dat", O_RDONLY, 0); ASSERT_OR_PRINT_ERRNO (in_stream, errno); file = mongoc_gridfs_create_file_from_stream (gridfs, in_stream, NULL); @@ -1032,8 +962,7 @@ test_stream (void) stream = mongoc_stream_gridfs_new (file); ASSERT (bson_in_range_signed (size_t, file->length)); - const ssize_t r = - mongoc_stream_readv (stream, &iov, 1, (size_t) file->length, 0); + const ssize_t r = mongoc_stream_readv (stream, &iov, 1, (size_t) file->length, 0); ASSERT_CMPINT64 ((int64_t) r, ==, file->length); /* cleanup */ @@ -1047,8 +976,7 @@ test_stream (void) } -#define ASSERT_TELL(file_, position_) \ - ASSERT_CMPUINT64 (mongoc_gridfs_file_tell (file_), ==, position_) +#define ASSERT_TELL(file_, position_) ASSERT_CMPUINT64 (mongoc_gridfs_file_tell (file_), ==, position_) static void @@ -1092,8 +1020,7 @@ test_long_seek (void *ctx) /* new file handle */ mongoc_gridfs_file_save (file); mongoc_gridfs_file_destroy (file); - file = mongoc_gridfs_find_one ( - gridfs, tmp_bson ("{'filename': 'filename'}"), &error); + file = mongoc_gridfs_find_one (gridfs, tmp_bson ("{'filename': 'filename'}"), &error); ASSERT_OR_PRINT (file, error); @@ -1145,9 +1072,7 @@ test_remove_by_filename (void) client = test_framework_new_default_client (); ASSERT (client); - ASSERT_OR_PRINT ( - gridfs = get_test_gridfs (client, "fs_remove_by_filename", &error), - error); + ASSERT_OR_PRINT (gridfs = get_test_gridfs (client, "fs_remove_by_filename", &error), error); mongoc_gridfs_drop (gridfs, &error); @@ -1162,9 +1087,7 @@ test_remove_by_filename (void) ASSERT (file); ASSERT (mongoc_gridfs_file_save (file)); - ASSERT_OR_PRINT ( - mongoc_gridfs_remove_by_filename (gridfs, "foo_file_1.txt", &error), - error); + ASSERT_OR_PRINT (mongoc_gridfs_remove_by_filename (gridfs, "foo_file_1.txt", &error), error); mongoc_gridfs_file_destroy (file); file = mongoc_gridfs_find_one_by_filename (gridfs, "foo_file_1.txt", &error); @@ -1225,8 +1148,7 @@ test_missing_chunk (void *ctx) /* chunks have n=0, 1, 2; remove the middle one */ chunks = mongoc_gridfs_get_chunks (gridfs); - ret = mongoc_collection_delete_many ( - chunks, tmp_bson ("{'n': 1}"), NULL, NULL, &error); + ret = mongoc_collection_delete_many (chunks, tmp_bson ("{'n': 1}"), NULL, NULL, &error); ASSERT_OR_PRINT (ret, error); @@ -1237,10 +1159,8 @@ test_missing_chunk (void *ctx) ASSERT_CMPSSIZE_T (r, ==, buflen); } else { ASSERT (mongoc_gridfs_file_error (file, &error)); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_GRIDFS, - MONGOC_ERROR_GRIDFS_CHUNK_MISSING, - "missing chunk number 1"); + ASSERT_ERROR_CONTAINS ( + error, MONGOC_ERROR_GRIDFS, MONGOC_ERROR_GRIDFS_CHUNK_MISSING, "missing chunk number 1"); break; } @@ -1271,22 +1191,20 @@ test_oversize (void) ASSERT_OR_PRINT (gridfs, error); /* 2-byte chunk, 'aa', but chunkSize and file size are 1 byte */ - ret = mongoc_collection_insert_one ( - gridfs->chunks, - tmp_bson ("{'files_id': 1, 'n': 0," - " 'data': {'$binary': {'subType': '0', 'base64': 'YWE='}}}"), - NULL, - NULL, - &error); + ret = mongoc_collection_insert_one (gridfs->chunks, + tmp_bson ("{'files_id': 1, 'n': 0," + " 'data': {'$binary': {'subType': '0', 'base64': 'YWE='}}}"), + NULL, + NULL, + &error); ASSERT_OR_PRINT (ret, error); - ret = mongoc_collection_insert_one ( - gridfs->files, - tmp_bson ("{'_id': 1, 'length': 1, 'chunkSize': 1," - " 'filename': 'filename'}"), - NULL, - NULL, - &error); + ret = mongoc_collection_insert_one (gridfs->files, + tmp_bson ("{'_id': 1, 'length': 1, 'chunkSize': 1," + " 'filename': 'filename'}"), + NULL, + NULL, + &error); ASSERT_OR_PRINT (ret, error); file = mongoc_gridfs_find_one_by_filename (gridfs, "filename", &error); @@ -1298,10 +1216,7 @@ test_oversize (void) r = mongoc_gridfs_file_readv (file, &iov, 1, sizeof (buf), 0); ASSERT_CMPSSIZE_T (r, ==, (ssize_t) -1); BSON_ASSERT (mongoc_gridfs_file_error (file, &error)); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_GRIDFS, - MONGOC_ERROR_GRIDFS_CORRUPT, - "corrupt chunk number 0: bad size"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_GRIDFS, MONGOC_ERROR_GRIDFS_CORRUPT, "corrupt chunk number 0: bad size"); mongoc_gridfs_file_destroy (file); ASSERT_OR_PRINT (mongoc_gridfs_drop (gridfs, &error), error); @@ -1323,13 +1238,11 @@ test_missing_file (void) iov.iov_len = sizeof buf; client = test_framework_new_default_client (); - gridfs = - mongoc_client_get_gridfs (client, "test_missing_file", NULL, &error); + gridfs = mongoc_client_get_gridfs (client, "test_missing_file", NULL, &error); ASSERT_OR_PRINT (gridfs, error); file = mongoc_gridfs_create_file (gridfs, NULL); - ASSERT_CMPSSIZE_T ( - mongoc_gridfs_file_writev (file, &iov, 1, 0), ==, (ssize_t) sizeof buf); + ASSERT_CMPSSIZE_T (mongoc_gridfs_file_writev (file, &iov, 1, 0), ==, (ssize_t) sizeof buf); ASSERT_CMPINT (mongoc_gridfs_file_seek (file, 0, SEEK_SET), ==, 0); BSON_ASSERT (mongoc_gridfs_file_save (file)); @@ -1337,25 +1250,16 @@ test_missing_file (void) BSON_ASSERT (mongoc_gridfs_file_remove (file, &error)); /* readv fails */ - ASSERT_CMPSSIZE_T (mongoc_gridfs_file_readv (file, &iov, 1, sizeof buf, 0), - ==, - (ssize_t) -1); + ASSERT_CMPSSIZE_T (mongoc_gridfs_file_readv (file, &iov, 1, sizeof buf, 0), ==, (ssize_t) -1); BSON_ASSERT (mongoc_gridfs_file_error (file, &error)); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_GRIDFS, - MONGOC_ERROR_GRIDFS_CHUNK_MISSING, - "missing chunk number 0"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_GRIDFS, MONGOC_ERROR_GRIDFS_CHUNK_MISSING, "missing chunk number 0"); memset (&error, 0, sizeof error); /* writev fails */ - ASSERT_CMPSSIZE_T ( - mongoc_gridfs_file_writev (file, &iov, 1, 0), ==, (ssize_t) -1); + ASSERT_CMPSSIZE_T (mongoc_gridfs_file_writev (file, &iov, 1, 0), ==, (ssize_t) -1); BSON_ASSERT (mongoc_gridfs_file_error (file, &error)); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_GRIDFS, - MONGOC_ERROR_GRIDFS_CHUNK_MISSING, - "missing chunk number 0"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_GRIDFS, MONGOC_ERROR_GRIDFS_CHUNK_MISSING, "missing chunk number 0"); mongoc_gridfs_file_destroy (file); mongoc_gridfs_destroy (gridfs); @@ -1430,16 +1334,14 @@ test_inherit_client_config (void) mock_server_auto_endsessions (server); /* configure read / write concern and read prefs on client */ - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); write_concern = mongoc_write_concern_new (); mongoc_write_concern_set_w (write_concern, 2); mongoc_client_set_write_concern (client, write_concern); read_concern = mongoc_read_concern_new (); - mongoc_read_concern_set_level (read_concern, - MONGOC_READ_CONCERN_LEVEL_MAJORITY); + mongoc_read_concern_set_level (read_concern, MONGOC_READ_CONCERN_LEVEL_MAJORITY); mongoc_client_set_read_concern (client, read_concern); secondary_pref = mongoc_read_prefs_new (MONGOC_READ_SECONDARY); @@ -1449,17 +1351,14 @@ test_inherit_client_config (void) /* test read prefs and read concern */ future = future_gridfs_find_one (gridfs, tmp_bson ("{}"), &error); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db'," - " 'find': 'fs.files'," - " 'readConcern': {'level': 'majority'}," - " '$readPreference': {'mode': 'secondary'}}")); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'db'," + " 'find': 'fs.files'," + " 'readConcern': {'level': 'majority'}," + " '$readPreference': {'mode': 'secondary'}}")); - reply_to_request_simple ( - request, - "{'ok': 1, 'cursor': {'ns': 'fs.files', 'firstBatch': [{'_id': 1}]}}"); + reply_to_request_simple (request, "{'ok': 1, 'cursor': {'ns': 'fs.files', 'firstBatch': [{'_id': 1}]}}"); file = future_get_mongoc_gridfs_file_ptr (future); ASSERT (file); @@ -1470,21 +1369,17 @@ test_inherit_client_config (void) /* test write concern */ future = future_gridfs_file_remove (file, &error); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ( - "{'$db': 'db', 'delete': 'fs.files', 'writeConcern': {'w': 2}}"), - tmp_bson ("{'q': {'_id': 1}, 'limit': 1}")); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'db', 'delete': 'fs.files', 'writeConcern': {'w': 2}}"), + tmp_bson ("{'q': {'_id': 1}, 'limit': 1}")); reply_to_request_with_ok_and_destroy (request); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ( - "{'$db': 'db', 'delete': 'fs.chunks', 'writeConcern': {'w': 2}}"), - tmp_bson ("{'q': {'files_id': 1}, 'limit': 0}")); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'db', 'delete': 'fs.chunks', 'writeConcern': {'w': 2}}"), + tmp_bson ("{'q': {'files_id': 1}, 'limit': 0}")); reply_to_request_with_ok_and_destroy (request); ASSERT (future_get_bool (future)); @@ -1509,8 +1404,7 @@ test_find_one_empty (void) client = test_framework_new_default_client (); gridfs = get_test_gridfs (client, "list", &error); ASSERT_OR_PRINT (gridfs, error); - ASSERT (!mongoc_gridfs_find_one ( - gridfs, tmp_bson ("{'x': 'doesntexist'}"), &error)); + ASSERT (!mongoc_gridfs_find_one (gridfs, tmp_bson ("{'x': 'doesntexist'}"), &error)); /* ensure "error" is cleared if we successfully find no file */ ASSERT_CMPINT (error.domain, ==, 0); @@ -1565,17 +1459,15 @@ test_write_failure (void) client = test_framework_client_new_from_uri (uri, NULL); gridfs = mongoc_client_get_gridfs (client, "db", "fs", &error); ASSERT_OR_PRINT (gridfs, error); - stream = - mongoc_stream_file_new_for_path (BINARY_DIR "/gridfs.dat", O_RDONLY, 0); + stream = mongoc_stream_file_new_for_path (BINARY_DIR "/gridfs.dat", O_RDONLY, 0); /* times out writing first chunk */ opt.chunk_size = 1; capture_logs (true); file = mongoc_gridfs_create_file_from_stream (gridfs, stream, &opt); BSON_ASSERT (!file); - ASSERT_CAPTURED_LOG ("mongoc_gridfs_create_file_from_stream", - MONGOC_LOG_LEVEL_ERROR, - "Failed to send \"update\" command"); + ASSERT_CAPTURED_LOG ( + "mongoc_gridfs_create_file_from_stream", MONGOC_LOG_LEVEL_ERROR, "Failed to send \"update\" command"); mongoc_stream_destroy (stream); mongoc_gridfs_destroy (gridfs); @@ -1589,14 +1481,11 @@ void test_gridfs_install (TestSuite *suite) { TestSuite_AddLive (suite, "/gridfs_old/create", test_create); - TestSuite_AddLive ( - suite, "/gridfs_old/create_from_stream", test_create_from_stream); + TestSuite_AddLive (suite, "/gridfs_old/create_from_stream", test_create_from_stream); TestSuite_AddLive (suite, "/gridfs_old/list", test_list); TestSuite_AddLive (suite, "/gridfs_old/find_one_empty", test_find_one_empty); TestSuite_AddLive (suite, "/gridfs_old/find_with_opts", test_find_with_opts); - TestSuite_AddMockServerTest (suite, - "/gridfs_old/find_one_with_opts/limit", - test_find_one_with_opts_limit); + TestSuite_AddMockServerTest (suite, "/gridfs_old/find_one_with_opts/limit", test_find_one_with_opts_limit); TestSuite_AddLive (suite, "/gridfs_old/properties", test_properties); TestSuite_AddLive (suite, "/gridfs_old/empty", test_empty); TestSuite_AddLive (suite, "/gridfs_old/read", test_read); @@ -1604,28 +1493,16 @@ test_gridfs_install (TestSuite *suite) TestSuite_AddLive (suite, "/gridfs_old/stream", test_stream); TestSuite_AddLive (suite, "/gridfs_old/remove", test_remove); TestSuite_AddLive (suite, "/gridfs_old/write", test_write); - TestSuite_AddLive ( - suite, "/gridfs_old/write_at_boundary", test_write_at_boundary); + TestSuite_AddLive (suite, "/gridfs_old/write_at_boundary", test_write_at_boundary); TestSuite_AddLive (suite, "/gridfs_old/write_past_end", test_write_past_end); - TestSuite_AddFull (suite, - "/gridfs_old/test_long_seek", - test_long_seek, - NULL, - NULL, - test_framework_skip_if_slow_or_live); - TestSuite_AddLive ( - suite, "/gridfs_old/remove_by_filename", test_remove_by_filename); - TestSuite_AddFull (suite, - "/gridfs_old/missing_chunk", - test_missing_chunk, - NULL, - NULL, - test_framework_skip_if_slow_or_live); + TestSuite_AddFull ( + suite, "/gridfs_old/test_long_seek", test_long_seek, NULL, NULL, test_framework_skip_if_slow_or_live); + TestSuite_AddLive (suite, "/gridfs_old/remove_by_filename", test_remove_by_filename); + TestSuite_AddFull ( + suite, "/gridfs_old/missing_chunk", test_missing_chunk, NULL, NULL, test_framework_skip_if_slow_or_live); TestSuite_AddLive (suite, "/gridfs_old/oversize_chunk", test_oversize); TestSuite_AddLive (suite, "/gridfs_old/missing_file", test_missing_file); TestSuite_AddLive (suite, "/gridfs_old/file_set_id", test_set_id); - TestSuite_AddMockServerTest ( - suite, "/gridfs_old/inherit_client_config", test_inherit_client_config); - TestSuite_AddMockServerTest ( - suite, "/gridfs_old/write_failure", test_write_failure); + TestSuite_AddMockServerTest (suite, "/gridfs_old/inherit_client_config", test_inherit_client_config); + TestSuite_AddMockServerTest (suite, "/gridfs_old/write_failure", test_write_failure); } diff --git a/src/libmongoc/tests/test-mongoc-gssapi.c b/src/libmongoc/tests/test-mongoc-gssapi.c index bb68abafa1..6ec1dcf985 100644 --- a/src/libmongoc/tests/test-mongoc-gssapi.c +++ b/src/libmongoc/tests/test-mongoc-gssapi.c @@ -71,8 +71,7 @@ static BSON_THREAD_FUN (gssapi_kerberos_worker, data) bson_t *cmd = BCON_NEW ("ping", BCON_INT32 (1)); client = mongoc_client_pool_pop (pool); - if (!mongoc_client_command_with_opts ( - client, "test", cmd, NULL, NULL, NULL, &error)) { + if (!mongoc_client_command_with_opts (client, "test", cmd, NULL, NULL, NULL, &error)) { fflush (stdout); fprintf (stderr, "ping command failed: %s\n", error.message); fflush (stderr); @@ -80,11 +79,9 @@ static BSON_THREAD_FUN (gssapi_kerberos_worker, data) } bson_destroy (cmd); collection = mongoc_client_get_collection (client, "kerberos", "test"); - cursor = mongoc_collection_find ( - collection, MONGOC_QUERY_NONE, 0, 0, 0, &query, NULL, NULL); + cursor = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, 0, &query, NULL, NULL); - if (!mongoc_cursor_next (cursor, &doc) && - mongoc_cursor_error (cursor, &error)) { + if (!mongoc_cursor_next (cursor, &doc) && mongoc_cursor_error (cursor, &error)) { fflush (stdout); fprintf (stderr, "Cursor Failure: %s\n", error.message); fflush (stderr); @@ -121,26 +118,19 @@ main (void) mongoc_init (); if (!host || !user) { - fprintf (stderr, - "%s and %s must be defined in environment\n", - GSSAPI_HOST, - GSSAPI_USER); + fprintf (stderr, "%s and %s must be defined in environment\n", GSSAPI_HOST, GSSAPI_USER); return 1; } bson_mutex_init (&closure.mutex); - uri_str = bson_strdup_printf ( - "mongodb://%s@%s/?authMechanism=GSSAPI&connectTimeoutMS=30000", - user, - host); + uri_str = bson_strdup_printf ("mongodb://%s@%s/?authMechanism=GSSAPI&connectTimeoutMS=30000", user, host); uri = mongoc_uri_new (uri_str); closure.pool = mongoc_client_pool_new (uri); for (i = 0; i < NTHREADS; i++) { - r = mcommon_thread_create ( - &threads[i], gssapi_kerberos_worker, (void *) &closure); + r = mcommon_thread_create (&threads[i], gssapi_kerberos_worker, (void *) &closure); BSON_ASSERT (r == 0); } diff --git a/src/libmongoc/tests/test-mongoc-handshake.c b/src/libmongoc/tests/test-mongoc-handshake.c index 92cfe8b5fe..1bf9c0bceb 100644 --- a/src/libmongoc/tests/test-mongoc-handshake.c +++ b/src/libmongoc/tests/test-mongoc-handshake.c @@ -68,12 +68,9 @@ test_mongoc_handshake_appname_in_uri (void) /* Shouldn't be able to set with appname really long */ capture_logs (true); - uri_str = bson_strdup_printf ("mongodb://a/?" MONGOC_URI_APPNAME "=%s", - long_string); + uri_str = bson_strdup_printf ("mongodb://a/?" MONGOC_URI_APPNAME "=%s", long_string); ASSERT (!test_framework_client_new (uri_str, NULL)); - ASSERT_CAPTURED_LOG ("_mongoc_topology_scanner_set_appname", - MONGOC_LOG_LEVEL_WARNING, - "Unsupported value"); + ASSERT_CAPTURED_LOG ("_mongoc_topology_scanner_set_appname", MONGOC_LOG_LEVEL_WARNING, "Unsupported value"); capture_logs (false); uri = mongoc_uri_new (good_uri); @@ -106,9 +103,8 @@ test_mongoc_handshake_appname_frozen_single (void) /* Shouldn't be able to set appname again */ capture_logs (true); ASSERT (!mongoc_client_set_appname (client, "a")); - ASSERT_CAPTURED_LOG ("_mongoc_topology_scanner_set_appname", - MONGOC_LOG_LEVEL_ERROR, - "Cannot set appname more than once"); + ASSERT_CAPTURED_LOG ( + "_mongoc_topology_scanner_set_appname", MONGOC_LOG_LEVEL_ERROR, "Cannot set appname more than once"); capture_logs (false); mongoc_client_destroy (client); @@ -126,9 +122,8 @@ test_mongoc_handshake_appname_frozen_pooled (void) pool = test_framework_client_pool_new_from_uri (uri, NULL); capture_logs (true); ASSERT (!mongoc_client_pool_set_appname (pool, "test")); - ASSERT_CAPTURED_LOG ("_mongoc_topology_scanner_set_appname", - MONGOC_LOG_LEVEL_ERROR, - "Cannot set appname more than once"); + ASSERT_CAPTURED_LOG ( + "_mongoc_topology_scanner_set_appname", MONGOC_LOG_LEVEL_ERROR, "Cannot set appname more than once"); capture_logs (false); mongoc_client_pool_destroy (pool); @@ -237,10 +232,7 @@ _handshake_check_os (bson_t *doc) } static void -_handshake_check_env (bson_t *doc, - int expected_memory_mb, - int expected_timeout_sec, - const char *expected_region) +_handshake_check_env (bson_t *doc, int expected_memory_mb, int expected_timeout_sec, const char *expected_region) { bson_iter_t md_iter; bson_iter_t inner_iter; @@ -286,8 +278,7 @@ _handshake_check_platform (bson_t *doc) ASSERT (BSON_ITER_HOLDS_UTF8 (&md_iter)); val = bson_iter_utf8 (&md_iter, NULL); ASSERT (val); - if (strlen (val) < - 250) { /* standard val are < 100, may be truncated on some platform */ + if (strlen (val) < 250) { /* standard val are < 100, may be truncated on some platform */ ASSERT (strstr (val, default_platform) != NULL); } } @@ -332,8 +323,7 @@ _get_handshake_document (bool default_append) /* Make sure setting the handshake works */ if (default_append) { - ASSERT (mongoc_handshake_data_append ( - default_driver_name, default_driver_version, default_platform)); + ASSERT (mongoc_handshake_data_append (default_driver_name, default_driver_version, default_platform)); } server = mock_server_new (); @@ -533,8 +523,7 @@ test_valid_gcp (void *test_ctx) _override_host_platform_os (); bson_t *doc = _get_handshake_document (true); _handshake_check_required_fields (doc); - _handshake_check_env ( - doc, default_memory_mb, default_timeout_sec, "us-central1"); + _handshake_check_env (doc, default_memory_mb, default_timeout_sec, "us-central1"); _handshake_check_env_name (doc, "gcp.func"); bson_destroy (doc); @@ -851,8 +840,7 @@ test_mongoc_handshake_too_big (void) ASSERT (mongoc_client_set_appname (client, "my app")); /* Send a ping, mock server deals with it */ - future = future_client_command_simple ( - client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, NULL); + future = future_client_command_simple (client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, NULL); request = mock_server_receives_any_hello (server); /* Make sure the hello request has a handshake field, and it's not huge */ @@ -870,14 +858,10 @@ test_mongoc_handshake_too_big (void) ASSERT (len == HANDSHAKE_MAX_SIZE); reply_to_request_simple ( - request, - tmp_str ("{'ok': 1, 'minWireVersion': %d, 'maxWireVersion': %d}", - WIRE_VERSION_MIN, - WIRE_VERSION_MAX)); + request, tmp_str ("{'ok': 1, 'minWireVersion': %d, 'maxWireVersion': %d}", WIRE_VERSION_MIN, WIRE_VERSION_MAX)); request_destroy (request); - request = mock_server_receives_msg ( - server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'admin', 'ping': 1}")); + request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'admin', 'ping': 1}")); reply_to_request_simple (request, "{'ok': 1}"); ASSERT (future_get_bool (future)); @@ -938,10 +922,8 @@ test_mongoc_platform_truncate (int drop) bson_free (md->os_version); md->os_version = big_string; - bson_t *handshake_no_platform = - _mongoc_handshake_build_doc_with_application (default_appname); - size_t handshake_remaining_space = - HANDSHAKE_MAX_SIZE - handshake_no_platform->len; + bson_t *handshake_no_platform = _mongoc_handshake_build_doc_with_application (default_appname); + size_t handshake_remaining_space = HANDSHAKE_MAX_SIZE - handshake_no_platform->len; bson_destroy (handshake_no_platform); md->os_version = bson_strdup ("test_c"); @@ -958,8 +940,7 @@ test_mongoc_platform_truncate (int drop) handshake_remaining_space -= strlen (md->compiler_info); undropped = bson_strdup_printf ("%s", md->compiler_info); } else { - handshake_remaining_space -= - strlen (md->flags) + strlen (md->compiler_info); + handshake_remaining_space -= strlen (md->flags) + strlen (md->compiler_info); undropped = bson_strdup_printf ("%s%s", md->compiler_info, md->flags); } @@ -967,8 +948,7 @@ test_mongoc_platform_truncate (int drop) ASSERT (mongoc_handshake_data_append (NULL, NULL, big_string)); bson_t *doc; - ASSERT (doc = - _mongoc_handshake_build_doc_with_application (default_appname)); + ASSERT (doc = _mongoc_handshake_build_doc_with_application (default_appname)); /* doc.len being strictly less than HANDSHAKE_MAX_SIZE proves that we have * dropped the flags correctly, instead of truncating anything @@ -1119,13 +1099,11 @@ test_handshake_platform_config (void) #endif #ifdef MONGOC_ENABLE_SSL_SECURE_TRANSPORT - BSON_ASSERT ( - _get_bit (config_str, MONGOC_MD_FLAG_ENABLE_SSL_SECURE_TRANSPORT)); + BSON_ASSERT (_get_bit (config_str, MONGOC_MD_FLAG_ENABLE_SSL_SECURE_TRANSPORT)); #endif #ifdef MONGOC_ENABLE_CRYPTO_COMMON_CRYPTO - BSON_ASSERT ( - _get_bit (config_str, MONGOC_MD_FLAG_ENABLE_CRYPTO_COMMON_CRYPTO)); + BSON_ASSERT (_get_bit (config_str, MONGOC_MD_FLAG_ENABLE_CRYPTO_COMMON_CRYPTO)); #endif #ifdef MONGOC_ENABLE_SSL_OPENSSL @@ -1145,8 +1123,7 @@ test_handshake_platform_config (void) #endif #ifdef MONGOC_ENABLE_CRYPTO_SYSTEM_PROFILE - BSON_ASSERT ( - _get_bit (config_str, MONGOC_MD_FLAG_ENABLE_CRYPTO_SYSTEM_PROFILE)); + BSON_ASSERT (_get_bit (config_str, MONGOC_MD_FLAG_ENABLE_CRYPTO_SYSTEM_PROFILE)); #endif #ifdef MONGOC_ENABLE_SASL @@ -1186,8 +1163,7 @@ test_handshake_platform_config (void) #endif #ifdef MONGOC_ENABLE_COMPRESSION_SNAPPY - BSON_ASSERT ( - _get_bit (config_str, MONGOC_MD_FLAG_ENABLE_COMPRESSION_SNAPPY)); + BSON_ASSERT (_get_bit (config_str, MONGOC_MD_FLAG_ENABLE_COMPRESSION_SNAPPY)); #endif #ifdef MONGOC_ENABLE_COMPRESSION_ZLIB @@ -1226,8 +1202,7 @@ test_handshake_platform_config (void) BSON_ASSERT (_get_bit (config_str, MONGOC_MD_FLAG_HAVE_SCHED_GETCPU)); #endif - BSON_ASSERT (_get_bit (config_str, MONGOC_MD_FLAG_ENABLE_SRV) == - MONGOC_SRV_ENABLED); + BSON_ASSERT (_get_bit (config_str, MONGOC_MD_FLAG_ENABLE_SRV) == MONGOC_SRV_ENABLED); #ifdef MONGOC_ENABLE_SHM_COUNTERS BSON_ASSERT (_get_bit (config_str, MONGOC_MD_FLAG_ENABLE_SHM_COUNTERS)); @@ -1242,8 +1217,7 @@ test_handshake_platform_config (void) BSON_ASSERT (!_get_bit (config_str, MONGOC_MD_FLAG_ENABLE_ICU_UNUSED)); #ifdef MONGOC_ENABLE_CLIENT_SIDE_ENCRYPTION - BSON_ASSERT ( - _get_bit (config_str, MONGOC_MD_FLAG_ENABLE_CLIENT_SIDE_ENCRYPTION)); + BSON_ASSERT (_get_bit (config_str, MONGOC_MD_FLAG_ENABLE_CLIENT_SIDE_ENCRYPTION)); #endif #ifdef MONGOC_ENABLE_MONGODB_AWS_AUTH @@ -1262,8 +1236,7 @@ static BSON_THREAD_FUN (handshake_append_worker, data) { BSON_UNUSED (data); - mongoc_handshake_data_append ( - default_driver_name, default_driver_version, default_platform); + mongoc_handshake_data_append (default_driver_name, default_driver_version, default_platform); BSON_THREAD_RETURN; } @@ -1279,8 +1252,7 @@ test_mongoc_handshake_race_condition (void) _reset_handshake (); for (j = 0; j < 4; ++j) { - BSON_ASSERT (!mcommon_thread_create ( - &threads[j], &handshake_append_worker, NULL /* args */)); + BSON_ASSERT (!mcommon_thread_create (&threads[j], &handshake_append_worker, NULL /* args */)); } for (j = 0; j < 4; ++j) { mcommon_thread_join (threads[j]); @@ -1293,44 +1265,20 @@ test_mongoc_handshake_race_condition (void) void test_handshake_install (TestSuite *suite) { - TestSuite_Add (suite, - "/MongoDB/handshake/appname_in_uri", - test_mongoc_handshake_appname_in_uri); - TestSuite_Add (suite, - "/MongoDB/handshake/appname_frozen_single", - test_mongoc_handshake_appname_frozen_single); - TestSuite_Add (suite, - "/MongoDB/handshake/appname_frozen_pooled", - test_mongoc_handshake_appname_frozen_pooled); - - TestSuite_AddMockServerTest (suite, - "/MongoDB/handshake/success", - test_mongoc_handshake_data_append_success); - TestSuite_AddMockServerTest (suite, - "/MongoDB/handshake/null_args", - test_mongoc_handshake_data_append_null_args); - TestSuite_Add (suite, - "/MongoDB/handshake/big_platform", - test_mongoc_handshake_big_platform); - TestSuite_Add (suite, - "/MongoDB/handshake/oversized_platform", - test_mongoc_handshake_oversized_platform); - TestSuite_Add (suite, - "/MongoDB/handshake/failure", - test_mongoc_handshake_data_append_after_cmd); - TestSuite_AddMockServerTest ( - suite, "/MongoDB/handshake/too_big", test_mongoc_handshake_too_big); - TestSuite_Add ( - suite, "/MongoDB/handshake/oversized_flags", test_mongoc_oversized_flags); - TestSuite_AddMockServerTest (suite, - "/MongoDB/handshake/cannot_send", - test_mongoc_handshake_cannot_send); - TestSuite_Add (suite, - "/MongoDB/handshake/platform_config", - test_handshake_platform_config); - TestSuite_Add (suite, - "/MongoDB/handshake/race_condition", - test_mongoc_handshake_race_condition); + TestSuite_Add (suite, "/MongoDB/handshake/appname_in_uri", test_mongoc_handshake_appname_in_uri); + TestSuite_Add (suite, "/MongoDB/handshake/appname_frozen_single", test_mongoc_handshake_appname_frozen_single); + TestSuite_Add (suite, "/MongoDB/handshake/appname_frozen_pooled", test_mongoc_handshake_appname_frozen_pooled); + + TestSuite_AddMockServerTest (suite, "/MongoDB/handshake/success", test_mongoc_handshake_data_append_success); + TestSuite_AddMockServerTest (suite, "/MongoDB/handshake/null_args", test_mongoc_handshake_data_append_null_args); + TestSuite_Add (suite, "/MongoDB/handshake/big_platform", test_mongoc_handshake_big_platform); + TestSuite_Add (suite, "/MongoDB/handshake/oversized_platform", test_mongoc_handshake_oversized_platform); + TestSuite_Add (suite, "/MongoDB/handshake/failure", test_mongoc_handshake_data_append_after_cmd); + TestSuite_AddMockServerTest (suite, "/MongoDB/handshake/too_big", test_mongoc_handshake_too_big); + TestSuite_Add (suite, "/MongoDB/handshake/oversized_flags", test_mongoc_oversized_flags); + TestSuite_AddMockServerTest (suite, "/MongoDB/handshake/cannot_send", test_mongoc_handshake_cannot_send); + TestSuite_Add (suite, "/MongoDB/handshake/platform_config", test_handshake_platform_config); + TestSuite_Add (suite, "/MongoDB/handshake/race_condition", test_mongoc_handshake_race_condition); TestSuite_AddFull (suite, "/MongoDB/handshake/faas/valid_aws", test_valid_aws, diff --git a/src/libmongoc/tests/test-mongoc-hedged-reads.c b/src/libmongoc/tests/test-mongoc-hedged-reads.c index 6625c0e257..9e9ae6db08 100644 --- a/src/libmongoc/tests/test-mongoc-hedged-reads.c +++ b/src/libmongoc/tests/test-mongoc-hedged-reads.c @@ -43,8 +43,7 @@ test_mongos_hedged_reads_read_pref (void) server = mock_mongos_new (WIRE_VERSION_MIN); mock_server_run (server); mock_server_auto_endsessions (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); collection = mongoc_client_get_collection (client, "db", "collection"); prefs = mongoc_read_prefs_new (MONGOC_READ_SECONDARY_PREFERRED); @@ -53,13 +52,11 @@ test_mongos_hedged_reads_read_pref (void) * readPreference. */ mongoc_collection_set_read_prefs (collection, prefs); - future = future_collection_count ( - collection, MONGOC_QUERY_NONE, NULL, 0, 0, NULL, &error); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db'," - " '$readPreference': {'mode': 'secondaryPreferred'}}")); + future = future_collection_count (collection, MONGOC_QUERY_NONE, NULL, 0, 0, NULL, &error); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'db'," + " '$readPreference': {'mode': 'secondaryPreferred'}}")); reply_to_request_simple (request, "{'ok': 1, 'n': 1}"); ASSERT_OR_PRINT (1 == future_get_int64_t (future), error); @@ -74,15 +71,13 @@ test_mongos_hedged_reads_read_pref (void) mongoc_read_prefs_set_hedge (prefs, &hedge_doc); mongoc_collection_set_read_prefs (collection, prefs); - future = future_collection_count ( - collection, MONGOC_QUERY_NONE, NULL, 0, 0, NULL, &error); - request = - mock_server_receives_msg (server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db'," - " '$readPreference': {" - " 'mode': 'secondaryPreferred'," - " 'hedge': {'enabled': true}}}")); + future = future_collection_count (collection, MONGOC_QUERY_NONE, NULL, 0, 0, NULL, &error); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'db'," + " '$readPreference': {" + " 'mode': 'secondaryPreferred'," + " 'hedge': {'enabled': true}}}")); reply_to_request_simple (request, "{'ok': 1, 'n': 1}"); ASSERT_OR_PRINT (1 == future_get_int64_t (future), error); @@ -101,6 +96,5 @@ test_mongos_hedged_reads_read_pref (void) void test_client_hedged_reads_install (TestSuite *suite) { - TestSuite_AddMockServerTest ( - suite, "/Client/hedged_reads/mongos", test_mongos_hedged_reads_read_pref); + TestSuite_AddMockServerTest (suite, "/Client/hedged_reads/mongos", test_mongos_hedged_reads_read_pref); } diff --git a/src/libmongoc/tests/test-mongoc-http.c b/src/libmongoc/tests/test-mongoc-http.c index 1de831f180..1dc303b995 100644 --- a/src/libmongoc/tests/test-mongoc-http.c +++ b/src/libmongoc/tests/test-mongoc-http.c @@ -86,17 +86,9 @@ test_mongoc_http_post (void *unused) void test_http_install (TestSuite *suite) { - TestSuite_AddFull (suite, - "/http/get", - test_mongoc_http_get, - NULL /* dtor */, - NULL /* ctx */, - test_framework_skip_if_offline); + TestSuite_AddFull ( + suite, "/http/get", test_mongoc_http_get, NULL /* dtor */, NULL /* ctx */, test_framework_skip_if_offline); - TestSuite_AddFull (suite, - "/http/post", - test_mongoc_http_post, - NULL /* dtor */, - NULL /* ctx */, - test_framework_skip_if_offline); + TestSuite_AddFull ( + suite, "/http/post", test_mongoc_http_post, NULL /* dtor */, NULL /* ctx */, test_framework_skip_if_offline); } diff --git a/src/libmongoc/tests/test-mongoc-interrupt.c b/src/libmongoc/tests/test-mongoc-interrupt.c index d9eb5ccfe8..0f435b1b88 100644 --- a/src/libmongoc/tests/test-mongoc-interrupt.c +++ b/src/libmongoc/tests/test-mongoc-interrupt.c @@ -109,8 +109,7 @@ test_interrupt (void) server = mock_server_new (); mock_server_run (server); uri = mock_server_get_uri (server); - stream = - mongoc_client_connect_tcp (10000, mongoc_uri_get_hosts (uri), &error); + stream = mongoc_client_connect_tcp (10000, mongoc_uri_get_hosts (uri), &error); ASSERT_OR_PRINT (stream, error); bson_free (poller); diff --git a/src/libmongoc/tests/test-mongoc-linux-distro-scanner.c b/src/libmongoc/tests/test-mongoc-linux-distro-scanner.c index c6ea1b56cf..eaceb4f5c4 100644 --- a/src/libmongoc/tests/test-mongoc-linux-distro-scanner.c +++ b/src/libmongoc/tests/test-mongoc-linux-distro-scanner.c @@ -46,8 +46,7 @@ test_read_generic_release_file (void) NULL, }; - _mongoc_linux_distro_scanner_read_generic_release_file ( - paths, &name, &version); + _mongoc_linux_distro_scanner_read_generic_release_file (paths, &name, &version); ASSERT (name); ASSERT (version); ASSERT_CMPSTR ("Fedora", name); @@ -55,25 +54,21 @@ test_read_generic_release_file (void) bson_free (name); bson_free (version); - _mongoc_linux_distro_scanner_read_generic_release_file ( - paths2, &name, &version); + _mongoc_linux_distro_scanner_read_generic_release_file (paths2, &name, &version); ASSERT (name); ASSERT_CMPSTR ("This one just has name, not that R word", name); ASSERT (version == NULL); bson_free (name); - _mongoc_linux_distro_scanner_read_generic_release_file ( - paths3, &name, &version); + _mongoc_linux_distro_scanner_read_generic_release_file (paths3, &name, &version); ASSERT (name == NULL); ASSERT (version == NULL); - _mongoc_linux_distro_scanner_split_line_by_release ( - " release ", -1, &name, &version); + _mongoc_linux_distro_scanner_split_line_by_release (" release ", -1, &name, &version); ASSERT (name == NULL); ASSERT (version == NULL); - _mongoc_linux_distro_scanner_split_line_by_release ( - "ends with release ", -1, &name, &version); + _mongoc_linux_distro_scanner_split_line_by_release ("ends with release ", -1, &name, &version); ASSERT_CMPSTR ("ends with", name); ASSERT (version == NULL); bson_free (name); @@ -91,14 +86,8 @@ test_read_key_value_file (void) char *name = NULL; char *version = NULL; - _mongoc_linux_distro_scanner_read_key_value_file (OS_RELEASE_FILE_DIR - "/example-lsb-file.txt", - "DISTRIB_ID", - -1, - &name, - "DISTRIB_RELEASE", - -1, - &version); + _mongoc_linux_distro_scanner_read_key_value_file ( + OS_RELEASE_FILE_DIR "/example-lsb-file.txt", "DISTRIB_ID", -1, &name, "DISTRIB_RELEASE", -1, &version); ASSERT (name); ASSERT_CMPSTR (name, "Ubuntu"); @@ -108,14 +97,13 @@ test_read_key_value_file (void) bson_free (name); bson_free (version); - _mongoc_linux_distro_scanner_read_key_value_file ( - OS_RELEASE_FILE_DIR "/example-lsb-file-with-super-long-line.txt", - "DISTRIB_ID", - -1, - &name, - "DISTRIB_RELEASE", - -1, - &version); + _mongoc_linux_distro_scanner_read_key_value_file (OS_RELEASE_FILE_DIR "/example-lsb-file-with-super-long-line.txt", + "DISTRIB_ID", + -1, + &name, + "DISTRIB_RELEASE", + -1, + &version); ASSERT (!name); ASSERT (version); ASSERT_CMPSTR (version, "12.04"); @@ -123,13 +111,7 @@ test_read_key_value_file (void) _mongoc_linux_distro_scanner_read_key_value_file ( - OS_RELEASE_FILE_DIR "/example-etc-os-release.txt", - "NAME", - -1, - &name, - "VERSION_ID", - -1, - &version); + OS_RELEASE_FILE_DIR "/example-etc-os-release.txt", "NAME", -1, &name, "VERSION_ID", -1, &version); ASSERT_CMPSTR (name, "Fedora"); ASSERT_CMPSTR (version, "17"); @@ -139,38 +121,20 @@ test_read_key_value_file (void) /* Now try some weird inputs */ _mongoc_linux_distro_scanner_read_key_value_file ( - OS_RELEASE_FILE_DIR "/example-etc-os-release.txt", - "ID=", - -1, - &name, - "VERSION_ID=", - -1, - &version); + OS_RELEASE_FILE_DIR "/example-etc-os-release.txt", "ID=", -1, &name, "VERSION_ID=", -1, &version); ASSERT (name == NULL); ASSERT (version == NULL); _mongoc_linux_distro_scanner_read_key_value_file ( - OS_RELEASE_FILE_DIR "/example-etc-os-release.txt", - "", - -1, - &name, - "", - -1, - &version); + OS_RELEASE_FILE_DIR "/example-etc-os-release.txt", "", -1, &name, "", -1, &version); ASSERT (name == NULL); ASSERT (version == NULL); /* Test case where we get one but not the other */ _mongoc_linux_distro_scanner_read_key_value_file ( - OS_RELEASE_FILE_DIR "/example-etc-os-release.txt", - "NAME", - -1, - &name, - "VERSION_", - -1, - &version); + OS_RELEASE_FILE_DIR "/example-etc-os-release.txt", "NAME", -1, &name, "VERSION_", -1, &version); ASSERT_CMPSTR (name, "Fedora"); ASSERT (version == NULL); @@ -178,25 +142,13 @@ test_read_key_value_file (void) /* Case where we say the key is the whole line */ _mongoc_linux_distro_scanner_read_key_value_file ( - OS_RELEASE_FILE_DIR "/example-etc-os-release.txt", - "NAME", - -1, - &name, - "VERSION_ID=17", - -1, - &version); + OS_RELEASE_FILE_DIR "/example-etc-os-release.txt", "NAME", -1, &name, "VERSION_ID=17", -1, &version); ASSERT_CMPSTR (name, "Fedora"); ASSERT (version == NULL); bson_free (name); _mongoc_linux_distro_scanner_read_key_value_file ( - OS_RELEASE_FILE_DIR "/example-etc-os-release-ubuntu1604.txt", - "NAME", - -1, - &name, - "VERSION_ID", - -1, - &version); + OS_RELEASE_FILE_DIR "/example-etc-os-release-ubuntu1604.txt", "NAME", -1, &name, "VERSION_ID", -1, &version); ASSERT_CMPSTR ("Ubuntu", name); ASSERT_CMPSTR ("16.04", version); bson_free (name); @@ -205,13 +157,7 @@ test_read_key_value_file (void) /* Case where the key is duplicated, make sure we keep first version */ _mongoc_linux_distro_scanner_read_key_value_file ( - OS_RELEASE_FILE_DIR "/example-key-value-file.txt", - "key", - -1, - &name, - "normalkey", - -1, - &version); + OS_RELEASE_FILE_DIR "/example-key-value-file.txt", "key", -1, &name, "normalkey", -1, &version); ASSERT_CMPSTR (name, "first value"); ASSERT_CMPSTR (version, "normalval"); bson_free (name); @@ -219,13 +165,7 @@ test_read_key_value_file (void) /* Case where the key is duplicated, make sure we keep first version */ _mongoc_linux_distro_scanner_read_key_value_file ( - OS_RELEASE_FILE_DIR "/example-key-value-file.txt", - "a-key-without-a-value", - -1, - &name, - "normalkey", - -1, - &version); + OS_RELEASE_FILE_DIR "/example-key-value-file.txt", "a-key-without-a-value", -1, &name, "normalkey", -1, &version); ASSERT_CMPSTR (name, ""); ASSERT_CMPSTR (version, "normalval"); bson_free (name); @@ -235,13 +175,7 @@ test_read_key_value_file (void) * just-a-key * (No equals, no value) */ _mongoc_linux_distro_scanner_read_key_value_file ( - OS_RELEASE_FILE_DIR "/example-key-value-file.txt", - "just-a-key", - -1, - &name, - "normalkey", - -1, - &version); + OS_RELEASE_FILE_DIR "/example-key-value-file.txt", "just-a-key", -1, &name, "normalkey", -1, &version); ASSERT (name == NULL); ASSERT_CMPSTR (version, "normalval"); bson_free (name); @@ -250,13 +184,7 @@ test_read_key_value_file (void) /* Try to get a key which is on line 101 of the file * (we stop reading at line 100) */ _mongoc_linux_distro_scanner_read_key_value_file ( - OS_RELEASE_FILE_DIR "/example-key-value-file.txt", - "lastkey", - -1, - &name, - "normalkey", - -1, - &version); + OS_RELEASE_FILE_DIR "/example-key-value-file.txt", "lastkey", -1, &name, "normalkey", -1, &version); ASSERT (name == NULL); ASSERT_CMPSTR (version, "normalval"); bson_free (version); @@ -289,14 +217,8 @@ void test_linux_distro_scanner_install (TestSuite *suite) { #ifdef MONGOC_OS_IS_LINUX - TestSuite_Add (suite, - "/LinuxDistroScanner/test_read_generic_release_file", - test_read_generic_release_file); - TestSuite_Add (suite, - "/LinuxDistroScanner/test_read_key_value_file", - test_read_key_value_file); - TestSuite_Add (suite, - "/LinuxDistroScanner/test_distro_scanner_reads", - test_distro_scanner_reads); + TestSuite_Add (suite, "/LinuxDistroScanner/test_read_generic_release_file", test_read_generic_release_file); + TestSuite_Add (suite, "/LinuxDistroScanner/test_read_key_value_file", test_read_key_value_file); + TestSuite_Add (suite, "/LinuxDistroScanner/test_distro_scanner_reads", test_distro_scanner_reads); #endif } diff --git a/src/libmongoc/tests/test-mongoc-loadbalanced.c b/src/libmongoc/tests/test-mongoc-loadbalanced.c index 8e2ef81d8f..e82d6c1762 100644 --- a/src/libmongoc/tests/test-mongoc-loadbalanced.c +++ b/src/libmongoc/tests/test-mongoc-loadbalanced.c @@ -265,18 +265,13 @@ test_loadbalanced_connect_single (void *unused) client = test_framework_new_default_client (); stats = set_client_callbacks (client); - ok = mongoc_client_command_simple (client, - "admin", - tmp_bson ("{'ping': 1}"), - NULL /* read prefs */, - NULL /* reply */, - &error); + ok = mongoc_client_command_simple ( + client, "admin", tmp_bson ("{'ping': 1}"), NULL /* read prefs */, NULL /* reply */, &error); ASSERT_OR_PRINT (ok, error); /* Ensure the server description is unchanged and remains as type * LoadBalancer. */ - monitor_sd = mongoc_client_select_server ( - client, true /* for writes */, NULL /* read prefs */, &error); + monitor_sd = mongoc_client_select_server (client, true /* for writes */, NULL /* read prefs */, &error); ASSERT_OR_PRINT (monitor_sd, error); ASSERT_CMPSTR ("LoadBalancer", mongoc_server_description_type (monitor_sd)); @@ -301,18 +296,13 @@ test_loadbalanced_connect_pooled (void *unused) stats = set_client_pool_callbacks (pool); client = mongoc_client_pool_pop (pool); - ok = mongoc_client_command_simple (client, - "admin", - tmp_bson ("{'ping': 1}"), - NULL /* read prefs */, - NULL /* reply */, - &error); + ok = mongoc_client_command_simple ( + client, "admin", tmp_bson ("{'ping': 1}"), NULL /* read prefs */, NULL /* reply */, &error); ASSERT_OR_PRINT (ok, error); /* Ensure the server description is unchanged and remains as type * LoadBalancer. */ - monitor_sd = mongoc_client_select_server ( - client, true /* for writes */, NULL /* read prefs */, &error); + monitor_sd = mongoc_client_select_server (client, true /* for writes */, NULL /* read prefs */, &error); ASSERT_OR_PRINT (monitor_sd, error); ASSERT_CMPSTR ("LoadBalancer", mongoc_server_description_type (monitor_sd)); @@ -337,15 +327,13 @@ test_loadbalanced_server_selection_establishes_connection_single (void *unused) client = test_framework_new_default_client (); stats = set_client_callbacks (client); - monitor_sd = mongoc_client_select_server ( - client, true /* for writes */, NULL /* read prefs */, &error); + monitor_sd = mongoc_client_select_server (client, true /* for writes */, NULL /* read prefs */, &error); ASSERT_OR_PRINT (monitor_sd, error); ASSERT_CMPSTR ("LoadBalancer", mongoc_server_description_type (monitor_sd)); /* Ensure that a connection has been established by getting the handshake's * server description. */ - handshake_sd = mongoc_client_get_handshake_description ( - client, monitor_sd->id, NULL /* opts */, &error); + handshake_sd = mongoc_client_get_handshake_description (client, monitor_sd->id, NULL /* opts */, &error); ASSERT_OR_PRINT (handshake_sd, error); ASSERT_CMPSTR ("Mongos", mongoc_server_description_type (handshake_sd)); @@ -371,57 +359,40 @@ test_loadbalanced_cooldown_is_bypassed_single (void *unused) client = test_framework_new_default_client (); stats = set_client_callbacks (client); - ok = mongoc_client_command_simple ( - client, - "admin", - tmp_bson ("{'configureFailPoint': 'failCommand', 'mode': { 'times': 2 }, " - "'data': {'closeConnection': true, 'failCommands': ['ping', " - "'hello']}}"), - NULL /* read prefs */, - NULL /* reply */, - &error); - ASSERT_OR_PRINT (ok, error); - ok = mongoc_client_command_simple (client, "admin", - tmp_bson ("{'ping': 1}"), + tmp_bson ("{'configureFailPoint': 'failCommand', 'mode': { 'times': 2 }, " + "'data': {'closeConnection': true, 'failCommands': ['ping', " + "'hello']}}"), NULL /* read prefs */, NULL /* reply */, &error); + ASSERT_OR_PRINT (ok, error); + + ok = mongoc_client_command_simple ( + client, "admin", tmp_bson ("{'ping': 1}"), NULL /* read prefs */, NULL /* reply */, &error); BSON_ASSERT (!ok); - ASSERT_ERROR_CONTAINS ( - error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "socket error"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "socket error"); /* The next attempted command should attempt to scan, and fail when * performing the handshake with the hello command. */ - ok = mongoc_client_command_simple (client, - "admin", - tmp_bson ("{'ping': 1}"), - NULL /* read prefs */, - NULL /* reply */, - &error); + ok = mongoc_client_command_simple ( + client, "admin", tmp_bson ("{'ping': 1}"), NULL /* read prefs */, NULL /* reply */, &error); BSON_ASSERT (!ok); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_NOT_ESTABLISHED, - "Could not establish stream"); + ASSERT_ERROR_CONTAINS ( + error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_NOT_ESTABLISHED, "Could not establish stream"); /* Failing to "scan" would normally cause the node to be in cooldown and fail * to reconnect (until the 5 second period has passed). But in load balancer * mode cooldown is bypassed, so the subsequent connect attempt should * succeed. */ - ok = mongoc_client_command_simple (client, - "admin", - tmp_bson ("{'ping': 1}"), - NULL /* read prefs */, - NULL /* reply */, - &error); + ok = mongoc_client_command_simple ( + client, "admin", tmp_bson ("{'ping': 1}"), NULL /* read prefs */, NULL /* reply */, &error); ASSERT_OR_PRINT (ok, error); /* Ensure the server description is unchanged and remains as type * LoadBalancer. */ - monitor_sd = mongoc_client_select_server ( - client, true /* for writes */, NULL /* read prefs */, &error); + monitor_sd = mongoc_client_select_server (client, true /* for writes */, NULL /* read prefs */, &error); ASSERT_OR_PRINT (monitor_sd, error); ASSERT_CMPSTR ("LoadBalancer", mongoc_server_description_type (monitor_sd)); @@ -463,14 +434,9 @@ test_loadbalanced_handshake_sends_loadbalanced (void) mongoc_uri_set_option_as_bool (uri, MONGOC_URI_LOADBALANCED, true); client = test_framework_client_new_from_uri (uri, NULL); - future = future_client_command_simple (client, - "admin", - tmp_bson ("{'ping': 1}"), - NULL /* read prefs */, - NULL /* reply */, - &error); - request = mock_server_receives_any_hello_with_match ( - server, "{'loadBalanced': true}", "{'loadBalanced': true}"); + future = future_client_command_simple ( + client, "admin", tmp_bson ("{'ping': 1}"), NULL /* read prefs */, NULL /* reply */, &error); + request = mock_server_receives_any_hello_with_match (server, "{'loadBalanced': true}", "{'loadBalanced': true}"); reply_to_request_simple (request, LB_HELLO); request_destroy (request); @@ -480,11 +446,9 @@ test_loadbalanced_handshake_sends_loadbalanced (void) ASSERT_OR_PRINT (future_get_bool (future), error); future_destroy (future); - monitor_sd = mongoc_client_select_server ( - client, true /* for writes */, NULL /* read prefs */, &error); + monitor_sd = mongoc_client_select_server (client, true /* for writes */, NULL /* read prefs */, &error); ASSERT_OR_PRINT (monitor_sd, error); - handshake_sd = mongoc_client_get_handshake_description ( - client, 1, NULL /* opts */, &error); + handshake_sd = mongoc_client_get_handshake_description (client, 1, NULL /* opts */, &error); ASSERT_OR_PRINT (handshake_sd, error); bson_oid_init_from_string (&expected, "AAAAAAAAAAAAAAAAAAAAAAAA"); @@ -525,14 +489,9 @@ test_loadbalanced_handshake_rejects_non_loadbalanced (void) mongoc_uri_set_option_as_bool (uri, MONGOC_URI_LOADBALANCED, true); client = test_framework_client_new_from_uri (uri, NULL); - future = future_client_command_simple (client, - "admin", - tmp_bson ("{'ping': 1}"), - NULL /* read prefs */, - NULL /* reply */, - &error); - request = mock_server_receives_any_hello_with_match ( - server, "{'loadBalanced': true}", "{'loadBalanced': true}"); + future = future_client_command_simple ( + client, "admin", tmp_bson ("{'ping': 1}"), NULL /* read prefs */, NULL /* reply */, &error); + request = mock_server_receives_any_hello_with_match (server, "{'loadBalanced': true}", "{'loadBalanced': true}"); reply_to_request_simple (request, NON_LB_HELLO); request_destroy (request); BSON_ASSERT (!future_get_bool (future)); @@ -574,16 +533,11 @@ test_pre_handshake_error_does_not_clear_pool (void) client_2 = mongoc_client_pool_pop (pool); /* client_1 opens a new connection to send "ping" */ - future = future_client_command_simple (client_1, - "admin", - tmp_bson ("{'ping': 1}"), - NULL /* read prefs */, - NULL /* reply */, - &error); + future = future_client_command_simple ( + client_1, "admin", tmp_bson ("{'ping': 1}"), NULL /* read prefs */, NULL /* reply */, &error); /* A new connection is opened. */ request = mock_server_receives_hello_op_msg (server); - ASSERT ( - request_matches_msg (request, MONGOC_MSG_NONE, &match_loadBalanced, 1)); + ASSERT (request_matches_msg (request, MONGOC_MSG_NONE, &match_loadBalanced, 1)); BSON_ASSERT (request); reply_to_request_simple (request, LB_HELLO); @@ -597,32 +551,22 @@ test_pre_handshake_error_does_not_clear_pool (void) /* client_2 attempts to open a new connection, but receives an error on the * handshake. */ - future = future_client_command_simple (client_2, - "admin", - tmp_bson ("{'ping': 1}"), - NULL /* read prefs */, - NULL /* reply */, - &error); + future = future_client_command_simple ( + client_2, "admin", tmp_bson ("{'ping': 1}"), NULL /* read prefs */, NULL /* reply */, &error); /* A new connection is opened. */ request = mock_server_receives_hello_op_msg (server); - ASSERT ( - request_matches_msg (request, MONGOC_MSG_NONE, &match_loadBalanced, 1)); + ASSERT (request_matches_msg (request, MONGOC_MSG_NONE, &match_loadBalanced, 1)); BSON_ASSERT (request); capture_logs (true); /* hide Failed to buffer logs. */ reply_to_request_with_hang_up (request); request_destroy (request); BSON_ASSERT (!future_get_bool (future)); - ASSERT_ERROR_CONTAINS ( - error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "Failed to send"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "Failed to send"); future_destroy (future); /* client_1 sends another "ping". */ - future = future_client_command_simple (client_1, - "admin", - tmp_bson ("{'ping': 1}"), - NULL /* read prefs */, - NULL /* reply */, - &error); + future = future_client_command_simple ( + client_1, "admin", tmp_bson ("{'ping': 1}"), NULL /* read prefs */, NULL /* reply */, &error); /* The connection pool must not have been cleared. It can reuse the previous * connection. The next command is the "ping". */ @@ -686,16 +630,11 @@ test_post_handshake_error_clears_pool (void) client_3_serviceid_b = mongoc_client_pool_pop (pool); /* client_1_serviceid_a opens a new connection to send "ping" */ - future = future_client_command_simple (client_1_serviceid_a, - "admin", - tmp_bson ("{'ping': 1}"), - NULL /* read prefs */, - NULL /* reply */, - &error); + future = future_client_command_simple ( + client_1_serviceid_a, "admin", tmp_bson ("{'ping': 1}"), NULL /* read prefs */, NULL /* reply */, &error); /* A new connection is opened. */ request = mock_server_receives_hello_op_msg (server); - ASSERT ( - request_matches_msg (request, MONGOC_MSG_NONE, &match_loadBalanced, 1)); + ASSERT (request_matches_msg (request, MONGOC_MSG_NONE, &match_loadBalanced, 1)); BSON_ASSERT (request); reply_to_request_simple (request, LB_HELLO_A); request_destroy (request); @@ -708,16 +647,11 @@ test_post_handshake_error_clears_pool (void) /* client_2_serviceid_a also opens a new connection and receives the same * service ID. */ - future = future_client_command_simple (client_2_serviceid_a, - "admin", - tmp_bson ("{'ping': 1}"), - NULL /* read prefs */, - NULL /* reply */, - &error); + future = future_client_command_simple ( + client_2_serviceid_a, "admin", tmp_bson ("{'ping': 1}"), NULL /* read prefs */, NULL /* reply */, &error); /* A new connection is opened. */ request = mock_server_receives_hello_op_msg (server); - ASSERT ( - request_matches_msg (request, MONGOC_MSG_NONE, &match_loadBalanced, 1)); + ASSERT (request_matches_msg (request, MONGOC_MSG_NONE, &match_loadBalanced, 1)); BSON_ASSERT (request); reply_to_request_simple (request, LB_HELLO_A); request_destroy (request); @@ -730,16 +664,11 @@ test_post_handshake_error_clears_pool (void) /* client_3_serviceid_b also opens a new connection, but receives a different * service ID. */ - future = future_client_command_simple (client_3_serviceid_b, - "admin", - tmp_bson ("{'ping': 1}"), - NULL /* read prefs */, - NULL /* reply */, - &error); + future = future_client_command_simple ( + client_3_serviceid_b, "admin", tmp_bson ("{'ping': 1}"), NULL /* read prefs */, NULL /* reply */, &error); /* A new connection is opened. */ request = mock_server_receives_hello_op_msg (server); - ASSERT ( - request_matches_msg (request, MONGOC_MSG_NONE, &match_loadBalanced, 1)); + ASSERT (request_matches_msg (request, MONGOC_MSG_NONE, &match_loadBalanced, 1)); BSON_ASSERT (request); reply_to_request_simple (request, LB_HELLO_B); request_destroy (request); @@ -751,12 +680,8 @@ test_post_handshake_error_clears_pool (void) future_destroy (future); /* client_1_serviceid_a receives a network error. */ - future = future_client_command_simple (client_1_serviceid_a, - "admin", - tmp_bson ("{'ping': 1}"), - NULL /* read prefs */, - NULL /* reply */, - &error); + future = future_client_command_simple ( + client_1_serviceid_a, "admin", tmp_bson ("{'ping': 1}"), NULL /* read prefs */, NULL /* reply */, &error); /* The "ping" command is sent. */ request = mock_server_receives_msg (server, 0, tmp_bson ("{'ping': 1}")); BSON_ASSERT (request); @@ -764,26 +689,19 @@ test_post_handshake_error_clears_pool (void) reply_to_request_with_hang_up (request); request_destroy (request); BSON_ASSERT (!future_get_bool (future)); - ASSERT_ERROR_CONTAINS ( - error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "Failed to send"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "Failed to send"); future_destroy (future); /* Assert that the server is NOT marked Unknown. */ - monitor_sd = mongoc_client_select_server ( - client_1_serviceid_a, true, NULL /* read prefs */, &error); + monitor_sd = mongoc_client_select_server (client_1_serviceid_a, true, NULL /* read prefs */, &error); ASSERT_CMPSTR ("LoadBalancer", mongoc_server_description_type (monitor_sd)); /* This should have invalidated the connection for client_2_serviceid_a. */ - future = future_client_command_simple (client_2_serviceid_a, - "admin", - tmp_bson ("{'ping': 1}"), - NULL /* read prefs */, - NULL /* reply */, - &error); + future = future_client_command_simple ( + client_2_serviceid_a, "admin", tmp_bson ("{'ping': 1}"), NULL /* read prefs */, NULL /* reply */, &error); /* A new connection is opened. */ request = mock_server_receives_hello_op_msg (server); - ASSERT ( - request_matches_msg (request, MONGOC_MSG_NONE, &match_loadBalanced, 1)); + ASSERT (request_matches_msg (request, MONGOC_MSG_NONE, &match_loadBalanced, 1)); BSON_ASSERT (request); reply_to_request_simple (request, LB_HELLO_A); request_destroy (request); @@ -795,12 +713,8 @@ test_post_handshake_error_clears_pool (void) future_destroy (future); /* But the connection for client_3_serviceid_b should still be OK. */ - future = future_client_command_simple (client_3_serviceid_b, - "admin", - tmp_bson ("{'ping': 1}"), - NULL /* read prefs */, - NULL /* reply */, - &error); + future = future_client_command_simple ( + client_3_serviceid_b, "admin", tmp_bson ("{'ping': 1}"), NULL /* read prefs */, NULL /* reply */, &error); /* The "ping" command is sent. */ request = mock_server_receives_msg (server, 0, tmp_bson ("{'ping': 1}")); BSON_ASSERT (request); @@ -849,64 +763,52 @@ test_loadbalanced_sends_recoveryToken (void *unused) // Set a callback to store the most recent command started. { mongoc_apm_callbacks_t *cbs = mongoc_apm_callbacks_new (); - mongoc_apm_set_command_started_cb (cbs, - store_last_command_started_callback); + mongoc_apm_set_command_started_cb (cbs, store_last_command_started_callback); mongoc_client_set_apm_callbacks (client, cbs, &last_command); mongoc_apm_callbacks_destroy (cbs); } - mongoc_client_session_t *session = - mongoc_client_start_session (client, NULL /* opts */, &error); + mongoc_client_session_t *session = mongoc_client_start_session (client, NULL /* opts */, &error); ASSERT_OR_PRINT (session, error); - mongoc_collection_t *coll = - mongoc_client_get_collection (client, "db", "coll"); + mongoc_collection_t *coll = mongoc_client_get_collection (client, "db", "coll"); // Commit a transaction. Expect `commitTransaction` to include // `recoveryToken`. { - bool ok = mongoc_client_session_start_transaction ( - session, NULL /* opts */, &error); + bool ok = mongoc_client_session_start_transaction (session, NULL /* opts */, &error); ASSERT_OR_PRINT (ok, error); bson_t *insert_opts = tmp_bson ("{}"); ok = mongoc_client_session_append (session, insert_opts, &error); ASSERT_OR_PRINT (ok, error); - ok = mongoc_collection_insert_one ( - coll, tmp_bson ("{}"), insert_opts, NULL, &error); + ok = mongoc_collection_insert_one (coll, tmp_bson ("{}"), insert_opts, NULL, &error); ASSERT_OR_PRINT (ok, error); - ok = mongoc_client_session_commit_transaction ( - session, NULL /* reply */, &error); + ok = mongoc_client_session_commit_transaction (session, NULL /* reply */, &error); ASSERT_OR_PRINT (ok, error); - ASSERT_MATCH ( - last_command, - "{'commitTransaction': 1, 'recoveryToken': { '$exists': true } }"); + ASSERT_MATCH (last_command, "{'commitTransaction': 1, 'recoveryToken': { '$exists': true } }"); } // Abort a transaction. Expect `abortTransaction` to include // `recoveryToken`. { - bool ok = mongoc_client_session_start_transaction ( - session, NULL /* opts */, &error); + bool ok = mongoc_client_session_start_transaction (session, NULL /* opts */, &error); ASSERT_OR_PRINT (ok, error); bson_t *insert_opts = tmp_bson ("{}"); ok = mongoc_client_session_append (session, insert_opts, &error); ASSERT_OR_PRINT (ok, error); - ok = mongoc_collection_insert_one ( - coll, tmp_bson ("{}"), insert_opts, NULL, &error); + ok = mongoc_collection_insert_one (coll, tmp_bson ("{}"), insert_opts, NULL, &error); ASSERT_OR_PRINT (ok, error); ok = mongoc_client_session_abort_transaction (session, &error); ASSERT_OR_PRINT (ok, error); - ASSERT_MATCH ( - last_command, - "{'abortTransaction': 1, 'recoveryToken': { '$exists': true } }"); + ASSERT_MATCH (last_command, "{'abortTransaction': 1, 'recoveryToken': { '$exists': true } }"); } mongoc_collection_destroy (coll); @@ -951,13 +853,12 @@ test_loadbalanced_install (TestSuite *suite) NULL /* dtor */, skip_if_not_loadbalanced); - TestSuite_AddFull ( - suite, - "/loadbalanced/server_selection_establishes_connection/single", - test_loadbalanced_server_selection_establishes_connection_single, - NULL /* ctx */, - NULL /* dtor */, - skip_if_not_loadbalanced); + TestSuite_AddFull (suite, + "/loadbalanced/server_selection_establishes_connection/single", + test_loadbalanced_server_selection_establishes_connection_single, + NULL /* ctx */, + NULL /* dtor */, + skip_if_not_loadbalanced); TestSuite_AddFull (suite, "/loadbalanced/cooldown_is_bypassed/single", @@ -967,24 +868,17 @@ test_loadbalanced_install (TestSuite *suite) skip_if_not_loadbalanced, test_framework_skip_if_no_failpoint); - TestSuite_AddMockServerTest (suite, - "/loadbalanced/handshake_sends_loadbalanced", - test_loadbalanced_handshake_sends_loadbalanced); + TestSuite_AddMockServerTest ( + suite, "/loadbalanced/handshake_sends_loadbalanced", test_loadbalanced_handshake_sends_loadbalanced); TestSuite_AddMockServerTest ( - suite, - "/loadbalanced/handshake_rejects_non_loadbalanced", - test_loadbalanced_handshake_rejects_non_loadbalanced); + suite, "/loadbalanced/handshake_rejects_non_loadbalanced", test_loadbalanced_handshake_rejects_non_loadbalanced); TestSuite_AddMockServerTest ( - suite, - "/loadbalanced/pre_handshake_error_does_not_clear_pool", - test_pre_handshake_error_does_not_clear_pool); + suite, "/loadbalanced/pre_handshake_error_does_not_clear_pool", test_pre_handshake_error_does_not_clear_pool); TestSuite_AddMockServerTest ( - suite, - "/loadbalanced/post_handshake_error_clears_pool", - test_post_handshake_error_clears_pool); + suite, "/loadbalanced/post_handshake_error_clears_pool", test_post_handshake_error_clears_pool); TestSuite_AddFull (suite, "/loadbalanced/sends_recoveryToken", diff --git a/src/libmongoc/tests/test-mongoc-log.c b/src/libmongoc/tests/test-mongoc-log.c index ff9d5f2fde..17ced18c56 100644 --- a/src/libmongoc/tests/test-mongoc-log.c +++ b/src/libmongoc/tests/test-mongoc-log.c @@ -57,10 +57,7 @@ struct log_func_data { void -log_func (mongoc_log_level_t log_level, - const char *log_domain, - const char *message, - void *user_data) +log_func (mongoc_log_level_t log_level, const char *log_domain, const char *message, void *user_data) { struct log_func_data *data = (struct log_func_data *) user_data; @@ -187,17 +184,8 @@ void test_log_install (TestSuite *suite) { TestSuite_Add (suite, "/Log/basic", test_mongoc_log_handler); - TestSuite_AddFull (suite, - "/Log/trace/enabled", - test_mongoc_log_trace_enabled, - NULL, - NULL, - should_run_trace_tests); - TestSuite_AddFull (suite, - "/Log/trace/disabled", - test_mongoc_log_trace_disabled, - NULL, - NULL, - should_not_run_trace_tests); + TestSuite_AddFull (suite, "/Log/trace/enabled", test_mongoc_log_trace_enabled, NULL, NULL, should_run_trace_tests); + TestSuite_AddFull ( + suite, "/Log/trace/disabled", test_mongoc_log_trace_disabled, NULL, NULL, should_not_run_trace_tests); TestSuite_Add (suite, "/Log/null", test_mongoc_log_null); } diff --git a/src/libmongoc/tests/test-mongoc-long-namespace.c b/src/libmongoc/tests/test-mongoc-long-namespace.c index 8f9b849cb1..af60e3c611 100644 --- a/src/libmongoc/tests/test-mongoc-long-namespace.c +++ b/src/libmongoc/tests/test-mongoc-long-namespace.c @@ -43,23 +43,18 @@ command_started (const mongoc_apm_command_started_t *event) test_fixture_t *test_fixture; test_fixture = mongoc_apm_command_started_get_context (event); - if (0 == strcmp (mongoc_apm_command_started_get_command_name (event), - "renameCollection")) { - ASSERT_CMPSTR (mongoc_apm_command_started_get_database_name (event), - "admin"); + if (0 == strcmp (mongoc_apm_command_started_get_command_name (event), "renameCollection")) { + ASSERT_CMPSTR (mongoc_apm_command_started_get_database_name (event), "admin"); /* Always runs on admin. */ } else { - ASSERT_CMPSTR (mongoc_apm_command_started_get_database_name (event), - test_fixture->ns_db); + ASSERT_CMPSTR (mongoc_apm_command_started_get_database_name (event), test_fixture->ns_db); } } /* Test long namespaces. Prior to SERVER-32959, the total namespace limit was * 120 characters. */ static void -test_fixture_init (test_fixture_t *test_fixture, - uint32_t db_len, - uint32_t coll_len) +test_fixture_init (test_fixture_t *test_fixture, uint32_t db_len, uint32_t coll_len) { bool ret; bson_error_t error; @@ -73,29 +68,23 @@ test_fixture_init (test_fixture_t *test_fixture, memset (test_fixture->ns_coll, 'c', coll_len); test_fixture->ns_coll[coll_len] = '\0'; - test_fixture->ns = - bson_strdup_printf ("%s.%s", test_fixture->ns_db, test_fixture->ns_coll); + test_fixture->ns = bson_strdup_printf ("%s.%s", test_fixture->ns_db, test_fixture->ns_coll); /* Construct client, database, and collection objects. */ test_fixture->client = test_framework_new_default_client (); test_framework_set_ssl_opts (test_fixture->client); - mongoc_client_set_error_api (test_fixture->client, - MONGOC_ERROR_API_VERSION_2); + mongoc_client_set_error_api (test_fixture->client, MONGOC_ERROR_API_VERSION_2); callbacks = mongoc_apm_callbacks_new (); mongoc_apm_set_command_started_cb (callbacks, command_started); - mongoc_client_set_apm_callbacks ( - test_fixture->client, callbacks, test_fixture); + mongoc_client_set_apm_callbacks (test_fixture->client, callbacks, test_fixture); - test_fixture->db = - mongoc_client_get_database (test_fixture->client, test_fixture->ns_db); + test_fixture->db = mongoc_client_get_database (test_fixture->client, test_fixture->ns_db); ASSERT_CMPSTR (test_fixture->db->name, test_fixture->ns_db); - test_fixture->coll = - mongoc_database_get_collection (test_fixture->db, test_fixture->ns_coll); + test_fixture->coll = mongoc_database_get_collection (test_fixture->db, test_fixture->ns_coll); ASSERT_CMPSTR (test_fixture->coll->collection, test_fixture->ns_coll); - ASSERT_CMPSIZE_T ( - test_fixture->coll->collectionlen, ==, strlen (test_fixture->ns_coll)); + ASSERT_CMPSIZE_T (test_fixture->coll->collectionlen, ==, strlen (test_fixture->ns_coll)); ASSERT_CMPSTR (test_fixture->coll->db, test_fixture->ns_db); ASSERT_CMPSTR (test_fixture->coll->ns, test_fixture->ns); ASSERT_CMPSIZE_T (test_fixture->coll->nslen, ==, strlen (test_fixture->ns)); @@ -110,12 +99,11 @@ test_fixture_init (test_fixture_t *test_fixture, /* Explicitly create 'coll', so it shows up in listCollections. */ mongoc_collection_destroy (test_fixture->coll); - test_fixture->coll = mongoc_database_create_collection ( - test_fixture->db, test_fixture->ns_coll, NULL /* opts */, &error); + test_fixture->coll = + mongoc_database_create_collection (test_fixture->db, test_fixture->ns_coll, NULL /* opts */, &error); ASSERT_OR_PRINT (test_fixture->coll, error); ASSERT_CMPSTR (test_fixture->coll->collection, test_fixture->ns_coll); - ASSERT_CMPSIZE_T ( - test_fixture->coll->collectionlen, ==, strlen (test_fixture->ns_coll)); + ASSERT_CMPSIZE_T (test_fixture->coll->collectionlen, ==, strlen (test_fixture->ns_coll)); ASSERT_CMPSTR (test_fixture->coll->db, test_fixture->ns_db); ASSERT_CMPSTR (test_fixture->coll->ns, test_fixture->ns); ASSERT_CMPSIZE_T (test_fixture->coll->nslen, ==, strlen (test_fixture->ns)); @@ -148,18 +136,13 @@ crud (test_fixture_t *test_fixture) const bson_t *found; /* Insert. */ - ret = mongoc_collection_insert_one (test_fixture->coll, - tmp_bson ("{'_id': 'hello'}"), - NULL /* opts */, - NULL /* reply */, - &error); + ret = mongoc_collection_insert_one ( + test_fixture->coll, tmp_bson ("{'_id': 'hello'}"), NULL /* opts */, NULL /* reply */, &error); ASSERT_OR_PRINT (ret, error); /* Find that document back. */ - cursor = mongoc_collection_find_with_opts (test_fixture->coll, - tmp_bson ("{'_id': 'hello'}"), - NULL /* opts */, - NULL /* read prefs */); + cursor = mongoc_collection_find_with_opts ( + test_fixture->coll, tmp_bson ("{'_id': 'hello'}"), NULL /* opts */, NULL /* read prefs */); ret = mongoc_cursor_next (cursor, &found); ASSERT_OR_PRINT (!mongoc_cursor_error (cursor, &error) && ret, error); ASSERT_MATCH (found, "{'_id': 'hello'}"); @@ -178,10 +161,8 @@ crud (test_fixture_t *test_fixture) /* Find that document back to ensure the document in the right collection was * updated. */ - cursor = mongoc_collection_find_with_opts (test_fixture->coll, - tmp_bson ("{'_id': 'hello'}"), - NULL /* opts */, - NULL /* read prefs */); + cursor = mongoc_collection_find_with_opts ( + test_fixture->coll, tmp_bson ("{'_id': 'hello'}"), NULL /* opts */, NULL /* read prefs */); ret = mongoc_cursor_next (cursor, &found); ASSERT_OR_PRINT (!mongoc_cursor_error (cursor, &error) && ret, error); ASSERT_MATCH (found, "{'_id': 'hello', 'x': 1}"); @@ -190,19 +171,14 @@ crud (test_fixture_t *test_fixture) mongoc_cursor_destroy (cursor); /* Delete it. */ - ret = mongoc_collection_delete_one (test_fixture->coll, - tmp_bson ("{'_id': 'hello'}"), - NULL /* opts */, - NULL /* reply */, - &error); + ret = mongoc_collection_delete_one ( + test_fixture->coll, tmp_bson ("{'_id': 'hello'}"), NULL /* opts */, NULL /* reply */, &error); ASSERT_OR_PRINT (ret, error); /* Attempt to find that document back to ensure the document in the right * collection was deleted. */ - cursor = mongoc_collection_find_with_opts (test_fixture->coll, - tmp_bson ("{'_id': 'hello'}"), - NULL /* opts */, - NULL /* read prefs */); + cursor = mongoc_collection_find_with_opts ( + test_fixture->coll, tmp_bson ("{'_id': 'hello'}"), NULL /* opts */, NULL /* read prefs */); ASSERT_CURSOR_DONE (cursor); ASSERT_CMPSTR (cursor->ns, test_fixture->ns); mongoc_cursor_destroy (cursor); @@ -219,25 +195,17 @@ getmore (test_fixture_t *test_fixture) const bson_t *found; /* Insert two documents. */ - ret = mongoc_collection_insert_one (test_fixture->coll, - tmp_bson ("{'_id': 'hello'}"), - NULL /* opts */, - NULL /* reply */, - &error); + ret = mongoc_collection_insert_one ( + test_fixture->coll, tmp_bson ("{'_id': 'hello'}"), NULL /* opts */, NULL /* reply */, &error); ASSERT_OR_PRINT (ret, error); - ret = mongoc_collection_insert_one (test_fixture->coll, - tmp_bson ("{'_id': 'world'}"), - NULL /* opts */, - NULL /* reply */, - &error); + ret = mongoc_collection_insert_one ( + test_fixture->coll, tmp_bson ("{'_id': 'world'}"), NULL /* opts */, NULL /* reply */, &error); ASSERT_OR_PRINT (ret, error); /* Find each document back in two separate batches. */ - cursor = mongoc_collection_find_with_opts (test_fixture->coll, - tmp_bson ("{}"), - tmp_bson ("{'batchSize': 1}"), - NULL /* read prefs */); + cursor = mongoc_collection_find_with_opts ( + test_fixture->coll, tmp_bson ("{}"), tmp_bson ("{'batchSize': 1}"), NULL /* read prefs */); ret = mongoc_cursor_next (cursor, &found); ASSERT_OR_PRINT (!mongoc_cursor_error (cursor, &error) && ret, error); ASSERT_MATCH (found, "{'_id': 'hello'}"); @@ -263,8 +231,7 @@ change_stream (test_fixture_t *test_fixture) mongoc_client_session_t *client_session; bson_t opts_w_session; - client_session = mongoc_client_start_session ( - test_fixture->client, NULL /* opts */, &error); + client_session = mongoc_client_start_session (test_fixture->client, NULL /* opts */, &error); ASSERT_OR_PRINT (client_session, error); bson_init (&opts_w_session); ret = mongoc_client_session_append (client_session, &opts_w_session, &error); @@ -272,29 +239,22 @@ change_stream (test_fixture_t *test_fixture) /* Create a change stream. Do all operations within a session, to guarantee * change stream sees the subsequent insert operation. */ - change_stream = mongoc_collection_watch ( - test_fixture->coll, tmp_bson ("{}"), &opts_w_session); + change_stream = mongoc_collection_watch (test_fixture->coll, tmp_bson ("{}"), &opts_w_session); ASSERT_CMPSTR (change_stream->db, test_fixture->ns_db); ASSERT_CMPSTR (change_stream->coll, test_fixture->ns_coll); /* Insert. */ - ret = mongoc_collection_insert_one (test_fixture->coll, - tmp_bson ("{'_id': 'hello'}"), - NULL /* opts */, - NULL /* reply */, - &error); + ret = mongoc_collection_insert_one ( + test_fixture->coll, tmp_bson ("{'_id': 'hello'}"), NULL /* opts */, NULL /* reply */, &error); ASSERT_OR_PRINT (ret, error); /* Get a change stream event. */ ret = mongoc_change_stream_next (change_stream, &found); - ASSERT_OR_PRINT ( - !mongoc_change_stream_error_document (change_stream, &error, NULL) && ret, - error); - ASSERT_MATCH ( - found, - "{'operationType': 'insert', 'ns': { 'db': '%s', 'coll': '%s' }}", - test_fixture->ns_db, - test_fixture->ns_coll); + ASSERT_OR_PRINT (!mongoc_change_stream_error_document (change_stream, &error, NULL) && ret, error); + ASSERT_MATCH (found, + "{'operationType': 'insert', 'ns': { 'db': '%s', 'coll': '%s' }}", + test_fixture->ns_db, + test_fixture->ns_coll); mongoc_change_stream_destroy (change_stream); mongoc_client_session_destroy (client_session); @@ -312,22 +272,18 @@ client_command (test_fixture_t *test_fixture) bool ret; bson_error_t error; - cursor = mongoc_client_command ( - test_fixture->client, - test_fixture->ns_db, - MONGOC_QUERY_NONE, - 0 /* skip */, - 0 /* limit */, - 0 /* batch size */, - tmp_bson ("{'listCollections': 1, 'filter': {'name': '%s'}}", - test_fixture->ns_coll), - NULL /* fields */, - NULL /* read prefs */); + cursor = mongoc_client_command (test_fixture->client, + test_fixture->ns_db, + MONGOC_QUERY_NONE, + 0 /* skip */, + 0 /* limit */, + 0 /* batch size */, + tmp_bson ("{'listCollections': 1, 'filter': {'name': '%s'}}", test_fixture->ns_coll), + NULL /* fields */, + NULL /* read prefs */); ret = mongoc_cursor_next (cursor, &found); ASSERT_OR_PRINT (!mongoc_cursor_error (cursor, &error) && ret, error); - ASSERT_MATCH (found, - "{'cursor': {'firstBatch': [{'name': '%s'}]}}", - test_fixture->ns_coll); + ASSERT_MATCH (found, "{'cursor': {'firstBatch': [{'name': '%s'}]}}", test_fixture->ns_coll); mongoc_cursor_destroy (cursor); } @@ -341,21 +297,18 @@ database_command (test_fixture_t *test_fixture) bool ret; bson_error_t error; - cursor = mongoc_database_command ( - test_fixture->db, - MONGOC_QUERY_NONE, - 0 /* skip */, - 0 /* limit */, - 0 /* batch size */, - tmp_bson ("{'listCollections': 1, 'filter': {'name': '%s'}}", - test_fixture->ns_coll), - NULL /* fields */, - NULL /* read prefs */); + cursor = + mongoc_database_command (test_fixture->db, + MONGOC_QUERY_NONE, + 0 /* skip */, + 0 /* limit */, + 0 /* batch size */, + tmp_bson ("{'listCollections': 1, 'filter': {'name': '%s'}}", test_fixture->ns_coll), + NULL /* fields */, + NULL /* read prefs */); ret = mongoc_cursor_next (cursor, &found); ASSERT_OR_PRINT (!mongoc_cursor_error (cursor, &error) && ret, error); - ASSERT_MATCH (found, - "{'cursor': {'firstBatch': [{'name': '%s'}]}}", - test_fixture->ns_coll); + ASSERT_MATCH (found, "{'cursor': {'firstBatch': [{'name': '%s'}]}}", test_fixture->ns_coll); mongoc_cursor_destroy (cursor); } @@ -369,30 +322,24 @@ collection_command (test_fixture_t *test_fixture) bool ret; bson_error_t error; - cursor = mongoc_collection_command ( - test_fixture->coll, - MONGOC_QUERY_NONE, - 0 /* skip */, - 0 /* limit */, - 0 /* batch size */, - tmp_bson ("{'listCollections': 1, 'filter': {'name': '%s'}}", - test_fixture->ns_coll), - NULL /* fields */, - NULL /* read prefs */); + cursor = + mongoc_collection_command (test_fixture->coll, + MONGOC_QUERY_NONE, + 0 /* skip */, + 0 /* limit */, + 0 /* batch size */, + tmp_bson ("{'listCollections': 1, 'filter': {'name': '%s'}}", test_fixture->ns_coll), + NULL /* fields */, + NULL /* read prefs */); ret = mongoc_cursor_next (cursor, &found); ASSERT_OR_PRINT (!mongoc_cursor_error (cursor, &error) && ret, error); - ASSERT_MATCH (found, - "{'cursor': {'firstBatch': [{'name': '%s'}]}}", - test_fixture->ns_coll); + ASSERT_MATCH (found, "{'cursor': {'firstBatch': [{'name': '%s'}]}}", test_fixture->ns_coll); mongoc_cursor_destroy (cursor); } /* Check whether a collection exists. */ static void -_check_existence (mongoc_client_t *client, - char *ns_db, - char *ns_coll, - bool should_exist) +_check_existence (mongoc_client_t *client, char *ns_db, char *ns_coll, bool should_exist) { mongoc_database_t *db; char **db_names; @@ -405,10 +352,8 @@ _check_existence (mongoc_client_t *client, ASSERT (client); db = mongoc_client_get_database (client, ns_db); - db_names = mongoc_client_get_database_names_with_opts ( - client, NULL /* opts */, &error); - coll_names = mongoc_database_get_collection_names_with_opts ( - db, NULL /* opts */, &error); + db_names = mongoc_client_get_database_names_with_opts (client, NULL /* opts */, &error); + coll_names = mongoc_database_get_collection_names_with_opts (db, NULL /* opts */, &error); for (iter = db_names; *iter != NULL; ++iter) { if (0 == strcmp (ns_db, *iter)) { @@ -455,15 +400,11 @@ collection_rename (test_fixture_t *test_fixture) new_ns = bson_strdup_printf ("%s.%s", new_db, new_coll); /* Insert to create source namespace. */ - ret = mongoc_collection_insert_one (test_fixture->coll, - tmp_bson ("{'_id': 'hello'}"), - NULL /* opts */, - NULL /* reply */, - &error); + ret = mongoc_collection_insert_one ( + test_fixture->coll, tmp_bson ("{'_id': 'hello'}"), NULL /* opts */, NULL /* reply */, &error); ASSERT_OR_PRINT (ret, error); - ret = mongoc_collection_rename ( - test_fixture->coll, new_db, new_coll, true, &error); + ret = mongoc_collection_rename (test_fixture->coll, new_db, new_coll, true, &error); ASSERT_OR_PRINT (ret, error); /* The fields in the collection struct are updated to the new names. */ @@ -533,8 +474,7 @@ unsupported_long_coll (void *unused) mongoc_client_set_error_api (client, MONGOC_ERROR_API_VERSION_2); coll = mongoc_client_get_collection (client, "test", long_coll); /* Insert. */ - ret = mongoc_collection_insert_one ( - coll, tmp_bson ("{'x': 1}"), NULL /* opts */, NULL /* reply */, &error); + ret = mongoc_collection_insert_one (coll, tmp_bson ("{'x': 1}"), NULL /* opts */, NULL /* reply */, &error); BSON_ASSERT (!ret); /* Error code changed in 4.0 and the message in 4.2. Just validate an error * happened. */ @@ -564,8 +504,7 @@ unsupported_long_db (void) mongoc_client_set_error_api (client, MONGOC_ERROR_API_VERSION_2); coll = mongoc_client_get_collection (client, long_db, "test"); /* Insert. */ - ret = mongoc_collection_insert_one ( - coll, tmp_bson ("{'x': 1}"), NULL /* opts */, NULL /* reply */, &error); + ret = mongoc_collection_insert_one (coll, tmp_bson ("{'x': 1}"), NULL /* opts */, NULL /* reply */, &error); BSON_ASSERT (!ret); /* Error code changed in 3.4. Just validate an error happened. */ @@ -580,45 +519,40 @@ test_long_namespace_install (TestSuite *suite) { /* MongoDB 4.4 (wire version 9) introduced support for long namespaces in * SERVER-32959 */ - TestSuite_AddFullWithTestFn ( - suite, - "/long_namespace/client_command", - run_test, - NULL /* dtor */, - client_command, - test_framework_skip_if_max_wire_version_less_than_9); - - TestSuite_AddFullWithTestFn ( - suite, - "/long_namespace/database_command", - run_test, - NULL /* dtor */, - database_command, - test_framework_skip_if_max_wire_version_less_than_9); - - TestSuite_AddFullWithTestFn ( - suite, - "/long_namespace/collection_command", - run_test, - NULL /* dtor */, - collection_command, - test_framework_skip_if_max_wire_version_less_than_9); - - TestSuite_AddFullWithTestFn ( - suite, - "/long_namespace/crud", - run_test, - NULL /* dtor */, - crud, - test_framework_skip_if_max_wire_version_less_than_9); - - TestSuite_AddFullWithTestFn ( - suite, - "/long_namespace/getmore", - run_test, - NULL /* dtor */, - getmore, - test_framework_skip_if_max_wire_version_less_than_9); + TestSuite_AddFullWithTestFn (suite, + "/long_namespace/client_command", + run_test, + NULL /* dtor */, + client_command, + test_framework_skip_if_max_wire_version_less_than_9); + + TestSuite_AddFullWithTestFn (suite, + "/long_namespace/database_command", + run_test, + NULL /* dtor */, + database_command, + test_framework_skip_if_max_wire_version_less_than_9); + + TestSuite_AddFullWithTestFn (suite, + "/long_namespace/collection_command", + run_test, + NULL /* dtor */, + collection_command, + test_framework_skip_if_max_wire_version_less_than_9); + + TestSuite_AddFullWithTestFn (suite, + "/long_namespace/crud", + run_test, + NULL /* dtor */, + crud, + test_framework_skip_if_max_wire_version_less_than_9); + + TestSuite_AddFullWithTestFn (suite, + "/long_namespace/getmore", + run_test, + NULL /* dtor */, + getmore, + test_framework_skip_if_max_wire_version_less_than_9); TestSuite_AddFullWithTestFn (suite, "/long_namespace/change_stream", @@ -628,14 +562,13 @@ test_long_namespace_install (TestSuite *suite) test_framework_skip_if_not_rs_version_9, test_framework_skip_if_no_sessions); - TestSuite_AddFullWithTestFn ( - suite, - "/long_namespace/collection_rename", - run_test, - NULL /* dtor */, - collection_rename, - test_framework_skip_if_max_wire_version_less_than_9, - test_framework_skip_if_mongos); + TestSuite_AddFullWithTestFn (suite, + "/long_namespace/collection_rename", + run_test, + NULL /* dtor */, + collection_rename, + test_framework_skip_if_max_wire_version_less_than_9, + test_framework_skip_if_mongos); TestSuite_AddFull (suite, "/long_namespace/unsupported_long_coll", @@ -644,6 +577,5 @@ test_long_namespace_install (TestSuite *suite) NULL /* ctx */, test_framework_skip_if_max_wire_version_more_than_8); - TestSuite_AddLive ( - suite, "/long_namespace/unsupported_long_db", unsupported_long_db); + TestSuite_AddLive (suite, "/long_namespace/unsupported_long_db", unsupported_long_db); } diff --git a/src/libmongoc/tests/test-mongoc-matcher.c b/src/libmongoc/tests/test-mongoc-matcher.c index aa269b9e13..8f15c13e98 100644 --- a/src/libmongoc/tests/test-mongoc-matcher.c +++ b/src/libmongoc/tests/test-mongoc-matcher.c @@ -115,8 +115,7 @@ test_mongoc_matcher_array (void) /* query matches itself */ BSON_ASSERT (mongoc_matcher_match (matcher, query)); - to_match = - BCON_NEW ("a", "[", BCON_INT32 (1), BCON_INT32 (2), "]", "b", "whatever"); + to_match = BCON_NEW ("a", "[", BCON_INT32 (1), BCON_INT32 (2), "]", "b", "whatever"); BSON_ASSERT (mongoc_matcher_match (matcher, to_match)); /* query {a: [1, 2]} doesn't match {a: 1} */ @@ -130,8 +129,7 @@ test_mongoc_matcher_array (void) bson_destroy (should_fail); /* query {a: [1, 2]} doesn't match {a: [1, 2, 3]} */ - should_fail = - BCON_NEW ("a", "[", BCON_INT32 (1), BCON_INT32 (2), BCON_INT32 (3), "]"); + should_fail = BCON_NEW ("a", "[", BCON_INT32 (1), BCON_INT32 (2), BCON_INT32 (3), "]"); BSON_ASSERT (!mongoc_matcher_match (matcher, should_fail)); bson_destroy (should_fail); @@ -225,28 +223,16 @@ test_mongoc_matcher_logic_ops (void) {"{\"$or\": [{\"a\": 1}, {\"b\": 2}]}", "{\"a\": 1}", true}, {"{\"$or\": [{\"a\": 1}, {\"b\": 2}]}", "{\"b\": 2}", true}, {"{\"$or\": [{\"a\": 1}, {\"b\": 2}]}", "{\"a\": 3}", false}, - {"{\"$or\": [{\"a\": {\"$gt\": 1}}, {\"a\": {\"$lt\": -1}}]}", - "{\"a\": 3}", - true}, - {"{\"$or\": [{\"a\": {\"$gt\": 1}}, {\"a\": {\"$lt\": -1}}]}", - "{\"a\": -2}", - true}, - {"{\"$or\": [{\"a\": {\"$gt\": 1}}, {\"a\": {\"$lt\": -1}}]}", - "{\"a\": 0}", - false}, + {"{\"$or\": [{\"a\": {\"$gt\": 1}}, {\"a\": {\"$lt\": -1}}]}", "{\"a\": 3}", true}, + {"{\"$or\": [{\"a\": {\"$gt\": 1}}, {\"a\": {\"$lt\": -1}}]}", "{\"a\": -2}", true}, + {"{\"$or\": [{\"a\": {\"$gt\": 1}}, {\"a\": {\"$lt\": -1}}]}", "{\"a\": 0}", false}, {"{\"$and\": [{\"a\": 1}, {\"b\": 2}]}", "{\"a\": 1, \"b\": 2}", true}, {"{\"$and\": [{\"a\": 1}, {\"b\": 2}]}", "{\"a\": 1, \"b\": 1}", false}, {"{\"$and\": [{\"a\": 1}, {\"b\": 2}]}", "{\"a\": 1}", false}, {"{\"$and\": [{\"a\": 1}, {\"b\": 2}]}", "{\"b\": 2}", false}, - {"{\"$and\": [{\"a\": {\"$gt\": -1}}, {\"a\": {\"$lt\": 1}}]}", - "{\"a\": 0}", - true}, - {"{\"$and\": [{\"a\": {\"$gt\": -1}}, {\"a\": {\"$lt\": 1}}]}", - "{\"a\": -2}", - false}, - {"{\"$and\": [{\"a\": {\"$gt\": -1}}, {\"a\": {\"$lt\": 1}}]}", - "{\"a\": 1}", - false}, + {"{\"$and\": [{\"a\": {\"$gt\": -1}}, {\"a\": {\"$lt\": 1}}]}", "{\"a\": 0}", true}, + {"{\"$and\": [{\"a\": {\"$gt\": -1}}, {\"a\": {\"$lt\": 1}}]}", "{\"a\": -2}", false}, + {"{\"$and\": [{\"a\": {\"$gt\": -1}}, {\"a\": {\"$lt\": 1}}]}", "{\"a\": 1}", false}, }; int n_tests = sizeof tests / sizeof (logic_op_test_t); @@ -262,8 +248,7 @@ test_mongoc_matcher_logic_ops (void) test = tests[i]; spec = bson_new_from_json ((uint8_t *) test.spec, -1, &error); if (!spec) { - test_error ( - "couldn't parse JSON query:\n\n%s\n\n%s", test.spec, error.message); + test_error ("couldn't parse JSON query:\n\n%s\n\n%s", test.spec, error.message); } matcher = mongoc_matcher_new (spec, &error); @@ -271,17 +256,12 @@ test_mongoc_matcher_logic_ops (void) doc = bson_new_from_json ((uint8_t *) test.doc, -1, &error); if (!doc) { - test_error ("couldn't parse JSON document:\n\n%s\n\n%s", - test.doc, - error.message); + test_error ("couldn't parse JSON document:\n\n%s\n\n%s", test.doc, error.message); } r = mongoc_matcher_match (matcher, doc); if (test.match != r) { - test_error ("query:\n\n%s\n\nshould %shave matched:\n\n%s", - test.match ? "" : "not ", - test.spec, - test.doc); + test_error ("query:\n\n%s\n\nshould %shave matched:\n\n%s", test.match ? "" : "not ", test.spec, test.doc); } mongoc_matcher_destroy (matcher); @@ -446,8 +426,7 @@ test_mongoc_matcher_eq_doc (void) BSON_ASSERT (mongoc_matcher_match (matcher, spec)); /* {doc: {a: 1}} matches {doc: {a: 1}, foo: "whatever"} */ - doc = BCON_NEW ( - "doc", "{", "a", BCON_INT32 (1), "}", "foo", BCON_UTF8 ("whatever")); + doc = BCON_NEW ("doc", "{", "a", BCON_INT32 (1), "}", "foo", BCON_UTF8 ("whatever")); BSON_ASSERT (mongoc_matcher_match (matcher, doc)); bson_destroy (doc); @@ -502,15 +481,7 @@ test_mongoc_matcher_in_basic (void) bson_t *spec; bson_t doc = BSON_INITIALIZER; - spec = BCON_NEW ("key", - "{", - "$in", - "[", - BCON_INT32 (1), - BCON_INT32 (2), - BCON_INT32 (3), - "]", - "}"); + spec = BCON_NEW ("key", "{", "$in", "[", BCON_INT32 (1), BCON_INT32 (2), BCON_INT32 (3), "]", "}"); matcher = mongoc_matcher_new (spec, &error); r = mongoc_matcher_match (matcher, &doc); diff --git a/src/libmongoc/tests/test-mongoc-max-staleness.c b/src/libmongoc/tests/test-mongoc-max-staleness.c index 1c8616bed7..10f67b120f 100644 --- a/src/libmongoc/tests/test-mongoc-max-staleness.c +++ b/src/libmongoc/tests/test-mongoc-max-staleness.c @@ -36,63 +36,47 @@ test_mongoc_client_max_staleness (void) ASSERT_CMPINT64 (get_max_staleness (client), ==, (int64_t) -1); mongoc_client_destroy (client); - client = test_framework_client_new ( - "mongodb://a/?" MONGOC_URI_READPREFERENCE "=secondary", NULL); + client = test_framework_client_new ("mongodb://a/?" MONGOC_URI_READPREFERENCE "=secondary", NULL); ASSERT_CMPINT64 (get_max_staleness (client), ==, (int64_t) -1); mongoc_client_destroy (client); /* -1 is the default, means "no max staleness" */ - client = test_framework_client_new ( - "mongodb://a/?" MONGOC_URI_MAXSTALENESSSECONDS "=-1", NULL); + client = test_framework_client_new ("mongodb://a/?" MONGOC_URI_MAXSTALENESSSECONDS "=-1", NULL); ASSERT_CMPINT64 (get_max_staleness (client), ==, (int64_t) -1); mongoc_client_destroy (client); client = test_framework_client_new ( - "mongodb://a/?" MONGOC_URI_READPREFERENCE - "=primary&" MONGOC_URI_MAXSTALENESSSECONDS "=-1", - NULL); + "mongodb://a/?" MONGOC_URI_READPREFERENCE "=primary&" MONGOC_URI_MAXSTALENESSSECONDS "=-1", NULL); ASSERT_CMPINT64 (get_max_staleness (client), ==, (int64_t) -1); mongoc_client_destroy (client); /* no " MONGOC_URI_MAXSTALENESSSECONDS " with primary mode */ capture_logs (true); - ASSERT (!test_framework_client_new ( - "mongodb://a/?" MONGOC_URI_MAXSTALENESSSECONDS "=120", NULL)); - ASSERT_CAPTURED_LOG (MONGOC_URI_MAXSTALENESSSECONDS "=120", - MONGOC_LOG_LEVEL_WARNING, - "Invalid readPreferences"); + ASSERT (!test_framework_client_new ("mongodb://a/?" MONGOC_URI_MAXSTALENESSSECONDS "=120", NULL)); + ASSERT_CAPTURED_LOG (MONGOC_URI_MAXSTALENESSSECONDS "=120", MONGOC_LOG_LEVEL_WARNING, "Invalid readPreferences"); capture_logs (true); ASSERT (!test_framework_client_new ( - "mongodb://a/?" MONGOC_URI_READPREFERENCE - "=primary&" MONGOC_URI_MAXSTALENESSSECONDS "=120", - NULL)); - ASSERT_CAPTURED_LOG (MONGOC_URI_MAXSTALENESSSECONDS "=120", - MONGOC_LOG_LEVEL_WARNING, - "Invalid readPreferences"); + "mongodb://a/?" MONGOC_URI_READPREFERENCE "=primary&" MONGOC_URI_MAXSTALENESSSECONDS "=120", NULL)); + ASSERT_CAPTURED_LOG (MONGOC_URI_MAXSTALENESSSECONDS "=120", MONGOC_LOG_LEVEL_WARNING, "Invalid readPreferences"); capture_logs (false); /* zero is prohibited */ capture_logs (true); client = test_framework_client_new ( - "mongodb://a/?" MONGOC_URI_READPREFERENCE - "=nearest&" MONGOC_URI_MAXSTALENESSSECONDS "=0", - NULL); + "mongodb://a/?" MONGOC_URI_READPREFERENCE "=nearest&" MONGOC_URI_MAXSTALENESSSECONDS "=0", NULL); - ASSERT_CAPTURED_LOG ( - MONGOC_URI_MAXSTALENESSSECONDS "=0", - MONGOC_LOG_LEVEL_WARNING, - "Unsupported value for \"" MONGOC_URI_MAXSTALENESSSECONDS "\": \"0\""); + ASSERT_CAPTURED_LOG (MONGOC_URI_MAXSTALENESSSECONDS "=0", + MONGOC_LOG_LEVEL_WARNING, + "Unsupported value for \"" MONGOC_URI_MAXSTALENESSSECONDS "\": \"0\""); capture_logs (false); ASSERT_CMPINT64 (get_max_staleness (client), ==, (int64_t) -1); mongoc_client_destroy (client); - client = - test_framework_client_new ("mongodb://a/?" MONGOC_URI_MAXSTALENESSSECONDS - "=120&" MONGOC_URI_READPREFERENCE "=secondary", - NULL); + client = test_framework_client_new ( + "mongodb://a/?" MONGOC_URI_MAXSTALENESSSECONDS "=120&" MONGOC_URI_READPREFERENCE "=secondary", NULL); ASSERT_CMPINT64 (get_max_staleness (client), ==, (int64_t) 120); mongoc_client_destroy (client); @@ -100,20 +84,15 @@ test_mongoc_client_max_staleness (void) /* float is ignored */ capture_logs (true); ASSERT (!test_framework_client_new ( - "mongodb://a/?" MONGOC_URI_READPREFERENCE - "=secondary&" MONGOC_URI_MAXSTALENESSSECONDS "=10.5", - NULL)); + "mongodb://a/?" MONGOC_URI_READPREFERENCE "=secondary&" MONGOC_URI_MAXSTALENESSSECONDS "=10.5", NULL)); - ASSERT_CAPTURED_LOG (MONGOC_URI_MAXSTALENESSSECONDS "=10.5", - MONGOC_LOG_LEVEL_WARNING, - "Invalid " MONGOC_URI_MAXSTALENESSSECONDS); + ASSERT_CAPTURED_LOG ( + MONGOC_URI_MAXSTALENESSSECONDS "=10.5", MONGOC_LOG_LEVEL_WARNING, "Invalid " MONGOC_URI_MAXSTALENESSSECONDS); capture_logs (false); /* 1 is allowed, it'll be rejected once we begin server selection */ client = test_framework_client_new ( - "mongodb://a/?" MONGOC_URI_READPREFERENCE - "=secondary&" MONGOC_URI_MAXSTALENESSSECONDS "=1", - NULL); + "mongodb://a/?" MONGOC_URI_READPREFERENCE "=secondary&" MONGOC_URI_MAXSTALENESSSECONDS "=1", NULL); ASSERT_EQUAL_DOUBLE (get_max_staleness (client), 1); mongoc_client_destroy (client); @@ -134,22 +113,19 @@ test_mongos_max_staleness_read_pref (void) server = mock_mongos_new (WIRE_VERSION_MIN); mock_server_run (server); mock_server_auto_endsessions (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); collection = mongoc_client_get_collection (client, "db", "collection"); /* count command with mode "secondary", no MONGOC_URI_MAXSTALENESSSECONDS. */ prefs = mongoc_read_prefs_new (MONGOC_READ_SECONDARY); mongoc_collection_set_read_prefs (collection, prefs); - future = future_collection_count ( - collection, MONGOC_QUERY_NONE, NULL, 0, 0, NULL, &error); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db'," - " '$readPreference': {" - " 'mode': 'secondary'," - " 'maxStalenessSeconds': {'$exists': false}}}")); + future = future_collection_count (collection, MONGOC_QUERY_NONE, NULL, 0, 0, NULL, &error); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'db'," + " '$readPreference': {" + " 'mode': 'secondary'," + " 'maxStalenessSeconds': {'$exists': false}}}")); reply_to_request_simple (request, "{'ok': 1, 'n': 1}"); ASSERT_OR_PRINT (1 == future_get_int64_t (future), error); @@ -163,15 +139,13 @@ test_mongos_max_staleness_read_pref (void) mongoc_collection_set_read_prefs (collection, prefs); mongoc_collection_set_read_prefs (collection, prefs); - future = future_collection_count ( - collection, MONGOC_QUERY_NONE, NULL, 0, 0, NULL, &error); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db'," - " '$readPreference': {" - " 'mode': 'secondary'," - " 'maxStalenessSeconds': {'$numberLong': '1'}}}")); + future = future_collection_count (collection, MONGOC_QUERY_NONE, NULL, 0, 0, NULL, &error); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'db'," + " '$readPreference': {" + " 'mode': 'secondary'," + " 'maxStalenessSeconds': {'$numberLong': '1'}}}")); reply_to_request_simple (request, "{'ok': 1, 'n': 1}"); ASSERT_OR_PRINT (1 == future_get_int64_t (future), error); @@ -185,13 +159,9 @@ test_mongos_max_staleness_read_pref (void) mongoc_read_prefs_set_max_staleness_seconds (prefs, MONGOC_NO_MAX_STALENESS); mongoc_collection_set_read_prefs (collection, prefs); - future = future_collection_count ( - collection, MONGOC_QUERY_NONE, NULL, 0, 0, NULL, &error); + future = future_collection_count (collection, MONGOC_QUERY_NONE, NULL, 0, 0, NULL, &error); request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ( - "{'$db': 'db', '$readPreference': {'mode': 'secondaryPreferred'}}")); + server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', '$readPreference': {'mode': 'secondaryPreferred'}}")); reply_to_request_simple (request, "{'ok': 1, 'n': 1}"); ASSERT_OR_PRINT (1 == future_get_int64_t (future), error); @@ -204,15 +174,13 @@ test_mongos_max_staleness_read_pref (void) mongoc_read_prefs_set_max_staleness_seconds (prefs, 1); mongoc_collection_set_read_prefs (collection, prefs); - future = future_collection_count ( - collection, MONGOC_QUERY_NONE, NULL, 0, 0, NULL, &error); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db'," - " '$readPreference': {" - " 'mode': 'secondaryPreferred'," - " 'maxStalenessSeconds': {'$numberLong': '1'}}}")); + future = future_collection_count (collection, MONGOC_QUERY_NONE, NULL, 0, 0, NULL, &error); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'db'," + " '$readPreference': {" + " 'mode': 'secondaryPreferred'," + " 'maxStalenessSeconds': {'$numberLong': '1'}}}")); reply_to_request_simple (request, "{'ok': 1, 'n': 1}"); ASSERT_OR_PRINT (1 == future_get_int64_t (future), error); @@ -253,23 +221,19 @@ _test_last_write_date (bool pooled) mongoc_uri_destroy (uri); collection = get_test_collection (client, "test_last_write_date"); - r = mongoc_collection_insert_one ( - collection, tmp_bson ("{}"), NULL, NULL, &error); + r = mongoc_collection_insert_one (collection, tmp_bson ("{}"), NULL, NULL, &error); ASSERT_OR_PRINT (r, error); _mongoc_usleep (1000 * 1000); - s0 = mongoc_topology_select ( - client->topology, MONGOC_SS_WRITE, NULL, NULL, &error); + s0 = mongoc_topology_select (client->topology, MONGOC_SS_WRITE, NULL, NULL, &error); ASSERT_OR_PRINT (s0, error); _mongoc_usleep (1000 * 1000); - r = mongoc_collection_insert_one ( - collection, tmp_bson ("{}"), NULL, NULL, &error); + r = mongoc_collection_insert_one (collection, tmp_bson ("{}"), NULL, NULL, &error); ASSERT_OR_PRINT (r, error); _mongoc_usleep (1000 * 1000); - s1 = mongoc_topology_select ( - client->topology, MONGOC_SS_WRITE, NULL, NULL, &error); + s1 = mongoc_topology_select (client->topology, MONGOC_SS_WRITE, NULL, NULL, &error); ASSERT_OR_PRINT (s1, error); ASSERT_CMPINT64 (s1->last_write_date_ms, !=, (int64_t) -1); @@ -326,8 +290,7 @@ _test_last_write_date_absent (bool pooled) client = test_framework_new_default_client (); } - sd = mongoc_topology_select ( - client->topology, MONGOC_SS_READ, NULL, NULL, &error); + sd = mongoc_topology_select (client->topology, MONGOC_SS_READ, NULL, NULL, &error); ASSERT_OR_PRINT (sd, error); /* lastWriteDate absent */ @@ -365,19 +328,15 @@ test_last_write_date_absent_pooled (void *ctx) static void test_all_spec_tests (TestSuite *suite) { - install_json_test_suite ( - suite, JSON_DIR, "max_staleness", &test_server_selection_logic_cb); + install_json_test_suite (suite, JSON_DIR, "max_staleness", &test_server_selection_logic_cb); } void test_client_max_staleness_install (TestSuite *suite) { test_all_spec_tests (suite); - TestSuite_Add ( - suite, "/Client/max_staleness", test_mongoc_client_max_staleness); - TestSuite_AddMockServerTest (suite, - "/Client/max_staleness/mongos", - test_mongos_max_staleness_read_pref); + TestSuite_Add (suite, "/Client/max_staleness", test_mongoc_client_max_staleness); + TestSuite_AddMockServerTest (suite, "/Client/max_staleness/mongos", test_mongos_max_staleness_read_pref); TestSuite_AddFull (suite, "/Client/last_write_date", test_last_write_date, @@ -392,12 +351,8 @@ test_client_max_staleness_install (TestSuite *suite) NULL, test_framework_skip_if_not_replset, test_framework_skip_if_slow); - TestSuite_AddFull (suite, - "/Client/last_write_date_absent", - test_last_write_date_absent, - NULL, - NULL, - test_framework_skip_if_replset); + TestSuite_AddFull ( + suite, "/Client/last_write_date_absent", test_last_write_date_absent, NULL, NULL, test_framework_skip_if_replset); TestSuite_AddFull (suite, "/Client/last_write_date_absent/pooled", test_last_write_date_absent_pooled, diff --git a/src/libmongoc/tests/test-mongoc-mongohouse.c b/src/libmongoc/tests/test-mongoc-mongohouse.c index 6e1582f6e4..a64fe3061b 100644 --- a/src/libmongoc/tests/test-mongoc-mongohouse.c +++ b/src/libmongoc/tests/test-mongoc-mongohouse.c @@ -4,19 +4,15 @@ #include "json-test-operations.h" #include "test-libmongoc.h" -static const char *uri_str = - "mongodb://mhuser:pencil@localhost/?serverSelectionTryOnce=false"; +static const char *uri_str = "mongodb://mhuser:pencil@localhost/?serverSelectionTryOnce=false"; static bool -mongohouse_test_operation_cb (json_test_ctx_t *ctx, - const bson_t *test, - const bson_t *operation) +mongohouse_test_operation_cb (json_test_ctx_t *ctx, const bson_t *test, const bson_t *operation) { bson_t reply; bool res; - res = - json_test_operation (ctx, test, operation, ctx->collection, NULL, &reply); + res = json_test_operation (ctx, test, operation, ctx->collection, NULL, &reply); bson_destroy (&reply); @@ -82,8 +78,7 @@ cmd_started_cb (const mongoc_apm_command_started_t *event) const char *db; char *ns; - if (strcmp (mongoc_apm_command_started_get_command_name (event), - "killCursors") != 0) { + if (strcmp (mongoc_apm_command_started_get_command_name (event), "killCursors") != 0) { return; } @@ -124,8 +119,7 @@ cmd_started_cb (const mongoc_apm_command_started_t *event) cursors_killed = bson_new_from_data (array_data, array_len); - test->parsed_cmd_started = - cursor_in_killed_array (cursors_killed, test->cursor_id); + test->parsed_cmd_started = cursor_in_killed_array (cursors_killed, test->cursor_id); bson_mutex_unlock (&test->mutex); bson_destroy (cursors_killed); @@ -183,8 +177,7 @@ cmd_succeeded_cb (const mongoc_apm_command_succeeded_t *event) cursors_killed = bson_new_from_data (array_data, array_len); - test->parsed_cmd_succeeded = - cursor_in_killed_array (cursors_killed, test->cursor_id); + test->parsed_cmd_succeeded = cursor_in_killed_array (cursors_killed, test->cursor_id); bson_mutex_unlock (&test->mutex); bson_destroy (cursors_killed); @@ -226,12 +219,11 @@ test_mongohouse_kill_cursors (void *ctx_unused) coll = mongoc_client_get_collection (client, "test", "driverdata"); /* Run a find on the server with a batchSize of 2 and a limit of 3. */ - cursor = mongoc_collection_find_with_opts ( - coll, - &query, - tmp_bson ("{ 'limit' : {'$numberLong' : '3'}, 'batchSize' : " - "{'$numberLong' : '2'}}"), - NULL); + cursor = mongoc_collection_find_with_opts (coll, + &query, + tmp_bson ("{ 'limit' : {'$numberLong' : '3'}, 'batchSize' : " + "{'$numberLong' : '2'}}"), + NULL); /* Iterate the cursor to run the find on the server. */ ASSERT_CURSOR_NEXT (cursor, &doc); @@ -264,8 +256,7 @@ _run_ping_test (const char *connection_string) client = test_framework_client_new_from_uri (uri, NULL); BSON_ASSERT (client); - res = mongoc_client_command_simple ( - client, "test", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); + res = mongoc_client_command_simple (client, "test", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); ASSERT_OR_PRINT (res, error); mongoc_client_destroy (client); @@ -280,12 +271,10 @@ test_mongohouse_auth (void *ctx_unused) BSON_UNUSED (ctx_unused); /* SCRAM-SHA-1 */ - _run_ping_test ( - "mongodb://mhuser:pencil@localhost/?authMechanism=SCRAM-SHA-1"); + _run_ping_test ("mongodb://mhuser:pencil@localhost/?authMechanism=SCRAM-SHA-1"); /* SCRAM-SHA-256 */ - _run_ping_test ( - "mongodb://mhuser:pencil@localhost/?authMechanism=SCRAM-SHA-256"); + _run_ping_test ("mongodb://mhuser:pencil@localhost/?authMechanism=SCRAM-SHA-256"); } /* Test that the driver can connect to ADL without authentication. */ @@ -301,11 +290,8 @@ test_mongohouse_no_auth (void *ctx_unused) void test_mongohouse_install (TestSuite *suite) { - install_json_test_suite_with_check (suite, - JSON_DIR, - "mongohouse", - &test_mongohouse_cb, - test_framework_skip_if_no_mongohouse); + install_json_test_suite_with_check ( + suite, JSON_DIR, "mongohouse", &test_mongohouse_cb, test_framework_skip_if_no_mongohouse); TestSuite_AddFull (suite, "/mongohouse/kill_cursors", @@ -314,17 +300,9 @@ test_mongohouse_install (TestSuite *suite) NULL, test_framework_skip_if_no_mongohouse); - TestSuite_AddFull (suite, - "/mongohouse/no_auth", - test_mongohouse_no_auth, - NULL, - NULL, - test_framework_skip_if_no_mongohouse); + TestSuite_AddFull ( + suite, "/mongohouse/no_auth", test_mongohouse_no_auth, NULL, NULL, test_framework_skip_if_no_mongohouse); - TestSuite_AddFull (suite, - "/mongohouse/auth", - test_mongohouse_auth, - NULL, - NULL, - test_framework_skip_if_no_mongohouse); + TestSuite_AddFull ( + suite, "/mongohouse/auth", test_mongohouse_auth, NULL, NULL, test_framework_skip_if_no_mongohouse); } diff --git a/src/libmongoc/tests/test-mongoc-mongos-pinning.c b/src/libmongoc/tests/test-mongoc-mongos-pinning.c index 9af3b48d18..47a22583e5 100644 --- a/src/libmongoc/tests/test-mongoc-mongos-pinning.c +++ b/src/libmongoc/tests/test-mongoc-mongos-pinning.c @@ -28,10 +28,8 @@ add_multiple_mongoses (mongoc_uri_t *uri) bson_error_t error; /* TODO CDRIVER-3285, fix this to be dynamic */ - ASSERT_OR_PRINT ( - mongoc_uri_upsert_host_and_port (uri, "localhost:27017", &error), error); - ASSERT_OR_PRINT ( - mongoc_uri_upsert_host_and_port (uri, "localhost:27018", &error), error); + ASSERT_OR_PRINT (mongoc_uri_upsert_host_and_port (uri, "localhost:27017", &error), error); + ASSERT_OR_PRINT (mongoc_uri_upsert_host_and_port (uri, "localhost:27018", &error), error); } static void @@ -60,25 +58,18 @@ test_new_transaction_unpins (void *ctx) /* Create a collection. */ coll = mongoc_client_get_collection (client, "test", "test"); - ASSERT_OR_PRINT ( - mongoc_collection_insert_one (coll, tmp_bson ("{}"), NULL, NULL, &error), - error); + ASSERT_OR_PRINT (mongoc_collection_insert_one (coll, tmp_bson ("{}"), NULL, NULL, &error), error); session = mongoc_client_start_session (client, NULL, &error); ASSERT_OR_PRINT (session != NULL, error); opts = bson_new (); - ASSERT_OR_PRINT (mongoc_client_session_append (session, opts, &error), - error); + ASSERT_OR_PRINT (mongoc_client_session_append (session, opts, &error), error); /* Under one transaction, insert a document. */ - ASSERT_OR_PRINT ( - mongoc_client_session_start_transaction (session, NULL, &error), error); - ASSERT_OR_PRINT ( - mongoc_collection_insert_one (coll, tmp_bson ("{}"), opts, NULL, &error), - error); - ASSERT_OR_PRINT ( - mongoc_client_session_commit_transaction (session, NULL, &error), error); + ASSERT_OR_PRINT (mongoc_client_session_start_transaction (session, NULL, &error), error); + ASSERT_OR_PRINT (mongoc_collection_insert_one (coll, tmp_bson ("{}"), opts, NULL, &error), error); + ASSERT_OR_PRINT (mongoc_client_session_commit_transaction (session, NULL, &error), error); /* Then, 50 times, start new transactions. Each time we start a new transaction, the session should be un-pinned, so by statistics, @@ -87,19 +78,14 @@ test_new_transaction_unpins (void *ctx) mongoc_host_list_t cursor_host; const bson_t *doc; - ASSERT_OR_PRINT ( - mongoc_client_session_start_transaction (session, NULL, &error), - error); + ASSERT_OR_PRINT (mongoc_client_session_start_transaction (session, NULL, &error), error); - cursor = - mongoc_collection_find_with_opts (coll, tmp_bson ("{}"), opts, NULL); + cursor = mongoc_collection_find_with_opts (coll, tmp_bson ("{}"), opts, NULL); ASSERT (mongoc_cursor_next (cursor, &doc)); mongoc_cursor_get_host (cursor, &cursor_host); _mongoc_host_list_upsert (&servers, &cursor_host); - ASSERT_OR_PRINT ( - mongoc_client_session_commit_transaction (session, NULL, &error), - error); + ASSERT_OR_PRINT (mongoc_client_session_commit_transaction (session, NULL, &error), error); mongoc_cursor_destroy (cursor); } @@ -140,25 +126,18 @@ test_non_transaction_unpins (void *ctx) /* Create a collection. */ coll = mongoc_client_get_collection (client, "test", "test"); - ASSERT_OR_PRINT ( - mongoc_collection_insert_one (coll, tmp_bson ("{}"), NULL, NULL, &error), - error); + ASSERT_OR_PRINT (mongoc_collection_insert_one (coll, tmp_bson ("{}"), NULL, NULL, &error), error); session = mongoc_client_start_session (client, NULL, &error); ASSERT_OR_PRINT (session != NULL, error); opts = bson_new (); - ASSERT_OR_PRINT (mongoc_client_session_append (session, opts, &error), - error); + ASSERT_OR_PRINT (mongoc_client_session_append (session, opts, &error), error); /* Under one transaction, insert a document. */ - ASSERT_OR_PRINT ( - mongoc_client_session_start_transaction (session, NULL, &error), error); - ASSERT_OR_PRINT ( - mongoc_collection_insert_one (coll, tmp_bson ("{}"), opts, NULL, &error), - error); - ASSERT_OR_PRINT ( - mongoc_client_session_commit_transaction (session, NULL, &error), error); + ASSERT_OR_PRINT (mongoc_client_session_start_transaction (session, NULL, &error), error); + ASSERT_OR_PRINT (mongoc_collection_insert_one (coll, tmp_bson ("{}"), opts, NULL, &error), error); + ASSERT_OR_PRINT (mongoc_client_session_commit_transaction (session, NULL, &error), error); /* After our initial transaction, the session should become un-pinned if we run further operations on the session. By statistics, @@ -167,8 +146,7 @@ test_non_transaction_unpins (void *ctx) mongoc_host_list_t cursor_host; const bson_t *doc; - cursor = - mongoc_collection_find_with_opts (coll, tmp_bson ("{}"), opts, NULL); + cursor = mongoc_collection_find_with_opts (coll, tmp_bson ("{}"), opts, NULL); ASSERT (mongoc_cursor_next (cursor, &doc)); mongoc_cursor_get_host (cursor, &cursor_host); _mongoc_host_list_upsert (&servers, &cursor_host); diff --git a/src/libmongoc/tests/test-mongoc-ocsp-cache.c b/src/libmongoc/tests/test-mongoc-ocsp-cache.c index 65737132ca..7b72149311 100644 --- a/src/libmongoc/tests/test-mongoc-ocsp-cache.c +++ b/src/libmongoc/tests/test-mongoc-ocsp-cache.c @@ -62,8 +62,7 @@ test_mongoc_cache_insert (void) { ASN1_GENERALIZEDTIME *this_update_in, *next_update_in; ASN1_GENERALIZEDTIME *this_update_out, *next_update_out; - int i, size = 5, status = V_OCSP_CERTSTATUS_GOOD, - reason = OCSP_REVOKED_STATUS_NOSTATUS; + int i, size = 5, status = V_OCSP_CERTSTATUS_GOOD, reason = OCSP_REVOKED_STATUS_NOSTATUS; CLEAR_CACHE; @@ -73,10 +72,8 @@ test_mongoc_cache_insert (void) int s, r; OCSP_CERTID *id = create_cert_id (i); - BSON_ASSERT (!_mongoc_ocsp_cache_get_status ( - id, &s, &r, &this_update_out, &next_update_out)); - _mongoc_ocsp_cache_set_resp ( - id, status, reason, this_update_in, next_update_in); + BSON_ASSERT (!_mongoc_ocsp_cache_get_status (id, &s, &r, &this_update_out, &next_update_out)); + _mongoc_ocsp_cache_set_resp (id, status, reason, this_update_in, next_update_in); OCSP_CERTID_free (id); } @@ -87,8 +84,7 @@ test_mongoc_cache_insert (void) OCSP_CERTID *id = create_cert_id (i); int s, r; - BSON_ASSERT (_mongoc_ocsp_cache_get_status ( - id, &s, &r, &this_update_out, &next_update_out)); + BSON_ASSERT (_mongoc_ocsp_cache_get_status (id, &s, &r, &this_update_out, &next_update_out)); BSON_ASSERT (status == s); BSON_ASSERT (reason == r); @@ -115,36 +111,28 @@ test_mongoc_cache_update (void) next_update_in = ASN1_GENERALIZEDTIME_set (NULL, time (NULL)); id = create_cert_id (1); - _mongoc_ocsp_cache_set_resp ( - id, V_OCSP_CERTSTATUS_GOOD, 0, NULL, next_update_in); + _mongoc_ocsp_cache_set_resp (id, V_OCSP_CERTSTATUS_GOOD, 0, NULL, next_update_in); BSON_ASSERT (_mongoc_ocsp_cache_length () == 1); - BSON_ASSERT (_mongoc_ocsp_cache_get_status ( - id, &status, &reason, &this_update_out, &next_update_out)); + BSON_ASSERT (_mongoc_ocsp_cache_get_status (id, &status, &reason, &this_update_out, &next_update_out)); BSON_ASSERT (status == V_OCSP_CERTSTATUS_GOOD); ASN1_GENERALIZEDTIME_free (next_update_in); - next_update_in = ASN1_GENERALIZEDTIME_set ( - NULL, time (NULL) + 999 /* some time in the future */); + next_update_in = ASN1_GENERALIZEDTIME_set (NULL, time (NULL) + 999 /* some time in the future */); - _mongoc_ocsp_cache_set_resp ( - id, V_OCSP_CERTSTATUS_REVOKED, 0, NULL, next_update_in); + _mongoc_ocsp_cache_set_resp (id, V_OCSP_CERTSTATUS_REVOKED, 0, NULL, next_update_in); BSON_ASSERT (_mongoc_ocsp_cache_length () == 1); - BSON_ASSERT (_mongoc_ocsp_cache_get_status ( - id, &status, &reason, &this_update_out, &next_update_out)); + BSON_ASSERT (_mongoc_ocsp_cache_get_status (id, &status, &reason, &this_update_out, &next_update_out)); BSON_ASSERT (status == V_OCSP_CERTSTATUS_REVOKED); ASN1_GENERALIZEDTIME_free (next_update_in); - next_update_in = ASN1_GENERALIZEDTIME_set ( - NULL, time (NULL) - 999 /* some time in the past */); + next_update_in = ASN1_GENERALIZEDTIME_set (NULL, time (NULL) - 999 /* some time in the past */); - _mongoc_ocsp_cache_set_resp ( - id, V_OCSP_CERTSTATUS_GOOD, 0, NULL, next_update_in); + _mongoc_ocsp_cache_set_resp (id, V_OCSP_CERTSTATUS_GOOD, 0, NULL, next_update_in); BSON_ASSERT (_mongoc_ocsp_cache_length () == 1); - BSON_ASSERT (_mongoc_ocsp_cache_get_status ( - id, &status, &reason, &this_update_out, &next_update_out)); + BSON_ASSERT (_mongoc_ocsp_cache_get_status (id, &status, &reason, &this_update_out, &next_update_out)); BSON_ASSERT (status == V_OCSP_CERTSTATUS_REVOKED); CLEAR_CACHE; @@ -165,8 +153,7 @@ test_mongoc_cache_remove_expired_cert (void) next_update_in = ASN1_GENERALIZEDTIME_set (NULL, time (NULL) - 1); this_update_in = ASN1_GENERALIZEDTIME_set (NULL, time (NULL) - 999); - _mongoc_ocsp_cache_set_resp ( - id, status, reason, this_update_in, next_update_in); + _mongoc_ocsp_cache_set_resp (id, status, reason, this_update_in, next_update_in); BSON_ASSERT (_mongoc_ocsp_cache_length () == 1); BSON_ASSERT (!_mongoc_ocsp_cache_get_status (id, NULL, NULL, NULL, NULL)); @@ -184,9 +171,7 @@ test_ocsp_cache_install (TestSuite *suite) { TestSuite_Add (suite, "/OCSPCache/insert", test_mongoc_cache_insert); TestSuite_Add (suite, "/OCSPCache/update", test_mongoc_cache_update); - TestSuite_Add (suite, - "/OCSPCache/remove_expired_cert", - test_mongoc_cache_remove_expired_cert); + TestSuite_Add (suite, "/OCSPCache/remove_expired_cert", test_mongoc_cache_remove_expired_cert); } #else extern int no_mongoc_ocsp; diff --git a/src/libmongoc/tests/test-mongoc-opts.c b/src/libmongoc/tests/test-mongoc-opts.c index 02ad7bdbe6..723916e34f 100644 --- a/src/libmongoc/tests/test-mongoc-opts.c +++ b/src/libmongoc/tests/test-mongoc-opts.c @@ -49,9 +49,7 @@ typedef enum { /* for mongoc_bulk_operation_t tests */ -typedef bool (*bulk_op_t) (mongoc_bulk_operation_t *bulk, - bson_error_t *error, - bson_t *cmd /* OUT */); +typedef bool (*bulk_op_t) (mongoc_bulk_operation_t *bulk, bson_error_t *error, bson_t *cmd /* OUT */); struct _opt_inheritance_test_t; @@ -141,27 +139,26 @@ func_ctx_cleanup (func_ctx_t *ctx) } else \ (void) 0 -#define SET_OPT(_type) \ - static void set_##_type##_opt (mongoc_##_type##_t *obj, \ - opt_type_t opt_type) \ - { \ - SET_OPT_PREAMBLE (_type); \ - \ - switch (opt_type) { \ - case OPT_READ_CONCERN: \ - mongoc_##_type##_set_read_concern (obj, rc); \ - break; \ - case OPT_WRITE_CONCERN: \ - mongoc_##_type##_set_write_concern (obj, wc); \ - break; \ - case OPT_READ_PREFS: \ - mongoc_##_type##_set_read_prefs (obj, prefs); \ - break; \ - default: \ - test_error ("invalid opt_type: %d", (int) opt_type); \ - } \ - \ - SET_OPT_CLEANUP; \ +#define SET_OPT(_type) \ + static void set_##_type##_opt (mongoc_##_type##_t *obj, opt_type_t opt_type) \ + { \ + SET_OPT_PREAMBLE (_type); \ + \ + switch (opt_type) { \ + case OPT_READ_CONCERN: \ + mongoc_##_type##_set_read_concern (obj, rc); \ + break; \ + case OPT_WRITE_CONCERN: \ + mongoc_##_type##_set_write_concern (obj, wc); \ + break; \ + case OPT_READ_PREFS: \ + mongoc_##_type##_set_read_prefs (obj, prefs); \ + break; \ + default: \ + test_error ("invalid opt_type: %d", (int) opt_type); \ + } \ + \ + SET_OPT_CLEANUP; \ } SET_OPT (client) @@ -170,9 +167,7 @@ SET_OPT (collection) static void -set_func_opt (bson_t *opts, - mongoc_read_prefs_t **prefs_ptr, - opt_type_t opt_type) +set_func_opt (bson_t *opts, mongoc_read_prefs_t **prefs_ptr, opt_type_t opt_type) { SET_OPT_PREAMBLE (function); @@ -223,9 +218,7 @@ add_expected_opt (opt_source_t opt_source, opt_type_t opt_type, bson_t *cmd) opt = tmp_bson ("{'writeConcern': {'w': '%s'}}", source_name); break; case OPT_READ_PREFS: - opt = tmp_bson ( - "{'$readPreference': {'mode': 'secondary', 'tags': [{'%s': 'yes'}]}}", - source_name); + opt = tmp_bson ("{'$readPreference': {'mode': 'secondary', 'tags': [{'%s': 'yes'}]}}", source_name); break; default: test_error ("invalid opt_type: %d", (int) opt_type); @@ -279,13 +272,8 @@ 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); + return future_client_read_command_with_opts ( + ctx->client, "db", tmp_bson ("{'foo': 1}"), ctx->prefs, ctx->opts, NULL, &ctx->error); } @@ -294,12 +282,7 @@ client_write_cmd (func_ctx_t *ctx, bson_t *cmd) { BSON_APPEND_UTF8 (cmd, "foo", "collection"); return future_client_write_command_with_opts ( - ctx->client, - "db", - tmp_bson ("{'foo': 'collection'}"), - ctx->opts, - NULL, - &ctx->error); + ctx->client, "db", tmp_bson ("{'foo': 'collection'}"), ctx->opts, NULL, &ctx->error); } @@ -308,13 +291,7 @@ client_read_write_cmd (func_ctx_t *ctx, bson_t *cmd) { BSON_APPEND_UTF8 (cmd, "foo", "collection"); return future_client_read_write_command_with_opts ( - ctx->client, - "db", - tmp_bson ("{'foo': 'collection'}"), - ctx->prefs, - ctx->opts, - NULL, - &ctx->error); + ctx->client, "db", tmp_bson ("{'foo': 'collection'}"), ctx->prefs, ctx->opts, NULL, &ctx->error); } @@ -344,12 +321,8 @@ static future_t * db_read_cmd (func_ctx_t *ctx, bson_t *cmd) { BSON_APPEND_UTF8 (cmd, "foo", "db"); - return future_database_read_command_with_opts (ctx->db, - tmp_bson ("{'foo': 'db'}"), - ctx->prefs, - ctx->opts, - NULL, - &ctx->error); + return future_database_read_command_with_opts ( + ctx->db, tmp_bson ("{'foo': 'db'}"), ctx->prefs, ctx->opts, NULL, &ctx->error); } @@ -357,8 +330,7 @@ static future_t * db_write_cmd (func_ctx_t *ctx, bson_t *cmd) { BSON_APPEND_UTF8 (cmd, "foo", "db"); - return future_database_write_command_with_opts ( - ctx->db, tmp_bson ("{'foo': 'db'}"), ctx->opts, NULL, &ctx->error); + return future_database_write_command_with_opts (ctx->db, tmp_bson ("{'foo': 'db'}"), ctx->opts, NULL, &ctx->error); } @@ -367,12 +339,7 @@ db_read_write_cmd (func_ctx_t *ctx, bson_t *cmd) { BSON_APPEND_UTF8 (cmd, "foo", "db"); return future_database_read_write_command_with_opts ( - ctx->db, - tmp_bson ("{'foo': 'db'}"), - ctx->prefs, - ctx->opts, - NULL, - &ctx->error); + ctx->db, tmp_bson ("{'foo': 'db'}"), ctx->prefs, ctx->opts, NULL, &ctx->error); } @@ -394,12 +361,8 @@ static future_t * aggregate (func_ctx_t *ctx, bson_t *cmd) { BSON_APPEND_UTF8 (cmd, "aggregate", "collection"); - ctx->cursor = - mongoc_collection_aggregate (ctx->collection, - MONGOC_QUERY_NONE, - tmp_bson ("{'pipeline': [{'$out': 'foo'}]}"), - ctx->opts, - ctx->prefs); + ctx->cursor = mongoc_collection_aggregate ( + ctx->collection, MONGOC_QUERY_NONE, tmp_bson ("{'pipeline': [{'$out': 'foo'}]}"), ctx->opts, ctx->prefs); /* use ctx->data as the bson_t** out-param to mongoc_cursor_next () */ return future_cursor_next (ctx->cursor, (const bson_t **) &ctx->data); @@ -410,11 +373,8 @@ static future_t * aggregate_raw_pipeline (func_ctx_t *ctx, bson_t *cmd) { BSON_APPEND_UTF8 (cmd, "aggregate", "collection"); - ctx->cursor = mongoc_collection_aggregate (ctx->collection, - MONGOC_QUERY_NONE, - tmp_bson ("[{'$out': 'foo'}]"), - ctx->opts, - ctx->prefs); + ctx->cursor = mongoc_collection_aggregate ( + ctx->collection, MONGOC_QUERY_NONE, tmp_bson ("[{'$out': 'foo'}]"), ctx->opts, ctx->prefs); /* use ctx->data as the bson_t** out-param to mongoc_cursor_next () */ return future_cursor_next (ctx->cursor, (const bson_t **) &ctx->data); @@ -425,8 +385,7 @@ static future_t * collection_drop (func_ctx_t *ctx, bson_t *cmd) { BSON_APPEND_UTF8 (cmd, "drop", "collection"); - return future_collection_drop_with_opts ( - ctx->collection, ctx->opts, &ctx->error); + return future_collection_drop_with_opts (ctx->collection, ctx->opts, &ctx->error); } @@ -435,12 +394,7 @@ collection_read_cmd (func_ctx_t *ctx, bson_t *cmd) { BSON_APPEND_UTF8 (cmd, "foo", "collection"); return future_collection_read_command_with_opts ( - ctx->collection, - tmp_bson ("{'foo': 'collection'}"), - ctx->prefs, - ctx->opts, - NULL, - &ctx->error); + ctx->collection, tmp_bson ("{'foo': 'collection'}"), ctx->prefs, ctx->opts, NULL, &ctx->error); } @@ -449,12 +403,7 @@ collection_read_write_cmd (func_ctx_t *ctx, bson_t *cmd) { BSON_APPEND_UTF8 (cmd, "foo", "collection"); return future_collection_read_write_command_with_opts ( - ctx->collection, - tmp_bson ("{'foo': 'collection'}"), - NULL, - ctx->opts, - NULL, - &ctx->error); + ctx->collection, tmp_bson ("{'foo': 'collection'}"), NULL, ctx->opts, NULL, &ctx->error); } @@ -463,11 +412,7 @@ collection_write_cmd (func_ctx_t *ctx, bson_t *cmd) { BSON_APPEND_UTF8 (cmd, "foo", "collection"); return future_collection_write_command_with_opts ( - ctx->collection, - tmp_bson ("{'foo': 'collection'}"), - ctx->opts, - NULL, - &ctx->error); + ctx->collection, tmp_bson ("{'foo': 'collection'}"), ctx->opts, NULL, &ctx->error); } @@ -483,14 +428,8 @@ static future_t * count (func_ctx_t *ctx, bson_t *cmd) { BSON_APPEND_UTF8 (cmd, "count", "collection"); - return future_collection_count_with_opts (ctx->collection, - MONGOC_QUERY_NONE, - NULL, - 0, - 0, - ctx->opts, - ctx->prefs, - &ctx->error); + return future_collection_count_with_opts ( + ctx->collection, MONGOC_QUERY_NONE, NULL, 0, 0, ctx->opts, ctx->prefs, &ctx->error); } @@ -498,12 +437,8 @@ static future_t * count_documents (func_ctx_t *ctx, bson_t *cmd) { BSON_APPEND_UTF8 (cmd, "aggregate", "collection"); - return future_collection_count_documents (ctx->collection, - tmp_bson ("{}"), - ctx->opts, - ctx->prefs, - NULL, - &ctx->error); + return future_collection_count_documents ( + ctx->collection, tmp_bson ("{}"), ctx->opts, ctx->prefs, NULL, &ctx->error); } @@ -520,8 +455,7 @@ static future_t * drop_index (func_ctx_t *ctx, bson_t *cmd) { BSON_APPEND_UTF8 (cmd, "dropIndexes", "collection"); - return future_collection_drop_index_with_opts ( - ctx->collection, "index name", ctx->opts, &ctx->error); + return future_collection_drop_index_with_opts (ctx->collection, "index name", ctx->opts, &ctx->error); } @@ -529,8 +463,7 @@ static future_t * estimated_document_count (func_ctx_t *ctx, bson_t *cmd) { BSON_APPEND_UTF8 (cmd, "count", "collection"); - return future_collection_estimated_document_count ( - ctx->collection, ctx->opts, ctx->prefs, NULL, &ctx->error); + return future_collection_estimated_document_count (ctx->collection, ctx->opts, ctx->prefs, NULL, &ctx->error); } @@ -538,8 +471,7 @@ static future_t * find (func_ctx_t *ctx, bson_t *cmd) { BSON_APPEND_UTF8 (cmd, "find", "collection"); - ctx->cursor = mongoc_collection_find_with_opts ( - ctx->collection, tmp_bson ("{}"), ctx->opts, ctx->prefs); + ctx->cursor = mongoc_collection_find_with_opts (ctx->collection, tmp_bson ("{}"), ctx->opts, ctx->prefs); /* use ctx->data as the bson_t** out-param to mongoc_cursor_next () */ return future_cursor_next (ctx->cursor, (const bson_t **) &ctx->data); @@ -566,8 +498,7 @@ find_and_modify (func_ctx_t *ctx, bson_t *cmd) ctx->data = fam; ctx->destructor = find_and_modify_cleanup; - return future_collection_find_and_modify_with_opts ( - ctx->collection, tmp_bson ("{}"), fam, NULL, &ctx->error); + return future_collection_find_and_modify_with_opts (ctx->collection, tmp_bson ("{}"), fam, NULL, &ctx->error); } @@ -582,8 +513,7 @@ delete_many (func_ctx_t *ctx, bson_t *cmd) { BSON_APPEND_UTF8 (cmd, "delete", "collection"); BSON_ASSERT (!ctx->prefs); - return future_collection_delete_many ( - ctx->collection, tmp_bson ("{}"), ctx->opts, NULL, &ctx->error); + return future_collection_delete_many (ctx->collection, tmp_bson ("{}"), ctx->opts, NULL, &ctx->error); } @@ -592,8 +522,7 @@ delete_one (func_ctx_t *ctx, bson_t *cmd) { BSON_APPEND_UTF8 (cmd, "delete", "collection"); BSON_ASSERT (!ctx->prefs); - return future_collection_delete_one ( - ctx->collection, tmp_bson ("{}"), ctx->opts, NULL, &ctx->error); + return future_collection_delete_one (ctx->collection, tmp_bson ("{}"), ctx->opts, NULL, &ctx->error); } @@ -604,12 +533,8 @@ insert_many (func_ctx_t *ctx, bson_t *cmd) BSON_ASSERT (!ctx->prefs); /* the "array" of input documents must be a valid pointer, stage it here */ ctx->data = tmp_bson ("{}"); - return future_collection_insert_many (ctx->collection, - (const bson_t **) &ctx->data, - 1, - ctx->opts, - NULL, - &ctx->error); + return future_collection_insert_many ( + ctx->collection, (const bson_t **) &ctx->data, 1, ctx->opts, NULL, &ctx->error); } @@ -618,8 +543,7 @@ insert_one (func_ctx_t *ctx, bson_t *cmd) { BSON_APPEND_UTF8 (cmd, "insert", "collection"); BSON_ASSERT (!ctx->prefs); - return future_collection_insert_one ( - ctx->collection, tmp_bson ("{}"), ctx->opts, NULL, &ctx->error); + return future_collection_insert_one (ctx->collection, tmp_bson ("{}"), ctx->opts, NULL, &ctx->error); } @@ -628,12 +552,8 @@ replace_one (func_ctx_t *ctx, bson_t *cmd) { BSON_APPEND_UTF8 (cmd, "update", "collection"); BSON_ASSERT (!ctx->prefs); - return future_collection_replace_one (ctx->collection, - tmp_bson ("{}"), - tmp_bson ("{}"), - ctx->opts, - NULL, - &ctx->error); + return future_collection_replace_one ( + ctx->collection, tmp_bson ("{}"), tmp_bson ("{}"), ctx->opts, NULL, &ctx->error); } @@ -642,12 +562,8 @@ update_many (func_ctx_t *ctx, bson_t *cmd) { BSON_APPEND_UTF8 (cmd, "update", "collection"); BSON_ASSERT (!ctx->prefs); - return future_collection_update_many (ctx->collection, - tmp_bson ("{}"), - tmp_bson ("{}"), - ctx->opts, - NULL, - &ctx->error); + return future_collection_update_many ( + ctx->collection, tmp_bson ("{}"), tmp_bson ("{}"), ctx->opts, NULL, &ctx->error); } @@ -656,12 +572,8 @@ update_one (func_ctx_t *ctx, bson_t *cmd) { BSON_APPEND_UTF8 (cmd, "update", "collection"); BSON_ASSERT (!ctx->prefs); - return future_collection_update_one (ctx->collection, - tmp_bson ("{}"), - tmp_bson ("{}"), - ctx->opts, - NULL, - &ctx->error); + return future_collection_update_one ( + ctx->collection, tmp_bson ("{}"), tmp_bson ("{}"), ctx->opts, NULL, &ctx->error); } @@ -685,8 +597,7 @@ bulk_exec (func_ctx_t *ctx, bson_t *cmd) bson_error_t error; bool r; - bulk = mongoc_collection_create_bulk_operation_with_opts (ctx->collection, - ctx->opts); + bulk = mongoc_collection_create_bulk_operation_with_opts (ctx->collection, ctx->opts); ctx->data = bulk; ctx->destructor = bulk_operation_cleanup; @@ -702,62 +613,46 @@ static bool bulk_insert (mongoc_bulk_operation_t *bulk, bson_error_t *error, bson_t *cmd) { BSON_APPEND_UTF8 (cmd, "insert", "collection"); - return mongoc_bulk_operation_insert_with_opts ( - bulk, tmp_bson ("{}"), NULL, error); + return mongoc_bulk_operation_insert_with_opts (bulk, tmp_bson ("{}"), NULL, error); } static bool -bulk_remove_many (mongoc_bulk_operation_t *bulk, - bson_error_t *error, - bson_t *cmd) +bulk_remove_many (mongoc_bulk_operation_t *bulk, bson_error_t *error, bson_t *cmd) { BSON_APPEND_UTF8 (cmd, "delete", "collection"); - return mongoc_bulk_operation_remove_many_with_opts ( - bulk, tmp_bson ("{}"), NULL, error); + return mongoc_bulk_operation_remove_many_with_opts (bulk, tmp_bson ("{}"), NULL, error); } static bool -bulk_remove_one (mongoc_bulk_operation_t *bulk, - bson_error_t *error, - bson_t *cmd) +bulk_remove_one (mongoc_bulk_operation_t *bulk, bson_error_t *error, bson_t *cmd) { BSON_APPEND_UTF8 (cmd, "delete", "collection"); - return mongoc_bulk_operation_remove_one_with_opts ( - bulk, tmp_bson ("{}"), NULL, error); + return mongoc_bulk_operation_remove_one_with_opts (bulk, tmp_bson ("{}"), NULL, error); } static bool -bulk_replace_one (mongoc_bulk_operation_t *bulk, - bson_error_t *error, - bson_t *cmd) +bulk_replace_one (mongoc_bulk_operation_t *bulk, bson_error_t *error, bson_t *cmd) { BSON_APPEND_UTF8 (cmd, "update", "collection"); - return mongoc_bulk_operation_replace_one_with_opts ( - bulk, tmp_bson ("{}"), tmp_bson ("{}"), NULL, error); + return mongoc_bulk_operation_replace_one_with_opts (bulk, tmp_bson ("{}"), tmp_bson ("{}"), NULL, error); } static bool -bulk_update_many (mongoc_bulk_operation_t *bulk, - bson_error_t *error, - bson_t *cmd) +bulk_update_many (mongoc_bulk_operation_t *bulk, bson_error_t *error, bson_t *cmd) { BSON_APPEND_UTF8 (cmd, "update", "collection"); - return mongoc_bulk_operation_update_many_with_opts ( - bulk, tmp_bson ("{}"), tmp_bson ("{}"), NULL, error); + return mongoc_bulk_operation_update_many_with_opts (bulk, tmp_bson ("{}"), tmp_bson ("{}"), NULL, error); } static bool -bulk_update_one (mongoc_bulk_operation_t *bulk, - bson_error_t *error, - bson_t *cmd) +bulk_update_one (mongoc_bulk_operation_t *bulk, bson_error_t *error, bson_t *cmd) { BSON_APPEND_UTF8 (cmd, "update", "collection"); - return mongoc_bulk_operation_update_one_with_opts ( - bulk, tmp_bson ("{}"), tmp_bson ("{}"), NULL, error); + return mongoc_bulk_operation_update_one_with_opts (bulk, tmp_bson ("{}"), tmp_bson ("{}"), NULL, error); } @@ -770,10 +665,8 @@ test_func_inherits_opts (void *ctx) * with a read pref set on the collection (OPT_SOURCE_COLL), with an explicit * read pref (OPT_SOURCE_FUNC), or with one read pref on the collection and * a different one passed explicitly */ - opt_source_t source_matrix[] = {OPT_SOURCE_NONE, - test->opt_source, - OPT_SOURCE_FUNC, - test->opt_source | OPT_SOURCE_FUNC}; + opt_source_t source_matrix[] = { + OPT_SOURCE_NONE, test->opt_source, OPT_SOURCE_FUNC, test->opt_source | OPT_SOURCE_FUNC}; size_t i; func_ctx_t func_ctx; @@ -829,8 +722,7 @@ test_func_inherits_opts (void *ctx) set_func_opt (&opts, &func_prefs, test->opt_type); } - func_ctx_init ( - &func_ctx, test, client, db, collection, func_prefs, &opts); + func_ctx_init (&func_ctx, test, client, db, collection, func_prefs, &opts); /* A warning is thrown if an aggregate command with $out attempts to write * to a secondary */ @@ -867,8 +759,7 @@ test_func_inherits_opts (void *ctx) BSON_ASSERT (!future_get_bool (future)); future_destroy (future); - ASSERT_OR_PRINT (!mongoc_cursor_error (func_ctx.cursor, &error), - error); + ASSERT_OR_PRINT (!mongoc_cursor_error (func_ctx.cursor, &error), error); } else { reply_to_request_simple (request, "{'ok': 1}"); cleanup_future (future); @@ -986,9 +877,7 @@ static opt_inheritance_test_t gInheritanceTests[] = { static void -install_inheritance_tests (TestSuite *suite, - opt_inheritance_test_t *tests, - size_t n) +install_inheritance_tests (TestSuite *suite, opt_inheritance_test_t *tests, size_t n) { size_t i; opt_inheritance_test_t *test; @@ -996,15 +885,9 @@ install_inheritance_tests (TestSuite *suite, for (i = 0; i < n; i++) { test = &tests[i]; - name = bson_strdup_printf ( - "/inheritance/%s/%s", test->func_name, opt_type_name (test->opt_type)); + name = bson_strdup_printf ("/inheritance/%s/%s", test->func_name, opt_type_name (test->opt_type)); - TestSuite_AddFull (suite, - name, - test_func_inherits_opts, - NULL, - test, - TestSuite_CheckMockServerAllowed); + TestSuite_AddFull (suite, name, test_func_inherits_opts, NULL, test, TestSuite_CheckMockServerAllowed); bson_free (name); } @@ -1014,8 +897,5 @@ install_inheritance_tests (TestSuite *suite, void test_opts_install (TestSuite *suite) { - install_inheritance_tests (suite, - gInheritanceTests, - sizeof (gInheritanceTests) / - sizeof (opt_inheritance_test_t)); + install_inheritance_tests (suite, gInheritanceTests, sizeof (gInheritanceTests) / sizeof (opt_inheritance_test_t)); } diff --git a/src/libmongoc/tests/test-mongoc-primary-stepdown.c b/src/libmongoc/tests/test-mongoc-primary-stepdown.c index e078a6f196..1e40110222 100644 --- a/src/libmongoc/tests/test-mongoc-primary-stepdown.c +++ b/src/libmongoc/tests/test-mongoc-primary-stepdown.c @@ -81,13 +81,11 @@ _connection_count (mongoc_client_t *client, uint32_t server_id) BSON_APPEND_INT32 (&cmd, "serverStatus", 1); - res = mongoc_client_command_simple_with_server_id ( - client, "admin", &cmd, NULL, server_id, &reply, &error); + res = mongoc_client_command_simple_with_server_id (client, "admin", &cmd, NULL, server_id, &reply, &error); ASSERT_OR_PRINT (res, error); ASSERT (bson_iter_init (&iter, &reply)); - ASSERT ( - bson_iter_find_descendant (&iter, "connections.totalCreated", &child)); + ASSERT (bson_iter_find_descendant (&iter, "connections.totalCreated", &child)); conns = bson_iter_int32 (&child); bson_destroy (&cmd); @@ -160,13 +158,12 @@ test_getmore_iteration (mongoc_client_t *client) /* Store the primary ID. After step down, the primary may be a different * server. We must execute serverStatus against the same server to check * connection counts. */ - primary_id = - mongoc_topology_select_server_id (client->topology, - MONGOC_SS_WRITE, - NULL /* read prefs */, - NULL /* chosen read mode */, - NULL /* deprioritized servers */, - &error); + primary_id = mongoc_topology_select_server_id (client->topology, + MONGOC_SS_WRITE, + NULL /* read prefs */, + NULL /* chosen read mode */, + NULL /* deprioritized servers */, + &error); ASSERT_OR_PRINT (primary_id, error); conn_count = _connection_count (client, primary_id); @@ -181,20 +178,14 @@ test_getmore_iteration (mongoc_client_t *client) } /* Retrieve the first batch of 2 documents */ - cursor = - mongoc_collection_find_with_opts (coll, tmp_bson ("{}"), NULL, NULL); + cursor = mongoc_collection_find_with_opts (coll, tmp_bson ("{}"), NULL, NULL); ASSERT (cursor); ASSERT (mongoc_cursor_next (cursor, &doc)); ASSERT (mongoc_cursor_next (cursor, &doc)); /* Send a stepdown to the primary, ensure it succeeds */ - res = mongoc_database_command_simple ( - db, - tmp_bson ("{ 'replSetStepDown': 5, 'force': true}"), - NULL, - NULL, - &error); + res = mongoc_database_command_simple (db, tmp_bson ("{ 'replSetStepDown': 5, 'force': true}"), NULL, NULL, &error); ASSERT_OR_PRINT (res, error); /* Retrieve the next results from the cursor, @@ -243,23 +234,21 @@ test_not_primary_keep_pool (mongoc_client_t *client) /* Store the primary ID. After step down, the primary may be a different * server. We must execute serverStatus against the same server to check * connection counts. */ - primary_id = - mongoc_topology_select_server_id (client->topology, - MONGOC_SS_WRITE, - NULL /* read prefs */, - NULL /* chosen read mode */, - NULL /* deprioritized servers */, - &error); + primary_id = mongoc_topology_select_server_id (client->topology, + MONGOC_SS_WRITE, + NULL /* read prefs */, + NULL /* chosen read mode */, + NULL /* deprioritized servers */, + &error); ASSERT_OR_PRINT (primary_id, error); conn_count = _connection_count (client, primary_id); - res = mongoc_database_command_simple ( - db, - tmp_bson ("{'configureFailPoint': 'failCommand', " - "'mode': {'times': 1}, " - "'data': {'failCommands': ['insert'], 'errorCode': 10107}}"), - NULL, - NULL, - &error); + res = mongoc_database_command_simple (db, + tmp_bson ("{'configureFailPoint': 'failCommand', " + "'mode': {'times': 1}, " + "'data': {'failCommands': ['insert'], 'errorCode': 10107}}"), + NULL, + NULL, + &error); ASSERT_OR_PRINT (res, error); /* Capture logs to swallow warnings about endSessions */ @@ -268,15 +257,13 @@ test_not_primary_keep_pool (mongoc_client_t *client) coll = mongoc_client_get_collection (client, "step-down", "step-down"); /* Execute an insert, verify that it fails with 10107 */ - res = mongoc_collection_insert_one ( - coll, tmp_bson ("{'test': 1}"), NULL, NULL, &error); + res = mongoc_collection_insert_one (coll, tmp_bson ("{'test': 1}"), NULL, NULL, &error); ASSERT (!res); ASSERT_CMPINT (error.code, ==, 10107); ASSERT_CONTAINS (error.message, "failpoint"); /* Execute a second insert, verify that it succeeds */ - res = mongoc_collection_insert_one ( - coll, tmp_bson ("{'test': 1}"), NULL, NULL, &error); + res = mongoc_collection_insert_one (coll, tmp_bson ("{'test': 1}"), NULL, NULL, &error); ASSERT (res); /* Verify that the connection pool has not been cleared */ @@ -318,23 +305,21 @@ test_not_primary_reset_pool (mongoc_client_t *client) /* Store the primary ID. After step down, the primary may be a different * server. We must execute serverStatus against the same server to check * connection counts. */ - primary_id = - mongoc_topology_select_server_id (client->topology, - MONGOC_SS_WRITE, - NULL /* read prefs */, - NULL /* chosen read mode */, - NULL /* deprioritized servers */, - &error); + primary_id = mongoc_topology_select_server_id (client->topology, + MONGOC_SS_WRITE, + NULL /* read prefs */, + NULL /* chosen read mode */, + NULL /* deprioritized servers */, + &error); ASSERT_OR_PRINT (primary_id, error); conn_count = _connection_count (client, primary_id); - res = mongoc_database_command_simple ( - db, - tmp_bson ("{'configureFailPoint': 'failCommand', " - "'mode': {'times': 1}, " - "'data': {'failCommands': ['insert'], 'errorCode': 10107}}"), - read_prefs, - NULL, - &error); + res = mongoc_database_command_simple (db, + tmp_bson ("{'configureFailPoint': 'failCommand', " + "'mode': {'times': 1}, " + "'data': {'failCommands': ['insert'], 'errorCode': 10107}}"), + read_prefs, + NULL, + &error); ASSERT_OR_PRINT (res, error); /* Capture logs to swallow warnings about endSessions */ @@ -343,8 +328,7 @@ test_not_primary_reset_pool (mongoc_client_t *client) coll = mongoc_client_get_collection (client, "step-down", "step-down"); /* Execute an insert, verify that it fails with 10107 */ - res = mongoc_collection_insert_one ( - coll, tmp_bson ("{'test': 1}"), NULL, NULL, &error); + res = mongoc_collection_insert_one (coll, tmp_bson ("{'test': 1}"), NULL, NULL, &error); ASSERT (!res); ASSERT_CMPINT (error.code, ==, 10107); ASSERT_CONTAINS (error.message, "failpoint"); @@ -353,8 +337,7 @@ test_not_primary_reset_pool (mongoc_client_t *client) ASSERT_CMPINT ((conn_count + 1), ==, _connection_count (client, primary_id)); /* Execute an insert into the test collection and verify it succeeds */ - res = mongoc_collection_insert_one ( - coll, tmp_bson ("{'test': 1}"), NULL, NULL, &error); + res = mongoc_collection_insert_one (coll, tmp_bson ("{'test': 1}"), NULL, NULL, &error); ASSERT_OR_PRINT (res, error); mongoc_read_prefs_destroy (read_prefs); @@ -397,30 +380,27 @@ test_shutdown_reset_pool (mongoc_client_t *client) /* Store the primary ID. After step down, the primary may be a different * server. We must execute serverStatus against the same server to check * connection counts. */ - primary_id = - mongoc_topology_select_server_id (client->topology, - MONGOC_SS_WRITE, - NULL /* read prefs */, - NULL /* chosen read mode */, - NULL /* deprioritized servers */, - &error); + primary_id = mongoc_topology_select_server_id (client->topology, + MONGOC_SS_WRITE, + NULL /* read prefs */, + NULL /* chosen read mode */, + NULL /* deprioritized servers */, + &error); ASSERT_OR_PRINT (primary_id, error); conn_count = _connection_count (client, primary_id); - res = mongoc_database_command_simple ( - db, - tmp_bson ("{'configureFailPoint': 'failCommand', " - "'mode': {'times': 1}, " - "'data': {'failCommands': ['insert'], 'errorCode': 91}}"), - read_prefs, - NULL, - &error); + res = mongoc_database_command_simple (db, + tmp_bson ("{'configureFailPoint': 'failCommand', " + "'mode': {'times': 1}, " + "'data': {'failCommands': ['insert'], 'errorCode': 91}}"), + read_prefs, + NULL, + &error); ASSERT_OR_PRINT (res, error); coll = mongoc_client_get_collection (client, "step-down", "step-down"); /* Execute an insert, verify that it fails with 91 */ - res = mongoc_collection_insert_one ( - coll, tmp_bson ("{'test': 1}"), NULL, NULL, &error); + res = mongoc_collection_insert_one (coll, tmp_bson ("{'test': 1}"), NULL, NULL, &error); ASSERT (!res); ASSERT_CMPINT (error.code, ==, 91); ASSERT_CONTAINS (error.message, "failpoint"); @@ -429,8 +409,7 @@ test_shutdown_reset_pool (mongoc_client_t *client) ASSERT_CMPINT ((conn_count + 1), ==, _connection_count (client, primary_id)); /* Execute an insert into the test collection and verify it succeeds */ - res = mongoc_collection_insert_one ( - coll, tmp_bson ("{'test': 1}"), NULL, NULL, &error); + res = mongoc_collection_insert_one (coll, tmp_bson ("{'test': 1}"), NULL, NULL, &error); ASSERT_OR_PRINT (res, error); mongoc_read_prefs_destroy (read_prefs); @@ -470,30 +449,27 @@ test_interrupted_shutdown_reset_pool (mongoc_client_t *client) /* Store the primary ID. After step down, the primary may be a different * server. We must execute serverStatus against the same server to check * connection counts. */ - primary_id = - mongoc_topology_select_server_id (client->topology, - MONGOC_SS_WRITE, - NULL /* read prefs */, - NULL /* chosen read mode */, - NULL /* deprioritized servers */, - &error); + primary_id = mongoc_topology_select_server_id (client->topology, + MONGOC_SS_WRITE, + NULL /* read prefs */, + NULL /* chosen read mode */, + NULL /* deprioritized servers */, + &error); ASSERT_OR_PRINT (primary_id, error); conn_count = _connection_count (client, primary_id); - res = mongoc_database_command_simple ( - db, - tmp_bson ("{'configureFailPoint': 'failCommand', " - "'mode': {'times': 1}, " - "'data': {'failCommands': ['insert'], 'errorCode': 11600}}"), - read_prefs, - NULL, - &error); + res = mongoc_database_command_simple (db, + tmp_bson ("{'configureFailPoint': 'failCommand', " + "'mode': {'times': 1}, " + "'data': {'failCommands': ['insert'], 'errorCode': 11600}}"), + read_prefs, + NULL, + &error); ASSERT_OR_PRINT (res, error); coll = mongoc_client_get_collection (client, "step-down", "step-down"); /* Execute an insert, verify that it fails with 11600 */ - res = mongoc_collection_insert_one ( - coll, tmp_bson ("{'test': 1}"), NULL, NULL, &error); + res = mongoc_collection_insert_one (coll, tmp_bson ("{'test': 1}"), NULL, NULL, &error); ASSERT (!res); ASSERT_CMPINT (error.code, ==, 11600); ASSERT_CONTAINS (error.message, "failpoint"); @@ -502,8 +478,7 @@ test_interrupted_shutdown_reset_pool (mongoc_client_t *client) ASSERT_CMPINT ((conn_count + 1), ==, _connection_count (client, primary_id)); /* Execute an insert into the test collection and verify it succeeds */ - res = mongoc_collection_insert_one ( - coll, tmp_bson ("{'test': 1}"), NULL, NULL, &error); + res = mongoc_collection_insert_one (coll, tmp_bson ("{'test': 1}"), NULL, NULL, &error); ASSERT_OR_PRINT (res, error); mongoc_read_prefs_destroy (read_prefs); @@ -521,8 +496,7 @@ test_interrupted_shutdown_reset_pool_runner (void *ctx_void) return; } - _run_test_single_or_pooled (test_interrupted_shutdown_reset_pool, - ctx->use_pooled); + _run_test_single_or_pooled (test_interrupted_shutdown_reset_pool, ctx->use_pooled); } void @@ -551,12 +525,8 @@ test_primary_stepdown_install (TestSuite *suite) (void) 0 TestPooledAndSingle ("/Stepdown/getmore", test_getmore_iteration_runner); - TestPooledAndSingle ("/Stepdown/not_primary_keep", - test_not_primary_keep_pool_runner); - TestPooledAndSingle ("/Stepdown/not_primary_reset", - test_not_primary_reset_pool_runner); - TestPooledAndSingle ("/Stepdown/shutdown_reset_pool", - test_shutdown_reset_pool_runner); - TestPooledAndSingle ("/Stepdown/interrupt_shutdown", - test_interrupted_shutdown_reset_pool_runner); + TestPooledAndSingle ("/Stepdown/not_primary_keep", test_not_primary_keep_pool_runner); + TestPooledAndSingle ("/Stepdown/not_primary_reset", test_not_primary_reset_pool_runner); + TestPooledAndSingle ("/Stepdown/shutdown_reset_pool", test_shutdown_reset_pool_runner); + TestPooledAndSingle ("/Stepdown/interrupt_shutdown", test_interrupted_shutdown_reset_pool_runner); } diff --git a/src/libmongoc/tests/test-mongoc-read-concern.c b/src/libmongoc/tests/test-mongoc-read-concern.c index bd00985cb0..0d3753ce88 100644 --- a/src/libmongoc/tests/test-mongoc-read-concern.c +++ b/src/libmongoc/tests/test-mongoc-read-concern.c @@ -51,17 +51,14 @@ test_read_concern_basic (void) /* * Test changes to level. */ - mongoc_read_concern_set_level (read_concern, - MONGOC_READ_CONCERN_LEVEL_LOCAL); + mongoc_read_concern_set_level (read_concern, MONGOC_READ_CONCERN_LEVEL_LOCAL); ASSERT (!mongoc_read_concern_is_default (read_concern)); - ASSERT_CMPSTR (mongoc_read_concern_get_level (read_concern), - MONGOC_READ_CONCERN_LEVEL_LOCAL); + ASSERT_CMPSTR (mongoc_read_concern_get_level (read_concern), MONGOC_READ_CONCERN_LEVEL_LOCAL); /* * Check generated bson. */ - ASSERT_MATCH (_mongoc_read_concern_get_bson (read_concern), - "{'level': 'local'}"); + ASSERT_MATCH (_mongoc_read_concern_get_bson (read_concern), "{'level': 'local'}"); mongoc_read_concern_destroy (read_concern); } @@ -98,20 +95,14 @@ test_read_concern_always_mutable (void) ASSERT (read_concern); - mongoc_read_concern_set_level (read_concern, - MONGOC_READ_CONCERN_LEVEL_LOCAL); - ASSERT_MATCH (_mongoc_read_concern_get_bson (read_concern), - "{'level': 'local'}"); + mongoc_read_concern_set_level (read_concern, MONGOC_READ_CONCERN_LEVEL_LOCAL); + ASSERT_MATCH (_mongoc_read_concern_get_bson (read_concern), "{'level': 'local'}"); - mongoc_read_concern_set_level (read_concern, - MONGOC_READ_CONCERN_LEVEL_MAJORITY); - ASSERT_MATCH (_mongoc_read_concern_get_bson (read_concern), - "{'level': 'majority'}"); + mongoc_read_concern_set_level (read_concern, MONGOC_READ_CONCERN_LEVEL_MAJORITY); + ASSERT_MATCH (_mongoc_read_concern_get_bson (read_concern), "{'level': 'majority'}"); - mongoc_read_concern_set_level (read_concern, - MONGOC_READ_CONCERN_LEVEL_LINEARIZABLE); - ASSERT_MATCH (_mongoc_read_concern_get_bson (read_concern), - "{'level': 'linearizable'}"); + mongoc_read_concern_set_level (read_concern, MONGOC_READ_CONCERN_LEVEL_LINEARIZABLE); + ASSERT_MATCH (_mongoc_read_concern_get_bson (read_concern), "{'level': 'linearizable'}"); mongoc_read_concern_destroy (read_concern); } @@ -136,8 +127,7 @@ _test_read_concern_wire_version (bool explicit) server = mock_server_with_auto_hello (WIRE_VERSION_MIN); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); collection = mongoc_client_get_collection (client, "db", "collection"); if (explicit) { @@ -150,16 +140,12 @@ _test_read_concern_wire_version (bool explicit) /* * aggregate */ - cursor = mongoc_collection_aggregate ( - collection, MONGOC_QUERY_NONE, tmp_bson (NULL), &opts, NULL); + cursor = mongoc_collection_aggregate (collection, MONGOC_QUERY_NONE, tmp_bson (NULL), &opts, NULL); future = future_cursor_next (cursor, &doc); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db', 'readConcern': {'level': 'foo'}}")); - reply_to_request_simple (request, - "{'ok': 1, 'cursor': {'id': 0, 'firstBatch': []}}"); + request = + mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', 'readConcern': {'level': 'foo'}}")); + reply_to_request_simple (request, "{'ok': 1, 'cursor': {'id': 0, 'firstBatch': []}}"); request_destroy (request); BSON_ASSERT (future_wait (future)); ASSERT_OR_PRINT (!mongoc_cursor_error (cursor, &error), error); @@ -169,12 +155,9 @@ _test_read_concern_wire_version (bool explicit) /* * generic mongoc_client_write_command_with_opts */ - future = future_client_read_command_with_opts ( - client, "db", tmp_bson ("{'foo': 1}"), NULL, &opts, NULL, &error); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db', 'readConcern': {'level': 'foo'}}")); + future = future_client_read_command_with_opts (client, "db", tmp_bson ("{'foo': 1}"), NULL, &opts, NULL, &error); + request = + mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', 'readConcern': {'level': 'foo'}}")); reply_to_request_with_ok_and_destroy (request); BSON_ASSERT (future_get_bool (future)); @@ -183,18 +166,10 @@ _test_read_concern_wire_version (bool explicit) /* * count */ - future = future_collection_count_with_opts (collection, - MONGOC_QUERY_NONE, - tmp_bson ("{}"), - 0, - 0, - &opts, - NULL, - &error); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db', 'readConcern': {'level': 'foo'}}")); + future = + future_collection_count_with_opts (collection, MONGOC_QUERY_NONE, tmp_bson ("{}"), 0, 0, &opts, NULL, &error); + request = + mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', 'readConcern': {'level': 'foo'}}")); reply_to_request_simple (request, "{'ok': 1, 'n': 1}"); request_destroy (request); ASSERT_CMPINT64 (future_get_int64_t (future), ==, (int64_t) 1); @@ -228,13 +203,8 @@ test_read_concern_install (TestSuite *suite) { TestSuite_Add (suite, "/ReadConcern/append", test_read_concern_append); TestSuite_Add (suite, "/ReadConcern/basic", test_read_concern_basic); - TestSuite_Add (suite, - "/ReadConcern/bson_omits_defaults", - test_read_concern_bson_omits_defaults); - TestSuite_Add ( - suite, "/ReadConcern/always_mutable", test_read_concern_always_mutable); - TestSuite_AddMockServerTest ( - suite, "/ReadConcern/inherited", test_inherited_read_concern); - TestSuite_AddMockServerTest ( - suite, "/ReadConcern/explicit", test_explicit_read_concern); + TestSuite_Add (suite, "/ReadConcern/bson_omits_defaults", test_read_concern_bson_omits_defaults); + TestSuite_Add (suite, "/ReadConcern/always_mutable", test_read_concern_always_mutable); + TestSuite_AddMockServerTest (suite, "/ReadConcern/inherited", test_inherited_read_concern); + TestSuite_AddMockServerTest (suite, "/ReadConcern/explicit", test_explicit_read_concern); } diff --git a/src/libmongoc/tests/test-mongoc-read-prefs.c b/src/libmongoc/tests/test-mongoc-read-prefs.c index 5e8c9713a6..555558982d 100644 --- a/src/libmongoc/tests/test-mongoc-read-prefs.c +++ b/src/libmongoc/tests/test-mongoc-read-prefs.c @@ -34,14 +34,7 @@ _test_op_msg (const mongoc_uri_t *uri, client = test_framework_client_new_from_uri (uri, NULL); collection = mongoc_client_get_collection (client, "test", "test"); - cursor = mongoc_collection_find (collection, - MONGOC_QUERY_NONE, - 0, - 1, - 0, - tmp_bson (query_or_cmd), - NULL, - read_prefs); + cursor = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 1, 0, tmp_bson (query_or_cmd), NULL, read_prefs); future = future_cursor_next (cursor, &doc); request = mock_server_receives_msg (server, 0, tmp_bson (expected_find)); @@ -83,19 +76,11 @@ _test_command (const mongoc_uri_t *uri, collection = mongoc_client_get_collection (client, "test", "test"); mongoc_collection_set_read_prefs (collection, read_prefs); - cursor = mongoc_collection_command (collection, - MONGOC_QUERY_NONE, - 0, - 1, - 0, - tmp_bson (command), - NULL, - read_prefs); + cursor = mongoc_collection_command (collection, MONGOC_QUERY_NONE, 0, 1, 0, tmp_bson (command), NULL, read_prefs); future = future_cursor_next (cursor, &doc); - request = mock_server_receives_msg ( - server, MONGOC_MSG_NONE, tmp_bson (expected_cmd)); + request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson (expected_cmd)); reply_to_request (request, MONGOC_REPLY_NONE, /* flags */ @@ -131,11 +116,9 @@ _test_command_simple (const mongoc_uri_t *uri, collection = mongoc_client_get_collection (client, "test", "test"); mongoc_collection_set_read_prefs (collection, read_prefs); - future = future_client_command_simple ( - client, "test", tmp_bson (command), read_prefs, NULL, NULL); + future = future_client_command_simple (client, "test", tmp_bson (command), read_prefs, NULL, NULL); - request = mock_server_receives_msg ( - server, MONGOC_MSG_NONE, tmp_bson (expected_cmd)); + request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson (expected_cmd)); reply_to_request (request, MONGOC_REPLY_NONE, /* flags */ @@ -261,8 +244,7 @@ _test_read_prefs_op_msg (read_pref_test_type_t test_type, if (_can_be_command (query_or_cmd)) { _test_command (uri, server, query_or_cmd, read_prefs, expected_cmd); - _test_command_simple ( - uri, server, query_or_cmd, read_prefs, expected_cmd); + _test_command_simple (uri, server, query_or_cmd, read_prefs, expected_cmd); } _test_op_msg (uri, server, query_or_cmd, read_prefs, expected_find); @@ -279,8 +261,7 @@ _test_read_prefs (read_pref_test_type_t test_type, const char *expected_cmd, const char *expected_find) { - _test_read_prefs_op_msg ( - test_type, read_prefs, query_or_cmd, expected_cmd, expected_find); + _test_read_prefs_op_msg (test_type, read_prefs, query_or_cmd, expected_cmd, expected_find); } @@ -395,17 +376,10 @@ test_read_prefs_primary_rsprimary (void) read_prefs = mongoc_read_prefs_new (MONGOC_READ_PRIMARY); - _test_read_prefs (READ_PREF_TEST_PRIMARY, - read_prefs, - "{}", - "{}", - "{'find': 'test', 'filter': {}}"); + _test_read_prefs (READ_PREF_TEST_PRIMARY, read_prefs, "{}", "{}", "{'find': 'test', 'filter': {}}"); - _test_read_prefs (READ_PREF_TEST_PRIMARY, - read_prefs, - "{'a': 1}", - "{'a': 1}", - "{'find': 'test', 'filter': {'a': 1}}"); + _test_read_prefs ( + READ_PREF_TEST_PRIMARY, read_prefs, "{'a': 1}", "{'a': 1}", "{'find': 'test', 'filter': {'a': 1}}"); mongoc_read_prefs_destroy (read_prefs); } @@ -418,17 +392,10 @@ test_read_prefs_secondary_rssecondary (void) read_prefs = mongoc_read_prefs_new (MONGOC_READ_SECONDARY); - _test_read_prefs (READ_PREF_TEST_SECONDARY, - read_prefs, - "{}", - "{}", - "{'find': 'test', 'filter': {}}"); + _test_read_prefs (READ_PREF_TEST_SECONDARY, read_prefs, "{}", "{}", "{'find': 'test', 'filter': {}}"); - _test_read_prefs (READ_PREF_TEST_SECONDARY, - read_prefs, - "{'a': 1}", - "{'a': 1}", - "{'find': 'test', 'filter': {'a': 1}}"); + _test_read_prefs ( + READ_PREF_TEST_SECONDARY, read_prefs, "{'a': 1}", "{'a': 1}", "{'find': 'test', 'filter': {'a': 1}}"); mongoc_read_prefs_destroy (read_prefs); } @@ -438,17 +405,9 @@ test_read_prefs_secondary_rssecondary (void) static void test_read_prefs_mongos_null (void) { - _test_read_prefs (READ_PREF_TEST_MONGOS, - NULL, - "{}", - "{}", - "{'find': 'test', 'filter': {}}"); - - _test_read_prefs (READ_PREF_TEST_MONGOS, - NULL, - "{'a': 1}", - "{'a': 1}", - "{'find': 'test', 'filter': {}}"); + _test_read_prefs (READ_PREF_TEST_MONGOS, NULL, "{}", "{}", "{'find': 'test', 'filter': {}}"); + + _test_read_prefs (READ_PREF_TEST_MONGOS, NULL, "{'a': 1}", "{'a': 1}", "{'find': 'test', 'filter': {}}"); } @@ -459,17 +418,10 @@ test_read_prefs_mongos_primary (void) read_prefs = mongoc_read_prefs_new (MONGOC_READ_PRIMARY); - _test_read_prefs (READ_PREF_TEST_MONGOS, - read_prefs, - "{}", - "{}", - "{'find': 'test', 'filter': {}}"); + _test_read_prefs (READ_PREF_TEST_MONGOS, read_prefs, "{}", "{}", "{'find': 'test', 'filter': {}}"); - _test_read_prefs (READ_PREF_TEST_MONGOS, - read_prefs, - "{'a': 1}", - "{'a': 1}", - "{'find': 'test', 'filter': {'a': 1}}"); + _test_read_prefs ( + READ_PREF_TEST_MONGOS, read_prefs, "{'a': 1}", "{'a': 1}", "{'find': 'test', 'filter': {'a': 1}}"); mongoc_read_prefs_destroy (read_prefs); } @@ -482,29 +434,26 @@ test_read_prefs_mongos_secondary (void) read_prefs = mongoc_read_prefs_new (MONGOC_READ_SECONDARY); - _test_read_prefs_op_msg ( - READ_PREF_TEST_MONGOS, - read_prefs, - "{}", - "{'find': 'test','$readPreference': {'mode': 'secondary'}}", - "{'find': 'test', 'filter': {}," - " '$readPreference': {'mode': 'secondary'}}"); - - _test_read_prefs_op_msg ( - READ_PREF_TEST_MONGOS, - read_prefs, - "{'a': 1}", - "{'a': 1, '$readPreference': {'mode': 'secondary'}}", - "{'find': 'test', 'filter': {'a': 1}," - " '$readPreference': {'mode': 'secondary'}}"); - - _test_read_prefs_op_msg ( - READ_PREF_TEST_MONGOS, - read_prefs, - "{'$query': {'a': 1}}", - "{'$query': {'a': 1}, '$readPreference': {'mode': 'secondary'}}", - "{'find': 'test', 'filter': {'a': 1}," - " '$readPreference': {'mode': 'secondary'}}"); + _test_read_prefs_op_msg (READ_PREF_TEST_MONGOS, + read_prefs, + "{}", + "{'find': 'test','$readPreference': {'mode': 'secondary'}}", + "{'find': 'test', 'filter': {}," + " '$readPreference': {'mode': 'secondary'}}"); + + _test_read_prefs_op_msg (READ_PREF_TEST_MONGOS, + read_prefs, + "{'a': 1}", + "{'a': 1, '$readPreference': {'mode': 'secondary'}}", + "{'find': 'test', 'filter': {'a': 1}," + " '$readPreference': {'mode': 'secondary'}}"); + + _test_read_prefs_op_msg (READ_PREF_TEST_MONGOS, + read_prefs, + "{'$query': {'a': 1}}", + "{'$query': {'a': 1}, '$readPreference': {'mode': 'secondary'}}", + "{'find': 'test', 'filter': {'a': 1}," + " '$readPreference': {'mode': 'secondary'}}"); mongoc_read_prefs_destroy (read_prefs); } @@ -518,17 +467,10 @@ test_read_prefs_mongos_secondary_preferred (void) read_prefs = mongoc_read_prefs_new (MONGOC_READ_SECONDARY_PREFERRED); /* $readPreference not sent, only secondaryOk */ - _test_read_prefs (READ_PREF_TEST_MONGOS, - read_prefs, - "{}", - "{}", - "{'find': 'test', 'filter': {}}"); - - _test_read_prefs (READ_PREF_TEST_MONGOS, - read_prefs, - "{'a': 1}", - "{'a': 1}", - "{'find': 'test', 'filter': {'a': 1}}"); + _test_read_prefs (READ_PREF_TEST_MONGOS, read_prefs, "{}", "{}", "{'find': 'test', 'filter': {}}"); + + _test_read_prefs ( + READ_PREF_TEST_MONGOS, read_prefs, "{'a': 1}", "{'a': 1}", "{'find': 'test', 'filter': {'a': 1}}"); mongoc_read_prefs_destroy (read_prefs); } @@ -546,26 +488,24 @@ test_read_prefs_mongos_tags (void) mongoc_read_prefs_add_tag (read_prefs, &b); mongoc_read_prefs_add_tag (read_prefs, NULL); - _test_read_prefs_op_msg ( - READ_PREF_TEST_MONGOS, - read_prefs, - "{}", - "{'$query': {}, '$readPreference': {'mode': 'secondaryPreferred'," - " 'tags': [{'dc': 'ny'}, {}]}}", - "{'find': 'test', 'filter': {}," - " '$readPreference': {'mode': 'secondaryPreferred'," - " 'tags': [{'dc': 'ny'}, {}]}}"); - - _test_read_prefs_op_msg ( - READ_PREF_TEST_MONGOS, - read_prefs, - "{'a': 1}", - "{'a': 1," - " '$readPreference': {'mode': 'secondaryPreferred'," - " 'tags': [{'dc': 'ny'}, {}]}}", - "{'find': 'test', 'filter': {}," - " '$readPreference': {'mode': 'secondaryPreferred'," - " 'tags': [{'dc': 'ny'}, {}]}}"); + _test_read_prefs_op_msg (READ_PREF_TEST_MONGOS, + read_prefs, + "{}", + "{'$query': {}, '$readPreference': {'mode': 'secondaryPreferred'," + " 'tags': [{'dc': 'ny'}, {}]}}", + "{'find': 'test', 'filter': {}," + " '$readPreference': {'mode': 'secondaryPreferred'," + " 'tags': [{'dc': 'ny'}, {}]}}"); + + _test_read_prefs_op_msg (READ_PREF_TEST_MONGOS, + read_prefs, + "{'a': 1}", + "{'a': 1," + " '$readPreference': {'mode': 'secondaryPreferred'," + " 'tags': [{'dc': 'ny'}, {}]}}", + "{'find': 'test', 'filter': {}," + " '$readPreference': {'mode': 'secondaryPreferred'," + " 'tags': [{'dc': 'ny'}, {}]}}"); mongoc_read_prefs_destroy (read_prefs); bson_destroy (&b); @@ -588,8 +528,7 @@ test_read_prefs_mongos_max_staleness (void) server = mock_mongos_new (WIRE_VERSION_MIN); mock_server_run (server); mock_server_auto_endsessions (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); collection = mongoc_client_get_collection (client, "test", "test"); prefs = mongoc_read_prefs_new (MONGOC_READ_SECONDARY_PREFERRED); @@ -597,27 +536,19 @@ test_read_prefs_mongos_max_staleness (void) /* exhaust cursor is required per CDRIVER-3633 so the driver downgrades the * OP_QUERY find command to an OP_QUERY legacy find */ - cursor = mongoc_collection_find_with_opts ( - collection, tmp_bson ("{'a': 1}"), tmp_bson ("{'exhaust': true}"), prefs); + cursor = mongoc_collection_find_with_opts (collection, tmp_bson ("{'a': 1}"), tmp_bson ("{'exhaust': true}"), prefs); future = future_cursor_next (cursor, &doc); - request = mock_server_receives_query ( - server, - "test.test", - MONGOC_QUERY_EXHAUST | MONGOC_QUERY_SECONDARY_OK, - 0, - 0, - "{'$query': {'a': 1}," - " '$readPreference': {'mode': 'secondaryPreferred'," - " 'maxStalenessSeconds': 120}}", - "{}"); - - reply_to_find_request (request, - MONGOC_QUERY_EXHAUST | MONGOC_QUERY_SECONDARY_OK, - 0, - 1, - "test.test", - "{}", - false); + request = mock_server_receives_query (server, + "test.test", + MONGOC_QUERY_EXHAUST | MONGOC_QUERY_SECONDARY_OK, + 0, + 0, + "{'$query': {'a': 1}," + " '$readPreference': {'mode': 'secondaryPreferred'," + " 'maxStalenessSeconds': 120}}", + "{}"); + + reply_to_find_request (request, MONGOC_QUERY_EXHAUST | MONGOC_QUERY_SECONDARY_OK, 0, 1, "test.test", "{}", false); /* mongoc_cursor_next returned true */ BSON_ASSERT (future_get_bool (future)); @@ -647,8 +578,7 @@ test_read_prefs_mongos_hedged_reads (void) server = mock_mongos_new (WIRE_VERSION_HEDGED_READS); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); collection = mongoc_client_get_collection (client, "test", "test"); prefs = mongoc_read_prefs_new (MONGOC_READ_SECONDARY_PREFERRED); @@ -656,16 +586,14 @@ test_read_prefs_mongos_hedged_reads (void) mongoc_read_prefs_set_hedge (prefs, &hedge_doc); - cursor = mongoc_collection_find_with_opts ( - collection, tmp_bson ("{'a': 1}"), tmp_bson ("{'exhaust': true}"), prefs); + cursor = mongoc_collection_find_with_opts (collection, tmp_bson ("{'a': 1}"), tmp_bson ("{'exhaust': true}"), prefs); future = future_cursor_next (cursor, &doc); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_EXHAUST_ALLOWED, - tmp_bson ("{'find': 'test'," - " 'filter': {'a': {'$numberInt': '1'}}," - " '$readPreference': {'mode': 'secondaryPreferred'," - " 'hedge': {'enabled': true}}}")); + request = mock_server_receives_msg (server, + MONGOC_MSG_EXHAUST_ALLOWED, + tmp_bson ("{'find': 'test'," + " 'filter': {'a': {'$numberInt': '1'}}," + " '$readPreference': {'mode': 'secondaryPreferred'," + " 'hedge': {'enabled': true}}}")); reply_to_request_simple (request, "{'ok': 1," " 'cursor': {" @@ -703,26 +631,21 @@ test_mongos_read_concern (void) server = mock_mongos_new (WIRE_VERSION_MIN); mock_server_run (server); mock_server_auto_endsessions (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); collection = mongoc_client_get_collection (client, "test", "test"); prefs = mongoc_read_prefs_new (MONGOC_READ_SECONDARY); cursor = mongoc_collection_find_with_opts ( - collection, - tmp_bson ("{'a': 1}"), - tmp_bson ("{'readConcern': {'level': 'foo'}}"), - prefs); + collection, tmp_bson ("{'a': 1}"), tmp_bson ("{'readConcern': {'level': 'foo'}}"), prefs); future = future_cursor_next (cursor, &doc); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'test'," - " 'find': 'test'," - " 'filter': {}," - " 'readConcern': {'level': 'foo'}," - " '$readPreference': {'mode': 'secondary'}," - " 'readConcern': {'level': 'foo'}}")); + request = mock_server_receives_msg (server, + MONGOC_MSG_NONE, + tmp_bson ("{'$db': 'test'," + " 'find': 'test'," + " 'filter': {}," + " 'readConcern': {'level': 'foo'}," + " '$readPreference': {'mode': 'secondary'}," + " 'readConcern': {'level': 'foo'}}")); reply_to_op_msg_request (request, MONGOC_MSG_NONE, @@ -745,16 +668,13 @@ test_mongos_read_concern (void) } -typedef mongoc_cursor_t *(*test_op_msg_direct_fn_t) (mongoc_collection_t *, - mongoc_read_prefs_t *); +typedef mongoc_cursor_t *(*test_op_msg_direct_fn_t) (mongoc_collection_t *, mongoc_read_prefs_t *); /* direct connection to a secondary requires read pref primaryPreferred to * avoid "not primary" error from server */ static void -_test_op_msg_direct_connection (bool is_mongos, - test_op_msg_direct_fn_t fn, - const char *expected_cmd) +_test_op_msg_direct_connection (bool is_mongos, test_op_msg_direct_fn_t fn, const char *expected_cmd) { mock_server_t *server; mongoc_client_t *client; @@ -787,8 +707,7 @@ _test_op_msg_direct_connection (bool is_mongos, mock_server_auto_endsessions (server); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); collection = mongoc_client_get_collection (client, "db", "collection"); for (i = 0; i < 2; i++) { @@ -824,16 +743,14 @@ _test_op_msg_direct_connection (bool is_mongos, static mongoc_cursor_t * find (mongoc_collection_t *collection, mongoc_read_prefs_t *prefs) { - return mongoc_collection_find_with_opts ( - collection, tmp_bson ("{}"), NULL /* opts */, prefs); + return mongoc_collection_find_with_opts (collection, tmp_bson ("{}"), NULL /* opts */, prefs); } static mongoc_cursor_t * aggregate (mongoc_collection_t *collection, mongoc_read_prefs_t *prefs) { - return mongoc_collection_aggregate ( - collection, MONGOC_QUERY_NONE, tmp_bson ("{}"), NULL /* opts */, prefs); + return mongoc_collection_aggregate (collection, MONGOC_QUERY_NONE, tmp_bson ("{}"), NULL /* opts */, prefs); } @@ -842,21 +759,19 @@ aggregate (mongoc_collection_t *collection, mongoc_read_prefs_t *prefs) static void test_op_msg_direct_secondary (void) { - _test_op_msg_direct_connection ( - false /* is_mongos */, - find, - "{" - " 'find': 'collection'," - " '$readPreference': {'mode': 'primaryPreferred'}" - "}"); - - _test_op_msg_direct_connection ( - false /* is_mongos */, - aggregate, - "{" - " 'aggregate': 'collection'," - " '$readPreference': {'mode': 'primaryPreferred'}" - "}"); + _test_op_msg_direct_connection (false /* is_mongos */, + find, + "{" + " 'find': 'collection'," + " '$readPreference': {'mode': 'primaryPreferred'}" + "}"); + + _test_op_msg_direct_connection (false /* is_mongos */, + aggregate, + "{" + " 'aggregate': 'collection'," + " '$readPreference': {'mode': 'primaryPreferred'}" + "}"); } @@ -883,42 +798,21 @@ test_op_msg_direct_mongos (void) void test_read_prefs_install (TestSuite *suite) { + TestSuite_AddMockServerTest (suite, "/ReadPrefs/standalone/null", test_read_prefs_standalone_null); + TestSuite_AddMockServerTest (suite, "/ReadPrefs/standalone/primary", test_read_prefs_standalone_primary); + TestSuite_AddMockServerTest (suite, "/ReadPrefs/standalone/secondary", test_read_prefs_standalone_secondary); + TestSuite_AddMockServerTest (suite, "/ReadPrefs/standalone/tags", test_read_prefs_standalone_tags); + TestSuite_AddMockServerTest (suite, "/ReadPrefs/rsprimary/primary", test_read_prefs_primary_rsprimary); + TestSuite_AddMockServerTest (suite, "/ReadPrefs/rssecondary/secondary", test_read_prefs_secondary_rssecondary); + TestSuite_AddMockServerTest (suite, "/ReadPrefs/mongos/null", test_read_prefs_mongos_null); + TestSuite_AddMockServerTest (suite, "/ReadPrefs/mongos/primary", test_read_prefs_mongos_primary); + TestSuite_AddMockServerTest (suite, "/ReadPrefs/mongos/secondary", test_read_prefs_mongos_secondary); TestSuite_AddMockServerTest ( - suite, "/ReadPrefs/standalone/null", test_read_prefs_standalone_null); - TestSuite_AddMockServerTest (suite, - "/ReadPrefs/standalone/primary", - test_read_prefs_standalone_primary); - TestSuite_AddMockServerTest (suite, - "/ReadPrefs/standalone/secondary", - test_read_prefs_standalone_secondary); - TestSuite_AddMockServerTest ( - suite, "/ReadPrefs/standalone/tags", test_read_prefs_standalone_tags); - TestSuite_AddMockServerTest ( - suite, "/ReadPrefs/rsprimary/primary", test_read_prefs_primary_rsprimary); - TestSuite_AddMockServerTest (suite, - "/ReadPrefs/rssecondary/secondary", - test_read_prefs_secondary_rssecondary); - TestSuite_AddMockServerTest ( - suite, "/ReadPrefs/mongos/null", test_read_prefs_mongos_null); - TestSuite_AddMockServerTest ( - suite, "/ReadPrefs/mongos/primary", test_read_prefs_mongos_primary); - TestSuite_AddMockServerTest ( - suite, "/ReadPrefs/mongos/secondary", test_read_prefs_mongos_secondary); - TestSuite_AddMockServerTest (suite, - "/ReadPrefs/mongos/secondaryPreferred", - test_read_prefs_mongos_secondary_preferred); - TestSuite_AddMockServerTest ( - suite, "/ReadPrefs/mongos/tags", test_read_prefs_mongos_tags); - TestSuite_AddMockServerTest (suite, - "/ReadPrefs/mongos/maxStaleness", - test_read_prefs_mongos_max_staleness); - TestSuite_AddMockServerTest (suite, - "/ReadPrefs/mongos/hedgedReads", - test_read_prefs_mongos_hedged_reads); - TestSuite_AddMockServerTest ( - suite, "/ReadPrefs/mongos/readConcern", test_mongos_read_concern); - TestSuite_AddMockServerTest ( - suite, "/ReadPrefs/OP_MSG/secondary", test_op_msg_direct_secondary); - TestSuite_AddMockServerTest ( - suite, "/ReadPrefs/OP_MSG/mongos", test_op_msg_direct_mongos); + suite, "/ReadPrefs/mongos/secondaryPreferred", test_read_prefs_mongos_secondary_preferred); + TestSuite_AddMockServerTest (suite, "/ReadPrefs/mongos/tags", test_read_prefs_mongos_tags); + TestSuite_AddMockServerTest (suite, "/ReadPrefs/mongos/maxStaleness", test_read_prefs_mongos_max_staleness); + TestSuite_AddMockServerTest (suite, "/ReadPrefs/mongos/hedgedReads", test_read_prefs_mongos_hedged_reads); + TestSuite_AddMockServerTest (suite, "/ReadPrefs/mongos/readConcern", test_mongos_read_concern); + TestSuite_AddMockServerTest (suite, "/ReadPrefs/OP_MSG/secondary", test_op_msg_direct_secondary); + TestSuite_AddMockServerTest (suite, "/ReadPrefs/OP_MSG/mongos", test_op_msg_direct_mongos); } diff --git a/src/libmongoc/tests/test-mongoc-read-write-concern.c b/src/libmongoc/tests/test-mongoc-read-write-concern.c index 079e6e15de..60b87f02b4 100644 --- a/src/libmongoc/tests/test-mongoc-read-write-concern.c +++ b/src/libmongoc/tests/test-mongoc-read-write-concern.c @@ -10,8 +10,7 @@ static void -compare_write_concern (const mongoc_write_concern_t *wc_correct, - const mongoc_write_concern_t *wc) +compare_write_concern (const mongoc_write_concern_t *wc_correct, const mongoc_write_concern_t *wc) { ASSERT_CMPINT32 (wc_correct->w, ==, wc->w); ASSERT_CMPINT64 (wc_correct->wtimeout, ==, wc->wtimeout); @@ -20,8 +19,7 @@ compare_write_concern (const mongoc_write_concern_t *wc_correct, static void -compare_read_concern (const mongoc_read_concern_t *rc_correct, - const mongoc_read_concern_t *rc) +compare_read_concern (const mongoc_read_concern_t *rc_correct, const mongoc_read_concern_t *rc) { ASSERT_CMPSTR (rc_correct->level, rc->level); } @@ -44,8 +42,7 @@ convert_write_concern (const bson_t *wc_doc) if (strcmp (bson_lookup_utf8 (wc_doc, "w"), "majority") == 0) { mongoc_write_concern_set_w (wc, MONGOC_WRITE_CONCERN_W_MAJORITY); } else { - mongoc_write_concern_set_wtag (wc, - bson_lookup_utf8 (wc_doc, "w")); + mongoc_write_concern_set_wtag (wc, bson_lookup_utf8 (wc_doc, "w")); } } else { if (bson_lookup_int32 (wc_doc, "w") < 0) { @@ -57,11 +54,9 @@ convert_write_concern (const bson_t *wc_doc) if (bson_lookup_int32 (wc_doc, "wtimeoutMS") < 0) { goto invalid; } - mongoc_write_concern_set_wtimeout_int64 ( - wc, bson_lookup_int32 (wc_doc, "wtimeoutMS")); + mongoc_write_concern_set_wtimeout_int64 (wc, bson_lookup_int32 (wc_doc, "wtimeoutMS")); } else if (strcmp (key, "journal") == 0) { - mongoc_write_concern_set_journal ( - wc, bson_iter_value (&iter)->value.v_bool); + mongoc_write_concern_set_journal (wc, bson_iter_value (&iter)->value.v_bool); } } @@ -91,8 +86,7 @@ convert_read_concern (const bson_t *rc_doc) if (strcmp (key, "level") == 0) { if (BSON_ITER_HOLDS_UTF8 (&iter)) { - mongoc_read_concern_set_level (rc, - bson_lookup_utf8 (rc_doc, "level")); + mongoc_read_concern_set_level (rc, bson_lookup_utf8 (rc_doc, "level")); } else { goto invalid; } @@ -136,8 +130,7 @@ test_rw_concern_uri (bson_t *scenario) valid = _mongoc_lookup_bool (&test, "valid", true); if (_mongoc_lookup_bool (&test, "warning", false)) { - test_error ("update the \"%s\" test to handle warning: true", - description); + test_error ("update the \"%s\" test to handle warning: true", description); } uri = mongoc_uri_new_with_error (uri_str, NULL); @@ -232,12 +225,6 @@ test_rw_concern_document (bson_t *scenario) void test_read_write_concern_install (TestSuite *suite) { - install_json_test_suite (suite, - JSON_DIR, - "read_write_concern/connection-string", - &test_rw_concern_uri); - install_json_test_suite (suite, - JSON_DIR, - "read_write_concern/document", - &test_rw_concern_document); + install_json_test_suite (suite, JSON_DIR, "read_write_concern/connection-string", &test_rw_concern_uri); + install_json_test_suite (suite, JSON_DIR, "read_write_concern/document", &test_rw_concern_document); } diff --git a/src/libmongoc/tests/test-mongoc-retryability-helpers.c b/src/libmongoc/tests/test-mongoc-retryability-helpers.c index 12f5b9ac64..d127fb4f92 100644 --- a/src/libmongoc/tests/test-mongoc-retryability-helpers.c +++ b/src/libmongoc/tests/test-mongoc-retryability-helpers.c @@ -21,16 +21,13 @@ _test_get_mongos_clients (const char **ports, size_t num_ports) for (size_t i = 0u; i < num_ports; ++i) { const char *const port = ports[i]; - char *const host_and_port = - bson_strdup_printf ("mongodb://localhost:%s", port); - char *const uri_str = - test_framework_add_user_password_from_env (host_and_port); + char *const host_and_port = bson_strdup_printf ("mongodb://localhost:%s", port); + char *const uri_str = test_framework_add_user_password_from_env (host_and_port); mongoc_uri_t *const uri = mongoc_uri_new_with_error (uri_str, &error); ASSERT_OR_PRINT (uri, error); - mongoc_client_t *const client = - mongoc_client_new_from_uri_with_error (uri, &error); + mongoc_client_t *const client = mongoc_client_new_from_uri_with_error (uri, &error); ASSERT_OR_PRINT (client, error); test_framework_set_ssl_opts (client); @@ -38,19 +35,11 @@ _test_get_mongos_clients (const char **ports, size_t num_ports) bson_t reply = BSON_INITIALIZER; ASSERT_OR_PRINT ( - mongoc_client_command_simple (client, - "admin", - tmp_bson ("{'hello': 1}"), - NULL, - &reply, - &error), - error); - - ASSERT_WITH_MSG ( - bson_has_field (&reply, "msg") && - strcmp (bson_lookup_utf8 (&reply, "msg"), "isdbgrid") == 0, - "expected a mongos on port %s", - port); + mongoc_client_command_simple (client, "admin", tmp_bson ("{'hello': 1}"), NULL, &reply, &error), error); + + ASSERT_WITH_MSG (bson_has_field (&reply, "msg") && strcmp (bson_lookup_utf8 (&reply, "msg"), "isdbgrid") == 0, + "expected a mongos on port %s", + port); bson_destroy (&reply); } diff --git a/src/libmongoc/tests/test-mongoc-retryable-reads.c b/src/libmongoc/tests/test-mongoc-retryable-reads.c index 97fb05679d..65b337cc5b 100644 --- a/src/libmongoc/tests/test-mongoc-retryable-reads.c +++ b/src/libmongoc/tests/test-mongoc-retryable-reads.c @@ -11,9 +11,7 @@ #include "test-mongoc-retryability-helpers.h" static bool -retryable_reads_test_run_operation (json_test_ctx_t *ctx, - const bson_t *test, - const bson_t *operation) +retryable_reads_test_run_operation (json_test_ctx_t *ctx, const bson_t *test, const bson_t *operation) { bool *explicit_session = (bool *) ctx->config->ctx; bson_t reply; @@ -24,18 +22,13 @@ retryable_reads_test_run_operation (json_test_ctx_t *ctx, bson_iter_init_find (&iter, operation, "name"); op_name = bson_iter_utf8 (&iter, &op_len); - if (strcmp (op_name, "estimatedDocumentCount") == 0 || - strcmp (op_name, "count") == 0) { + if (strcmp (op_name, "estimatedDocumentCount") == 0 || strcmp (op_name, "count") == 0) { /* CDRIVER-3612: mongoc_collection_estimated_document_count does not * support explicit sessions */ *explicit_session = false; } - res = json_test_operation (ctx, - test, - operation, - ctx->collection, - *explicit_session ? ctx->sessions[0] : NULL, - &reply); + res = + json_test_operation (ctx, test, operation, ctx->collection, *explicit_session ? ctx->sessions[0] : NULL, &reply); bson_destroy (&reply); @@ -66,16 +59,13 @@ static void _set_failpoint (mongoc_client_t *client) { bson_error_t error; - bson_t *cmd = - tmp_bson ("{'configureFailPoint': 'failCommand'," - " 'mode': {'times': 1}," - " 'data': {'errorCode': 10107, 'failCommands': ['count']}}"); + bson_t *cmd = tmp_bson ("{'configureFailPoint': 'failCommand'," + " 'mode': {'times': 1}," + " 'data': {'errorCode': 10107, 'failCommands': ['count']}}"); ASSERT (client); - ASSERT_OR_PRINT ( - mongoc_client_command_simple (client, "admin", cmd, NULL, NULL, &error), - error); + ASSERT_OR_PRINT (mongoc_client_command_simple (client, "admin", cmd, NULL, NULL, &error), error); } /* Test code paths for all command helpers */ static void @@ -104,8 +94,7 @@ test_cmd_helpers (void *ctx) mongoc_uri_destroy (uri); /* clean up in case a previous test aborted */ - server_id = mongoc_topology_select_server_id ( - client->topology, MONGOC_SS_WRITE, NULL, NULL, NULL, &error); + server_id = mongoc_topology_select_server_id (client->topology, MONGOC_SS_WRITE, NULL, NULL, NULL, &error); ASSERT_OR_PRINT (server_id, error); deactivate_fail_points (client, server_id); @@ -119,36 +108,26 @@ test_cmd_helpers (void *ctx) } } - ASSERT_OR_PRINT (mongoc_collection_insert_one ( - collection, tmp_bson ("{'_id': 0}"), NULL, NULL, &error), - error); - ASSERT_OR_PRINT (mongoc_collection_insert_one ( - collection, tmp_bson ("{'_id': 1}"), NULL, NULL, &error), - error); + ASSERT_OR_PRINT (mongoc_collection_insert_one (collection, tmp_bson ("{'_id': 0}"), NULL, NULL, &error), error); + ASSERT_OR_PRINT (mongoc_collection_insert_one (collection, tmp_bson ("{'_id': 1}"), NULL, NULL, &error), error); cmd = tmp_bson ("{'count': '%s'}", collection->collection); /* read helpers must retry. */ _set_failpoint (client); - ASSERT_OR_PRINT (mongoc_client_read_command_with_opts ( - client, "test", cmd, NULL, NULL, &reply, &error), - error); + ASSERT_OR_PRINT (mongoc_client_read_command_with_opts (client, "test", cmd, NULL, NULL, &reply, &error), error); bson_iter_init_find (&iter, &reply, "n"); ASSERT (bson_iter_as_int64 (&iter) == 2); bson_destroy (&reply); _set_failpoint (client); - ASSERT_OR_PRINT (mongoc_database_read_command_with_opts ( - database, cmd, NULL, NULL, &reply, &error), - error); + ASSERT_OR_PRINT (mongoc_database_read_command_with_opts (database, cmd, NULL, NULL, &reply, &error), error); bson_iter_init_find (&iter, &reply, "n"); ASSERT (bson_iter_as_int64 (&iter) == 2); bson_destroy (&reply); _set_failpoint (client); - ASSERT_OR_PRINT (mongoc_collection_read_command_with_opts ( - collection, cmd, NULL, NULL, &reply, &error), - error); + ASSERT_OR_PRINT (mongoc_collection_read_command_with_opts (collection, cmd, NULL, NULL, &reply, &error), error); bson_iter_init_find (&iter, &reply, "n"); ASSERT (bson_iter_as_int64 (&iter) == 2); bson_destroy (&reply); @@ -157,8 +136,7 @@ test_cmd_helpers (void *ctx) /* read/write agnostic command_simple helpers must not retry. */ _set_failpoint (client); - ASSERT ( - !mongoc_client_command_simple (client, "test", cmd, NULL, NULL, &error)); + ASSERT (!mongoc_client_command_simple (client, "test", cmd, NULL, NULL, &error)); ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_SERVER, 10107, "Failing command"); _set_failpoint (client); @@ -166,59 +144,50 @@ test_cmd_helpers (void *ctx) ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_SERVER, 10107, "Failing command"); _set_failpoint (client); - ASSERT ( - !mongoc_collection_command_simple (collection, cmd, NULL, NULL, &error)); + ASSERT (!mongoc_collection_command_simple (collection, cmd, NULL, NULL, &error)); ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_SERVER, 10107, "Failing command"); /* read/write agnostic command_with_opts helpers must not retry. */ _set_failpoint (client); - ASSERT (!mongoc_client_command_with_opts ( - client, "test", cmd, NULL, NULL, NULL, &error)); + ASSERT (!mongoc_client_command_with_opts (client, "test", cmd, NULL, NULL, NULL, &error)); ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_SERVER, 10107, "Failing command"); _set_failpoint (client); - ASSERT (!mongoc_database_command_with_opts ( - database, cmd, NULL, NULL, NULL, &error)); + ASSERT (!mongoc_database_command_with_opts (database, cmd, NULL, NULL, NULL, &error)); ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_SERVER, 10107, "Failing command"); _set_failpoint (client); - ASSERT (!mongoc_collection_command_with_opts ( - collection, cmd, NULL, NULL, NULL, &error)); + ASSERT (!mongoc_collection_command_with_opts (collection, cmd, NULL, NULL, NULL, &error)); ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_SERVER, 10107, "Failing command"); /* read/write agnostic command_simple_with_server_id helper must not retry. */ - server_id = mongoc_topology_select_server_id ( - client->topology, MONGOC_SS_WRITE, NULL, NULL, NULL, &error); + server_id = mongoc_topology_select_server_id (client->topology, MONGOC_SS_WRITE, NULL, NULL, NULL, &error); ASSERT_OR_PRINT (server_id, error); _set_failpoint (client); - ASSERT (!mongoc_client_command_simple_with_server_id ( - client, "test", cmd, NULL, server_id, NULL, &error)); + ASSERT (!mongoc_client_command_simple_with_server_id (client, "test", cmd, NULL, server_id, NULL, &error)); ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_SERVER, 10107, "Failing command"); /* deprecated command helpers (which goes through cursor logic) function must * not retry. */ _set_failpoint (client); - cursor = mongoc_client_command ( - client, "test", MONGOC_QUERY_NONE, 0, 1, 1, cmd, NULL, NULL); + cursor = mongoc_client_command (client, "test", MONGOC_QUERY_NONE, 0, 1, 1, cmd, NULL, NULL); ASSERT (!mongoc_cursor_next (cursor, &doc)); ASSERT (mongoc_cursor_error (cursor, &error)); ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_SERVER, 10107, "Failing command"); mongoc_cursor_destroy (cursor); _set_failpoint (client); - cursor = mongoc_database_command ( - database, MONGOC_QUERY_NONE, 0, 1, 1, cmd, NULL, NULL); + cursor = mongoc_database_command (database, MONGOC_QUERY_NONE, 0, 1, 1, cmd, NULL, NULL); ASSERT (!mongoc_cursor_next (cursor, &doc)); ASSERT (mongoc_cursor_error (cursor, &error)); ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_SERVER, 10107, "Failing command"); mongoc_cursor_destroy (cursor); _set_failpoint (client); - cursor = mongoc_collection_command ( - collection, MONGOC_QUERY_NONE, 0, 1, 1, cmd, NULL, NULL); + cursor = mongoc_collection_command (collection, MONGOC_QUERY_NONE, 0, 1, 1, cmd, NULL, NULL); ASSERT (!mongoc_cursor_next (cursor, &doc)); ASSERT (mongoc_cursor_error (cursor, &error)); ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_SERVER, 10107, "Failing command"); @@ -251,8 +220,7 @@ test_retry_reads_off (void *ctx) test_framework_set_ssl_opts (client); /* clean up in case a previous test aborted */ - server_id = mongoc_topology_select_server_id ( - client->topology, MONGOC_SS_WRITE, NULL, NULL, NULL, &error); + server_id = mongoc_topology_select_server_id (client->topology, MONGOC_SS_WRITE, NULL, NULL, NULL, &error); ASSERT_OR_PRINT (server_id, error); deactivate_fail_points (client, server_id); @@ -261,14 +229,12 @@ test_retry_reads_off (void *ctx) cmd = tmp_bson ("{'configureFailPoint': 'failCommand'," " 'mode': {'times': 1}," " 'data': {'errorCode': 10107, 'failCommands': ['count']}}"); - ASSERT_OR_PRINT (mongoc_client_command_simple_with_server_id ( - client, "admin", cmd, NULL, server_id, NULL, &error), + ASSERT_OR_PRINT (mongoc_client_command_simple_with_server_id (client, "admin", cmd, NULL, server_id, NULL, &error), error); cmd = tmp_bson ("{'count': 'coll'}", collection->collection); - res = mongoc_collection_read_command_with_opts ( - collection, cmd, NULL, NULL, NULL, &error); + res = mongoc_collection_read_command_with_opts (collection, cmd, NULL, NULL, NULL, &error); ASSERT (!res); ASSERT_CONTAINS (error.message, "failpoint"); @@ -285,21 +251,17 @@ typedef struct _test_retry_reads_sharded_on_other_mongos_ctx { } test_retry_reads_sharded_on_other_mongos_ctx; static void -_test_retry_reads_sharded_on_other_mongos_cb ( - const mongoc_apm_command_failed_t *event) +_test_retry_reads_sharded_on_other_mongos_cb (const mongoc_apm_command_failed_t *event) { BSON_ASSERT_PARAM (event); test_retry_reads_sharded_on_other_mongos_ctx *const ctx = - (test_retry_reads_sharded_on_other_mongos_ctx *) - mongoc_apm_command_failed_get_context (event); + (test_retry_reads_sharded_on_other_mongos_ctx *) mongoc_apm_command_failed_get_context (event); BSON_ASSERT (ctx); - ASSERT_WITH_MSG (ctx->count < 2, - "expected at most two failpoints to trigger"); + ASSERT_WITH_MSG (ctx->count < 2, "expected at most two failpoints to trigger"); - const mongoc_host_list_t *const host = - mongoc_apm_command_failed_get_host (event); + const mongoc_host_list_t *const host = mongoc_apm_command_failed_get_host (event); BSON_ASSERT (host); BSON_ASSERT (!host->next); ctx->ports[ctx->count++] = host->port; @@ -319,10 +281,8 @@ test_retry_reads_sharded_on_other_mongos (void *_ctx) const size_t num_ports = sizeof (ports) / sizeof (*ports); mongoc_array_t clients = _test_get_mongos_clients (ports, num_ports); BSON_ASSERT (clients.len == 2u); - mongoc_client_t *const s0 = - _mongoc_array_index (&clients, mongoc_client_t *, 0u); - mongoc_client_t *const s1 = - _mongoc_array_index (&clients, mongoc_client_t *, 1u); + mongoc_client_t *const s0 = _mongoc_array_index (&clients, mongoc_client_t *, 0u); + mongoc_client_t *const s1 = _mongoc_array_index (&clients, mongoc_client_t *, 1u); BSON_ASSERT (s0 && s1); // Deprioritization cannot be deterministically asserted by this test due to @@ -331,22 +291,17 @@ test_retry_reads_sharded_on_other_mongos (void *_ctx) for (int i = 0; i < 10; ++i) { // Configure the following fail point for both s0 and s1: { - bson_t *const command = - tmp_bson ("{" - " 'configureFailPoint': 'failCommand'," - " 'mode': { 'times': 1 }," - " 'data': {" - " 'failCommands': ['find']," - " 'errorCode': 6" - " }" - "}"); - - ASSERT_OR_PRINT (mongoc_client_command_simple ( - s0, "admin", command, NULL, NULL, &error), - error); - ASSERT_OR_PRINT (mongoc_client_command_simple ( - s1, "admin", command, NULL, NULL, &error), - error); + bson_t *const command = tmp_bson ("{" + " 'configureFailPoint': 'failCommand'," + " 'mode': { 'times': 1 }," + " 'data': {" + " 'failCommands': ['find']," + " 'errorCode': 6" + " }" + "}"); + + ASSERT_OR_PRINT (mongoc_client_command_simple (s0, "admin", command, NULL, NULL, &error), error); + ASSERT_OR_PRINT (mongoc_client_command_simple (s1, "admin", command, NULL, NULL, &error), error); } // Create a client client with `retryReads=true` that connects to the @@ -354,10 +309,8 @@ test_retry_reads_sharded_on_other_mongos (void *_ctx) // list. mongoc_client_t *client = NULL; { - const char *const host_and_port = - "mongodb://localhost:27017,localhost:27018/?retryReads=true"; - char *const uri_str = - test_framework_add_user_password_from_env (host_and_port); + const char *const host_and_port = "mongodb://localhost:27017,localhost:27018/?retryReads=true"; + char *const uri_str = test_framework_add_user_password_from_env (host_and_port); mongoc_uri_t *const uri = mongoc_uri_new (uri_str); client = mongoc_client_new_from_uri_with_error (uri, &error); @@ -374,10 +327,8 @@ test_retry_reads_sharded_on_other_mongos (void *_ctx) // Enable failed command event monitoring for client. { - mongoc_apm_callbacks_t *const callbacks = - mongoc_apm_callbacks_new (); - mongoc_apm_set_command_failed_cb ( - callbacks, _test_retry_reads_sharded_on_other_mongos_cb); + mongoc_apm_callbacks_t *const callbacks = mongoc_apm_callbacks_new (); + mongoc_apm_set_command_failed_cb (callbacks, _test_retry_reads_sharded_on_other_mongos_cb); mongoc_client_set_apm_callbacks (client, callbacks, &ctx); mongoc_apm_callbacks_destroy (callbacks); } @@ -385,17 +336,12 @@ test_retry_reads_sharded_on_other_mongos (void *_ctx) // Execute a `find` command with `client`. Assert that the command // failed. { - mongoc_database_t *const db = - mongoc_client_get_database (client, "db"); - mongoc_collection_t *const coll = - mongoc_database_get_collection (db, "test"); - mongoc_cursor_t *const cursor = mongoc_collection_find_with_opts ( - coll, tmp_bson ("{}"), NULL, NULL); + mongoc_database_t *const db = mongoc_client_get_database (client, "db"); + mongoc_collection_t *const coll = mongoc_database_get_collection (db, "test"); + mongoc_cursor_t *const cursor = mongoc_collection_find_with_opts (coll, tmp_bson ("{}"), NULL, NULL); const bson_t *reply = NULL; - ASSERT_WITH_MSG (!mongoc_cursor_next (cursor, &reply), - "expected find command to fail"); - ASSERT_WITH_MSG (mongoc_cursor_error (cursor, &error), - "expected find command to fail"); + ASSERT_WITH_MSG (!mongoc_cursor_next (cursor, &reply), "expected find command to fail"); + ASSERT_WITH_MSG (mongoc_cursor_error (cursor, &error), "expected find command to fail"); mongoc_cursor_destroy (cursor); mongoc_collection_destroy (coll); mongoc_database_destroy (db); @@ -410,8 +356,7 @@ test_retry_reads_sharded_on_other_mongos (void *_ctx) // Assert that both events occurred on different mongoses. ASSERT_WITH_MSG ((ctx.ports[0] == 27017 || ctx.ports[0] == 27018) && - (ctx.ports[1] == 27017 || ctx.ports[1] == 27018) && - (ctx.ports[0] != ctx.ports[1]), + (ctx.ports[1] == 27017 || ctx.ports[1] == 27018) && (ctx.ports[0] != ctx.ports[1]), "expected failpoints to trigger once on each mongos, " "but observed failures on %d and %d", ctx.ports[0], @@ -422,18 +367,13 @@ test_retry_reads_sharded_on_other_mongos (void *_ctx) // Disable the fail point on both s0 and s1. { - bson_t *const command = - tmp_bson ("{" - " 'configureFailPoint': 'failCommand'," - " 'mode': 'off'" - "}"); - - ASSERT_OR_PRINT (mongoc_client_command_simple ( - s0, "admin", command, NULL, NULL, &error), - error); - ASSERT_OR_PRINT (mongoc_client_command_simple ( - s1, "admin", command, NULL, NULL, &error), - error); + bson_t *const command = tmp_bson ("{" + " 'configureFailPoint': 'failCommand'," + " 'mode': 'off'" + "}"); + + ASSERT_OR_PRINT (mongoc_client_command_simple (s0, "admin", command, NULL, NULL, &error), error); + ASSERT_OR_PRINT (mongoc_client_command_simple (s1, "admin", command, NULL, NULL, &error), error); } } @@ -450,26 +390,23 @@ typedef struct _test_retry_reads_sharded_on_same_mongos_ctx { } test_retry_reads_sharded_on_same_mongos_ctx; static void -_test_retry_reads_sharded_on_same_mongos_cb ( - test_retry_reads_sharded_on_same_mongos_ctx *ctx, - const mongoc_apm_command_failed_t *failed, - const mongoc_apm_command_succeeded_t *succeeded) +_test_retry_reads_sharded_on_same_mongos_cb (test_retry_reads_sharded_on_same_mongos_ctx *ctx, + const mongoc_apm_command_failed_t *failed, + const mongoc_apm_command_succeeded_t *succeeded) { BSON_ASSERT_PARAM (ctx); BSON_ASSERT (failed || true); BSON_ASSERT (succeeded || true); - ASSERT_WITH_MSG ( - ctx->failed_count + ctx->succeeded_count < 2, - "expected at most two events, but observed %d failed and %d succeeded", - ctx->failed_count, - ctx->succeeded_count); + ASSERT_WITH_MSG (ctx->failed_count + ctx->succeeded_count < 2, + "expected at most two events, but observed %d failed and %d succeeded", + ctx->failed_count, + ctx->succeeded_count); if (failed) { ctx->failed_count += 1; - const mongoc_host_list_t *const host = - mongoc_apm_command_failed_get_host (failed); + const mongoc_host_list_t *const host = mongoc_apm_command_failed_get_host (failed); BSON_ASSERT (host); BSON_ASSERT (!host->next); ctx->failed_port = host->port; @@ -478,8 +415,7 @@ _test_retry_reads_sharded_on_same_mongos_cb ( if (succeeded) { ctx->succeeded_count += 1; - const mongoc_host_list_t *const host = - mongoc_apm_command_succeeded_get_host (succeeded); + const mongoc_host_list_t *const host = mongoc_apm_command_succeeded_get_host (succeeded); BSON_ASSERT (host); BSON_ASSERT (!host->next); ctx->succeeded_port = host->port; @@ -487,19 +423,15 @@ _test_retry_reads_sharded_on_same_mongos_cb ( } static void -_test_retry_reads_sharded_on_same_mongos_failed_cb ( - const mongoc_apm_command_failed_t *event) +_test_retry_reads_sharded_on_same_mongos_failed_cb (const mongoc_apm_command_failed_t *event) { - _test_retry_reads_sharded_on_same_mongos_cb ( - mongoc_apm_command_failed_get_context (event), event, NULL); + _test_retry_reads_sharded_on_same_mongos_cb (mongoc_apm_command_failed_get_context (event), event, NULL); } static void -_test_retry_reads_sharded_on_same_mongos_succeeded_cb ( - const mongoc_apm_command_succeeded_t *event) +_test_retry_reads_sharded_on_same_mongos_succeeded_cb (const mongoc_apm_command_succeeded_t *event) { - _test_retry_reads_sharded_on_same_mongos_cb ( - mongoc_apm_command_succeeded_get_context (event), NULL, event); + _test_retry_reads_sharded_on_same_mongos_cb (mongoc_apm_command_succeeded_get_context (event), NULL, event); } // Retryable Reads Are Retried on the Same mongos if No Others are Available @@ -515,25 +447,23 @@ test_retry_reads_sharded_on_same_mongos (void *_ctx) const size_t num_ports = sizeof (ports) / sizeof (*ports); mongoc_array_t clients = _test_get_mongos_clients (ports, num_ports); BSON_ASSERT (clients.len == 1u); - mongoc_client_t *const s0 = - _mongoc_array_index (&clients, mongoc_client_t *, 0u); + mongoc_client_t *const s0 = _mongoc_array_index (&clients, mongoc_client_t *, 0u); BSON_ASSERT (s0); // Configure the following fail point for `s0`: - ASSERT_OR_PRINT (mongoc_client_command_simple ( - s0, - "admin", - tmp_bson ("{" - " 'configureFailPoint': 'failCommand'," - " 'mode': { 'times': 1 }," - " 'data': {" - " 'failCommands': ['find']," - " 'errorCode': 6" - " }" - "}"), - NULL, - NULL, - &error), + ASSERT_OR_PRINT (mongoc_client_command_simple (s0, + "admin", + tmp_bson ("{" + " 'configureFailPoint': 'failCommand'," + " 'mode': { 'times': 1 }," + " 'data': {" + " 'failCommands': ['find']," + " 'errorCode': 6" + " }" + "}"), + NULL, + NULL, + &error), error); // Create a client client with `directConnection=false` (when not set by @@ -541,10 +471,8 @@ test_retry_reads_sharded_on_same_mongos (void *_ctx) // single mongos as `s0`. mongoc_client_t *client = NULL; { - const char *const host_and_port = - "mongodb://localhost:27017/?retryReads=true&directConnection=false"; - char *const uri_str = - test_framework_add_user_password_from_env (host_and_port); + const char *const host_and_port = "mongodb://localhost:27017/?retryReads=true&directConnection=false"; + char *const uri_str = test_framework_add_user_password_from_env (host_and_port); mongoc_uri_t *const uri = mongoc_uri_new (uri_str); client = mongoc_client_new_from_uri_with_error (uri, &error); @@ -565,10 +493,8 @@ test_retry_reads_sharded_on_same_mongos (void *_ctx) // Enable succeeded and failed command event monitoring for `client`. { mongoc_apm_callbacks_t *const callbacks = mongoc_apm_callbacks_new (); - mongoc_apm_set_command_failed_cb ( - callbacks, _test_retry_reads_sharded_on_same_mongos_failed_cb); - mongoc_apm_set_command_succeeded_cb ( - callbacks, _test_retry_reads_sharded_on_same_mongos_succeeded_cb); + mongoc_apm_set_command_failed_cb (callbacks, _test_retry_reads_sharded_on_same_mongos_failed_cb); + mongoc_apm_set_command_succeeded_cb (callbacks, _test_retry_reads_sharded_on_same_mongos_succeeded_cb); mongoc_client_set_apm_callbacks (client, callbacks, &ctx); mongoc_apm_callbacks_destroy (callbacks); } @@ -576,26 +502,21 @@ test_retry_reads_sharded_on_same_mongos (void *_ctx) // Execute a `find` command with `client`. Assert that the command // succeeded. { - mongoc_database_t *const db = - mongoc_client_get_database (client, "db"); - mongoc_collection_t *const coll = - mongoc_database_get_collection (db, "test"); + mongoc_database_t *const db = mongoc_client_get_database (client, "db"); + mongoc_collection_t *const coll = mongoc_database_get_collection (db, "test"); bson_t opts = BSON_INITIALIZER; { // Ensure drop from earlier is observed. mongoc_read_concern_t *const rc = mongoc_read_concern_new (); - mongoc_read_concern_set_level (rc, - MONGOC_READ_CONCERN_LEVEL_MAJORITY); + mongoc_read_concern_set_level (rc, MONGOC_READ_CONCERN_LEVEL_MAJORITY); mongoc_read_concern_append (rc, &opts); mongoc_read_concern_destroy (rc); } - mongoc_cursor_t *const cursor = - mongoc_collection_find_with_opts (coll, &opts, NULL, NULL); + mongoc_cursor_t *const cursor = mongoc_collection_find_with_opts (coll, &opts, NULL, NULL); const bson_t *reply = NULL; (void) mongoc_cursor_next (cursor, &reply); - ASSERT_WITH_MSG (!mongoc_cursor_error (cursor, &error), - "expecting find to succeed, but observed error: %s", - error.message); + ASSERT_WITH_MSG ( + !mongoc_cursor_error (cursor, &error), "expecting find to succeed, but observed error: %s", error.message); mongoc_cursor_destroy (cursor); bson_destroy (&opts); mongoc_collection_destroy (coll); @@ -607,36 +528,33 @@ test_retry_reads_sharded_on_same_mongos (void *_ctx) // Assert that exactly one failed command event and one succeeded command // event occurred. - ASSERT_WITH_MSG ( - ctx.failed_count == 1 && ctx.succeeded_count == 1, - "expected exactly one failed event and one succeeded " - "event, but observed %d failures and %d successes with error: %s", - ctx.failed_count, - ctx.succeeded_count, - ctx.succeeded_count > 1 ? "none" : error.message); + ASSERT_WITH_MSG (ctx.failed_count == 1 && ctx.succeeded_count == 1, + "expected exactly one failed event and one succeeded " + "event, but observed %d failures and %d successes with error: %s", + ctx.failed_count, + ctx.succeeded_count, + ctx.succeeded_count > 1 ? "none" : error.message); // Assert that both events occurred on the same mongos. - ASSERT_WITH_MSG ( - ctx.failed_port == ctx.succeeded_port, - "expected failed and succeeded events on the same mongos, but " - "instead observed port %d (failed) and port %d (succeeded)", - ctx.failed_port, - ctx.succeeded_port); + ASSERT_WITH_MSG (ctx.failed_port == ctx.succeeded_port, + "expected failed and succeeded events on the same mongos, but " + "instead observed port %d (failed) and port %d (succeeded)", + ctx.failed_port, + ctx.succeeded_port); mongoc_client_destroy (client); } // Disable the fail point on s0. - ASSERT_OR_PRINT (mongoc_client_command_simple ( - s0, - "admin", - tmp_bson ("{" - " 'configureFailPoint': 'failCommand'," - " 'mode': 'off'" - "}"), - NULL, - NULL, - &error), + ASSERT_OR_PRINT (mongoc_client_command_simple (s0, + "admin", + tmp_bson ("{" + " 'configureFailPoint': 'failCommand'," + " 'mode': 'off'" + "}"), + NULL, + NULL, + &error), error); mongoc_client_destroy (s0); diff --git a/src/libmongoc/tests/test-mongoc-retryable-writes.c b/src/libmongoc/tests/test-mongoc-retryable-writes.c index 4c9805069f..bcc6519a13 100644 --- a/src/libmongoc/tests/test-mongoc-retryable-writes.c +++ b/src/libmongoc/tests/test-mongoc-retryable-writes.c @@ -12,20 +12,14 @@ static bool -retryable_writes_test_run_operation (json_test_ctx_t *ctx, - const bson_t *test, - const bson_t *operation) +retryable_writes_test_run_operation (json_test_ctx_t *ctx, const bson_t *test, const bson_t *operation) { bool *explicit_session = (bool *) ctx->config->ctx; bson_t reply; bool res; - res = json_test_operation (ctx, - test, - operation, - ctx->collection, - *explicit_session ? ctx->sessions[0] : NULL, - &reply); + res = + json_test_operation (ctx, test, operation, ctx->collection, *explicit_session ? ctx->sessions[0] : NULL, &reply); bson_destroy (&reply); @@ -34,9 +28,7 @@ retryable_writes_test_run_operation (json_test_ctx_t *ctx, static test_skip_t skips[] = { - {"InsertOne fails after multiple retryable writeConcernErrors", - "Waiting on CDRIVER-3790"}, - {0}}; + {"InsertOne fails after multiple retryable writeConcernErrors", "Waiting on CDRIVER-3790"}, {0}}; /* Callback for JSON tests from Retryable Writes Spec */ static void @@ -74,10 +66,7 @@ test_rs_failover (void) bson_error_t error; bson_t *b = tmp_bson ("{}"); - rs = mock_rs_with_auto_hello (WIRE_VERSION_MAX, - true /* has primary */, - 2 /* secondaries */, - 0 /* arbiters */); + rs = mock_rs_with_auto_hello (WIRE_VERSION_MAX, true /* has primary */, 2 /* secondaries */, 0 /* arbiters */); mock_rs_run (rs); uri = mongoc_uri_copy (mock_rs_get_uri (rs)); @@ -90,8 +79,7 @@ test_rs_failover (void) /* initial insert triggers replica set discovery */ future = future_collection_insert_one (collection, b, &opts, NULL, &error); - request = - mock_rs_receives_msg (rs, 0, tmp_bson ("{'insert': 'collection'}"), b); + request = mock_rs_receives_msg (rs, 0, tmp_bson ("{'insert': 'collection'}"), b); reply_to_request_with_ok_and_destroy (request); BSON_ASSERT (future_get_bool (future)); future_destroy (future); @@ -101,11 +89,9 @@ test_rs_failover (void) mock_rs_elect (rs, 1 /* server id */); /* insert receives "not primary" from old primary, reselects and retries */ - future = future_collection_insert_one ( - collection, tmp_bson ("{}"), &opts, NULL, &error); + future = future_collection_insert_one (collection, tmp_bson ("{}"), &opts, NULL, &error); - request = - mock_rs_receives_msg (rs, 0, tmp_bson ("{'insert': 'collection'}"), b); + request = mock_rs_receives_msg (rs, 0, tmp_bson ("{'insert': 'collection'}"), b); BSON_ASSERT (mock_rs_request_is_to_secondary (rs, request)); reply_to_request_simple (request, "{" @@ -116,8 +102,7 @@ test_rs_failover (void) "}"); request_destroy (request); - request = - mock_rs_receives_msg (rs, 0, tmp_bson ("{'insert': 'collection'}"), b); + request = mock_rs_receives_msg (rs, 0, tmp_bson ("{'insert': 'collection'}"), b); BSON_ASSERT (mock_rs_request_is_to_primary (rs, request)); reply_to_request_with_ok_and_destroy (request); BSON_ASSERT (future_get_bool (future)); @@ -157,8 +142,7 @@ test_command_with_opts (void *ctx) mongoc_uri_destroy (uri); /* clean up in case a previous test aborted */ - server_id = mongoc_topology_select_server_id ( - client->topology, MONGOC_SS_WRITE, NULL, NULL, NULL, &error); + server_id = mongoc_topology_select_server_id (client->topology, MONGOC_SS_WRITE, NULL, NULL, NULL, &error); ASSERT_OR_PRINT (server_id, error); deactivate_fail_points (client, server_id); @@ -171,25 +155,21 @@ test_command_with_opts (void *ctx) } } - ASSERT_OR_PRINT ( - mongoc_collection_insert_one ( - collection, tmp_bson ("{'_id':1, 'x': 1}"), NULL, NULL, &error), - error); + ASSERT_OR_PRINT (mongoc_collection_insert_one (collection, tmp_bson ("{'_id':1, 'x': 1}"), NULL, NULL, &error), + error); cmd = tmp_bson ("{'configureFailPoint': 'onPrimaryTransactionalWrite'," " 'mode': {'times': 1}," " 'data': {'failBeforeCommitExceptionCode': 1}}"); - ASSERT_OR_PRINT (mongoc_client_command_simple_with_server_id ( - client, "admin", cmd, NULL, server_id, NULL, &error), + ASSERT_OR_PRINT (mongoc_client_command_simple_with_server_id (client, "admin", cmd, NULL, server_id, NULL, &error), error); cmd = tmp_bson ("{'findAndModify': '%s', 'query': {'_id': 1}, 'update': " "{'$inc': {'x': 1}}, 'new': true}", collection->collection); - ASSERT_OR_PRINT (mongoc_collection_read_write_command_with_opts ( - collection, cmd, NULL, NULL, &reply, &error), + ASSERT_OR_PRINT (mongoc_collection_read_write_command_with_opts (collection, cmd, NULL, NULL, &reply, &error), error); bson_lookup_doc (&reply, "value", &reply_result); @@ -231,15 +211,12 @@ test_insert_one_unacknowledged (void) mongoc_write_concern_set_journal (wc, false); mongoc_write_concern_append (wc, &opts); - future = future_collection_insert_one ( - collection, tmp_bson ("{}"), &opts, NULL, &error); + future = future_collection_insert_one (collection, tmp_bson ("{}"), &opts, NULL, &error); - request = mock_server_receives_msg ( - server, - 2, /* set moreToCome bit in mongoc_op_msg_flags_t */ - tmp_bson ( - "{'txnNumber': {'$exists': false}, 'lsid': {'$exists': false}}"), - tmp_bson ("{}")); + request = mock_server_receives_msg (server, + 2, /* set moreToCome bit in mongoc_op_msg_flags_t */ + tmp_bson ("{'txnNumber': {'$exists': false}, 'lsid': {'$exists': false}}"), + tmp_bson ("{}")); ASSERT (future_get_bool (future)); mock_server_auto_endsessions (server); @@ -279,19 +256,13 @@ test_update_one_unacknowledged (void) mongoc_write_concern_set_journal (wc, false); mongoc_write_concern_append (wc, &opts); - future = future_collection_update_one (collection, - tmp_bson ("{}"), - tmp_bson ("{'$set': {'x': 1}}"), - &opts, - NULL, - &error); - - request = mock_server_receives_msg ( - server, - 2, /* set moreToCome bit in mongoc_op_msg_flags_t */ - tmp_bson ( - "{'txnNumber': {'$exists': false}, 'lsid': {'$exists': false}}"), - tmp_bson ("{'q': {}, 'u': {'$set': {'x': 1}}}")); + future = + future_collection_update_one (collection, tmp_bson ("{}"), tmp_bson ("{'$set': {'x': 1}}"), &opts, NULL, &error); + + request = mock_server_receives_msg (server, + 2, /* set moreToCome bit in mongoc_op_msg_flags_t */ + tmp_bson ("{'txnNumber': {'$exists': false}, 'lsid': {'$exists': false}}"), + tmp_bson ("{'q': {}, 'u': {'$set': {'x': 1}}}")); ASSERT (future_get_bool (future)); mongoc_write_concern_destroy (wc); @@ -330,15 +301,12 @@ test_delete_one_unacknowledged (void) mongoc_write_concern_set_journal (wc, false); mongoc_write_concern_append (wc, &opts); - future = future_collection_delete_one ( - collection, tmp_bson ("{}"), &opts, NULL, &error); + future = future_collection_delete_one (collection, tmp_bson ("{}"), &opts, NULL, &error); - request = mock_server_receives_msg ( - server, - 2, /* set moreToCome bit in mongoc_op_msg_flags_t */ - tmp_bson ( - "{'txnNumber': {'$exists': false}, 'lsid': {'$exists': false}}"), - tmp_bson ("{'q': {}, 'limit': 1}")); + request = mock_server_receives_msg (server, + 2, /* set moreToCome bit in mongoc_op_msg_flags_t */ + tmp_bson ("{'txnNumber': {'$exists': false}, 'lsid': {'$exists': false}}"), + tmp_bson ("{'q': {}, 'limit': 1}")); ASSERT (future_get_bool (future)); mongoc_write_concern_destroy (wc); @@ -382,12 +350,10 @@ test_bulk_operation_execute_unacknowledged (void) mongoc_bulk_operation_insert (bulk, tmp_bson ("{'_id': 1}")); future = future_bulk_operation_execute (bulk, NULL, &error); - request = mock_server_receives_msg ( - server, - 2, /* set moreToCome bit in mongoc_op_msg_flags_t */ - tmp_bson ( - "{'txnNumber': {'$exists': false}, 'lsid': {'$exists': false}}"), - tmp_bson ("{'_id': 1}")); + request = mock_server_receives_msg (server, + 2, /* set moreToCome bit in mongoc_op_msg_flags_t */ + tmp_bson ("{'txnNumber': {'$exists': false}, 'lsid': {'$exists': false}}"), + tmp_bson ("{'_id': 1}")); ASSERT (future_get_uint32_t (future) == 1); mongoc_write_concern_destroy (wc); @@ -426,15 +392,12 @@ test_remove_unacknowledged (void) mongoc_write_concern_set_w (wc, 0); mongoc_write_concern_set_journal (wc, false); - future = future_collection_remove ( - collection, MONGOC_REMOVE_NONE, tmp_bson ("{'a': 1}"), wc, &error); + future = future_collection_remove (collection, MONGOC_REMOVE_NONE, tmp_bson ("{'a': 1}"), wc, &error); - request = mock_server_receives_msg ( - server, - 2, /* set moreToCome bit in mongoc_op_msg_flags_t */ - tmp_bson ( - "{'txnNumber': {'$exists': false}, 'lsid': {'$exists': false}}"), - tmp_bson ("{'q': {'a': 1}, 'limit': 0}")); + request = mock_server_receives_msg (server, + 2, /* set moreToCome bit in mongoc_op_msg_flags_t */ + tmp_bson ("{'txnNumber': {'$exists': false}, 'lsid': {'$exists': false}}"), + tmp_bson ("{'q': {'a': 1}, 'limit': 0}")); ASSERT (future_get_bool (future)); mongoc_write_concern_destroy (wc); @@ -462,8 +425,7 @@ test_retry_no_crypto (void *ctx) /* Test that no warning is logged if retryWrites is disabled. Warning logic * is implemented in mongoc_topology_new, but test all public APIs that use * the common code path. */ - client = test_framework_client_new ("mongodb://localhost/?retryWrites=false", - NULL); + client = test_framework_client_new ("mongodb://localhost/?retryWrites=false", NULL); BSON_ASSERT (client); ASSERT_NO_CAPTURED_LOGS ("test_framework_client_new and retryWrites=false"); mongoc_client_destroy (client); @@ -473,26 +435,22 @@ test_retry_no_crypto (void *ctx) client = test_framework_client_new_from_uri (uri, NULL); BSON_ASSERT (client); - ASSERT_NO_CAPTURED_LOGS ( - "test_framework_client_new_from_uri and retryWrites=false"); + ASSERT_NO_CAPTURED_LOGS ("test_framework_client_new_from_uri and retryWrites=false"); mongoc_client_destroy (client); pool = test_framework_client_pool_new_from_uri (uri, NULL); BSON_ASSERT (pool); - ASSERT_NO_CAPTURED_LOGS ( - "test_framework_client_pool_new_from_uri and retryWrites=false"); + ASSERT_NO_CAPTURED_LOGS ("test_framework_client_pool_new_from_uri and retryWrites=false"); mongoc_client_pool_destroy (pool); mongoc_uri_destroy (uri); /* Test that a warning is logged if retryWrites is enabled. */ - client = - test_framework_client_new ("mongodb://localhost/?retryWrites=true", NULL); + client = test_framework_client_new ("mongodb://localhost/?retryWrites=true", NULL); BSON_ASSERT (client); - ASSERT_CAPTURED_LOG ( - "test_framework_client_new and retryWrites=true", - MONGOC_LOG_LEVEL_WARNING, - "retryWrites not supported without an SSL crypto library"); + ASSERT_CAPTURED_LOG ("test_framework_client_new and retryWrites=true", + MONGOC_LOG_LEVEL_WARNING, + "retryWrites not supported without an SSL crypto library"); mongoc_client_destroy (client); clear_captured_logs (); @@ -502,20 +460,18 @@ test_retry_no_crypto (void *ctx) client = test_framework_client_new_from_uri (uri, NULL); BSON_ASSERT (client); - ASSERT_CAPTURED_LOG ( - "test_framework_client_new_from_uri and retryWrites=true", - MONGOC_LOG_LEVEL_WARNING, - "retryWrites not supported without an SSL crypto library"); + ASSERT_CAPTURED_LOG ("test_framework_client_new_from_uri and retryWrites=true", + MONGOC_LOG_LEVEL_WARNING, + "retryWrites not supported without an SSL crypto library"); mongoc_client_destroy (client); clear_captured_logs (); pool = test_framework_client_pool_new_from_uri (uri, NULL); BSON_ASSERT (pool); - ASSERT_CAPTURED_LOG ( - "test_framework_client_pool_new_from_uri and retryWrites=true", - MONGOC_LOG_LEVEL_WARNING, - "retryWrites not supported without an SSL crypto library"); + ASSERT_CAPTURED_LOG ("test_framework_client_pool_new_from_uri and retryWrites=true", + MONGOC_LOG_LEVEL_WARNING, + "retryWrites not supported without an SSL crypto library"); mongoc_client_pool_destroy (pool); mongoc_uri_destroy (uri); @@ -548,21 +504,13 @@ test_unsupported_storage_engine_error (void) mongoc_client_set_error_api (client, MONGOC_ERROR_API_VERSION_2); coll = mongoc_client_get_collection (client, "test", "test"); bson_init (&opts); - ASSERT_OR_PRINT (mongoc_client_session_append (session, &opts, &error), - error); + ASSERT_OR_PRINT (mongoc_client_session_append (session, &opts, &error), error); /* findandmodify is retryable through mongoc_client_write_command_with_opts. */ future = future_client_write_command_with_opts ( - client, - "test", - tmp_bson ("{'findandmodify': 'coll' }"), - &opts, - &reply, - &error); + client, "test", tmp_bson ("{'findandmodify': 'coll' }"), &opts, &reply, &error); request = mock_rs_receives_request (rs); - reply_to_request_simple ( - request, - "{'ok': 0, 'code': 20, 'errmsg': 'Transaction numbers are great'}"); + reply_to_request_simple (request, "{'ok': 0, 'code': 20, 'errmsg': 'Transaction numbers are great'}"); request_destroy (request); BSON_ASSERT (!future_get_bool (future)); @@ -601,26 +549,22 @@ prose_test_3_on_command_success (const mongoc_apm_command_succeeded_t *event) bson_iter_t iter; bson_error_t error; const bson_t *reply = mongoc_apm_command_succeeded_get_reply (event); - prose_test_3_apm_ctx_t *ctx = - mongoc_apm_command_succeeded_get_context (event); + prose_test_3_apm_ctx_t *ctx = mongoc_apm_command_succeeded_get_context (event); // wait for a writeConcernError and then set a second failpoint - if (bson_iter_init_find (&iter, reply, "writeConcernError") && - ctx->configure_second_fail) { + if (bson_iter_init_find (&iter, reply, "writeConcernError") && ctx->configure_second_fail) { ctx->configure_second_fail = false; ASSERT_OR_PRINT ( - mongoc_client_command_simple ( - ctx->client, - "admin", - tmp_bson ( - "{'configureFailPoint': 'failCommand', 'mode': {'times': 1}," - " 'data': { 'failCommands': ['%s'], 'errorCode': " - "10107, " - "'errorLabels': ['RetryableWriteError', 'NoWritesPerformed']}}", - ctx->failCommand), - NULL, - NULL, - &error), + mongoc_client_command_simple (ctx->client, + "admin", + tmp_bson ("{'configureFailPoint': 'failCommand', 'mode': {'times': 1}," + " 'data': { 'failCommands': ['%s'], 'errorCode': " + "10107, " + "'errorLabels': ['RetryableWriteError', 'NoWritesPerformed']}}", + ctx->failCommand), + NULL, + NULL, + &error), error); } } @@ -637,8 +581,7 @@ set_up_original_error_test (mongoc_apm_callbacks_t *callbacks, ASSERT (client); // clean up in case a previous test aborted - server_id = mongoc_topology_select_server_id ( - client->topology, MONGOC_SS_WRITE, NULL, NULL, NULL, &error); + server_id = mongoc_topology_select_server_id (client->topology, MONGOC_SS_WRITE, NULL, NULL, NULL, &error); ASSERT_OR_PRINT (server_id, error); deactivate_fail_points (client, server_id); @@ -646,21 +589,19 @@ set_up_original_error_test (mongoc_apm_callbacks_t *callbacks, apm_ctx->client = client; apm_ctx->failCommand = failCommand; apm_ctx->configure_second_fail = true; - mongoc_apm_set_command_succeeded_cb (callbacks, - prose_test_3_on_command_success); + mongoc_apm_set_command_succeeded_cb (callbacks, prose_test_3_on_command_success); mongoc_client_set_apm_callbacks (client, callbacks, apm_ctx); // configure the first fail point - bool ret = mongoc_client_command_simple ( - client, - "admin", - tmp_bson ("{'configureFailPoint': 'failCommand', 'mode': {'times': 1}, " - "'data': {'failCommands': ['%s'], 'errorLabels': " - "['RetryableWriteError'], 'writeConcernError': {'code': 91 }}}", - failCommand), - NULL, - NULL, - &error); + bool ret = mongoc_client_command_simple (client, + "admin", + tmp_bson ("{'configureFailPoint': 'failCommand', 'mode': {'times': 1}, " + "'data': {'failCommands': ['%s'], 'errorLabels': " + "['RetryableWriteError'], 'writeConcernError': {'code': 91 }}}", + failCommand), + NULL, + NULL, + &error); ASSERT_OR_PRINT (ret, error); return server_id; @@ -700,12 +641,10 @@ retryable_writes_prose_test_3 (void *ctx) callbacks = mongoc_apm_callbacks_new (); // setup test - const uint32_t server_id = - set_up_original_error_test (callbacks, &apm_ctx, "insert", client); + const uint32_t server_id = set_up_original_error_test (callbacks, &apm_ctx, "insert", client); // attempt an insertOne operation - ASSERT (!mongoc_collection_insert_one ( - coll, tmp_bson ("{'x': 1}"), NULL /* opts */, &reply, &error)); + ASSERT (!mongoc_collection_insert_one (coll, tmp_bson ("{'x': 1}"), NULL /* opts */, &reply, &error)); // writeConcernErrors are returned in the reply and not as an error ASSERT_ERROR_CONTAINS (error, 0, 0, ""); @@ -738,8 +677,7 @@ retryable_writes_original_error_find_modify (void *ctx) callbacks = mongoc_apm_callbacks_new (); // setup the test - const uint32_t server_id = - set_up_original_error_test (callbacks, &apm_ctx, "findAndModify", client); + const uint32_t server_id = set_up_original_error_test (callbacks, &apm_ctx, "findAndModify", client); // setup for findAndModify bson_t query = BSON_INITIALIZER; @@ -749,18 +687,16 @@ retryable_writes_original_error_find_modify (void *ctx) mongoc_find_and_modify_opts_set_update (opts, update); // attempt a findAndModify operation - ASSERT (!mongoc_collection_find_and_modify_with_opts ( - coll, &query, opts, &reply, &error)); + ASSERT (!mongoc_collection_find_and_modify_with_opts (coll, &query, opts, &reply, &error)); // assert error contains a writeConcernError with original error code ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_WRITE_CONCERN, 91, ""); // the reply holds the original error information - ASSERT_MATCH ( - &reply, - "{'lastErrorObject' : { 'n': 0, 'updatedExisting' : false }, 'value' : " - "null, 'writeConcernError' : { 'code': 91 }, 'errorLabels' : [ " - "'RetryableWriteError' ], 'ok' : 1.0}"); + ASSERT_MATCH (&reply, + "{'lastErrorObject' : { 'n': 0, 'updatedExisting' : false }, 'value' : " + "null, 'writeConcernError' : { 'code': 91 }, 'errorLabels' : [ " + "'RetryableWriteError' ], 'ok' : 1.0}"); cleanup_original_error_test (client, server_id, &reply, coll, callbacks); mongoc_find_and_modify_opts_destroy (opts); @@ -786,20 +722,12 @@ retryable_writes_original_error_general_command (void *ctx) callbacks = mongoc_apm_callbacks_new (); // setup test - const uint32_t server_id = - set_up_original_error_test (callbacks, &apm_ctx, "insert", client); + const uint32_t server_id = set_up_original_error_test (callbacks, &apm_ctx, "insert", client); - bson_t *cmd = BCON_NEW ("insert", - mongoc_collection_get_name (coll), - "documents", - "[", - "{", - "}", - "]"); + bson_t *cmd = BCON_NEW ("insert", mongoc_collection_get_name (coll), "documents", "[", "{", "}", "]"); // attempt an insert operation - ASSERT (!mongoc_client_write_command_with_opts ( - client, "test", cmd, NULL, &reply, &error)); + ASSERT (!mongoc_client_write_command_with_opts (client, "test", cmd, NULL, &reply, &error)); // assert error contains a writeConcernError with original error code ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_WRITE_CONCERN, 91, ""); @@ -846,9 +774,7 @@ _tracks_new_server_cb (const mongoc_apm_command_started_t *event) _tracks_new_server_counters_t *counters; cmd_name = mongoc_apm_command_started_get_command_name (event); - counters = - (_tracks_new_server_counters_t *) mongoc_apm_command_started_get_context ( - event); + counters = (_tracks_new_server_counters_t *) mongoc_apm_command_started_get_context (event); if (0 == strcmp (cmd_name, "insert")) { counters->num_inserts++; @@ -889,19 +815,14 @@ test_bulk_retry_tracks_new_server (void *unused) /* The bulk write contains two operations, an insert, followed by an * update. */ - ret = mongoc_bulk_operation_insert_with_opts ( - bulk, tmp_bson ("{'x': 1}"), NULL /* opts */, &error); + ret = mongoc_bulk_operation_insert_with_opts (bulk, tmp_bson ("{'x': 1}"), NULL /* opts */, &error); ASSERT_OR_PRINT (ret, error); - mongoc_bulk_operation_update_one (bulk, - tmp_bson ("{}"), - tmp_bson ("{'$inc': {'x': 1}}"), - false /* upsert */); + mongoc_bulk_operation_update_one (bulk, tmp_bson ("{}"), tmp_bson ("{'$inc': {'x': 1}}"), false /* upsert */); /* Explicitly tell the bulk write to use a secondary. That will result in * a retryable error, causing the first command to be sent twice. */ read_prefs = mongoc_read_prefs_new (MONGOC_READ_SECONDARY); - sd = mongoc_client_select_server ( - client, false /* for_writes */, read_prefs, &error); + sd = mongoc_client_select_server (client, false /* for_writes */, read_prefs, &error); ASSERT_OR_PRINT (sd, error); mongoc_bulk_operation_set_hint (bulk, mongoc_server_description_id (sd)); ret = mongoc_bulk_operation_execute (bulk, NULL /* reply */, &error); @@ -913,9 +834,7 @@ test_bulk_retry_tracks_new_server (void *unused) * the first try. */ ASSERT_CMPINT (counters.num_inserts, ==, 2); ASSERT_CMPINT (counters.num_updates, ==, 1); - ASSERT_CMPINT (mongoc_bulk_operation_get_hint (bulk), - !=, - mongoc_server_description_id (sd)); + ASSERT_CMPINT (mongoc_bulk_operation_get_hint (bulk), !=, mongoc_server_description_id (sd)); mongoc_apm_callbacks_destroy (callbacks); mongoc_server_description_destroy (sd); @@ -931,21 +850,17 @@ typedef struct _test_retry_writes_sharded_on_other_mongos_ctx { } test_retry_writes_sharded_on_other_mongos_ctx; static void -_test_retry_writes_sharded_on_other_mongos_cb ( - const mongoc_apm_command_failed_t *event) +_test_retry_writes_sharded_on_other_mongos_cb (const mongoc_apm_command_failed_t *event) { BSON_ASSERT_PARAM (event); test_retry_writes_sharded_on_other_mongos_ctx *const ctx = - (test_retry_writes_sharded_on_other_mongos_ctx *) - mongoc_apm_command_failed_get_context (event); + (test_retry_writes_sharded_on_other_mongos_ctx *) mongoc_apm_command_failed_get_context (event); BSON_ASSERT (ctx); - ASSERT_WITH_MSG (ctx->count < 2, - "expected at most two failpoints to trigger"); + ASSERT_WITH_MSG (ctx->count < 2, "expected at most two failpoints to trigger"); - const mongoc_host_list_t *const host = - mongoc_apm_command_failed_get_host (event); + const mongoc_host_list_t *const host = mongoc_apm_command_failed_get_host (event); BSON_ASSERT (host); BSON_ASSERT (!host->next); ctx->ports[ctx->count++] = host->port; @@ -966,10 +881,8 @@ retryable_writes_sharded_on_other_mongos (void *_ctx) const size_t num_ports = sizeof (ports) / sizeof (*ports); mongoc_array_t clients = _test_get_mongos_clients (ports, num_ports); BSON_ASSERT (clients.len == 2u); - mongoc_client_t *const s0 = - _mongoc_array_index (&clients, mongoc_client_t *, 0u); - mongoc_client_t *const s1 = - _mongoc_array_index (&clients, mongoc_client_t *, 1u); + mongoc_client_t *const s0 = _mongoc_array_index (&clients, mongoc_client_t *, 0u); + mongoc_client_t *const s1 = _mongoc_array_index (&clients, mongoc_client_t *, 1u); BSON_ASSERT (s0 && s1); // Deprioritization cannot be deterministically asserted by this test due to @@ -978,23 +891,18 @@ retryable_writes_sharded_on_other_mongos (void *_ctx) for (int i = 0; i < 10; ++i) { // Configure the following fail point for both `s0` and `s1`: { - bson_t *const command = - tmp_bson ("{" - " 'configureFailPoint': 'failCommand'," - " 'mode': { 'times': 1 }," - " 'data': {" - " 'failCommands': ['insert']," - " 'errorCode': 6," - " 'errorLabels': ['RetryableWriteError']" - " }" - "}"); - - ASSERT_OR_PRINT (mongoc_client_command_simple ( - s0, "admin", command, NULL, NULL, &error), - error); - ASSERT_OR_PRINT (mongoc_client_command_simple ( - s1, "admin", command, NULL, NULL, &error), - error); + bson_t *const command = tmp_bson ("{" + " 'configureFailPoint': 'failCommand'," + " 'mode': { 'times': 1 }," + " 'data': {" + " 'failCommands': ['insert']," + " 'errorCode': 6," + " 'errorLabels': ['RetryableWriteError']" + " }" + "}"); + + ASSERT_OR_PRINT (mongoc_client_command_simple (s0, "admin", command, NULL, NULL, &error), error); + ASSERT_OR_PRINT (mongoc_client_command_simple (s1, "admin", command, NULL, NULL, &error), error); } // Create a client `client` with `retryWrites=true` that connects to the @@ -1002,10 +910,8 @@ retryable_writes_sharded_on_other_mongos (void *_ctx) // list. mongoc_client_t *client = NULL; { - const char *const host_and_port = - "mongodb://localhost:27017,localhost:27018/?retryWrites=true"; - char *const uri_str = - test_framework_add_user_password_from_env (host_and_port); + const char *const host_and_port = "mongodb://localhost:27017,localhost:27018/?retryWrites=true"; + char *const uri_str = test_framework_add_user_password_from_env (host_and_port); mongoc_uri_t *const uri = mongoc_uri_new (uri_str); client = mongoc_client_new_from_uri_with_error (uri, &error); @@ -1022,10 +928,8 @@ retryable_writes_sharded_on_other_mongos (void *_ctx) // Enable failed command event monitoring for `client`. { - mongoc_apm_callbacks_t *const callbacks = - mongoc_apm_callbacks_new (); - mongoc_apm_set_command_failed_cb ( - callbacks, _test_retry_writes_sharded_on_other_mongos_cb); + mongoc_apm_callbacks_t *const callbacks = mongoc_apm_callbacks_new (); + mongoc_apm_set_command_failed_cb (callbacks, _test_retry_writes_sharded_on_other_mongos_cb); mongoc_client_set_apm_callbacks (client, callbacks, &ctx); mongoc_apm_callbacks_destroy (callbacks); } @@ -1033,14 +937,10 @@ retryable_writes_sharded_on_other_mongos (void *_ctx) // Execute an `insert` command with `client`. Assert that the command // failed. { - mongoc_database_t *const db = - mongoc_client_get_database (client, "db"); - mongoc_collection_t *const coll = - mongoc_database_get_collection (db, "test"); - ASSERT_WITH_MSG ( - !mongoc_collection_insert_one ( - coll, tmp_bson ("{'x': 1}"), NULL, NULL, &error), - "expected insert command to fail"); + mongoc_database_t *const db = mongoc_client_get_database (client, "db"); + mongoc_collection_t *const coll = mongoc_database_get_collection (db, "test"); + ASSERT_WITH_MSG (!mongoc_collection_insert_one (coll, tmp_bson ("{'x': 1}"), NULL, NULL, &error), + "expected insert command to fail"); MONGOC_DEBUG ("insert error: %s", error.message); mongoc_collection_destroy (coll); mongoc_database_destroy (db); @@ -1056,8 +956,7 @@ retryable_writes_sharded_on_other_mongos (void *_ctx) // Assert that the failed command events occurred on different // mongoses. ASSERT_WITH_MSG ((ctx.ports[0] == 27017 || ctx.ports[0] == 27018) && - (ctx.ports[1] == 27017 || ctx.ports[1] == 27018) && - (ctx.ports[0] != ctx.ports[1]), + (ctx.ports[1] == 27017 || ctx.ports[1] == 27018) && (ctx.ports[0] != ctx.ports[1]), "expected failpoints to trigger once on each mongos, " "but observed failures on %d and %d", ctx.ports[0], @@ -1068,18 +967,13 @@ retryable_writes_sharded_on_other_mongos (void *_ctx) // Disable the fail points. { - bson_t *const command = - tmp_bson ("{" - " 'configureFailPoint': 'failCommand'," - " 'mode': 'off'" - "}"); - - ASSERT_OR_PRINT (mongoc_client_command_simple ( - s0, "admin", command, NULL, NULL, &error), - error); - ASSERT_OR_PRINT (mongoc_client_command_simple ( - s1, "admin", command, NULL, NULL, &error), - error); + bson_t *const command = tmp_bson ("{" + " 'configureFailPoint': 'failCommand'," + " 'mode': 'off'" + "}"); + + ASSERT_OR_PRINT (mongoc_client_command_simple (s0, "admin", command, NULL, NULL, &error), error); + ASSERT_OR_PRINT (mongoc_client_command_simple (s1, "admin", command, NULL, NULL, &error), error); } } @@ -1096,26 +990,23 @@ typedef struct _test_retry_writes_sharded_on_same_mongos_ctx { } test_retry_writes_sharded_on_same_mongos_ctx; static void -_test_retry_writes_sharded_on_same_mongos_cb ( - test_retry_writes_sharded_on_same_mongos_ctx *ctx, - const mongoc_apm_command_failed_t *failed, - const mongoc_apm_command_succeeded_t *succeeded) +_test_retry_writes_sharded_on_same_mongos_cb (test_retry_writes_sharded_on_same_mongos_ctx *ctx, + const mongoc_apm_command_failed_t *failed, + const mongoc_apm_command_succeeded_t *succeeded) { BSON_ASSERT_PARAM (ctx); BSON_ASSERT (failed || true); BSON_ASSERT (succeeded || true); - ASSERT_WITH_MSG ( - ctx->failed_count + ctx->succeeded_count < 2, - "expected at most two events, but observed %d failed and %d succeeded", - ctx->failed_count, - ctx->succeeded_count); + ASSERT_WITH_MSG (ctx->failed_count + ctx->succeeded_count < 2, + "expected at most two events, but observed %d failed and %d succeeded", + ctx->failed_count, + ctx->succeeded_count); if (failed) { ctx->failed_count += 1; - const mongoc_host_list_t *const host = - mongoc_apm_command_failed_get_host (failed); + const mongoc_host_list_t *const host = mongoc_apm_command_failed_get_host (failed); BSON_ASSERT (host); BSON_ASSERT (!host->next); ctx->failed_port = host->port; @@ -1124,8 +1015,7 @@ _test_retry_writes_sharded_on_same_mongos_cb ( if (succeeded) { ctx->succeeded_count += 1; - const mongoc_host_list_t *const host = - mongoc_apm_command_succeeded_get_host (succeeded); + const mongoc_host_list_t *const host = mongoc_apm_command_succeeded_get_host (succeeded); BSON_ASSERT (host); BSON_ASSERT (!host->next); ctx->succeeded_port = host->port; @@ -1133,19 +1023,15 @@ _test_retry_writes_sharded_on_same_mongos_cb ( } static void -_test_retry_writes_sharded_on_same_mongos_failed_cb ( - const mongoc_apm_command_failed_t *event) +_test_retry_writes_sharded_on_same_mongos_failed_cb (const mongoc_apm_command_failed_t *event) { - _test_retry_writes_sharded_on_same_mongos_cb ( - mongoc_apm_command_failed_get_context (event), event, NULL); + _test_retry_writes_sharded_on_same_mongos_cb (mongoc_apm_command_failed_get_context (event), event, NULL); } static void -_test_retry_writes_sharded_on_same_mongos_succeeded_cb ( - const mongoc_apm_command_succeeded_t *event) +_test_retry_writes_sharded_on_same_mongos_succeeded_cb (const mongoc_apm_command_succeeded_t *event) { - _test_retry_writes_sharded_on_same_mongos_cb ( - mongoc_apm_command_succeeded_get_context (event), NULL, event); + _test_retry_writes_sharded_on_same_mongos_cb (mongoc_apm_command_succeeded_get_context (event), NULL, event); } // Test that in a sharded cluster writes are retried on the same mongos when no @@ -1162,26 +1048,24 @@ retryable_writes_sharded_on_same_mongos (void *_ctx) const size_t num_ports = sizeof (ports) / sizeof (*ports); mongoc_array_t clients = _test_get_mongos_clients (ports, num_ports); BSON_ASSERT (clients.len == 1u); - mongoc_client_t *const s0 = - _mongoc_array_index (&clients, mongoc_client_t *, 0u); + mongoc_client_t *const s0 = _mongoc_array_index (&clients, mongoc_client_t *, 0u); BSON_ASSERT (s0); // Configure the following fail point for `s0`: - ASSERT_OR_PRINT (mongoc_client_command_simple ( - s0, - "admin", - tmp_bson ("{" - " 'configureFailPoint': 'failCommand'," - " 'mode': { 'times': 1 }," - " 'data': {" - " 'failCommands': ['insert']," - " 'errorCode': 6," - " 'errorLabels': ['RetryableWriteError']" - " }" - "}"), - NULL, - NULL, - &error), + ASSERT_OR_PRINT (mongoc_client_command_simple (s0, + "admin", + tmp_bson ("{" + " 'configureFailPoint': 'failCommand'," + " 'mode': { 'times': 1 }," + " 'data': {" + " 'failCommands': ['insert']," + " 'errorCode': 6," + " 'errorLabels': ['RetryableWriteError']" + " }" + "}"), + NULL, + NULL, + &error), error); // Create a client client with `directConnection=false` (when not set by @@ -1189,11 +1073,9 @@ retryable_writes_sharded_on_same_mongos (void *_ctx) // same single mongos as `s0`. mongoc_client_t *client = NULL; { - const char *const host_and_port = - "mongodb://localhost:27017/" - "?retryWrites=true&directConnection=false"; - char *const uri_str = - test_framework_add_user_password_from_env (host_and_port); + const char *const host_and_port = "mongodb://localhost:27017/" + "?retryWrites=true&directConnection=false"; + char *const uri_str = test_framework_add_user_password_from_env (host_and_port); mongoc_uri_t *const uri = mongoc_uri_new (uri_str); client = mongoc_client_new_from_uri_with_error (uri, &error); @@ -1214,10 +1096,8 @@ retryable_writes_sharded_on_same_mongos (void *_ctx) // Enable succeeded and failed command event monitoring for `client`. { mongoc_apm_callbacks_t *const callbacks = mongoc_apm_callbacks_new (); - mongoc_apm_set_command_failed_cb ( - callbacks, _test_retry_writes_sharded_on_same_mongos_failed_cb); - mongoc_apm_set_command_succeeded_cb ( - callbacks, _test_retry_writes_sharded_on_same_mongos_succeeded_cb); + mongoc_apm_set_command_failed_cb (callbacks, _test_retry_writes_sharded_on_same_mongos_failed_cb); + mongoc_apm_set_command_succeeded_cb (callbacks, _test_retry_writes_sharded_on_same_mongos_succeeded_cb); mongoc_client_set_apm_callbacks (client, callbacks, &ctx); mongoc_apm_callbacks_destroy (callbacks); } @@ -1225,12 +1105,9 @@ retryable_writes_sharded_on_same_mongos (void *_ctx) // Execute an `insert` command with `client`. Assert that the command // succeeded. { - mongoc_database_t *const db = - mongoc_client_get_database (client, "db"); - mongoc_collection_t *const coll = - mongoc_database_get_collection (db, "test"); - ASSERT_WITH_MSG (mongoc_collection_insert_one ( - coll, tmp_bson ("{'x': 1}"), NULL, NULL, &error), + mongoc_database_t *const db = mongoc_client_get_database (client, "db"); + mongoc_collection_t *const coll = mongoc_database_get_collection (db, "test"); + ASSERT_WITH_MSG (mongoc_collection_insert_one (coll, tmp_bson ("{'x': 1}"), NULL, NULL, &error), "expecting insert to succeed, but observed error: %s", error.message); mongoc_collection_destroy (coll); @@ -1242,36 +1119,33 @@ retryable_writes_sharded_on_same_mongos (void *_ctx) // Assert that exactly one failed command event and one succeeded // command event occurred. - ASSERT_WITH_MSG ( - ctx.failed_count == 1 && ctx.succeeded_count == 1, - "expected exactly one failed event and one succeeded " - "event, but observed %d failures and %d successes with error: %s", - ctx.failed_count, - ctx.succeeded_count, - ctx.succeeded_count > 1 ? "none" : error.message); + ASSERT_WITH_MSG (ctx.failed_count == 1 && ctx.succeeded_count == 1, + "expected exactly one failed event and one succeeded " + "event, but observed %d failures and %d successes with error: %s", + ctx.failed_count, + ctx.succeeded_count, + ctx.succeeded_count > 1 ? "none" : error.message); // Assert that both events occurred on the same mongos. - ASSERT_WITH_MSG ( - ctx.failed_port == ctx.succeeded_port, - "expected failed and succeeded events on the same mongos, but " - "instead observed port %d (failed) and port %d (succeeded)", - ctx.failed_port, - ctx.succeeded_port); + ASSERT_WITH_MSG (ctx.failed_port == ctx.succeeded_port, + "expected failed and succeeded events on the same mongos, but " + "instead observed port %d (failed) and port %d (succeeded)", + ctx.failed_port, + ctx.succeeded_port); mongoc_client_destroy (client); } // Disable the fail point. - ASSERT_OR_PRINT (mongoc_client_command_simple ( - s0, - "admin", - tmp_bson ("{" - " 'configureFailPoint': 'failCommand'," - " 'mode': 'off'" - "}"), - NULL, - NULL, - &error), + ASSERT_OR_PRINT (mongoc_client_command_simple (s0, + "admin", + tmp_bson ("{" + " 'configureFailPoint': 'failCommand'," + " 'mode': 'off'" + "}"), + NULL, + NULL, + &error), error); mongoc_client_destroy (s0); @@ -1283,10 +1157,8 @@ void test_retryable_writes_install (TestSuite *suite) { test_all_spec_tests (suite); - TestSuite_AddMockServerTest (suite, - "/retryable_writes/failover", - test_rs_failover, - test_framework_skip_if_no_crypto); + TestSuite_AddMockServerTest ( + suite, "/retryable_writes/failover", test_rs_failover, test_framework_skip_if_no_crypto); TestSuite_AddFull (suite, "/retryable_writes/command_with_opts", test_command_with_opts, @@ -1305,26 +1177,18 @@ test_retryable_writes_install (TestSuite *suite) "/retryable_writes/delete_one_unacknowledged", test_delete_one_unacknowledged, test_framework_skip_if_no_crypto); + TestSuite_AddMockServerTest ( + suite, "/retryable_writes/remove_unacknowledged", test_remove_unacknowledged, test_framework_skip_if_no_crypto); TestSuite_AddMockServerTest (suite, - "/retryable_writes/remove_unacknowledged", - test_remove_unacknowledged, + "/retryable_writes/bulk_operation_execute_unacknowledged", + test_bulk_operation_execute_unacknowledged, + test_framework_skip_if_no_crypto); + TestSuite_AddFull ( + suite, "/retryable_writes/no_crypto", test_retry_no_crypto, NULL, NULL, test_framework_skip_if_crypto); + TestSuite_AddMockServerTest (suite, + "/retryable_writes/unsupported_storage_engine_error", + test_unsupported_storage_engine_error, test_framework_skip_if_no_crypto); - TestSuite_AddMockServerTest ( - suite, - "/retryable_writes/bulk_operation_execute_unacknowledged", - test_bulk_operation_execute_unacknowledged, - test_framework_skip_if_no_crypto); - TestSuite_AddFull (suite, - "/retryable_writes/no_crypto", - test_retry_no_crypto, - NULL, - NULL, - test_framework_skip_if_crypto); - TestSuite_AddMockServerTest ( - suite, - "/retryable_writes/unsupported_storage_engine_error", - test_unsupported_storage_engine_error, - test_framework_skip_if_no_crypto); TestSuite_AddFull (suite, "/retryable_writes/bulk_tracks_new_server", test_bulk_retry_tracks_new_server, diff --git a/src/libmongoc/tests/test-mongoc-sample-commands.c b/src/libmongoc/tests/test-mongoc-sample-commands.c index 18656dd8de..3ab321a40e 100644 --- a/src/libmongoc/tests/test-mongoc-sample-commands.c +++ b/src/libmongoc/tests/test-mongoc-sample-commands.c @@ -2485,9 +2485,7 @@ insert_pet (mongoc_collection_t *collection, bool is_adoptable) rc = mongoc_collection_insert_one (collection, doc, NULL, NULL, &error); if (!rc) { - MONGOC_ERROR ("insert into pets.%s failed: %s", - mongoc_collection_get_name (collection), - error.message); + MONGOC_ERROR ("insert into pets.%s failed: %s", mongoc_collection_get_name (collection), error.message); goto cleanup; } @@ -2498,8 +2496,7 @@ insert_pet (mongoc_collection_t *collection, bool is_adoptable) static bool -pet_setup (mongoc_collection_t *cats_collection, - mongoc_collection_t *dogs_collection) +pet_setup (mongoc_collection_t *cats_collection, mongoc_collection_t *dogs_collection) { bool ok = true; @@ -2563,8 +2560,7 @@ accumulate_adoptable_count (const mongoc_client_session_t *cs, "}", "]"); - cursor = mongoc_collection_aggregate ( - collection, MONGOC_QUERY_NONE, pipeline, &opts, NULL); + cursor = mongoc_collection_aggregate (collection, MONGOC_QUERY_NONE, pipeline, &opts, NULL); bson_destroy (&opts); rc = mongoc_cursor_next (cursor, &doc); @@ -2665,9 +2661,7 @@ test_example_59 (mongoc_database_t *db) /* End Snapshot Query Example 1 */ if (adoptable_pets_count != 2) { - MONGOC_ERROR ( - "there should be exatly 2 adoptable_pets_count, found: %" PRId64, - adoptable_pets_count); + MONGOC_ERROR ("there should be exatly 2 adoptable_pets_count, found: %" PRId64, adoptable_pets_count); } /* Start Snapshot Query Example 1 Post */ @@ -2696,15 +2690,10 @@ retail_setup (mongoc_collection_t *sales_collection) mongoc_collection_drop (sales_collection, NULL); - doc = BCON_NEW ("shoeType", - BCON_UTF8 ("boot"), - "price", - BCON_INT64 (30), - "saleDate", - BCON_DATE_TIME (unix_time_now)); + doc = + BCON_NEW ("shoeType", BCON_UTF8 ("boot"), "price", BCON_INT64 (30), "saleDate", BCON_DATE_TIME (unix_time_now)); - ok = - mongoc_collection_insert_one (sales_collection, doc, NULL, NULL, &error); + ok = mongoc_collection_insert_one (sales_collection, doc, NULL, NULL, &error); if (!ok) { MONGOC_ERROR ("insert into retail.sales failed: %s", error.message); goto cleanup; @@ -2794,8 +2783,7 @@ test_example_60 (mongoc_database_t *db) "}", "]"); - cursor = mongoc_collection_aggregate ( - sales_collection, MONGOC_QUERY_NONE, pipeline, &opts, NULL); + cursor = mongoc_collection_aggregate (sales_collection, MONGOC_QUERY_NONE, pipeline, &opts, NULL); bson_destroy (&opts); ok = mongoc_cursor_next (cursor, &doc); @@ -2821,8 +2809,7 @@ test_example_60 (mongoc_database_t *db) /* End Snapshot Query Example 2 */ if (total_sales != 1) { - MONGOC_ERROR ("there should be exactly 1 total_sales, found: %" PRId64, - total_sales); + MONGOC_ERROR ("there should be exactly 1 total_sales, found: %" PRId64, total_sales); } /* Start Snapshot Query Example 2 Post */ @@ -3561,16 +3548,12 @@ insert_employee (mongoc_client_t *client, int employee) /* clang-format on */ /* Start Transactions Retry Example 3 */ /* takes a session, an out-param for server reply, and out-param for error. */ -typedef bool (*txn_func_t) (mongoc_client_session_t *, - bson_t *, - bson_error_t *); +typedef bool (*txn_func_t) (mongoc_client_session_t *, bson_t *, bson_error_t *); /* runs transactions with retry logic */ bool -run_transaction_with_retry (txn_func_t txn_func, - mongoc_client_session_t *cs, - bson_error_t *error) +run_transaction_with_retry (txn_func_t txn_func, mongoc_client_session_t *cs, bson_error_t *error) { bson_t reply; bool r; @@ -3633,9 +3616,7 @@ commit_with_retry (mongoc_client_session_t *cs, bson_error_t *error) /* updates two collections in a transaction and calls commit_with_retry */ bool -update_employee_info (mongoc_client_session_t *cs, - bson_t *reply, - bson_error_t *error) +update_employee_info (mongoc_client_session_t *cs, bson_t *reply, bson_error_t *error) { mongoc_client_t *client; mongoc_collection_t *employees; @@ -3677,8 +3658,7 @@ update_employee_info (mongoc_client_session_t *cs, update = BCON_NEW ("$set", "{", "status", "Inactive", "}"); /* mongoc_collection_update_one will reinitialize reply */ bson_destroy (reply); - r = mongoc_collection_update_one ( - employees, filter, update, &opts, reply, error); + r = mongoc_collection_update_one (employees, filter, update, &opts, reply, error); if (!r) { goto abort; @@ -3733,8 +3713,7 @@ example_func (mongoc_client_t *client) r = run_transaction_with_retry (update_employee_info, cs, &error); if (!r) { - MONGOC_ERROR ("Could not update employee, permanent error: %s", - error.message); + MONGOC_ERROR ("Could not update employee, permanent error: %s", error.message); } mongoc_client_session_destroy (cs); @@ -3791,10 +3770,7 @@ get_client_for_version_api_example (void) } static bool -callback (mongoc_client_session_t *session, - void *ctx, - bson_t **reply, - bson_error_t *error); +callback (mongoc_client_session_t *session, void *ctx, bson_t **reply, bson_error_t *error); /* See additional usage of mongoc_client_session_with_transaction at * https://www.mongoc.org/libmongoc/1.15.3/mongoc_client_session_with_transaction.html @@ -3835,8 +3811,7 @@ with_transaction_example (bson_error_t *error) mongoc_write_concern_append (wc, insert_opts); coll = mongoc_client_get_collection (client, "mydb1", "foo"); doc = BCON_NEW ("abc", BCON_INT32 (0)); - ret = mongoc_collection_insert_one ( - coll, doc, insert_opts, NULL /* reply */, error); + ret = mongoc_collection_insert_one (coll, doc, insert_opts, NULL /* reply */, error); if (!ret) { goto fail; } @@ -3844,8 +3819,7 @@ with_transaction_example (bson_error_t *error) mongoc_collection_destroy (coll); coll = mongoc_client_get_collection (client, "mydb2", "bar"); doc = BCON_NEW ("xyz", BCON_INT32 (0)); - ret = mongoc_collection_insert_one ( - coll, doc, insert_opts, NULL /* reply */, error); + ret = mongoc_collection_insert_one (coll, doc, insert_opts, NULL /* reply */, error); if (!ret) { goto fail; } @@ -3867,8 +3841,7 @@ with_transaction_example (bson_error_t *error) /* Step 3: Use mongoc_client_session_with_transaction to start a transaction, * execute the callback, and commit (or abort on error). */ - ret = mongoc_client_session_with_transaction ( - session, callback, txn_opts, NULL /* ctx */, NULL /* reply */, error); + ret = mongoc_client_session_with_transaction (session, callback, txn_opts, NULL /* ctx */, NULL /* reply */, error); if (!ret) { goto fail; } @@ -3890,10 +3863,7 @@ with_transaction_example (bson_error_t *error) /* Define the callback that specifies the sequence of operations to perform * inside the transactions. */ static bool -callback (mongoc_client_session_t *session, - void *ctx, - bson_t **reply, - bson_error_t *error) +callback (mongoc_client_session_t *session, void *ctx, bson_t **reply, bson_error_t *error) { mongoc_client_t *client = NULL; mongoc_collection_t *coll = NULL; @@ -3906,8 +3876,7 @@ callback (mongoc_client_session_t *session, client = mongoc_client_session_get_client (session); coll = mongoc_client_get_collection (client, "mydb1", "foo"); doc = BCON_NEW ("abc", BCON_INT32 (1)); - ret = - mongoc_collection_insert_one (coll, doc, NULL /* opts */, *reply, error); + ret = mongoc_collection_insert_one (coll, doc, NULL /* opts */, *reply, error); if (!ret) { goto fail; } @@ -3915,8 +3884,7 @@ callback (mongoc_client_session_t *session, mongoc_collection_destroy (coll); coll = mongoc_client_get_collection (client, "mydb2", "bar"); doc = BCON_NEW ("xyz", BCON_INT32 (999)); - ret = - mongoc_collection_insert_one (coll, doc, NULL /* opts */, *reply, error); + ret = mongoc_collection_insert_one (coll, doc, NULL /* opts */, *reply, error); if (!ret) { goto fail; } @@ -4198,8 +4166,7 @@ _test_sample_versioned_api_example_5_6_7_8 (void) BCON_INT32 (5), "date", BCON_DATE_TIME (iso_to_unix ("2021-03-16T20:20:13Z"))); - ok = mongoc_collection_insert_many ( - sales, (const bson_t **) docs, N_DOCS, NULL /* opts */, &reply, &error); + ok = mongoc_collection_insert_many (sales, (const bson_t **) docs, N_DOCS, NULL /* opts */, &reply, &error); /* End Versioned API Example 5 */ ASSERT_OR_PRINT (ok, error); bson_destroy (&reply); @@ -4211,21 +4178,18 @@ _test_sample_versioned_api_example_5_6_7_8 (void) // and 5.3.2 (see SERVER-63850 and DRIVERS-2228). This test assumes count // command is not in API version 1. Skip until examples are updated // accordingly (see DRIVERS-1846). - const bool should_skip = - (version >= 106100100) || // [6.0.0, inf) - (version >= 105103102 && version < 106100100) || // [5.3.2, 6.0.0) - (version >= 105100109 && version < 105101100); // [5.0.9, 5.1.0) + const bool should_skip = (version >= 106100100) || // [6.0.0, inf) + (version >= 105103102 && version < 106100100) || // [5.3.2, 6.0.0) + (version >= 105100109 && version < 105101100); // [5.0.9, 5.1.0) if (!should_skip) { bson_t *cmd = BCON_NEW ("count", "sales"); - ok = mongoc_database_command_simple ( - db, cmd, NULL /* read_prefs */, &reply, &error); - ASSERT_ERROR_CONTAINS ( - error, - MONGOC_ERROR_SERVER, - 323, - "Provided apiStrict:true, but the command count " - "is not in API Version 1"); + ok = mongoc_database_command_simple (db, cmd, NULL /* read_prefs */, &reply, &error); + ASSERT_ERROR_CONTAINS (error, + MONGOC_ERROR_SERVER, + 323, + "Provided apiStrict:true, but the command count " + "is not in API Version 1"); ASSERT (!ok); bson_destroy (&reply); bson_destroy (cmd); @@ -4245,8 +4209,7 @@ _test_sample_versioned_api_example_5_6_7_8 (void) /* Start Versioned API Example 7 */ filter = bson_new (); - count = mongoc_collection_count_documents ( - sales, filter, NULL /* opts */, NULL /* read_prefs */, &reply, &error); + count = mongoc_collection_count_documents (sales, filter, NULL /* opts */, NULL /* read_prefs */, &reply, &error); /* End Versioned API Example 7 */ if (N_DOCS != count) { test_error ("expected %d documents, got %" PRId64, N_DOCS, count); @@ -4379,10 +4342,5 @@ void test_samples_install (TestSuite *suite) { TestSuite_AddLive (suite, "/Samples", test_sample_commands); - TestSuite_AddFull (suite, - "/Samples/with_txn", - test_with_txn_example, - NULL, - NULL, - test_framework_skip_if_no_txns); + TestSuite_AddFull (suite, "/Samples/with_txn", test_with_txn_example, NULL, NULL, test_framework_skip_if_no_txns); } diff --git a/src/libmongoc/tests/test-mongoc-scram.c b/src/libmongoc/tests/test-mongoc-scram.c index 6421400a33..3173dd391e 100644 --- a/src/libmongoc/tests/test-mongoc-scram.c +++ b/src/libmongoc/tests/test-mongoc-scram.c @@ -23,14 +23,11 @@ test_mongoc_scram_step_username_not_set (void) _mongoc_scram_init (&scram, MONGOC_CRYPTO_ALGORITHM_SHA_1); _mongoc_scram_set_pass (&scram, "password"); - success = _mongoc_scram_step ( - &scram, buf, buflen, buf, sizeof buf, &buflen, &error); + success = _mongoc_scram_step (&scram, buf, buflen, buf, sizeof buf, &buflen, &error); ASSERT (!success); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_SCRAM, - MONGOC_ERROR_SCRAM_PROTOCOL_ERROR, - "SCRAM Failure: username is not set"); + ASSERT_ERROR_CONTAINS ( + error, MONGOC_ERROR_SCRAM, MONGOC_ERROR_SCRAM_PROTOCOL_ERROR, "SCRAM Failure: username is not set"); _mongoc_scram_destroy (&scram); } @@ -56,13 +53,11 @@ test_iteration_count (int count, bool should_succeed) char *server_response; bool success; - server_response = bson_strdup_printf ( - "r=YWJjZA==YWJjZA==,s=r6+P1iLmSJvhrRyuFi6Wsg==,i=%d", count); + server_response = bson_strdup_printf ("r=YWJjZA==YWJjZA==,s=r6+P1iLmSJvhrRyuFi6Wsg==,i=%d", count); /* set up the scram state to immediately test step 2. */ _mongoc_scram_init (&scram, MONGOC_CRYPTO_ALGORITHM_SHA_1); _mongoc_scram_set_pass (&scram, "password"); - bson_strncpy ( - scram.encoded_nonce, client_nonce, sizeof (scram.encoded_nonce)); + bson_strncpy (scram.encoded_nonce, client_nonce, sizeof (scram.encoded_nonce)); scram.encoded_nonce_len = (int32_t) strlen (client_nonce); scram.auth_message = bson_malloc0 (4096); scram.auth_messagemax = 4096; @@ -70,8 +65,7 @@ test_iteration_count (int count, bool should_succeed) memcpy (buf, server_response, strlen (server_response) + 1); buflen = (int32_t) strlen (server_response); scram.step = 1; - success = _mongoc_scram_step ( - &scram, buf, buflen, buf, sizeof buf, &buflen, &error); + success = _mongoc_scram_step (&scram, buf, buflen, buf, sizeof buf, &buflen, &error); if (should_succeed) { ASSERT_OR_PRINT (success, error); } else { @@ -101,35 +95,32 @@ test_mongoc_scram_sasl_prep (void) char *normalized; bson_error_t err; /* examples from RFC 4013 section 3. */ - sasl_prep_testcase_t tests[] = { - // normalization - {"\x65\xCC\x81", "\xC3\xA9", true, true}, - {"\xC2\xAA", "a", true, true}, - {"Henry \xE2\x85\xA3", "Henry IV", true, true}, - {"A\xEF\xAC\x83n", "Affin", true, true}, - // mapped to nothing character (Table B.1) - {"I\xC2\xADX", "IX", true, true}, - // mapped to nothing character (Table C.1.2) - {"I\xE2\x80\x80\xC2\xA0X", "I X", true, true}, - // prohibited character - {"banana \x07 apple", "(invalid)", true, false}, - // unassigned codepoint (Table A.1) - {"banana \xe0\xAA\xBA apple", "(invalid)", true, false}, - // bidi: RandALCat but not RandALCat at beginning and end - {"\xD8\xA7\x31", "(invalid)", true, false}, - // bidi: RandALCat and LCat characters - {"\xFB\x1D apple \x09\xA8", "(invalid)", true, false}, - // bidi: RandALCat with RandALCat at beginning and end - {"\xD8\xA1 \xDC\x92", "\xD8\xA1 \xDC\x92", true, true}, - // normalization and mapped to nothing - {"I\xE2\x80\x80\xC2\xA0X \xE2\x85\xA3", "I X IV", true, true}, - {"user", "user", false, true}, - {"USER", "USER", false, true}}; + sasl_prep_testcase_t tests[] = {// normalization + {"\x65\xCC\x81", "\xC3\xA9", true, true}, + {"\xC2\xAA", "a", true, true}, + {"Henry \xE2\x85\xA3", "Henry IV", true, true}, + {"A\xEF\xAC\x83n", "Affin", true, true}, + // mapped to nothing character (Table B.1) + {"I\xC2\xADX", "IX", true, true}, + // mapped to nothing character (Table C.1.2) + {"I\xE2\x80\x80\xC2\xA0X", "I X", true, true}, + // prohibited character + {"banana \x07 apple", "(invalid)", true, false}, + // unassigned codepoint (Table A.1) + {"banana \xe0\xAA\xBA apple", "(invalid)", true, false}, + // bidi: RandALCat but not RandALCat at beginning and end + {"\xD8\xA7\x31", "(invalid)", true, false}, + // bidi: RandALCat and LCat characters + {"\xFB\x1D apple \x09\xA8", "(invalid)", true, false}, + // bidi: RandALCat with RandALCat at beginning and end + {"\xD8\xA1 \xDC\x92", "\xD8\xA1 \xDC\x92", true, true}, + // normalization and mapped to nothing + {"I\xE2\x80\x80\xC2\xA0X \xE2\x85\xA3", "I X IV", true, true}, + {"user", "user", false, true}, + {"USER", "USER", false, true}}; ntests = sizeof (tests) / sizeof (sasl_prep_testcase_t); for (i = 0; i < ntests; i++) { - ASSERT_CMPINT (tests[i].should_be_required, - ==, - _mongoc_sasl_prep_required (tests[i].original)); + ASSERT_CMPINT (tests[i].should_be_required, ==, _mongoc_sasl_prep_required (tests[i].original)); memset (&err, 0, sizeof (err)); normalized = _mongoc_sasl_prep (tests[i].original, &err); if (tests[i].should_succeed) { @@ -159,8 +150,7 @@ test_mongoc_utf8_string_length (void) ASSERT_CMPSIZE_T (_mongoc_utf8_string_length (",ase"), ==, 4u); ASSERT_CMPSIZE_T (_mongoc_utf8_string_length ("ɸɴ"), ==, 2u); ASSERT_CMPSIZE_T (_mongoc_utf8_string_length ("ྡྷ🌂e4🌕"), ==, 5u); - ASSERT_CMPSIZE_T ( - _mongoc_utf8_string_length ("no special characters"), ==, 21u); + ASSERT_CMPSIZE_T (_mongoc_utf8_string_length ("no special characters"), ==, 21u); } static void @@ -189,13 +179,11 @@ static BSON_THREAD_FUN (_scram_cache_invalidation_thread, username_number_ptr) bson_error_t error; const char *password = "mypass"; - char *username = - bson_strdup_printf ("cachetestuser%dX", *(int *) username_number_ptr); + char *username = bson_strdup_printf ("cachetestuser%dX", *(int *) username_number_ptr); bson_free (username_number_ptr); const char *uri_str = _scram_cache_invalidation_uri_str; - char *cache_test_user_uri = - test_framework_add_user_password (uri_str, username, password); + char *cache_test_user_uri = test_framework_add_user_password (uri_str, username, password); BSON_ASSERT (cache_test_user_uri); mongoc_uri_t *cache_test_uri = mongoc_uri_new (cache_test_user_uri); @@ -203,23 +191,19 @@ static BSON_THREAD_FUN (_scram_cache_invalidation_thread, username_number_ptr) // Set serverSelectionTryOnce=false so a single failed connection attempt // does not result in an error. - mongoc_uri_set_option_as_bool ( - cache_test_uri, MONGOC_URI_SERVERSELECTIONTRYONCE, false); + mongoc_uri_set_option_as_bool (cache_test_uri, MONGOC_URI_SERVERSELECTIONTRYONCE, false); - mongoc_client_t *client = - test_framework_client_new_from_uri (cache_test_uri, NULL /* api */); + mongoc_client_t *client = test_framework_client_new_from_uri (cache_test_uri, NULL /* api */); BSON_ASSERT (client); test_framework_set_ssl_opts (client); BSON_ASSERT (client); - mongoc_collection_t *collection = - mongoc_client_get_collection (client, "admin", "testcache"); + mongoc_collection_t *collection = mongoc_client_get_collection (client, "admin", "testcache"); BSON_ASSERT (collection); bson_t insert = BSON_INITIALIZER; - bool ok = - mongoc_collection_insert_one (collection, &insert, NULL, NULL, &error); + bool ok = mongoc_collection_insert_one (collection, &insert, NULL, NULL, &error); ASSERT_OR_PRINT (ok, error); mongoc_collection_destroy (collection); @@ -248,8 +232,7 @@ test_mongoc_scram_cache_invalidation (void *ctx) bson_t *roles = tmp_bson ("[{'role': 'readWrite', 'db': 'admin'}]"); - _scram_cache_invalidation_uri_str = - test_framework_get_uri_str_no_auth ("admin"); + _scram_cache_invalidation_uri_str = test_framework_get_uri_str_no_auth ("admin"); /* Remove cache test users if they already exist. * Create more test users than could exist in cache. */ @@ -258,8 +241,7 @@ test_mongoc_scram_cache_invalidation (void *ctx) char *username = bson_strdup_printf ("cachetestuser%dX", i); mongoc_database_remove_user (db, username, &error); - bool ok = - mongoc_database_add_user (db, username, password, roles, NULL, &error); + bool ok = mongoc_database_add_user (db, username, password, roles, NULL, &error); ASSERT_OR_PRINT (ok, error); bson_free (username); } @@ -268,8 +250,7 @@ test_mongoc_scram_cache_invalidation (void *ctx) for (int i = 0; i < NUM_CACHE_TEST_THREADS; i++) { int *username_number_ptr = bson_malloc (sizeof (*username_number_ptr)); *username_number_ptr = i % NUM_CACHE_TEST_USERS; - int rc = mcommon_thread_create ( - &threads[i], _scram_cache_invalidation_thread, username_number_ptr); + int rc = mcommon_thread_create (&threads[i], _scram_cache_invalidation_thread, username_number_ptr); BSON_ASSERT (rc == 0); } @@ -306,32 +287,29 @@ _create_scram_users (void) bool res; bson_error_t error; client = test_framework_new_default_client (); - res = mongoc_client_command_simple ( - client, - "admin", - tmp_bson ("{'createUser': 'sha1', 'pwd': 'sha1', 'roles': ['root'], " - "'mechanisms': ['SCRAM-SHA-1']}"), - NULL /* read_prefs */, - NULL /* reply */, - &error); + res = mongoc_client_command_simple (client, + "admin", + tmp_bson ("{'createUser': 'sha1', 'pwd': 'sha1', 'roles': ['root'], " + "'mechanisms': ['SCRAM-SHA-1']}"), + NULL /* read_prefs */, + NULL /* reply */, + &error); ASSERT_OR_PRINT (res, error); - res = mongoc_client_command_simple ( - client, - "admin", - tmp_bson ("{'createUser': 'sha256', 'pwd': 'sha256', 'roles': ['root'], " - "'mechanisms': ['SCRAM-SHA-256']}"), - NULL /* read_prefs */, - NULL /* reply */, - &error); + res = mongoc_client_command_simple (client, + "admin", + tmp_bson ("{'createUser': 'sha256', 'pwd': 'sha256', 'roles': ['root'], " + "'mechanisms': ['SCRAM-SHA-256']}"), + NULL /* read_prefs */, + NULL /* reply */, + &error); ASSERT_OR_PRINT (res, error); - res = mongoc_client_command_simple ( - client, - "admin", - tmp_bson ("{'createUser': 'both', 'pwd': 'both', 'roles': ['root'], " - "'mechanisms': ['SCRAM-SHA-1', 'SCRAM-SHA-256']}"), - NULL /* read_prefs */, - NULL /* reply */, - &error); + res = mongoc_client_command_simple (client, + "admin", + tmp_bson ("{'createUser': 'both', 'pwd': 'both', 'roles': ['root'], " + "'mechanisms': ['SCRAM-SHA-1', 'SCRAM-SHA-256']}"), + NULL /* read_prefs */, + NULL /* reply */, + &error); ASSERT_OR_PRINT (res, error); mongoc_client_destroy (client); } @@ -356,10 +334,7 @@ _drop_scram_users (void) } static void -_check_mechanism (bool pooled, - const char *client_mech, - const char *server_mechs, - const char *expected_used_mech) +_check_mechanism (bool pooled, const char *client_mech, const char *server_mechs, const char *expected_used_mech) { mock_server_t *server; mongoc_client_pool_t *client_pool = NULL; @@ -397,14 +372,9 @@ _check_mechanism (bool pooled, } else { client = test_framework_client_new_from_uri (uri, NULL); } - future = future_client_command_simple (client, - "admin", - tmp_bson ("{'dbstats': 1}"), - NULL /* read_prefs. */, - NULL /* reply. */, - NULL /* error. */); - request = - mock_server_receives_msg (server, MONGOC_QUERY_NONE, tmp_bson ("{}")); + future = future_client_command_simple ( + client, "admin", tmp_bson ("{'dbstats': 1}"), NULL /* read_prefs. */, NULL /* reply. */, NULL /* error. */); + request = mock_server_receives_msg (server, MONGOC_QUERY_NONE, tmp_bson ("{}")); sasl_doc = request_get_doc (request, 0); used_mech = bson_lookup_utf8 (sasl_doc, "mechanism"); ASSERT_CMPSTR (used_mech, expected_used_mech); @@ -424,11 +394,7 @@ _check_mechanism (bool pooled, mock_server_destroy (server); } -typedef enum { - MONGOC_TEST_NO_ERROR, - MONGOC_TEST_USER_NOT_FOUND_ERROR, - MONGOC_TEST_AUTH_ERROR -} test_error_t; +typedef enum { MONGOC_TEST_NO_ERROR, MONGOC_TEST_USER_NOT_FOUND_ERROR, MONGOC_TEST_AUTH_ERROR } test_error_t; void _check_error (const bson_error_t *error, test_error_t expected_error) @@ -445,10 +411,8 @@ _check_error (const bson_error_t *error, test_error_t expected_error) ASSERT_CMPUINT32 (error->code, ==, code); const char *const a = "Authentication failed"; const char *const b = "Unable to use"; - const bool found = - strstr (error->message, a) || strstr (error->message, b); - ASSERT_WITH_MSG ( - found, "[%s] does not contain [%s] or [%s]", error->message, a, b); + const bool found = strstr (error->message, a) || strstr (error->message, b); + ASSERT_WITH_MSG (found, "[%s] does not contain [%s] or [%s]", error->message, a, b); break; } case MONGOC_TEST_USER_NOT_FOUND_ERROR: @@ -487,8 +451,7 @@ _try_auth_from_uri (bool pooled, mongoc_uri_t *uri, test_error_t expected_error) test_framework_set_ssl_opts (client); } coll = get_test_collection (client, "try_auth"); - res = mongoc_collection_insert_one ( - coll, tmp_bson ("{'x': 1}"), NULL /* opts */, &reply, &error); + res = mongoc_collection_insert_one (coll, tmp_bson ("{'x': 1}"), NULL /* opts */, &reply, &error); if (expected_error == MONGOC_TEST_NO_ERROR) { ASSERT_OR_PRINT (res, error); @@ -510,11 +473,7 @@ _try_auth_from_uri (bool pooled, mongoc_uri_t *uri, test_error_t expected_error) /* if auth is expected to succeed, expected_error is zero'd out. */ static void -_try_auth (bool pooled, - const char *user, - const char *pwd, - const char *mechanism, - test_error_t expected_error) +_try_auth (bool pooled, const char *user, const char *pwd, const char *mechanism, test_error_t expected_error) { mongoc_uri_t *uri; @@ -539,8 +498,7 @@ _test_mongoc_scram_auth (bool pooled) _try_auth (pooled, "sha1", "sha1", NULL, MONGOC_TEST_NO_ERROR); _try_auth (pooled, "sha1", "sha1", "SCRAM-SHA-1", MONGOC_TEST_NO_ERROR); _try_auth (pooled, "sha256", "sha256", NULL, MONGOC_TEST_NO_ERROR); - _try_auth ( - pooled, "sha256", "sha256", "SCRAM-SHA-256", MONGOC_TEST_NO_ERROR); + _try_auth (pooled, "sha256", "sha256", "SCRAM-SHA-256", MONGOC_TEST_NO_ERROR); _try_auth (pooled, "both", "both", NULL, MONGOC_TEST_NO_ERROR); _try_auth (pooled, "both", "both", "SCRAM-SHA-1", MONGOC_TEST_NO_ERROR); _try_auth (pooled, "both", "both", "SCRAM-SHA-256", MONGOC_TEST_NO_ERROR); @@ -548,23 +506,17 @@ _test_mongoc_scram_auth (bool pooled) _check_mechanism (pooled, NULL, NULL, "SCRAM-SHA-1"); _check_mechanism (pooled, NULL, "'SCRAM-SHA-1'", "SCRAM-SHA-1"); _check_mechanism (pooled, NULL, "'SCRAM-SHA-256'", "SCRAM-SHA-256"); - _check_mechanism ( - pooled, NULL, "'SCRAM-SHA-1','SCRAM-SHA-256'", "SCRAM-SHA-256"); + _check_mechanism (pooled, NULL, "'SCRAM-SHA-1','SCRAM-SHA-256'", "SCRAM-SHA-256"); _check_mechanism (pooled, "SCRAM-SHA-1", NULL, "SCRAM-SHA-1"); _check_mechanism (pooled, "SCRAM-SHA-1", "'SCRAM-SHA-1'", "SCRAM-SHA-1"); _check_mechanism (pooled, "SCRAM-SHA-1", "'SCRAM-SHA-256'", "SCRAM-SHA-1"); - _check_mechanism ( - pooled, "SCRAM-SHA-1", "'SCRAM-SHA-1','SCRAM-SHA-256'", "SCRAM-SHA-1"); + _check_mechanism (pooled, "SCRAM-SHA-1", "'SCRAM-SHA-1','SCRAM-SHA-256'", "SCRAM-SHA-1"); _check_mechanism (pooled, "SCRAM-SHA-256", NULL, "SCRAM-SHA-256"); _check_mechanism (pooled, "SCRAM-SHA-256", "'SCRAM-SHA-1'", "SCRAM-SHA-256"); - _check_mechanism ( - pooled, "SCRAM-SHA-256", "'SCRAM-SHA-256'", "SCRAM-SHA-256"); - _check_mechanism (pooled, - "SCRAM-SHA-256", - "'SCRAM-SHA-1','SCRAM-SHA-256'", - "SCRAM-SHA-256"); + _check_mechanism (pooled, "SCRAM-SHA-256", "'SCRAM-SHA-256'", "SCRAM-SHA-256"); + _check_mechanism (pooled, "SCRAM-SHA-256", "'SCRAM-SHA-1','SCRAM-SHA-256'", "SCRAM-SHA-256"); /* Test some failure auths. */ _try_auth (pooled, "sha1", "bad", NULL, MONGOC_TEST_AUTH_ERROR); @@ -606,14 +558,13 @@ _skip_if_no_sha256 (void) /* Check if SCRAM-SHA-256 is a supported auth mechanism by attempting to * create a new user with it. */ - res = mongoc_client_command_simple ( - client, - "admin", - tmp_bson ("{'createUser': 'temp', 'pwd': 'sha256', 'roles': ['root'], " - "'mechanisms': ['SCRAM-SHA-256']}"), - NULL /* read_prefs */, - NULL /* reply */, - &error); + res = mongoc_client_command_simple (client, + "admin", + tmp_bson ("{'createUser': 'temp', 'pwd': 'sha256', 'roles': ['root'], " + "'mechanisms': ['SCRAM-SHA-256']}"), + NULL /* read_prefs */, + NULL /* reply */, + &error); if (res) { mongoc_database_t *db; @@ -650,24 +601,21 @@ _create_saslprep_users (void) bool res; bson_error_t error; client = test_framework_new_default_client (); - res = mongoc_client_command_simple ( - client, - "admin", - tmp_bson ("{'createUser': 'IX', 'pwd': 'IX', 'roles': ['root'], " - "'mechanisms': ['SCRAM-SHA-256']}"), - NULL /* read_prefs */, - NULL /* reply */, - &error); + res = mongoc_client_command_simple (client, + "admin", + tmp_bson ("{'createUser': 'IX', 'pwd': 'IX', 'roles': ['root'], " + "'mechanisms': ['SCRAM-SHA-256']}"), + NULL /* read_prefs */, + NULL /* reply */, + &error); ASSERT_OR_PRINT (res, error); - res = mongoc_client_command_simple ( - client, - "admin", - tmp_bson ("{'createUser': '" ROMAN_NUMERAL_NINE - "', 'pwd': '" ROMAN_NUMERAL_FOUR - "', 'roles': ['root'], 'mechanisms': ['SCRAM-SHA-256']}"), - NULL /* read_prefs */, - NULL /* reply */, - &error); + res = mongoc_client_command_simple (client, + "admin", + tmp_bson ("{'createUser': '" ROMAN_NUMERAL_NINE "', 'pwd': '" ROMAN_NUMERAL_FOUR + "', 'roles': ['root'], 'mechanisms': ['SCRAM-SHA-256']}"), + NULL /* read_prefs */, + NULL /* reply */, + &error); ASSERT_OR_PRINT (res, error); mongoc_client_destroy (client); } @@ -754,11 +702,7 @@ _test_mongoc_scram_saslprep_auth (bool pooled) _try_auth (pooled, "IX", "IX", NULL, MONGOC_TEST_NO_ERROR); _try_auth (pooled, "IX", ROMAN_NUMERAL_NINE, NULL, MONGOC_TEST_NO_ERROR); _try_auth (pooled, ROMAN_NUMERAL_NINE, "IV", NULL, MONGOC_TEST_NO_ERROR); - _try_auth (pooled, - ROMAN_NUMERAL_NINE, - ROMAN_NUMERAL_FOUR, - NULL, - MONGOC_TEST_NO_ERROR); + _try_auth (pooled, ROMAN_NUMERAL_NINE, ROMAN_NUMERAL_FOUR, NULL, MONGOC_TEST_NO_ERROR); } @@ -778,16 +722,11 @@ void test_scram_install (TestSuite *suite) { #ifdef MONGOC_ENABLE_SSL - TestSuite_Add (suite, - "/scram/username_not_set", - test_mongoc_scram_step_username_not_set); + TestSuite_Add (suite, "/scram/username_not_set", test_mongoc_scram_step_username_not_set); TestSuite_Add (suite, "/scram/sasl_prep", test_mongoc_scram_sasl_prep); - TestSuite_Add ( - suite, "/scram/iteration_count", test_mongoc_scram_iteration_count); - TestSuite_Add ( - suite, "/scram/utf8_char_length", test_mongoc_utf8_char_length); - TestSuite_Add ( - suite, "/scram/utf8_string_length", test_mongoc_utf8_string_length); + TestSuite_Add (suite, "/scram/iteration_count", test_mongoc_scram_iteration_count); + TestSuite_Add (suite, "/scram/utf8_char_length", test_mongoc_utf8_char_length); + TestSuite_Add (suite, "/scram/utf8_string_length", test_mongoc_utf8_string_length); TestSuite_Add (suite, "/scram/utf8_to_unicode", test_mongoc_utf8_to_unicode); #endif TestSuite_AddFull (suite, diff --git a/src/libmongoc/tests/test-mongoc-sdam-monitoring.c b/src/libmongoc/tests/test-mongoc-sdam-monitoring.c index 7622a970aa..720c973784 100644 --- a/src/libmongoc/tests/test-mongoc-sdam-monitoring.c +++ b/src/libmongoc/tests/test-mongoc-sdam-monitoring.c @@ -60,11 +60,9 @@ context_init (context_t *context) { bson_init (&context->events); context->n_events = 0; - _mongoc_array_init (&context->heartbeat_succeeded_durations, - sizeof (int64_t)); + _mongoc_array_init (&context->heartbeat_succeeded_durations, sizeof (int64_t)); _mongoc_array_init (&context->heartbeat_failed_durations, sizeof (int64_t)); - bson_oid_init_from_string (&context->topology_id, - "000000000000000000000000"); + bson_oid_init_from_string (&context->topology_id, "000000000000000000000000"); } static void @@ -144,8 +142,7 @@ td_to_bson (const mongoc_topology_description_t *td, bson_t *bson) } bson_init (bson); - BSON_APPEND_UTF8 ( - bson, "topologyType", mongoc_topology_description_type (td)); + BSON_APPEND_UTF8 (bson, "topologyType", mongoc_topology_description_type (td)); if (td->set_name) { BSON_APPEND_UTF8 (bson, "setName", td->set_name); @@ -172,8 +169,7 @@ server_changed (const mongoc_apm_server_changed_t *event) ASSERT (bson_oid_equal (&topology_id, &ctx->topology_id)); host_and_port = mongoc_apm_server_changed_get_host (event)->host_and_port; - sd_to_bson (mongoc_apm_server_changed_get_previous_description (event), - &prev_sd); + sd_to_bson (mongoc_apm_server_changed_get_previous_description (event), &prev_sd); sd_to_bson (mongoc_apm_server_changed_get_new_description (event), &new_sd); context_append (ctx, @@ -206,14 +202,10 @@ server_opening (const mongoc_apm_server_opening_t *event) ASSERT (bson_oid_equal (&topology_id, &ctx->topology_id)); host_and_port = mongoc_apm_server_opening_get_host (event)->host_and_port; - context_append (ctx, - BCON_NEW ("server_opening_event", - "{", - "address", - BCON_UTF8 (host_and_port), - "topologyId", - BCON_UTF8 ("42"), - "}")); + context_append ( + ctx, + BCON_NEW ( + "server_opening_event", "{", "address", BCON_UTF8 (host_and_port), "topologyId", BCON_UTF8 ("42"), "}")); } static void @@ -229,14 +221,9 @@ server_closed (const mongoc_apm_server_closed_t *event) ASSERT (bson_oid_equal (&topology_id, &ctx->topology_id)); host_and_port = mongoc_apm_server_closed_get_host (event)->host_and_port; - context_append (ctx, - BCON_NEW ("server_closed_event", - "{", - "address", - BCON_UTF8 (host_and_port), - "topologyId", - BCON_UTF8 ("42"), - "}")); + context_append ( + ctx, + BCON_NEW ("server_closed_event", "{", "address", BCON_UTF8 (host_and_port), "topologyId", BCON_UTF8 ("42"), "}")); } static void @@ -252,10 +239,8 @@ topology_changed (const mongoc_apm_topology_changed_t *event) mongoc_apm_topology_changed_get_topology_id (event, &topology_id); ASSERT (bson_oid_equal (&topology_id, &ctx->topology_id)); - td_to_bson (mongoc_apm_topology_changed_get_previous_description (event), - &prev_td); - td_to_bson (mongoc_apm_topology_changed_get_new_description (event), - &new_td); + td_to_bson (mongoc_apm_topology_changed_get_previous_description (event), &prev_td); + td_to_bson (mongoc_apm_topology_changed_get_new_description (event), &new_td); context_append (ctx, BCON_NEW ("topology_description_changed_event", @@ -284,10 +269,7 @@ topology_opening (const mongoc_apm_topology_opening_t *event) ctx = (context_t *) mongoc_apm_topology_opening_get_context (event); mongoc_apm_topology_opening_get_topology_id (event, &ctx->topology_id); - context_append ( - ctx, - BCON_NEW ( - "topology_opening_event", "{", "topologyId", BCON_UTF8 ("42"), "}")); + context_append (ctx, BCON_NEW ("topology_opening_event", "{", "topologyId", BCON_UTF8 ("42"), "}")); } static void @@ -299,10 +281,7 @@ topology_closed (const mongoc_apm_topology_closed_t *event) ctx = (context_t *) mongoc_apm_topology_closed_get_context (event); mongoc_apm_topology_closed_get_topology_id (event, &topology_id); ASSERT (bson_oid_equal (&topology_id, &ctx->topology_id)); - context_append ( - ctx, - BCON_NEW ( - "topology_closed_event", "{", "topologyId", BCON_UTF8 ("42"), "}")); + context_append (ctx, BCON_NEW ("topology_closed_event", "{", "topologyId", BCON_UTF8 ("42"), "}")); } /* no standard tests in the specs repo for heartbeat events, so invent some */ @@ -314,39 +293,33 @@ server_heartbeat_started (const mongoc_apm_server_heartbeat_started_t *event) ctx = (context_t *) mongoc_apm_server_heartbeat_started_get_context (event); host = mongoc_apm_server_heartbeat_started_get_host (event); - context_append ( - ctx, - BCON_NEW ( - "heartbeat_started_event", - "{", - "host", - BCON_UTF8 (host->host_and_port), - "awaited", - BCON_BOOL (mongoc_apm_server_heartbeat_started_get_awaited (event)), - "}")); + context_append (ctx, + BCON_NEW ("heartbeat_started_event", + "{", + "host", + BCON_UTF8 (host->host_and_port), + "awaited", + BCON_BOOL (mongoc_apm_server_heartbeat_started_get_awaited (event)), + "}")); } static void -server_heartbeat_succeeded ( - const mongoc_apm_server_heartbeat_succeeded_t *event) +server_heartbeat_succeeded (const mongoc_apm_server_heartbeat_succeeded_t *event) { context_t *ctx; const mongoc_host_list_t *host; int64_t duration; - ctx = - (context_t *) mongoc_apm_server_heartbeat_succeeded_get_context (event); + ctx = (context_t *) mongoc_apm_server_heartbeat_succeeded_get_context (event); host = mongoc_apm_server_heartbeat_succeeded_get_host (event); - context_append ( - ctx, - BCON_NEW ( - "heartbeat_succeeded_event", - "{", - "host", - BCON_UTF8 (host->host_and_port), - "awaited", - BCON_BOOL (mongoc_apm_server_heartbeat_succeeded_get_awaited (event)), - "}")); + context_append (ctx, + BCON_NEW ("heartbeat_succeeded_event", + "{", + "host", + BCON_UTF8 (host->host_and_port), + "awaited", + BCON_BOOL (mongoc_apm_server_heartbeat_succeeded_get_awaited (event)), + "}")); duration = mongoc_apm_server_heartbeat_succeeded_get_duration (event); _mongoc_array_append_val (&ctx->heartbeat_succeeded_durations, duration); @@ -361,16 +334,14 @@ server_heartbeat_failed (const mongoc_apm_server_heartbeat_failed_t *event) ctx = (context_t *) mongoc_apm_server_heartbeat_failed_get_context (event); host = mongoc_apm_server_heartbeat_failed_get_host (event); - context_append ( - ctx, - BCON_NEW ( - "heartbeat_failed_event", - "{", - "host", - BCON_UTF8 (host->host_and_port), - "awaited", - BCON_BOOL (mongoc_apm_server_heartbeat_failed_get_awaited (event)), - "}")); + context_append (ctx, + BCON_NEW ("heartbeat_failed_event", + "{", + "host", + BCON_UTF8 (host->host_and_port), + "awaited", + BCON_BOOL (mongoc_apm_server_heartbeat_failed_get_awaited (event)), + "}")); duration = mongoc_apm_server_heartbeat_failed_get_duration (event); _mongoc_array_append_val (&ctx->heartbeat_failed_durations, duration); @@ -393,8 +364,7 @@ topology_event_callbacks (void) } static void -client_set_topology_event_callbacks (mongoc_client_t *client, - context_t *context) +client_set_topology_event_callbacks (mongoc_client_t *client, context_t *context) { mongoc_apm_callbacks_t *callbacks; @@ -406,8 +376,7 @@ client_set_topology_event_callbacks (mongoc_client_t *client, } static void -pool_set_topology_event_callbacks (mongoc_client_pool_t *pool, - context_t *context) +pool_set_topology_event_callbacks (mongoc_client_pool_t *pool, context_t *context) { mongoc_apm_callbacks_t *callbacks; @@ -424,19 +393,15 @@ heartbeat_event_callbacks (void) mongoc_apm_callbacks_t *callbacks; callbacks = mongoc_apm_callbacks_new (); - mongoc_apm_set_server_heartbeat_started_cb (callbacks, - server_heartbeat_started); - mongoc_apm_set_server_heartbeat_succeeded_cb (callbacks, - server_heartbeat_succeeded); - mongoc_apm_set_server_heartbeat_failed_cb (callbacks, - server_heartbeat_failed); + mongoc_apm_set_server_heartbeat_started_cb (callbacks, server_heartbeat_started); + mongoc_apm_set_server_heartbeat_succeeded_cb (callbacks, server_heartbeat_succeeded); + mongoc_apm_set_server_heartbeat_failed_cb (callbacks, server_heartbeat_failed); return callbacks; } static void -client_set_heartbeat_event_callbacks (mongoc_client_t *client, - context_t *context) +client_set_heartbeat_event_callbacks (mongoc_client_t *client, context_t *context) { mongoc_apm_callbacks_t *callbacks; @@ -448,8 +413,7 @@ client_set_heartbeat_event_callbacks (mongoc_client_t *client, } static void -pool_set_heartbeat_event_callbacks (mongoc_client_pool_t *pool, - context_t *context) +pool_set_heartbeat_event_callbacks (mongoc_client_pool_t *pool, context_t *context) { mongoc_apm_callbacks_t *callbacks; @@ -524,9 +488,7 @@ test_sdam_monitoring_cb (bson_t *test) bson_iter_bson (&outcome_iter, &events_expected); check_json_sdam_events (&context.events, &events_expected); } else { - fprintf (stderr, - "ERROR: unparsed test field %s\n", - bson_iter_key (&outcome_iter)); + fprintf (stderr, "ERROR: unparsed test field %s\n", bson_iter_key (&outcome_iter)); BSON_ASSERT (false); } } @@ -546,10 +508,7 @@ test_sdam_monitoring_cb (bson_t *test) static void test_all_spec_tests (TestSuite *suite) { - install_json_test_suite (suite, - JSON_DIR, - "server_discovery_and_monitoring/monitoring", - &test_sdam_monitoring_cb); + install_json_test_suite (suite, JSON_DIR, "server_discovery_and_monitoring/monitoring", &test_sdam_monitoring_cb); } static void @@ -575,8 +534,7 @@ _test_topology_events (bool pooled) client_set_topology_event_callbacks (client, &context); } - r = mongoc_client_command_simple ( - client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); + r = mongoc_client_command_simple (client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); ASSERT_OR_PRINT (r, error); if (pooled) { @@ -634,8 +592,7 @@ test_topology_events_disabled (void) client = test_framework_new_default_client (); client_set_topology_event_callbacks (client, &context); - r = mongoc_client_command_simple ( - client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); + r = mongoc_client_command_simple (client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); ASSERT_OR_PRINT (r, error); /* disable callbacks before destroying so we don't see a topology closed @@ -718,8 +675,7 @@ _test_heartbeat_events (bool pooled, bool succeeded) } /* trigger "hello" handshake */ - future = future_client_command_simple ( - client, "admin", tmp_bson ("{'foo': 1}"), NULL, NULL, &error); + future = future_client_command_simple (client, "admin", tmp_bson ("{'foo': 1}"), NULL, NULL, &error); /* topology scanner calls hello once */ request = mock_server_receives_any_hello (server); @@ -731,9 +687,7 @@ _test_heartbeat_events (bool pooled, bool succeeded) 0, 0, 1, - tmp_str ("{'ok': 1, 'minWireVersion': %d, 'maxWireVersion': %d}", - WIRE_VERSION_MIN, - WIRE_VERSION_MAX)); + tmp_str ("{'ok': 1, 'minWireVersion': %d, 'maxWireVersion': %d}", WIRE_VERSION_MIN, WIRE_VERSION_MAX)); request_destroy (request); } else { reply_to_request_with_hang_up (request); @@ -749,9 +703,7 @@ _test_heartbeat_events (bool pooled, bool succeeded) 0, 0, 1, - tmp_str ("{'ok': 1, 'minWireVersion': %d, 'maxWireVersion': %d}", - WIRE_VERSION_MIN, - WIRE_VERSION_MAX)); + tmp_str ("{'ok': 1, 'minWireVersion': %d, 'maxWireVersion': %d}", WIRE_VERSION_MIN, WIRE_VERSION_MAX)); request_destroy (request); } @@ -774,19 +726,17 @@ _test_heartbeat_events (bool pooled, bool succeeded) /* even if pooled, only topology scanner sends events, so we get one pair */ if (succeeded) { durations = &context.heartbeat_succeeded_durations; - expected_json = bson_strdup_printf ( - "{'0': {'heartbeat_started_event': {'host': '%s', 'awaited': false}}," - " '1': {'heartbeat_succeeded_event': {'host': '%s', 'awaited': " - "false}}}", - mock_server_get_host_and_port (server), - mock_server_get_host_and_port (server)); + expected_json = bson_strdup_printf ("{'0': {'heartbeat_started_event': {'host': '%s', 'awaited': false}}," + " '1': {'heartbeat_succeeded_event': {'host': '%s', 'awaited': " + "false}}}", + mock_server_get_host_and_port (server), + mock_server_get_host_and_port (server)); } else { durations = &context.heartbeat_failed_durations; - expected_json = bson_strdup_printf ( - "{'0': {'heartbeat_started_event': {'host': '%s', 'awaited': false}}," - " '1': {'heartbeat_failed_event': {'host': '%s', 'awaited': false}}}", - mock_server_get_host_and_port (server), - mock_server_get_host_and_port (server)); + expected_json = bson_strdup_printf ("{'0': {'heartbeat_started_event': {'host': '%s', 'awaited': false}}," + " '1': {'heartbeat_failed_event': {'host': '%s', 'awaited': false}}}", + mock_server_get_host_and_port (server), + mock_server_get_host_and_port (server)); } ASSERT_CMPSIZE_T (durations->len, >, (size_t) 0); @@ -847,8 +797,7 @@ _test_heartbeat_fails_dns (bool pooled) /* Track time before scanning starts (which is triggered by popping the first * client for a client pool). */ start = bson_get_monotonic_time (); - uri = mongoc_uri_new ( - "mongodb://doesntexist.invalid/?serverSelectionTimeoutMS=100"); + uri = mongoc_uri_new ("mongodb://doesntexist.invalid/?serverSelectionTimeoutMS=100"); if (pooled) { pool = test_framework_client_pool_new_from_uri (uri, NULL); pool_set_heartbeat_event_callbacks (pool, &context); @@ -859,15 +808,12 @@ _test_heartbeat_fails_dns (bool pooled) } /* trigger "hello" handshake */ - r = mongoc_client_command_simple ( - client, "admin", tmp_bson ("{'foo': 1}"), NULL, NULL, &error); + r = mongoc_client_command_simple (client, "admin", tmp_bson ("{'foo': 1}"), NULL, NULL, &error); /* Expect a server selection error. */ ASSERT (!r); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_SERVER_SELECTION, - MONGOC_ERROR_SERVER_SELECTION_FAILURE, - "No suitable servers found"); + ASSERT_ERROR_CONTAINS ( + error, MONGOC_ERROR_SERVER_SELECTION, MONGOC_ERROR_SERVER_SELECTION_FAILURE, "No suitable servers found"); if (pooled) { @@ -970,38 +916,29 @@ test_no_duplicates (void) /* Perform a ping, which creates a new connection, which performs the * hello handshake before sending the ping command. */ - future = future_client_command_simple (client, - "admin", - tmp_bson ("{'ping': 1}"), - NULL /* read prefs */, - NULL /* reply */, - &error); + future = future_client_command_simple ( + client, "admin", tmp_bson ("{'ping': 1}"), NULL /* read prefs */, NULL /* reply */, &error); request = mock_server_receives_any_hello (server); - reply_to_request_simple ( - request, - tmp_str ( - "{'ok': 1.0," - " 'isWritablePrimary': true," - " 'minWireVersion': %d," - " 'maxWireVersion': %d," - " 'lastWrite': {" - " 'lastWriteDate': {'$date': {'$numberLong': '123'}}, 'opTime': 2}}", - WIRE_VERSION_MIN, - WIRE_VERSION_4_4)); + reply_to_request_simple (request, + tmp_str ("{'ok': 1.0," + " 'isWritablePrimary': true," + " 'minWireVersion': %d," + " 'maxWireVersion': %d," + " 'lastWrite': {" + " 'lastWriteDate': {'$date': {'$numberLong': '123'}}, 'opTime': 2}}", + WIRE_VERSION_MIN, + WIRE_VERSION_4_4)); request_destroy (request); - request = mock_server_receives_msg ( - server, MONGOC_QUERY_NONE, tmp_bson ("{'ping': 1}")); + request = mock_server_receives_msg (server, MONGOC_QUERY_NONE, tmp_bson ("{'ping': 1}")); reply_to_request_with_ok_and_destroy (request); ASSERT_OR_PRINT (future_get_bool (future), error); future_destroy (future); - ASSERT_CMPINT ( - duplicates_counter.num_server_description_changed_events, ==, 1); + ASSERT_CMPINT (duplicates_counter.num_server_description_changed_events, ==, 1); /* There should be two topology changed events. One for the initial topology * (where the server is set to Unknown), and one for the first hello (but * not the second) */ - ASSERT_CMPINT ( - duplicates_counter.num_topology_description_changed_events, ==, 2); + ASSERT_CMPINT (duplicates_counter.num_topology_description_changed_events, ==, 2); /* Even though no topology description changed event was emitted, the newly * created server description should still overwrite the old one in the @@ -1023,45 +960,27 @@ test_sdam_monitoring_install (TestSuite *suite) { test_all_spec_tests (suite); TestSuite_AddLive ( - suite, - "/server_discovery_and_monitoring/monitoring/topology/single", - test_topology_events_single); + suite, "/server_discovery_and_monitoring/monitoring/topology/single", test_topology_events_single); TestSuite_AddLive ( - suite, - "/server_discovery_and_monitoring/monitoring/topology/pooled", - test_topology_events_pooled); + suite, "/server_discovery_and_monitoring/monitoring/topology/pooled", test_topology_events_pooled); TestSuite_AddLive ( - suite, - "/server_discovery_and_monitoring/monitoring/topology/disabled", - test_topology_events_disabled); - TestSuite_AddMockServerTest ( - suite, - "/server_discovery_and_monitoring/monitoring/heartbeat/single/succeeded", - test_heartbeat_events_single_succeeded); - TestSuite_AddMockServerTest ( - suite, - "/server_discovery_and_monitoring/monitoring/heartbeat/single/failed", - test_heartbeat_events_single_failed); - TestSuite_AddMockServerTest ( - suite, - "/server_discovery_and_monitoring/monitoring/heartbeat/pooled/succeeded", - test_heartbeat_events_pooled_succeeded); - TestSuite_AddMockServerTest ( - suite, - "/server_discovery_and_monitoring/monitoring/heartbeat/pooled/failed", - test_heartbeat_events_pooled_failed); + suite, "/server_discovery_and_monitoring/monitoring/topology/disabled", test_topology_events_disabled); + TestSuite_AddMockServerTest (suite, + "/server_discovery_and_monitoring/monitoring/heartbeat/single/succeeded", + test_heartbeat_events_single_succeeded); + TestSuite_AddMockServerTest (suite, + "/server_discovery_and_monitoring/monitoring/heartbeat/single/failed", + test_heartbeat_events_single_failed); + TestSuite_AddMockServerTest (suite, + "/server_discovery_and_monitoring/monitoring/heartbeat/pooled/succeeded", + test_heartbeat_events_pooled_succeeded); + TestSuite_AddMockServerTest (suite, + "/server_discovery_and_monitoring/monitoring/heartbeat/pooled/failed", + test_heartbeat_events_pooled_failed); TestSuite_Add ( - suite, - "/server_discovery_and_monitoring/monitoring/heartbeat/single/dns", - test_heartbeat_fails_dns_single); + suite, "/server_discovery_and_monitoring/monitoring/heartbeat/single/dns", test_heartbeat_fails_dns_single); TestSuite_Add ( - suite, - "/server_discovery_and_monitoring/monitoring/heartbeat/pooled/dns", - test_heartbeat_fails_dns_pooled); + suite, "/server_discovery_and_monitoring/monitoring/heartbeat/pooled/dns", test_heartbeat_fails_dns_pooled); TestSuite_AddMockServerTest ( - suite, - "/server_discovery_and_monitoring/monitoring/no_duplicates", - test_no_duplicates, - NULL, - NULL); + suite, "/server_discovery_and_monitoring/monitoring/no_duplicates", test_no_duplicates, NULL, NULL); } diff --git a/src/libmongoc/tests/test-mongoc-sdam.c b/src/libmongoc/tests/test-mongoc-sdam.c index 2d70c08c6b..3acd58cad2 100644 --- a/src/libmongoc/tests/test-mongoc-sdam.c +++ b/src/libmongoc/tests/test-mongoc-sdam.c @@ -15,9 +15,7 @@ static void -_topology_has_description (const mongoc_topology_description_t *topology, - bson_t *server, - const char *address) +_topology_has_description (const mongoc_topology_description_t *topology, bson_t *server, const char *address) { mongoc_server_description_t const *sd; bson_iter_t server_iter; @@ -47,9 +45,7 @@ _topology_has_description (const mongoc_topology_description_t *topology, } else if (strcmp ("type", bson_iter_key (&server_iter)) == 0) { server_type = bson_iter_utf8 (&server_iter, NULL); if (sd->type != server_type_from_test (server_type)) { - test_error ("expected server type %s not %s", - server_type, - mongoc_server_description_type (sd)); + test_error ("expected server type %s not %s", server_type, mongoc_server_description_type (sd)); } } else if (strcmp ("setVersion", bson_iter_key (&server_iter)) == 0) { int64_t expected_set_version; @@ -62,42 +58,34 @@ _topology_has_description (const mongoc_topology_description_t *topology, } else if (strcmp ("electionId", bson_iter_key (&server_iter)) == 0) { bson_oid_t expected_oid; if (BSON_ITER_HOLDS_NULL (&server_iter)) { - bson_oid_init_from_string (&expected_oid, - "000000000000000000000000"); + bson_oid_init_from_string (&expected_oid, "000000000000000000000000"); } else { ASSERT (BSON_ITER_HOLDS_OID (&server_iter)); bson_oid_copy (bson_iter_oid (&server_iter), &expected_oid); } ASSERT_CMPOID (&sd->election_id, &expected_oid); - } else if (strcmp ("topologyVersion", bson_iter_key (&server_iter)) == - 0) { + } else if (strcmp ("topologyVersion", bson_iter_key (&server_iter)) == 0) { bson_t expected_topology_version; if (BSON_ITER_HOLDS_NULL (&server_iter)) { bson_init (&expected_topology_version); } else { ASSERT (BSON_ITER_HOLDS_DOCUMENT (&server_iter)); - bson_lookup_doc ( - server, "topologyVersion", &expected_topology_version); + bson_lookup_doc (server, "topologyVersion", &expected_topology_version); } - assert_match_bson ( - &sd->topology_version, &expected_topology_version, false); + assert_match_bson (&sd->topology_version, &expected_topology_version, false); bson_destroy (&expected_topology_version); } else if (strcmp ("pool", bson_iter_key (&server_iter)) == 0) { bson_iter_t iter; uint32_t expected_generation; BSON_ASSERT (bson_iter_recurse (&server_iter, &iter)); - BSON_ASSERT (bson_iter_find (&iter, "generation") && - BSON_ITER_HOLDS_INT32 (&iter)); + BSON_ASSERT (bson_iter_find (&iter, "generation") && BSON_ITER_HOLDS_INT32 (&iter)); expected_generation = bson_iter_int32 (&iter); - ASSERT_CMPINT32 (expected_generation, - ==, - mc_tpl_sd_get_generation (sd, &kZeroServiceId)); - } else if (strcmp ("logicalSessionTimeoutMinutes", - bson_iter_key (&server_iter)) == 0) { + ASSERT_CMPINT32 (expected_generation, ==, mc_tpl_sd_get_generation (sd, &kZeroServiceId)); + } else if (strcmp ("logicalSessionTimeoutMinutes", bson_iter_key (&server_iter)) == 0) { if (BSON_ITER_HOLDS_NULL (&server_iter)) { if (sd->session_timeout_minutes != MONGOC_NO_SESSIONS) { test_error ("ERROR: expected unset value for " @@ -105,9 +93,7 @@ _topology_has_description (const mongoc_topology_description_t *topology, sd->session_timeout_minutes); } } else { - ASSERT_CMPINT64 (bson_iter_as_int64 (&server_iter), - ==, - sd->session_timeout_minutes); + ASSERT_CMPINT64 (bson_iter_as_int64 (&server_iter), ==, sd->session_timeout_minutes); } } else if (strcmp ("minWireVersion", bson_iter_key (&server_iter)) == 0) { if (BSON_ITER_HOLDS_NULL (&server_iter)) { @@ -117,8 +103,7 @@ _topology_has_description (const mongoc_topology_description_t *topology, sd->min_wire_version); } } else { - ASSERT_CMPINT32 ( - bson_iter_int32 (&server_iter), ==, sd->min_wire_version); + ASSERT_CMPINT32 (bson_iter_int32 (&server_iter), ==, sd->min_wire_version); } } else if (strcmp ("maxWireVersion", bson_iter_key (&server_iter)) == 0) { if (BSON_ITER_HOLDS_NULL (&server_iter)) { @@ -128,12 +113,10 @@ _topology_has_description (const mongoc_topology_description_t *topology, sd->max_wire_version); } } else { - ASSERT_CMPINT32 ( - bson_iter_int32 (&server_iter), ==, sd->max_wire_version); + ASSERT_CMPINT32 (bson_iter_int32 (&server_iter), ==, sd->max_wire_version); } } else { - fprintf ( - stderr, "ERROR: unparsed field %s\n", bson_iter_key (&server_iter)); + fprintf (stderr, "ERROR: unparsed field %s\n", bson_iter_key (&server_iter)); BSON_ASSERT (0); } } @@ -195,9 +178,7 @@ test_sdam_cb (bson_t *test) mc_tpld_renew_ref (&td, client->topology); if (strcmp ("servers", bson_iter_key (&outcome_iter)) == 0) { bson_iter_bson (&outcome_iter, &servers); - ASSERT_CMPSIZE_T (bson_count_keys (&servers), - ==, - mc_tpld_servers_const (td.ptr)->items_len); + ASSERT_CMPSIZE_T (bson_count_keys (&servers), ==, mc_tpld_servers_const (td.ptr)->items_len); bson_iter_init (&servers_iter, &servers); @@ -215,36 +196,25 @@ test_sdam_cb (bson_t *test) ASSERT_CMPSTR (td.ptr->set_name, set_name); } else { if (td.ptr->set_name) { - test_error ("expected NULL setName, got: %s", - td.ptr->set_name); + test_error ("expected NULL setName, got: %s", td.ptr->set_name); } } - } else if (strcmp ("topologyType", bson_iter_key (&outcome_iter)) == - 0) { - ASSERT_CMPSTR (mongoc_topology_description_type (td.ptr), - bson_iter_utf8 (&outcome_iter, NULL)); - } else if (strcmp ("logicalSessionTimeoutMinutes", - bson_iter_key (&outcome_iter)) == 0) { + } else if (strcmp ("topologyType", bson_iter_key (&outcome_iter)) == 0) { + ASSERT_CMPSTR (mongoc_topology_description_type (td.ptr), bson_iter_utf8 (&outcome_iter, NULL)); + } else if (strcmp ("logicalSessionTimeoutMinutes", bson_iter_key (&outcome_iter)) == 0) { if (BSON_ITER_HOLDS_NULL (&outcome_iter)) { - ASSERT_CMPINT64 (td.ptr->session_timeout_minutes, - ==, - (int64_t) MONGOC_NO_SESSIONS); + ASSERT_CMPINT64 (td.ptr->session_timeout_minutes, ==, (int64_t) MONGOC_NO_SESSIONS); } else { - ASSERT_CMPINT64 (td.ptr->session_timeout_minutes, - ==, - bson_iter_as_int64 (&outcome_iter)); + ASSERT_CMPINT64 (td.ptr->session_timeout_minutes, ==, bson_iter_as_int64 (&outcome_iter)); } } else if (strcmp ("compatible", bson_iter_key (&outcome_iter)) == 0) { if (bson_iter_as_bool (&outcome_iter)) { ASSERT_CMPINT (0, ==, td.ptr->compatibility_error.domain); } else { - ASSERT_ERROR_CONTAINS (td.ptr->compatibility_error, - MONGOC_ERROR_PROTOCOL, - MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION, - ""); + ASSERT_ERROR_CONTAINS ( + td.ptr->compatibility_error, MONGOC_ERROR_PROTOCOL, MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION, ""); } - } else if (strcmp ("maxSetVersion", bson_iter_key (&outcome_iter)) == - 0) { + } else if (strcmp ("maxSetVersion", bson_iter_key (&outcome_iter)) == 0) { if (BSON_ITER_HOLDS_NULL (&outcome_iter)) { if (td.ptr->max_set_version != MONGOC_NO_SET_VERSION) { test_error ("ERROR: expected unset value for maxSetVersion " @@ -252,12 +222,9 @@ test_sdam_cb (bson_t *test) td.ptr->max_set_version); } } else { - ASSERT_CMPINT64 (bson_iter_as_int64 (&outcome_iter), - ==, - td.ptr->max_set_version); + ASSERT_CMPINT64 (bson_iter_as_int64 (&outcome_iter), ==, td.ptr->max_set_version); } - } else if (strcmp ("maxElectionId", bson_iter_key (&outcome_iter)) == - 0) { + } else if (strcmp ("maxElectionId", bson_iter_key (&outcome_iter)) == 0) { const bson_oid_t *expected_oid; bson_oid_t zeroed = {.bytes = {0}}; @@ -278,8 +245,7 @@ test_sdam_cb (bson_t *test) expected_oid_str, actual_oid_str); } - } else if (strcmp ("logicalSessionTimeoutMinutes", - bson_iter_key (&outcome_iter)) == 0) { + } else if (strcmp ("logicalSessionTimeoutMinutes", bson_iter_key (&outcome_iter)) == 0) { if (BSON_ITER_HOLDS_NULL (&outcome_iter)) { if (td.ptr->session_timeout_minutes != MONGOC_NO_SESSIONS) { test_error ("ERROR: expected unset value for " @@ -287,14 +253,10 @@ test_sdam_cb (bson_t *test) td.ptr->session_timeout_minutes); } } else { - ASSERT_CMPINT64 (bson_iter_as_int64 (&outcome_iter), - ==, - td.ptr->session_timeout_minutes); + ASSERT_CMPINT64 (bson_iter_as_int64 (&outcome_iter), ==, td.ptr->session_timeout_minutes); } } else { - fprintf (stderr, - "ERROR: unparsed test field %s\n", - bson_iter_key (&outcome_iter)); + fprintf (stderr, "ERROR: unparsed test field %s\n", bson_iter_key (&outcome_iter)); BSON_ASSERT (false); } } @@ -309,9 +271,7 @@ test_sdam_cb (bson_t *test) * check for sessions support. That interferes with failpoints set on hello. */ static void -sdam_json_test_ctx_init (json_test_ctx_t *ctx, - const json_test_config_t *config, - mongoc_client_pool_t *pool) +sdam_json_test_ctx_init (json_test_ctx_t *ctx, const json_test_config_t *config, mongoc_client_pool_t *pool) { const char *db_name; const char *coll_name; @@ -351,15 +311,12 @@ sdam_json_test_ctx_cleanup (json_test_ctx_t *ctx) } static bool -sdam_integration_operation_cb (json_test_ctx_t *ctx, - const bson_t *test, - const bson_t *operation) +sdam_integration_operation_cb (json_test_ctx_t *ctx, const bson_t *test, const bson_t *operation) { bson_t reply; bool res; - res = - json_test_operation (ctx, test, operation, ctx->collection, NULL, &reply); + res = json_test_operation (ctx, test, operation, ctx->collection, NULL, &reply); bson_destroy (&reply); @@ -389,13 +346,8 @@ deactivate_failpoints_on_all_servers (mongoc_client_t *client) bool ret; server_id = servers->items[i].id; - ret = mongoc_client_command_simple_with_server_id (client, - "admin", - &cmd, - NULL /* read prefs */, - server_id, - NULL /* reply */, - &error); + ret = mongoc_client_command_simple_with_server_id ( + client, "admin", &cmd, NULL /* read prefs */, server_id, NULL /* reply */, &error); if (!ret) { MONGOC_DEBUG ("error disabling failpoint: %s", error.message); } @@ -440,12 +392,7 @@ run_one_integration_test (json_test_config_t *config, bson_t *test) setup_client = test_framework_new_default_client (); /* Disable failpoints that may have been enabled in a previous test run. */ deactivate_failpoints_on_all_servers (setup_client); - mongoc_client_command_simple (setup_client, - "admin", - tmp_bson ("{'killAllSessions': []}"), - NULL, - NULL, - &error); + mongoc_client_command_simple (setup_client, "admin", tmp_bson ("{'killAllSessions': []}"), NULL, NULL, &error); insert_data (db_name, coll_name, config->scenario); @@ -480,9 +427,7 @@ run_one_integration_test (json_test_config_t *config, bson_t *test) if (bson_has_field (test, "outcome.collection")) { mongoc_collection_t *outcome_coll; outcome_coll = mongoc_client_get_collection ( - setup_client, - mongoc_database_get_name (ctx.db), - mongoc_collection_get_name (ctx.collection)); + setup_client, mongoc_database_get_name (ctx.db), mongoc_collection_get_name (ctx.collection)); check_outcome_collection (outcome_coll, test); mongoc_collection_destroy (outcome_coll); } @@ -543,44 +488,31 @@ static void test_all_spec_tests (TestSuite *suite) { /* Single */ - install_json_test_suite ( - suite, JSON_DIR, "server_discovery_and_monitoring/single", &test_sdam_cb); + install_json_test_suite (suite, JSON_DIR, "server_discovery_and_monitoring/single", &test_sdam_cb); /* Replica set */ - install_json_test_suite ( - suite, JSON_DIR, "server_discovery_and_monitoring/rs", &test_sdam_cb); + install_json_test_suite (suite, JSON_DIR, "server_discovery_and_monitoring/rs", &test_sdam_cb); /* Sharded */ - install_json_test_suite (suite, - JSON_DIR, - "server_discovery_and_monitoring/sharded", - &test_sdam_cb); + install_json_test_suite (suite, JSON_DIR, "server_discovery_and_monitoring/sharded", &test_sdam_cb); - install_json_test_suite ( - suite, JSON_DIR, "server_discovery_and_monitoring/errors", &test_sdam_cb); + install_json_test_suite (suite, JSON_DIR, "server_discovery_and_monitoring/errors", &test_sdam_cb); /* Tests not in official Server Discovery And Monitoring Spec */ - install_json_test_suite (suite, - JSON_DIR, - "server_discovery_and_monitoring/supplemental", - &test_sdam_cb); + install_json_test_suite (suite, JSON_DIR, "server_discovery_and_monitoring/supplemental", &test_sdam_cb); /* Integration tests. */ /* The integration tests configure retryable writes, which requires crypto. */ - install_json_test_suite_with_check ( - suite, - JSON_DIR, - "server_discovery_and_monitoring/integration", - &test_sdam_integration_cb, - TestSuite_CheckLive, - test_framework_skip_if_no_crypto, - test_framework_skip_if_slow); - - install_json_test_suite (suite, - JSON_DIR, - "server_discovery_and_monitoring/load-balanced", - &test_sdam_cb); + install_json_test_suite_with_check (suite, + JSON_DIR, + "server_discovery_and_monitoring/integration", + &test_sdam_integration_cb, + TestSuite_CheckLive, + test_framework_skip_if_no_crypto, + test_framework_skip_if_slow); + + install_json_test_suite (suite, JSON_DIR, "server_discovery_and_monitoring/load-balanced", &test_sdam_cb); } static void @@ -623,8 +555,7 @@ test_topology_discovery (void *ctx) * * Outcome: Verify that the write succeeded. */ bson_free (uri_str); - uri_str = bson_strdup_printf ("mongodb://%s/?directConnection=false", - hl_secondary->host_and_port); + uri_str = bson_strdup_printf ("mongodb://%s/?directConnection=false", hl_secondary->host_and_port); uri_str_auth = test_framework_add_user_password_from_env (uri_str); mongoc_client_destroy (client); @@ -689,8 +620,7 @@ test_direct_connection (void *ctx) * * Outcome: Verify that the write failed with a NotPrimary error. */ bson_free (uri_str); - uri_str = bson_strdup_printf ("mongodb://%s/?directConnection=true", - hl_secondary->host_and_port); + uri_str = bson_strdup_printf ("mongodb://%s/?directConnection=true", hl_secondary->host_and_port); uri_str_auth = test_framework_add_user_password_from_env (uri_str); mongoc_client_destroy (client); @@ -700,8 +630,7 @@ test_direct_connection (void *ctx) BSON_APPEND_UTF8 (&doc, "hello", "world"); r = mongoc_collection_insert_one (collection, &doc, NULL, &reply, &error); ASSERT_OR_PRINT (!r, error); - ASSERT (strstr (error.message, "not master") || - strstr (error.message, "not primary")); + ASSERT (strstr (error.message, "not master") || strstr (error.message, "not primary")); bson_destroy (&reply); bson_destroy (&doc); @@ -767,8 +696,7 @@ test_existing_behavior (void *ctx) BSON_APPEND_UTF8 (&doc, "hello", "world"); r = mongoc_collection_insert_one (collection, &doc, NULL, &reply, &error); ASSERT_OR_PRINT (!r, error); - ASSERT (strstr (error.message, "not master") || - strstr (error.message, "not primary")); + ASSERT (strstr (error.message, "not master") || strstr (error.message, "not primary")); bson_destroy (&reply); bson_destroy (&doc); @@ -791,9 +719,7 @@ heartbeat_succeeded (const mongoc_apm_server_heartbeat_succeeded_t *event) { prose_test_ctx_t *ctx; - ctx = - (prose_test_ctx_t *) mongoc_apm_server_heartbeat_succeeded_get_context ( - event); + ctx = (prose_test_ctx_t *) mongoc_apm_server_heartbeat_succeeded_get_context (event); ctx->n_heartbeat_succeeded++; /* The reported duration may be 0 on Windows due to poor clock resolution. * bson_get_monotonic_time () uses GetTickCount64. MS docs say: @@ -836,8 +762,7 @@ test_prose_rtt (void *unused) mongoc_uri_set_option_as_int32 (uri, MONGOC_URI_HEARTBEATFREQUENCYMS, 500); callbacks = mongoc_apm_callbacks_new (); - mongoc_apm_set_server_heartbeat_succeeded_cb (callbacks, - heartbeat_succeeded); + mongoc_apm_set_server_heartbeat_succeeded_cb (callbacks, heartbeat_succeeded); pool = test_framework_client_pool_new_from_uri (uri, NULL); test_framework_set_pool_ssl_opts (pool); memset (&ctx, 0, sizeof (prose_test_ctx_t)); @@ -846,8 +771,7 @@ test_prose_rtt (void *unused) /* Run a find command for the server to be discovered. */ coll = get_test_collection (client, "streamingRttTest"); - cursor = mongoc_collection_find_with_opts ( - coll, tmp_bson ("{}"), NULL /* opts */, NULL /* read prefs */); + cursor = mongoc_collection_find_with_opts (coll, tmp_bson ("{}"), NULL /* opts */, NULL /* read prefs */); mongoc_cursor_next (cursor, &doc); /* Sleep for RTT_TEST_INITIAL_SLEEP_SEC seconds to allow multiple heartbeats @@ -873,20 +797,17 @@ test_prose_rtt (void *unused) "appName", "streamingRttTest", "}"); - ret = mongoc_client_command_simple ( - client, "admin", &cmd, NULL /* read prefs. */, NULL /* reply */, &error); + ret = mongoc_client_command_simple (client, "admin", &cmd, NULL /* read prefs. */, NULL /* reply */, &error); ASSERT_OR_PRINT (ret, error); /* Wait for the server's RTT to exceed 250ms. If this does not happen for * RTT_TEST_TIMEOUT_SEC seconds, consider it a failure. */ satisfied = false; start_us = bson_get_monotonic_time (); - while (!satisfied && bson_get_monotonic_time () < - start_us + RTT_TEST_TIMEOUT_SEC * 1000 * 1000) { + while (!satisfied && bson_get_monotonic_time () < start_us + RTT_TEST_TIMEOUT_SEC * 1000 * 1000) { mongoc_server_description_t *sd; - sd = mongoc_client_select_server ( - client, true, NULL /* read prefs */, &error); + sd = mongoc_client_select_server (client, true, NULL /* read prefs */, &error); ASSERT_OR_PRINT (sd, error); rtt = mongoc_server_description_round_trip_time (sd); if (rtt > 250) { @@ -897,17 +818,14 @@ test_prose_rtt (void *unused) } if (!satisfied) { - test_error ("After %d seconds, the latest observed RTT was only %" PRId64, - RTT_TEST_TIMEOUT_SEC, - rtt); + test_error ("After %d seconds, the latest observed RTT was only %" PRId64, RTT_TEST_TIMEOUT_SEC, rtt); } /* Disable the failpoint. */ bson_reinit (&cmd); BCON_APPEND (&cmd, "configureFailPoint", "failCommand"); BCON_APPEND (&cmd, "mode", "off"); - ret = mongoc_client_command_simple ( - client, "admin", &cmd, NULL /* read prefs. */, NULL /* reply */, &error); + ret = mongoc_client_command_simple (client, "admin", &cmd, NULL /* read prefs. */, NULL /* reply */, &error); ASSERT_OR_PRINT (ret, error); bson_destroy (&cmd); diff --git a/src/libmongoc/tests/test-mongoc-server-description.c b/src/libmongoc/tests/test-mongoc-server-description.c index 4a43d32590..007ff3c8b3 100644 --- a/src/libmongoc/tests/test-mongoc-server-description.c +++ b/src/libmongoc/tests/test-mongoc-server-description.c @@ -26,10 +26,7 @@ reset_basic_sd (mongoc_server_description_t *sd) bson_error_t error; bson_t *hello; - hello = BCON_NEW ("minWireVersion", - BCON_INT32 (WIRE_VERSION_MIN), - "maxWireVersion", - BCON_INT32 (WIRE_VERSION_MAX)); + hello = BCON_NEW ("minWireVersion", BCON_INT32 (WIRE_VERSION_MIN), "maxWireVersion", BCON_INT32 (WIRE_VERSION_MAX)); mongoc_server_description_reset (sd); memset (&error, 0, sizeof (bson_error_t)); @@ -277,8 +274,7 @@ test_server_description_ignores_rtt (void) ASSERT_CMPINT64 (sd.round_trip_time_msec, ==, MONGOC_RTT_UNSET); BSON_ASSERT (sd.type == MONGOC_SERVER_UNKNOWN); /* If MONGOC_RTT_UNSET is passed as the RTT, it remains MONGOC_RTT_UNSET. */ - mongoc_server_description_handle_hello ( - &sd, &hello, MONGOC_RTT_UNSET, &error); + mongoc_server_description_handle_hello (&sd, &hello, MONGOC_RTT_UNSET, &error); ASSERT_CMPINT64 (sd.round_trip_time_msec, ==, MONGOC_RTT_UNSET); BSON_ASSERT (sd.type == MONGOC_SERVER_STANDALONE); /* The first real RTT overwrites the stored RTT. */ @@ -286,8 +282,7 @@ test_server_description_ignores_rtt (void) ASSERT_CMPINT64 (sd.round_trip_time_msec, ==, 10); BSON_ASSERT (sd.type == MONGOC_SERVER_STANDALONE); /* But subsequent MONGOC_RTT_UNSET values do not effect it. */ - mongoc_server_description_handle_hello ( - &sd, &hello, MONGOC_RTT_UNSET, &error); + mongoc_server_description_handle_hello (&sd, &hello, MONGOC_RTT_UNSET, &error); ASSERT_CMPINT64 (sd.round_trip_time_msec, ==, 10); BSON_ASSERT (sd.type == MONGOC_SERVER_STANDALONE); @@ -344,8 +339,7 @@ test_server_description_legacy_hello (void) bson_t hello_response; bson_init (&hello_response); - BCON_APPEND ( - &hello_response, HANDSHAKE_RESPONSE_LEGACY_HELLO, BCON_BOOL (true)); + BCON_APPEND (&hello_response, HANDSHAKE_RESPONSE_LEGACY_HELLO, BCON_BOOL (true)); memset (&error, 0, sizeof (bson_error_t)); mongoc_server_description_init (&sd, "host:1234", 1); @@ -366,8 +360,7 @@ test_server_description_legacy_hello_ok (void) bson_t hello_response; bson_init (&hello_response); - BCON_APPEND ( - &hello_response, HANDSHAKE_RESPONSE_LEGACY_HELLO, BCON_BOOL (true)); + BCON_APPEND (&hello_response, HANDSHAKE_RESPONSE_LEGACY_HELLO, BCON_BOOL (true)); BCON_APPEND (&hello_response, "helloOk", BCON_BOOL (true)); memset (&error, 0, sizeof (bson_error_t)); @@ -443,28 +436,24 @@ test_server_description_hello_type_error (void) { mongoc_server_description_t sd; bson_error_t error; - const char *hello = - "{" - " 'ok' : { '$numberInt' : '1' }," - " 'ismaster' : true," - " 'maxBsonObjectSize' : { '$numberInt' : '16777216' }," - " 'maxMessageSizeBytes' : { '$numberInt' : '48000000'}," - " 'maxWriteBatchSize' : { '$numberLong' : '565160423'}," - " 'logicalSessionTimeoutMinutes' : { '$numberInt' : '30'}," - " 'connectionId' : { '$numberLong' : '565160423'}," - " 'minWireVersion' : { '$numberInt' : '0'}," - " 'maxWireVersion' : { '$numberInt' : '15'}," - " 'readOnly' : true" - "}"; + const char *hello = "{" + " 'ok' : { '$numberInt' : '1' }," + " 'ismaster' : true," + " 'maxBsonObjectSize' : { '$numberInt' : '16777216' }," + " 'maxMessageSizeBytes' : { '$numberInt' : '48000000'}," + " 'maxWriteBatchSize' : { '$numberLong' : '565160423'}," + " 'logicalSessionTimeoutMinutes' : { '$numberInt' : '30'}," + " 'connectionId' : { '$numberLong' : '565160423'}," + " 'minWireVersion' : { '$numberInt' : '0'}," + " 'maxWireVersion' : { '$numberInt' : '15'}," + " 'readOnly' : true" + "}"; mongoc_server_description_init (&sd, "host:1234", 1); memset (&error, 0, sizeof (bson_error_t)); mongoc_server_description_handle_hello (&sd, tmp_bson (hello), 0, &error); BSON_ASSERT (sd.type == MONGOC_SERVER_UNKNOWN); BSON_ASSERT (sd.error.code == MONGOC_ERROR_STREAM_INVALID_TYPE); - ASSERT_ERROR_CONTAINS (sd.error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_INVALID_TYPE, - "unexpected type"); + ASSERT_ERROR_CONTAINS (sd.error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_INVALID_TYPE, "unexpected type"); mongoc_server_description_cleanup (&sd); } @@ -472,29 +461,13 @@ test_server_description_hello_type_error (void) void test_server_description_install (TestSuite *suite) { - TestSuite_Add ( - suite, "/server_description/equal", test_server_description_equal); - TestSuite_Add (suite, - "/server_description/msg_without_isdbgrid", - test_server_description_msg_without_isdbgrid); - TestSuite_Add (suite, - "/server_description/ignores_unset_rtt", - test_server_description_ignores_rtt); - TestSuite_Add ( - suite, "/server_description/hello", test_server_description_hello); - TestSuite_Add (suite, - "/server_description/hello_cmd_not_found", - test_server_description_hello_cmd_not_found); - TestSuite_Add (suite, - "/server_description/legacy_hello", - test_server_description_legacy_hello); - TestSuite_Add (suite, - "/server_description/legacy_hello_ok", - test_server_description_legacy_hello_ok); - TestSuite_Add (suite, - "/server_description/connection_id", - test_server_description_connection_id); - TestSuite_Add (suite, - "/server_description/hello_type_error", - test_server_description_hello_type_error); + TestSuite_Add (suite, "/server_description/equal", test_server_description_equal); + TestSuite_Add (suite, "/server_description/msg_without_isdbgrid", test_server_description_msg_without_isdbgrid); + TestSuite_Add (suite, "/server_description/ignores_unset_rtt", test_server_description_ignores_rtt); + TestSuite_Add (suite, "/server_description/hello", test_server_description_hello); + TestSuite_Add (suite, "/server_description/hello_cmd_not_found", test_server_description_hello_cmd_not_found); + TestSuite_Add (suite, "/server_description/legacy_hello", test_server_description_legacy_hello); + TestSuite_Add (suite, "/server_description/legacy_hello_ok", test_server_description_legacy_hello_ok); + TestSuite_Add (suite, "/server_description/connection_id", test_server_description_connection_id); + TestSuite_Add (suite, "/server_description/hello_type_error", test_server_description_hello_type_error); } diff --git a/src/libmongoc/tests/test-mongoc-server-selection-errors.c b/src/libmongoc/tests/test-mongoc-server-selection-errors.c index e0de9960f2..c62971cce3 100644 --- a/src/libmongoc/tests/test-mongoc-server-selection-errors.c +++ b/src/libmongoc/tests/test-mongoc-server-selection-errors.c @@ -8,29 +8,19 @@ static mongoc_stream_t * -cannot_resolve (const mongoc_uri_t *uri, - const mongoc_host_list_t *host, - void *user_data, - bson_error_t *error) +cannot_resolve (const mongoc_uri_t *uri, const mongoc_host_list_t *host, void *user_data, bson_error_t *error) { BSON_UNUSED (uri); BSON_UNUSED (user_data); - bson_set_error (error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_NAME_RESOLUTION, - "Fake error for '%s'", - host->host); + bson_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_NAME_RESOLUTION, "Fake error for '%s'", host->host); return NULL; } static void -server_selection_error_dns (const char *uri_str, - const char *errmsg, - bool expect_success, - bool pooled) +server_selection_error_dns (const char *uri_str, const char *errmsg, bool expect_success, bool pooled) { mongoc_uri_t *uri; mongoc_client_pool_t *pool = NULL; @@ -66,8 +56,7 @@ server_selection_error_dns (const char *uri_str, collection = mongoc_client_get_collection (client, "test", "test"); command = tmp_bson ("{'ping': 1}"); - success = mongoc_collection_command_simple ( - collection, command, NULL, &reply, &error); + success = mongoc_collection_command_simple (collection, command, NULL, &reply, &error); ASSERT_OR_PRINT (success == expect_success, error); if (!success && errmsg) { @@ -90,12 +79,11 @@ server_selection_error_dns (const char *uri_str, static void test_server_selection_error_dns_direct_single (void) { - server_selection_error_dns ( - "mongodb://example-localhost.invalid:27017/", - "No suitable servers found (`serverSelectionTryOnce` set): " - "[Fake error for 'example-localhost.invalid']", - false, - false); + server_selection_error_dns ("mongodb://example-localhost.invalid:27017/", + "No suitable servers found (`serverSelectionTryOnce` set): " + "[Fake error for 'example-localhost.invalid']", + false, + false); } static void @@ -103,25 +91,23 @@ test_server_selection_error_dns_direct_pooled (void *ctx) { BSON_UNUSED (ctx); - server_selection_error_dns ( - "mongodb://example-localhost.invalid:27017/", - "No suitable servers found: `serverSelectionTimeoutMS` expired: " - "[Fake error for 'example-localhost.invalid']", - false, - true); + server_selection_error_dns ("mongodb://example-localhost.invalid:27017/", + "No suitable servers found: `serverSelectionTimeoutMS` expired: " + "[Fake error for 'example-localhost.invalid']", + false, + true); } static void test_server_selection_error_dns_multi_fail_single (void) { - server_selection_error_dns ( - "mongodb://" - "example-localhost.invalid:27017,other-example-localhost.invalid:27017/", - "No suitable servers found (`serverSelectionTryOnce` set):" - " [Fake error for 'example-localhost.invalid']" - " [Fake error for 'other-example-localhost.invalid']", - false, - false); + server_selection_error_dns ("mongodb://" + "example-localhost.invalid:27017,other-example-localhost.invalid:27017/", + "No suitable servers found (`serverSelectionTryOnce` set):" + " [Fake error for 'example-localhost.invalid']" + " [Fake error for 'other-example-localhost.invalid']", + false, + false); } static void @@ -129,14 +115,13 @@ test_server_selection_error_dns_multi_fail_pooled (void *ctx) { BSON_UNUSED (ctx); - server_selection_error_dns ( - "mongodb://" - "example-localhost.invalid:27017,other-example-localhost.invalid:27017/", - "No suitable servers found: `serverSelectionTimeoutMS` expired:" - " [Fake error for 'example-localhost.invalid']" - " [Fake error for 'other-example-localhost.invalid']", - false, - true); + server_selection_error_dns ("mongodb://" + "example-localhost.invalid:27017,other-example-localhost.invalid:27017/", + "No suitable servers found: `serverSelectionTimeoutMS` expired:" + " [Fake error for 'example-localhost.invalid']" + " [Fake error for 'other-example-localhost.invalid']", + false, + true); } static void @@ -206,8 +191,7 @@ _test_server_selection_uds_auth_failure (bool pooled) capture_logs (true); ASSERT_OR_PRINT ( - !mongoc_client_read_command_with_opts ( - client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, NULL, &error), + !mongoc_client_read_command_with_opts (client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, NULL, &error), error); ASSERT_CMPINT (error.domain, ==, MONGOC_ERROR_CLIENT); @@ -270,8 +254,7 @@ _test_server_selection_uds_not_found (bool pooled) test_framework_set_ssl_opts (client); #endif - ASSERT (!mongoc_client_read_command_with_opts ( - client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, NULL, &error)); + ASSERT (!mongoc_client_read_command_with_opts (client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, NULL, &error)); ASSERT_CMPINT (error.domain, ==, MONGOC_ERROR_SERVER_SELECTION); ASSERT_CMPINT (error.code, ==, MONGOC_ERROR_SERVER_SELECTION_FAILURE); @@ -305,18 +288,15 @@ test_server_selection_uds_not_found_pooled (void *context) void test_server_selection_errors_install (TestSuite *suite) { - TestSuite_Add (suite, - "/server_selection/errors/dns/direct/single", - test_server_selection_error_dns_direct_single); + TestSuite_Add (suite, "/server_selection/errors/dns/direct/single", test_server_selection_error_dns_direct_single); TestSuite_AddFull (suite, "/server_selection/errors/dns/direct/pooled", test_server_selection_error_dns_direct_pooled, NULL, NULL, test_framework_skip_if_slow); - TestSuite_Add (suite, - "/server_selection/errors/dns/multi/fail/single", - test_server_selection_error_dns_multi_fail_single); + TestSuite_Add ( + suite, "/server_selection/errors/dns/multi/fail/single", test_server_selection_error_dns_multi_fail_single); TestSuite_AddFull (suite, "/server_selection/errors/dns/multi/fail/pooled", test_server_selection_error_dns_multi_fail_pooled, diff --git a/src/libmongoc/tests/test-mongoc-server-selection.c b/src/libmongoc/tests/test-mongoc-server-selection.c index 3ac661c3d6..604e20c3fb 100644 --- a/src/libmongoc/tests/test-mongoc-server-selection.c +++ b/src/libmongoc/tests/test-mongoc-server-selection.c @@ -23,8 +23,7 @@ test_rtt_calculation_cb (bson_t *test) BSON_ASSERT (test); - description = - (mongoc_server_description_t *) bson_malloc0 (sizeof *description); + description = (mongoc_server_description_t *) bson_malloc0 (sizeof *description); mongoc_server_description_init (description, "localhost:27017", 1); /* parse RTT into server description */ @@ -54,14 +53,10 @@ static void test_all_spec_tests (TestSuite *suite) { /* RTT calculation */ - install_json_test_suite ( - suite, JSON_DIR, "server_selection/rtt", &test_rtt_calculation_cb); + install_json_test_suite (suite, JSON_DIR, "server_selection/rtt", &test_rtt_calculation_cb); /* SS logic */ - install_json_test_suite (suite, - JSON_DIR, - "server_selection/server_selection", - &test_server_selection_logic_cb); + install_json_test_suite (suite, JSON_DIR, "server_selection/server_selection", &test_server_selection_logic_cb); } void diff --git a/src/libmongoc/tests/test-mongoc-server-stream.c b/src/libmongoc/tests/test-mongoc-server-stream.c index fc2c9967de..25093ea6ac 100644 --- a/src/libmongoc/tests/test-mongoc-server-stream.c +++ b/src/libmongoc/tests/test-mongoc-server-stream.c @@ -46,9 +46,7 @@ * If @expect_error is true, expect a client-side error from a maxWireVersion < * WIRE_VERSION_DELETE_HINT. */ static void -run_delete_with_hint_and_wc0 (bool expect_error, - mongoc_client_t *client, - mock_server_t *server) +run_delete_with_hint_and_wc0 (bool expect_error, mongoc_client_t *client, mock_server_t *server) { mongoc_collection_t *coll; mongoc_write_concern_t *wc; @@ -71,22 +69,18 @@ run_delete_with_hint_and_wc0 (bool expect_error, r = mongoc_write_concern_append (wc, delete_opts); ASSERT_WITH_MSG (r, "mongoc_write_concern_append failed"); - future = future_collection_delete_one ( - coll, delete_selector, delete_opts, NULL /* reply */, &error); + future = future_collection_delete_one (coll, delete_selector, delete_opts, NULL /* reply */, &error); if (expect_error) { /* Expect a client side error. The server does not receive anything. */ r = future_get_bool (future); - ASSERT_ERROR_CONTAINS ( - error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION, - "The selected server does not support hint for delete"); + ASSERT_ERROR_CONTAINS (error, + MONGOC_ERROR_COMMAND, + MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION, + "The selected server does not support hint for delete"); ASSERT (!r); } else { - request = mock_server_receives_msg (server, - MONGOC_MSG_MORE_TO_COME, - tmp_bson ("{ 'delete': 'coll' }"), - tmp_bson ("{'q': {}, 'hint': {}}")); + request = mock_server_receives_msg ( + server, MONGOC_MSG_MORE_TO_COME, tmp_bson ("{ 'delete': 'coll' }"), tmp_bson ("{'q': {}, 'hint': {}}")); reply_to_request_with_ok_and_destroy (request); r = future_get_bool (future); ASSERT (r); @@ -130,42 +124,31 @@ test_server_stream_ties_server_description_pooled (void *unused) request_destroy (request); /* Create a connection on client_one. */ - future = future_client_command_simple (client_one, - "admin", - tmp_bson ("{'ping': 1}"), - NULL /* read prefs */, - NULL /* reply */, - &error); + future = future_client_command_simple ( + client_one, "admin", tmp_bson ("{'ping': 1}"), NULL /* read prefs */, NULL /* reply */, &error); /* The first command on a pooled client creates a new connection. */ request = mock_server_receives_any_hello (server); reply_to_request_simple (request, HELLO_SERVER_ONE); request_destroy (request); - request = mock_server_receives_msg ( - server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'admin', 'ping': 1}")); + request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'admin', 'ping': 1}")); reply_to_request_with_ok_and_destroy (request); ASSERT_OR_PRINT (future_get_bool (future), error); future_destroy (future); /* Create a connection on client_two. */ - future = future_client_command_simple (client_two, - "admin", - tmp_bson ("{'ping': 1}"), - NULL /* read prefs */, - NULL /* reply */, - &error); + future = future_client_command_simple ( + client_two, "admin", tmp_bson ("{'ping': 1}"), NULL /* read prefs */, NULL /* reply */, &error); /* The first command on a pooled client creates a new connection. */ request = mock_server_receives_any_hello (server); reply_to_request_simple (request, HELLO_SERVER_TWO); request_destroy (request); - request = mock_server_receives_msg ( - server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'admin', 'ping': 1}")); + request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'admin', 'ping': 1}")); reply_to_request_with_ok_and_destroy (request); ASSERT_OR_PRINT (future_get_bool (future), error); future_destroy (future); /* Check that selecting the server returns the second server */ - sd = mongoc_client_select_server ( - client_two, true /* for writes */, NULL /* read prefs */, &error); + sd = mongoc_client_select_server (client_two, true /* for writes */, NULL /* read prefs */, &error); ASSERT_OR_PRINT (sd, error); ASSERT_MATCH (mongoc_server_description_hello_response (sd), tmp_str ("{'maxWireVersion': %d}", WIRE_VERSION_DELETE_HINT)); @@ -210,18 +193,13 @@ test_server_stream_ties_server_description_single (void *unused) client = test_framework_client_new_from_uri (uri, NULL); /* Create a connection on client. */ - future = future_client_command_simple (client, - "admin", - tmp_bson ("{'ping': 1}"), - NULL /* read prefs */, - NULL /* reply */, - &error); + future = future_client_command_simple ( + client, "admin", tmp_bson ("{'ping': 1}"), NULL /* read prefs */, NULL /* reply */, &error); /* The first command on a client creates a new connection. */ request = mock_server_receives_any_hello (server); reply_to_request_simple (request, HELLO_SERVER_TWO); request_destroy (request); - request = mock_server_receives_msg ( - server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'admin', 'ping': 1}")); + request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'admin', 'ping': 1}")); reply_to_request_with_ok_and_destroy (request); ASSERT_OR_PRINT (future_get_bool (future), error); future_destroy (future); @@ -230,28 +208,20 @@ test_server_stream_ties_server_description_single (void *unused) /* Pass in a zeroed out error. */ memset (&error, 0, sizeof (bson_error_t)); tdmod = mc_tpld_modify_begin (client->topology); - mongoc_topology_description_handle_hello ( - tdmod.new_td, 1, tmp_bson (HELLO_SERVER_ONE), 0, &error); + mongoc_topology_description_handle_hello (tdmod.new_td, 1, tmp_bson (HELLO_SERVER_ONE), 0, &error); mc_tpld_modify_commit (tdmod); - future = future_client_command_simple (client, - "admin", - tmp_bson ("{'ping': 1}"), - NULL /* read prefs */, - NULL /* reply */, - &error); - request = mock_server_receives_msg ( - server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'admin', 'ping': 1}")); + future = future_client_command_simple ( + client, "admin", tmp_bson ("{'ping': 1}"), NULL /* read prefs */, NULL /* reply */, &error); + request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'admin', 'ping': 1}")); reply_to_request_with_ok_and_destroy (request); ASSERT_OR_PRINT (future_get_bool (future), error); future_destroy (future); /* Check that selecting the server returns the first server */ - sd = mongoc_client_select_server ( - client, true /* for writes */, NULL /* read prefs */, &error); + sd = mongoc_client_select_server (client, true /* for writes */, NULL /* read prefs */, &error); ASSERT_OR_PRINT (sd, error); - ASSERT_MATCH (mongoc_server_description_hello_response (sd), - tmp_str ("{'maxWireVersion': %d}", WIRE_VERSION_MIN)); + ASSERT_MATCH (mongoc_server_description_hello_response (sd), tmp_str ("{'maxWireVersion': %d}", WIRE_VERSION_MIN)); mongoc_server_description_destroy (sd); /* Expect client to continue to use maxWireVersion=WIRE_VERSION_DELETE_HINT diff --git a/src/libmongoc/tests/test-mongoc-shared.c b/src/libmongoc/tests/test-mongoc-shared.c index eda643fa63..ac8302d0e7 100644 --- a/src/libmongoc/tests/test-mongoc-shared.c +++ b/src/libmongoc/tests/test-mongoc-shared.c @@ -100,8 +100,7 @@ test_aliased (void) struct widget *w; mongoc_shared_ptr ptr = MONGOC_SHARED_PTR_NULL; - ptr = mongoc_shared_ptr_create (bson_malloc0 (sizeof (struct widget)), - widget_delete); + ptr = mongoc_shared_ptr_create (bson_malloc0 (sizeof (struct widget)), widget_delete); w = ptr.ptr; w->store_value_here = &destroyed_valued; diff --git a/src/libmongoc/tests/test-mongoc-socket.c b/src/libmongoc/tests/test-mongoc-socket.c index d0be67ee58..0e6ddbdc17 100644 --- a/src/libmongoc/tests/test-mongoc-socket.c +++ b/src/libmongoc/tests/test-mongoc-socket.c @@ -50,13 +50,11 @@ static BSON_THREAD_FUN (socket_test_server, data_) server_addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK); server_addr.sin_port = htons (0); - r = mongoc_socket_bind ( - listen_sock, (struct sockaddr *) &server_addr, sizeof server_addr); + r = mongoc_socket_bind (listen_sock, (struct sockaddr *) &server_addr, sizeof server_addr); BSON_ASSERT (r == 0); sock_len = sizeof (server_addr); - r = mongoc_socket_getsockname ( - listen_sock, (struct sockaddr *) &server_addr, &sock_len); + r = mongoc_socket_getsockname (listen_sock, (struct sockaddr *) &server_addr, &sock_len); BSON_ASSERT (r == 0); r = mongoc_socket_listen (listen_sock, 10); @@ -128,8 +126,7 @@ static BSON_THREAD_FUN (socket_test_client, data_) server_addr.sin_port = htons (data->server_port); server_addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK); - r = mongoc_socket_connect ( - conn_sock, (struct sockaddr *) &server_addr, sizeof (server_addr), -1); + r = mongoc_socket_connect (conn_sock, (struct sockaddr *) &server_addr, sizeof (server_addr), -1); BSON_ASSERT (r == 0); stream = mongoc_stream_socket_new (conn_sock); @@ -197,15 +194,13 @@ static BSON_THREAD_FUN (sendv_test_server, data_) server_addr.sin_port = htons (0); { - const int r = mongoc_socket_bind ( - listen_sock, (struct sockaddr *) &server_addr, sizeof server_addr); + const int r = mongoc_socket_bind (listen_sock, (struct sockaddr *) &server_addr, sizeof server_addr); ASSERT_CMPINT (r, ==, 0); } { mongoc_socklen_t sock_len = (mongoc_socklen_t) sizeof (server_addr); - const int r = mongoc_socket_getsockname ( - listen_sock, (struct sockaddr *) &server_addr, &sock_len); + const int r = mongoc_socket_getsockname (listen_sock, (struct sockaddr *) &server_addr, &sock_len); ASSERT_CMPINT (r, ==, 0); } @@ -237,8 +232,7 @@ static BSON_THREAD_FUN (sendv_test_server, data_) /* Start reading everything off the socket to unblock the client */ do { ASSERT (bson_in_range_signed (size_t, amount)); - const ssize_t r = - mongoc_stream_readv (stream, &iov, 1, (size_t) amount, WAIT); + const ssize_t r = mongoc_stream_readv (stream, &iov, 1, (size_t) amount, WAIT); if (r > 0) { ASSERT (bson_in_range_signed (int, r)); amount -= (int) r; @@ -258,8 +252,7 @@ static BSON_THREAD_FUN (sendv_test_server, data_) do { ASSERT (bson_in_range_signed (size_t, amount)); - const ssize_t r = - mongoc_stream_readv (stream, &iov, 1, (size_t) amount, WAIT); + const ssize_t r = mongoc_stream_readv (stream, &iov, 1, (size_t) amount, WAIT); if (r > 0) { ASSERT (bson_in_range_signed (int, r)); amount -= (int) r; @@ -305,8 +298,7 @@ static BSON_THREAD_FUN (sendv_test_client, data_) server_addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK); { - const ssize_t r = mongoc_socket_connect ( - conn_sock, (struct sockaddr *) &server_addr, sizeof (server_addr), -1); + const ssize_t r = mongoc_socket_connect (conn_sock, (struct sockaddr *) &server_addr, sizeof (server_addr), -1); ASSERT_CMPSSIZE_T (r, ==, 0); } @@ -434,8 +426,7 @@ test_mongoc_socket_poll_refusal (void *ctx) /* create a new non-blocking socket. */ sock = mongoc_socket_new (AF_INET, SOCK_STREAM, 0); - (void) mongoc_socket_connect ( - sock, (struct sockaddr *) &ipv4_addr, sizeof (ipv4_addr), 0); + (void) mongoc_socket_connect (sock, (struct sockaddr *) &ipv4_addr, sizeof (ipv4_addr), 0); start = bson_get_monotonic_time (); @@ -457,35 +448,19 @@ test_mongoc_socket_poll_refusal (void *ctx) bson_free (poller); #ifdef _WIN32 - ASSERT_WITHIN_TIME_INTERVAL ( - (int) (bson_get_monotonic_time () - start), 1000 * 500, 1500 * 1000); + ASSERT_WITHIN_TIME_INTERVAL ((int) (bson_get_monotonic_time () - start), 1000 * 500, 1500 * 1000); #else - ASSERT_WITHIN_TIME_INTERVAL ( - (int) (bson_get_monotonic_time () - start), 0, 500); + ASSERT_WITHIN_TIME_INTERVAL ((int) (bson_get_monotonic_time () - start), 0, 500); #endif } void test_socket_install (TestSuite *suite) { - TestSuite_Add ( - suite, "/Socket/check_closed", test_mongoc_socket_check_closed); - TestSuite_AddFull (suite, - "/Socket/timed_out", - test_mongoc_socket_timed_out, - NULL, - NULL, - test_framework_skip_if_slow); - TestSuite_AddFull (suite, - "/Socket/sendv", - test_mongoc_socket_sendv, - NULL, - NULL, - test_framework_skip_if_slow); - TestSuite_AddFull (suite, - "/Socket/connect_refusal", - test_mongoc_socket_poll_refusal, - NULL, - NULL, - test_framework_skip_if_slow); + TestSuite_Add (suite, "/Socket/check_closed", test_mongoc_socket_check_closed); + TestSuite_AddFull ( + suite, "/Socket/timed_out", test_mongoc_socket_timed_out, NULL, NULL, test_framework_skip_if_slow); + TestSuite_AddFull (suite, "/Socket/sendv", test_mongoc_socket_sendv, NULL, NULL, test_framework_skip_if_slow); + TestSuite_AddFull ( + suite, "/Socket/connect_refusal", test_mongoc_socket_poll_refusal, NULL, NULL, test_framework_skip_if_slow); } diff --git a/src/libmongoc/tests/test-mongoc-speculative-auth.c b/src/libmongoc/tests/test-mongoc-speculative-auth.c index 34dcb5aedc..afd1c91820 100644 --- a/src/libmongoc/tests/test-mongoc-speculative-auth.c +++ b/src/libmongoc/tests/test-mongoc-speculative-auth.c @@ -46,8 +46,7 @@ _force_hello_with_ping (mongoc_client_t *client) ASSERT (client); /* Send a ping */ - future = future_client_command_simple ( - client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, NULL); + future = future_client_command_simple (client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, NULL); ASSERT (future); return future; @@ -69,8 +68,7 @@ _respond_to_ping (future_t *future, mock_server_t *server, bool expect_ping) return; } - request = mock_server_receives_msg ( - server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'admin', 'ping': 1}")); + request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'admin', 'ping': 1}")); ASSERT (request); @@ -91,13 +89,11 @@ _auto_hello_without_speculative_auth (request_t *request, void *data) return false; } - if (strcasecmp (request->command_name, HANDSHAKE_CMD_LEGACY_HELLO) && - strcmp (request->command_name, "hello")) { + if (strcasecmp (request->command_name, HANDSHAKE_CMD_LEGACY_HELLO) && strcmp (request->command_name, "hello")) { return false; } - if (bson_has_field (request_get_doc (request, 0), - "speculativeAuthenticate")) { + if (bson_has_field (request_get_doc (request, 0), "speculativeAuthenticate")) { return false; } @@ -219,8 +215,7 @@ _test_mongoc_speculative_auth (bool pooled, BCON_INT32 (WIRE_VERSION_MAX)); if (speculative_auth_response) { - BSON_APPEND_DOCUMENT ( - response, "speculativeAuthenticate", speculative_auth_response); + BSON_APPEND_DOCUMENT (response, "speculativeAuthenticate", speculative_auth_response); } str = bson_as_canonical_extended_json (response, NULL); @@ -273,8 +268,7 @@ _post_hello_scram_invalid_auth_response (mock_server_t *srv) request_t *request; const bson_t *request_doc; - request = mock_server_receives_msg ( - srv, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'admin'}")); + request = mock_server_receives_msg (srv, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'admin'}")); ASSERT (request); request_doc = request_get_doc (request, 0); ASSERT (request_doc); @@ -287,8 +281,7 @@ _post_hello_scram_invalid_auth_response (mock_server_t *srv) /* Let authentication fail directly since we won't be able to continue the * scram conversation. */ - reply_to_request_simple ( - request, "{ 'ok': 1, 'errmsg': 'Cannot mock scram auth conversation' }"); + reply_to_request_simple (request, "{ 'ok': 1, 'errmsg': 'Cannot mock scram auth conversation' }"); request_destroy (request); } @@ -296,46 +289,39 @@ _post_hello_scram_invalid_auth_response (mock_server_t *srv) static void test_mongoc_speculative_auth_request_none (void) { - _test_mongoc_speculative_auth ( - false, false, NULL, false, NULL, NULL, NULL, true); + _test_mongoc_speculative_auth (false, false, NULL, false, NULL, NULL, NULL, true); } static void test_mongoc_speculative_auth_request_none_pool (void) { - _test_mongoc_speculative_auth ( - true, false, NULL, false, NULL, NULL, NULL, true); + _test_mongoc_speculative_auth (true, false, NULL, false, NULL, NULL, NULL, true); } -#if defined(MONGOC_ENABLE_SSL_OPENSSL) || \ - defined(MONGOC_ENABLE_SSL_SECURE_TRANSPORT) +#if defined(MONGOC_ENABLE_SSL_OPENSSL) || defined(MONGOC_ENABLE_SSL_SECURE_TRANSPORT) static void _setup_speculative_auth_x_509 (mongoc_uri_t *uri) { mongoc_uri_set_auth_mechanism (uri, "MONGODB-X509"); - mongoc_uri_set_username ( - uri, - "CN=myName,OU=myOrgUnit,O=myOrg,L=myLocality,ST=myState,C=myCountry"); + mongoc_uri_set_username (uri, "CN=myName,OU=myOrgUnit,O=myOrg,L=myLocality,ST=myState,C=myCountry"); } static void _compare_auth_cmd_x509 (bson_t *auth_cmd) { - bson_t *expected_auth_cmd = BCON_NEW ( - "authenticate", - BCON_INT32 (1), - "mechanism", - BCON_UTF8 ("MONGODB-X509"), - "user", - BCON_UTF8 ( - "CN=myName,OU=myOrgUnit,O=myOrg,L=myLocality,ST=myState,C=myCountry"), - "db", - BCON_UTF8 ("$external")); + bson_t *expected_auth_cmd = + BCON_NEW ("authenticate", + BCON_INT32 (1), + "mechanism", + BCON_UTF8 ("MONGODB-X509"), + "user", + BCON_UTF8 ("CN=myName,OU=myOrgUnit,O=myOrg,L=myLocality,ST=myState,C=myCountry"), + "db", + BCON_UTF8 ("$external")); char *auth_cmd_str = bson_as_canonical_extended_json (auth_cmd, NULL); - char *expected_auth_cmd_str = - bson_as_canonical_extended_json (expected_auth_cmd, NULL); + char *expected_auth_cmd_str = bson_as_canonical_extended_json (expected_auth_cmd, NULL); ASSERT_CMPSTR (auth_cmd_str, expected_auth_cmd_str); @@ -347,21 +333,14 @@ _compare_auth_cmd_x509 (bson_t *auth_cmd) static void test_mongoc_speculative_auth_request_x509 (void) { - bson_t *response = - BCON_NEW ("dbname", - BCON_UTF8 ("$external"), - "user", - BCON_UTF8 ("CN=myName,OU=myOrgUnit,O=myOrg,L=myLocality,ST=" - "myState,C=myCountry")); + bson_t *response = BCON_NEW ("dbname", + BCON_UTF8 ("$external"), + "user", + BCON_UTF8 ("CN=myName,OU=myOrgUnit,O=myOrg,L=myLocality,ST=" + "myState,C=myCountry")); - _test_mongoc_speculative_auth (false, - true, - _setup_speculative_auth_x_509, - true, - _compare_auth_cmd_x509, - response, - NULL, - true); + _test_mongoc_speculative_auth ( + false, true, _setup_speculative_auth_x_509, true, _compare_auth_cmd_x509, response, NULL, true); bson_destroy (response); } @@ -369,21 +348,14 @@ test_mongoc_speculative_auth_request_x509 (void) static void test_mongoc_speculative_auth_request_x509_pool (void) { - bson_t *response = - BCON_NEW ("dbname", - BCON_UTF8 ("$external"), - "user", - BCON_UTF8 ("CN=myName,OU=myOrgUnit,O=myOrg,L=myLocality,ST=" - "myState,C=myCountry")); + bson_t *response = BCON_NEW ("dbname", + BCON_UTF8 ("$external"), + "user", + BCON_UTF8 ("CN=myName,OU=myOrgUnit,O=myOrg,L=myLocality,ST=" + "myState,C=myCountry")); - _test_mongoc_speculative_auth (true, - true, - _setup_speculative_auth_x_509, - true, - _compare_auth_cmd_x509, - response, - NULL, - true); + _test_mongoc_speculative_auth ( + true, true, _setup_speculative_auth_x_509, true, _compare_auth_cmd_x509, response, NULL, true); bson_destroy (response); } @@ -408,8 +380,7 @@ test_mongoc_speculative_auth_request_x509_network_error (void) mongoc_uri_t *uri; { uri = mongoc_uri_copy (mock_server_get_uri (server)); - mongoc_uri_set_option_as_int32 ( - uri, MONGOC_URI_HEARTBEATFREQUENCYMS, 15000); + mongoc_uri_set_option_as_int32 (uri, MONGOC_URI_HEARTBEATFREQUENCYMS, 15000); _setup_speculative_auth_x_509 (uri); } @@ -429,8 +400,7 @@ test_mongoc_speculative_auth_request_x509_network_error (void) bson_error_t error; // Send ping. - future_t *future = future_client_command_simple ( - client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); + future_t *future = future_client_command_simple (client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); // Expect a hello including speculativeAuthenticate field. { @@ -438,12 +408,10 @@ test_mongoc_speculative_auth_request_x509_network_error (void) ASSERT (request); const bson_t *request_doc = request_get_doc (request, 0); ASSERT (request_doc); - char *request_str = - bson_as_canonical_extended_json (request_doc, NULL); - ASSERT_WITH_MSG ( - bson_has_field (request_doc, "speculativeAuthenticate"), - "expected hello to contain 'speculativeAuthenticate', got: %s", - request_str); + char *request_str = bson_as_canonical_extended_json (request_doc, NULL); + ASSERT_WITH_MSG (bson_has_field (request_doc, "speculativeAuthenticate"), + "expected hello to contain 'speculativeAuthenticate', got: %s", + request_str); // Respond with a non-empty document "speculativeAuthenticate" field. // The C driver will interpret this as a successful X509 // authentication. @@ -471,8 +439,7 @@ test_mongoc_speculative_auth_request_x509_network_error (void) // Expect a ping command. Respond with a network error. { - request_t *request = mock_server_receives_msg ( - server, MONGOC_MSG_NONE, tmp_bson ("{'ping': 1}")); + request_t *request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'ping': 1}")); ASSERT (request); // Cause a network error. reply_to_request_with_hang_up (request); @@ -481,10 +448,7 @@ test_mongoc_speculative_auth_request_x509_network_error (void) // Expect error. ASSERT (!future_get_bool (future)); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_SOCKET, - "socket error"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "socket error"); future_destroy (future); } @@ -493,8 +457,7 @@ test_mongoc_speculative_auth_request_x509_network_error (void) bson_error_t error; // Send ping. - future_t *future = future_client_command_simple ( - client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); + future_t *future = future_client_command_simple (client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); // Expect a hello including speculativeAuthenticate field. { @@ -502,12 +465,10 @@ test_mongoc_speculative_auth_request_x509_network_error (void) ASSERT (request); const bson_t *request_doc = request_get_doc (request, 0); ASSERT (request_doc); - char *request_str = - bson_as_canonical_extended_json (request_doc, NULL); - ASSERT_WITH_MSG ( - bson_has_field (request_doc, "speculativeAuthenticate"), - "expected hello to contain 'speculativeAuthenticate', got: %s", - request_str); + char *request_str = bson_as_canonical_extended_json (request_doc, NULL); + ASSERT_WITH_MSG (bson_has_field (request_doc, "speculativeAuthenticate"), + "expected hello to contain 'speculativeAuthenticate', got: %s", + request_str); // Respond with a non-empty document "speculativeAuthenticate" field. // The C driver will interpret this as a successful X509 // authentication. @@ -535,8 +496,7 @@ test_mongoc_speculative_auth_request_x509_network_error (void) // Expect a ping command. Respond with {"ok": 1}. { - request_t *request = mock_server_receives_msg ( - server, MONGOC_MSG_NONE, tmp_bson ("{'ping': 1}")); + request_t *request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'ping': 1}")); ASSERT (request); reply_to_request_with_ok_and_destroy (request); } @@ -558,11 +518,10 @@ test_mongoc_speculative_auth_request_x509_network_error (void) static void test_mongoc_speculative_auth_request_scram (void) { - bson_t *response = BCON_NEW ( - "conversationId", - BCON_INT32 (15081984), - "payload", - BCON_BIN (BSON_SUBTYPE_BINARY, (const uint8_t *) "deadbeef", 8)); + bson_t *response = BCON_NEW ("conversationId", + BCON_INT32 (15081984), + "payload", + BCON_BIN (BSON_SUBTYPE_BINARY, (const uint8_t *) "deadbeef", 8)); _test_mongoc_speculative_auth (false, false, @@ -579,11 +538,10 @@ test_mongoc_speculative_auth_request_scram (void) static void test_mongoc_speculative_auth_request_scram_pool (void) { - bson_t *response = BCON_NEW ( - "conversationId", - BCON_INT32 (15081984), - "payload", - BCON_BIN (BSON_SUBTYPE_BINARY, (const uint8_t *) "deadbeef", 8)); + bson_t *response = BCON_NEW ("conversationId", + BCON_INT32 (15081984), + "payload", + BCON_BIN (BSON_SUBTYPE_BINARY, (const uint8_t *) "deadbeef", 8)); _test_mongoc_speculative_auth (true, false, @@ -602,31 +560,18 @@ void test_speculative_auth_install (TestSuite *suite) { #ifdef MONGOC_ENABLE_CRYPTO - TestSuite_AddMockServerTest (suite, - "/speculative_auth/request_none", - test_mongoc_speculative_auth_request_none); - TestSuite_AddMockServerTest (suite, - "/speculative_auth/request_scram", - test_mongoc_speculative_auth_request_scram); - TestSuite_AddMockServerTest (suite, - "/speculative_auth_pool/request_none", - test_mongoc_speculative_auth_request_none_pool); -#if defined(MONGOC_ENABLE_SSL_OPENSSL) || \ - defined(MONGOC_ENABLE_SSL_SECURE_TRANSPORT) - TestSuite_AddMockServerTest (suite, - "/speculative_auth/request_x509", - test_mongoc_speculative_auth_request_x509); - TestSuite_AddMockServerTest (suite, - "/speculative_auth_pool/request_x509", - test_mongoc_speculative_auth_request_x509_pool); + TestSuite_AddMockServerTest (suite, "/speculative_auth/request_none", test_mongoc_speculative_auth_request_none); + TestSuite_AddMockServerTest (suite, "/speculative_auth/request_scram", test_mongoc_speculative_auth_request_scram); + TestSuite_AddMockServerTest ( + suite, "/speculative_auth_pool/request_none", test_mongoc_speculative_auth_request_none_pool); +#if defined(MONGOC_ENABLE_SSL_OPENSSL) || defined(MONGOC_ENABLE_SSL_SECURE_TRANSPORT) + TestSuite_AddMockServerTest (suite, "/speculative_auth/request_x509", test_mongoc_speculative_auth_request_x509); + TestSuite_AddMockServerTest ( + suite, "/speculative_auth_pool/request_x509", test_mongoc_speculative_auth_request_x509_pool); TestSuite_AddMockServerTest ( - suite, - "/speculative_auth/request_x509/network_error", - test_mongoc_speculative_auth_request_x509_network_error); + suite, "/speculative_auth/request_x509/network_error", test_mongoc_speculative_auth_request_x509_network_error); #endif /* MONGOC_ENABLE_SSL_* */ TestSuite_AddMockServerTest ( - suite, - "/speculative_auth_pool/request_scram", - test_mongoc_speculative_auth_request_scram_pool); + suite, "/speculative_auth_pool/request_scram", test_mongoc_speculative_auth_request_scram_pool); #endif /* MONGOC_ENABLE_CRYPTO */ } diff --git a/src/libmongoc/tests/test-mongoc-ssl.c b/src/libmongoc/tests/test-mongoc-ssl.c index 9a2e01e7ba..17d208f63b 100644 --- a/src/libmongoc/tests/test-mongoc-ssl.c +++ b/src/libmongoc/tests/test-mongoc-ssl.c @@ -51,99 +51,97 @@ MONGOC_URI_TLSDISABLEOCSPENDPOINTCHECK "tlsdisableocspendpointcheck" static void test_mongoc_ssl_opts_from_bson (void) { - testcase_t tests[] = { - { - "test all options set", - "{'tlsCertificateKeyFile': 'test_pem_file', " - "'tlsCertificateKeyFilePassword': 'test_pem_pwd', 'tlsCAFile': " - "'test_ca_file', 'tlsAllowInvalidCertificates': true, " - "'tlsAllowInvalidHostnames': true, 'tlsInsecure': true, " - "'tlsDisableCertificateRevocationCheck': true, " - "'tlsDisableOCSPEndpointCheck': true }", - NULL /* expect_error */, - "test_pem_file" /* pem_file */, - "test_pem_pwd" /* pem_pwd */, - "test_ca_file" /* ca_file */, - true /* weak_cert_validation */, - true /* allow_invalid_hostname */, - true /* disable_ocsp_endpoint_check */, - true /* disable_certificate_revocation_check */ - }, - { - "test options are case insentive", - "{'tlscertificatekeyfile': 'test_pem_file', " - "'tlscertificatekeyfilepassword': 'test_pem_pwd', 'tlscafile': " - "'test_ca_file', 'tlsallowinvalidcertificates': true, " - "'tlsallowinvalidhostnames': true, 'tlsinsecure': true, " - "'tlsdisablecertificaterevocationcheck': true, " - "'tlsdisableocspendpointcheck': true }", - NULL /* expect_error */, - "test_pem_file" /* pem_file */, - "test_pem_pwd" /* pem_pwd */, - "test_ca_file" /* ca_file */, - true /* weak_cert_validation */, - true /* allow_invalid_hostname */, - true /* disable_ocsp_endpoint_check */, - true /* disable_certificate_revocation_check */ - }, - { - "test no options set", - "{}", - NULL /* expect_error */, - NULL /* pem_file */, - NULL /* pem_pwd */, - NULL /* ca_file */, - false /* weak_cert_validation */, - false /* allow_invalid_hostname */, - false /* disable_ocsp_endpoint_check */, - false /* disable_certificate_revocation_check */ - }, - { - "test tlsInsecure overrides tlsAllowInvalidHostnames and " - "tlsAllowInvalidCertificates set", - "{'tlsInsecure': true, 'tlsAllowInvalidHostnames': false, " - "'tlsAllowInvalidCertificates': false}", - NULL /* expect_error */, - NULL /* pem_file */, - NULL /* pem_pwd */, - NULL /* ca_file */, - true /* weak_cert_validation */, - true /* allow_invalid_hostname */, - false /* disable_ocsp_endpoint_check */, - false /* disable_certificate_revocation_check */ - }, - { - "test unrecognized option", - "{'foo': true }", - "unexpected BOOL option: foo" /* expect_error */, - NULL /* pem_file */, - NULL /* pem_pwd */, - NULL /* ca_file */, - false /* weak_cert_validation */, - false /* allow_invalid_hostname */, - false /* disable_ocsp_endpoint_check */, - false /* disable_certificate_revocation_check */ - }, - { - "test wrong value type", - "{'tlsCaFile': true }", - "unexpected BOOL option: tlsCaFile" /* expect_error */, - NULL /* pem_file */, - NULL /* pem_pwd */, - NULL /* ca_file */, - false /* weak_cert_validation */, - false /* allow_invalid_hostname */, - false /* disable_ocsp_endpoint_check */, - false /* disable_certificate_revocation_check */ - }, - {0}}; + testcase_t tests[] = {{ + "test all options set", + "{'tlsCertificateKeyFile': 'test_pem_file', " + "'tlsCertificateKeyFilePassword': 'test_pem_pwd', 'tlsCAFile': " + "'test_ca_file', 'tlsAllowInvalidCertificates': true, " + "'tlsAllowInvalidHostnames': true, 'tlsInsecure': true, " + "'tlsDisableCertificateRevocationCheck': true, " + "'tlsDisableOCSPEndpointCheck': true }", + NULL /* expect_error */, + "test_pem_file" /* pem_file */, + "test_pem_pwd" /* pem_pwd */, + "test_ca_file" /* ca_file */, + true /* weak_cert_validation */, + true /* allow_invalid_hostname */, + true /* disable_ocsp_endpoint_check */, + true /* disable_certificate_revocation_check */ + }, + { + "test options are case insentive", + "{'tlscertificatekeyfile': 'test_pem_file', " + "'tlscertificatekeyfilepassword': 'test_pem_pwd', 'tlscafile': " + "'test_ca_file', 'tlsallowinvalidcertificates': true, " + "'tlsallowinvalidhostnames': true, 'tlsinsecure': true, " + "'tlsdisablecertificaterevocationcheck': true, " + "'tlsdisableocspendpointcheck': true }", + NULL /* expect_error */, + "test_pem_file" /* pem_file */, + "test_pem_pwd" /* pem_pwd */, + "test_ca_file" /* ca_file */, + true /* weak_cert_validation */, + true /* allow_invalid_hostname */, + true /* disable_ocsp_endpoint_check */, + true /* disable_certificate_revocation_check */ + }, + { + "test no options set", + "{}", + NULL /* expect_error */, + NULL /* pem_file */, + NULL /* pem_pwd */, + NULL /* ca_file */, + false /* weak_cert_validation */, + false /* allow_invalid_hostname */, + false /* disable_ocsp_endpoint_check */, + false /* disable_certificate_revocation_check */ + }, + { + "test tlsInsecure overrides tlsAllowInvalidHostnames and " + "tlsAllowInvalidCertificates set", + "{'tlsInsecure': true, 'tlsAllowInvalidHostnames': false, " + "'tlsAllowInvalidCertificates': false}", + NULL /* expect_error */, + NULL /* pem_file */, + NULL /* pem_pwd */, + NULL /* ca_file */, + true /* weak_cert_validation */, + true /* allow_invalid_hostname */, + false /* disable_ocsp_endpoint_check */, + false /* disable_certificate_revocation_check */ + }, + { + "test unrecognized option", + "{'foo': true }", + "unexpected BOOL option: foo" /* expect_error */, + NULL /* pem_file */, + NULL /* pem_pwd */, + NULL /* ca_file */, + false /* weak_cert_validation */, + false /* allow_invalid_hostname */, + false /* disable_ocsp_endpoint_check */, + false /* disable_certificate_revocation_check */ + }, + { + "test wrong value type", + "{'tlsCaFile': true }", + "unexpected BOOL option: tlsCaFile" /* expect_error */, + NULL /* pem_file */, + NULL /* pem_pwd */, + NULL /* ca_file */, + false /* weak_cert_validation */, + false /* allow_invalid_hostname */, + false /* disable_ocsp_endpoint_check */, + false /* disable_certificate_revocation_check */ + }, + {0}}; testcase_t *test; for (test = tests; test->bson != NULL; test++) { mongoc_ssl_opt_t ssl_opt = {0}; bson_string_t *errmsg = bson_string_new (NULL); - bool ok = - _mongoc_ssl_opts_from_bson (&ssl_opt, tmp_bson (test->bson), errmsg); + bool ok = _mongoc_ssl_opts_from_bson (&ssl_opt, tmp_bson (test->bson), errmsg); MONGOC_DEBUG ("testcase: %s", test->bson); if (test->expect_error) { @@ -176,12 +174,9 @@ test_mongoc_ssl_opts_from_bson (void) ASSERT_CMPSTR (test->expect_ca_file, ssl_opt.ca_file); } - ASSERT (test->expect_weak_cert_validation == - ssl_opt.weak_cert_validation); - ASSERT (test->expect_allow_invalid_hostname == - ssl_opt.allow_invalid_hostname); - ASSERT (test->expect_disable_ocsp_endpoint_check == - _mongoc_ssl_opts_disable_ocsp_endpoint_check (&ssl_opt)); + ASSERT (test->expect_weak_cert_validation == ssl_opt.weak_cert_validation); + ASSERT (test->expect_allow_invalid_hostname == ssl_opt.allow_invalid_hostname); + ASSERT (test->expect_disable_ocsp_endpoint_check == _mongoc_ssl_opts_disable_ocsp_endpoint_check (&ssl_opt)); ASSERT (test->expect_disable_certificate_revocation_check == _mongoc_ssl_opts_disable_certificate_revocation_check (&ssl_opt)); diff --git a/src/libmongoc/tests/test-mongoc-stream-tls-error.c b/src/libmongoc/tests/test-mongoc-stream-tls-error.c index a9d9faa03f..b3d31001b7 100644 --- a/src/libmongoc/tests/test-mongoc-stream-tls-error.c +++ b/src/libmongoc/tests/test-mongoc-stream-tls-error.c @@ -14,8 +14,7 @@ #define TIMEOUT 10000 /* milliseconds */ -#if !defined(MONGOC_ENABLE_SSL_SECURE_CHANNEL) && \ - !defined(MONGOC_ENABLE_SSL_LIBRESSL) && \ +#if !defined(MONGOC_ENABLE_SSL_SECURE_CHANNEL) && !defined(MONGOC_ENABLE_SSL_LIBRESSL) && \ !defined(MONGOC_ENABLE_SSL_SECURE_TRANSPORT) /** run as a child thread by test_mongoc_tls_hangup * @@ -52,13 +51,11 @@ static BSON_THREAD_FUN (ssl_error_server, ptr) server_addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK); server_addr.sin_port = htons (0); - r = mongoc_socket_bind ( - listen_sock, (struct sockaddr *) &server_addr, sizeof server_addr); + r = mongoc_socket_bind (listen_sock, (struct sockaddr *) &server_addr, sizeof server_addr); BSON_ASSERT (r == 0); sock_len = sizeof (server_addr); - r = mongoc_socket_getsockname ( - listen_sock, (struct sockaddr *) &server_addr, &sock_len); + r = mongoc_socket_getsockname (listen_sock, (struct sockaddr *) &server_addr, &sock_len); BSON_ASSERT (r == 0); r = mongoc_socket_listen (listen_sock, 10); @@ -75,8 +72,7 @@ static BSON_THREAD_FUN (ssl_error_server, ptr) sock_stream = mongoc_stream_socket_new (conn_sock); BSON_ASSERT (sock_stream); - ssl_stream = mongoc_stream_tls_new_with_hostname ( - sock_stream, data->host, data->server, 0); + ssl_stream = mongoc_stream_tls_new_with_hostname (sock_stream, data->host, data->server, 0); BSON_ASSERT (ssl_stream); switch (data->behavior) { @@ -84,8 +80,7 @@ static BSON_THREAD_FUN (ssl_error_server, ptr) _mongoc_usleep (data->handshake_stall_ms * 1000); break; case SSL_TEST_BEHAVIOR_HANGUP_AFTER_HANDSHAKE: - r = mongoc_stream_tls_handshake_block ( - ssl_stream, data->host, TIMEOUT, &error); + r = mongoc_stream_tls_handshake_block (ssl_stream, data->host, TIMEOUT, &error); BSON_ASSERT (r); r = mongoc_stream_readv (ssl_stream, &iov, 1, 1, TIMEOUT); @@ -144,19 +139,16 @@ static BSON_THREAD_FUN (ssl_hangup_client, ptr) server_addr.sin_port = htons (data->server_port); server_addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK); - r = mongoc_socket_connect ( - conn_sock, (struct sockaddr *) &server_addr, sizeof (server_addr), -1); + r = mongoc_socket_connect (conn_sock, (struct sockaddr *) &server_addr, sizeof (server_addr), -1); BSON_ASSERT (r == 0); sock_stream = mongoc_stream_socket_new (conn_sock); BSON_ASSERT (sock_stream); - ssl_stream = mongoc_stream_tls_new_with_hostname ( - sock_stream, data->host, data->client, 1); + ssl_stream = mongoc_stream_tls_new_with_hostname (sock_stream, data->host, data->client, 1); BSON_ASSERT (ssl_stream); - r = mongoc_stream_tls_handshake_block ( - ssl_stream, data->host, TIMEOUT, &error); + r = mongoc_stream_tls_handshake_block (ssl_stream, data->host, TIMEOUT, &error); BSON_ASSERT (r); wiov.iov_base = (void *) &buf; @@ -268,20 +260,16 @@ static BSON_THREAD_FUN (handshake_stall_client, ptr) /* we should time out after about 200ms */ start_time = bson_get_monotonic_time (); - mongoc_client_read_command_with_opts ( - client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, &reply, &error); + mongoc_client_read_command_with_opts (client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, &reply, &error); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_SERVER_SELECTION, - MONGOC_ERROR_SERVER_SELECTION_FAILURE, - "socket timeout"); + ASSERT_ERROR_CONTAINS ( + error, MONGOC_ERROR_SERVER_SELECTION, MONGOC_ERROR_SERVER_SELECTION_FAILURE, "socket timeout"); /* time is in microseconds */ duration_ms = (bson_get_monotonic_time () - start_time) / 1000; if (llabs (duration_ms - connect_timeout_ms) > 100) { - test_error ("expected timeout after about 200ms, not %" PRId64, - duration_ms); + test_error ("expected timeout after about 200ms, not %" PRId64, duration_ms); } data->client_result->result = SSL_TEST_SUCCESS; @@ -348,24 +336,22 @@ test_mongoc_tls_handshake_stall (void) /* TLS stream should be NULL and base stream should still be valid, and error * messages should be consistent across TLS libs. Until CDRIVER-2844, just * assert message includes the filename, and handle NULL or non-NULL return. */ -#define TLS_LOAD_ERR(_field) \ - do { \ - (_field) = "badfile"; \ - capture_logs (true); \ - base = mongoc_stream_socket_new ( \ - mongoc_socket_new (AF_INET, SOCK_STREAM, 0)); \ - tls_stream = mongoc_stream_tls_new_with_hostname (base, NULL, &opt, 0); \ - \ - ASSERT_CAPTURED_LOG ( \ - "bad TLS config file", MONGOC_LOG_LEVEL_ERROR, "badfile"); \ - \ - if (tls_stream) { \ - mongoc_stream_destroy (tls_stream); \ - } else { \ - mongoc_stream_destroy (base); \ - } \ - \ - opt.pem_file = opt.ca_file = opt.ca_dir = opt.crl_file = NULL; \ +#define TLS_LOAD_ERR(_field) \ + do { \ + (_field) = "badfile"; \ + capture_logs (true); \ + base = mongoc_stream_socket_new (mongoc_socket_new (AF_INET, SOCK_STREAM, 0)); \ + tls_stream = mongoc_stream_tls_new_with_hostname (base, NULL, &opt, 0); \ + \ + ASSERT_CAPTURED_LOG ("bad TLS config file", MONGOC_LOG_LEVEL_ERROR, "badfile"); \ + \ + if (tls_stream) { \ + mongoc_stream_destroy (tls_stream); \ + } else { \ + mongoc_stream_destroy (base); \ + } \ + \ + opt.pem_file = opt.ca_file = opt.ca_dir = opt.crl_file = NULL; \ } while (0) static void @@ -383,16 +369,14 @@ test_mongoc_tls_load_files (void) void test_stream_tls_error_install (TestSuite *suite) { -#if !defined(MONGOC_ENABLE_SSL_SECURE_CHANNEL) && \ - !defined(MONGOC_ENABLE_SSL_LIBRESSL) +#if !defined(MONGOC_ENABLE_SSL_SECURE_CHANNEL) && !defined(MONGOC_ENABLE_SSL_LIBRESSL) #if !defined(__APPLE__) TestSuite_Add (suite, "/TLS/hangup", test_mongoc_tls_hangup); #endif /* see CDRIVER-2222 this occasionally stalls for a few 100ms on Mac */ #if !defined(MONGOC_ENABLE_SSL_SECURE_TRANSPORT) - TestSuite_Add ( - suite, "/TLS/handshake_stall", test_mongoc_tls_handshake_stall); + TestSuite_Add (suite, "/TLS/handshake_stall", test_mongoc_tls_handshake_stall); #endif #endif /* !MONGOC_ENABLE_SSL_SECURE_CHANNEL && !MONGOC_ENABLE_SSL_LIBRESSL */ TestSuite_Add (suite, "/TLS/load_files", test_mongoc_tls_load_files); diff --git a/src/libmongoc/tests/test-mongoc-stream-tls.c b/src/libmongoc/tests/test-mongoc-stream-tls.c index aa7012a798..904af424d7 100644 --- a/src/libmongoc/tests/test-mongoc-stream-tls.c +++ b/src/libmongoc/tests/test-mongoc-stream-tls.c @@ -10,8 +10,7 @@ #include "test-libmongoc.h" #include "test-conveniences.h" -#if !defined(MONGOC_ENABLE_SSL_SECURE_CHANNEL) && \ - !defined(MONGOC_ENABLE_SSL_LIBRESSL) +#if !defined(MONGOC_ENABLE_SSL_SECURE_CHANNEL) && !defined(MONGOC_ENABLE_SSL_LIBRESSL) static void test_mongoc_tls_no_certs (void) @@ -366,8 +365,8 @@ test_mongoc_tls_ip (void) #endif -#if !defined(__APPLE__) && !defined(_WIN32) && \ - defined(MONGOC_ENABLE_SSL_OPENSSL) && OPENSSL_VERSION_NUMBER >= 0x10000000L +#if !defined(__APPLE__) && !defined(_WIN32) && defined(MONGOC_ENABLE_SSL_OPENSSL) && \ + OPENSSL_VERSION_NUMBER >= 0x10000000L static void test_mongoc_tls_trust_dir (void) { @@ -404,12 +403,8 @@ test_mongoc_tls_insecure_nowarning (void) client = test_framework_client_new_from_uri (uri, NULL); capture_logs (true); - mongoc_client_command_simple (client, - "admin", - tmp_bson ("{'ping': 1}"), - NULL /* read prefs */, - NULL /* reply */, - NULL /* error */); + mongoc_client_command_simple ( + client, "admin", tmp_bson ("{'ping': 1}"), NULL /* read prefs */, NULL /* reply */, NULL /* error */); ASSERT_NO_CAPTURED_LOGS ("has no effect"); mongoc_client_destroy (client); mongoc_uri_destroy (uri); @@ -418,8 +413,7 @@ test_mongoc_tls_insecure_nowarning (void) void test_stream_tls_install (TestSuite *suite) { -#if !defined(MONGOC_ENABLE_SSL_SECURE_CHANNEL) && \ - !defined(MONGOC_ENABLE_SSL_LIBRESSL) +#if !defined(MONGOC_ENABLE_SSL_SECURE_CHANNEL) && !defined(MONGOC_ENABLE_SSL_LIBRESSL) /* Disable /TLS/commonName on macOS due to CDRIVER-4256. */ #if !defined(MONGOC_ENABLE_SSL_SECURE_TRANSPORT) @@ -427,9 +421,7 @@ test_stream_tls_install (TestSuite *suite) #endif TestSuite_Add (suite, "/TLS/altname", test_mongoc_tls_altname); TestSuite_Add (suite, "/TLS/basic", test_mongoc_tls_basic); - TestSuite_Add (suite, - "/TLS/allow_invalid_hostname", - test_mongoc_tls_allow_invalid_hostname); + TestSuite_Add (suite, "/TLS/allow_invalid_hostname", test_mongoc_tls_allow_invalid_hostname); TestSuite_Add (suite, "/TLS/wild", test_mongoc_tls_wild); TestSuite_Add (suite, "/TLS/no_verify", test_mongoc_tls_no_verify); TestSuite_Add (suite, "/TLS/bad_verify", test_mongoc_tls_bad_verify); @@ -441,17 +433,15 @@ test_stream_tls_install (TestSuite *suite) TestSuite_Add (suite, "/TLS/ip", test_mongoc_tls_ip); TestSuite_Add (suite, "/TLS/password", test_mongoc_tls_password); TestSuite_Add (suite, "/TLS/bad_password", test_mongoc_tls_bad_password); - TestSuite_Add ( - suite, "/TLS/weak_cert_validation", test_mongoc_tls_weak_cert_validation); + TestSuite_Add (suite, "/TLS/weak_cert_validation", test_mongoc_tls_weak_cert_validation); TestSuite_Add (suite, "/TLS/crl", test_mongoc_tls_crl); #endif -#if !defined(__APPLE__) && !defined(_WIN32) && \ - defined(MONGOC_ENABLE_SSL_OPENSSL) && OPENSSL_VERSION_NUMBER >= 0x10000000L +#if !defined(__APPLE__) && !defined(_WIN32) && defined(MONGOC_ENABLE_SSL_OPENSSL) && \ + OPENSSL_VERSION_NUMBER >= 0x10000000L TestSuite_Add (suite, "/TLS/trust_dir", test_mongoc_tls_trust_dir); #endif - TestSuite_AddLive ( - suite, "/TLS/insecure_nowarning", test_mongoc_tls_insecure_nowarning); + TestSuite_AddLive (suite, "/TLS/insecure_nowarning", test_mongoc_tls_insecure_nowarning); #endif } diff --git a/src/libmongoc/tests/test-mongoc-stream.c b/src/libmongoc/tests/test-mongoc-stream.c index b3a86cf726..2a3126d69b 100644 --- a/src/libmongoc/tests/test-mongoc-stream.c +++ b/src/libmongoc/tests/test-mongoc-stream.c @@ -16,8 +16,7 @@ test_buffered_basic (void) ssize_t r; char buf[16236]; - stream = - mongoc_stream_file_new_for_path (BINARY_DIR "/reply2.dat", O_RDONLY, 0); + stream = mongoc_stream_file_new_for_path (BINARY_DIR "/reply2.dat", O_RDONLY, 0); BSON_ASSERT (stream); /* buffered assumes ownership of stream */ @@ -30,11 +29,7 @@ test_buffered_basic (void) if (r != iov.iov_len) { char msg[100]; - bson_snprintf (msg, - 100, - "Expected %lld got %llu", - (long long) r, - (unsigned long long) iov.iov_len); + bson_snprintf (msg, 100, "Expected %lld got %llu", (long long) r, (unsigned long long) iov.iov_len); ASSERT_CMPSTR (msg, "failed"); } @@ -52,8 +47,7 @@ test_buffered_oversized (void) ssize_t r; char buf[16236]; - stream = - mongoc_stream_file_new_for_path (BINARY_DIR "/reply2.dat", O_RDONLY, 0); + stream = mongoc_stream_file_new_for_path (BINARY_DIR "/reply2.dat", O_RDONLY, 0); BSON_ASSERT (stream); /* buffered assumes ownership of stream */ @@ -66,11 +60,7 @@ test_buffered_oversized (void) if (r != iov.iov_len) { char msg[100]; - bson_snprintf (msg, - 100, - "Expected %lld got %llu", - (long long) r, - (unsigned long long) iov.iov_len); + bson_snprintf (msg, 100, "Expected %lld got %llu", (long long) r, (unsigned long long) iov.iov_len); ASSERT_CMPSTR (msg, "failed"); } @@ -85,10 +75,7 @@ typedef struct { } failing_stream_t; static ssize_t -failing_stream_writev (mongoc_stream_t *stream, - mongoc_iovec_t *iov, - size_t iovcnt, - int32_t timeout_msec) +failing_stream_writev (mongoc_stream_t *stream, mongoc_iovec_t *iov, size_t iovcnt, int32_t timeout_msec) { failing_stream_t *fstream = (failing_stream_t *) stream; @@ -177,16 +164,12 @@ _writev_timeout_stream_destroy (mongoc_stream_t *stream) } static ssize_t -_writev_timeout_stream_writev (mongoc_stream_t *stream_param, - mongoc_iovec_t *iov, - size_t iovcnt, - int32_t timeout_msec) +_writev_timeout_stream_writev (mongoc_stream_t *stream_param, mongoc_iovec_t *iov, size_t iovcnt, int32_t timeout_msec) { BSON_UNUSED (iov); BSON_UNUSED (iovcnt); - writev_timeout_stream_t *const stream = - (writev_timeout_stream_t *) stream_param; + writev_timeout_stream_t *const stream = (writev_timeout_stream_t *) stream_param; stream->is_set = true; stream->timeout_msec = timeout_msec; @@ -197,8 +180,7 @@ _writev_timeout_stream_writev (mongoc_stream_t *stream_param, static writev_timeout_stream_t * _writev_timeout_stream_new (void) { - writev_timeout_stream_t *const stream = - bson_malloc (sizeof (writev_timeout_stream_t)); + writev_timeout_stream_t *const stream = bson_malloc (sizeof (writev_timeout_stream_t)); *stream = (writev_timeout_stream_t){ .vtable = @@ -227,17 +209,10 @@ test_stream_writev_timeout (void) writev_timeout_stream_t *const stream = _writev_timeout_stream_new (); ssize_t const res = - _mongoc_stream_writev_full ((mongoc_stream_t *) stream, - &iov, - 1u, - MONGOC_DEFAULT_SOCKETTIMEOUTMS, - &error); + _mongoc_stream_writev_full ((mongoc_stream_t *) stream, &iov, 1u, MONGOC_DEFAULT_SOCKETTIMEOUTMS, &error); ASSERT_CMPSSIZE_T (res, ==, 0); - ASSERT_WITH_MSG ( - stream->is_set, - "expected _writev_timeout_stream_writev() to be invoked"); - ASSERT_CMPINT32 ( - stream->timeout_msec, ==, MONGOC_DEFAULT_SOCKETTIMEOUTMS); + ASSERT_WITH_MSG (stream->is_set, "expected _writev_timeout_stream_writev() to be invoked"); + ASSERT_CMPINT32 (stream->timeout_msec, ==, MONGOC_DEFAULT_SOCKETTIMEOUTMS); mongoc_stream_destroy ((mongoc_stream_t *) stream); } @@ -246,12 +221,9 @@ test_stream_writev_timeout (void) { writev_timeout_stream_t *const stream = _writev_timeout_stream_new (); - ssize_t const res = _mongoc_stream_writev_full ( - (mongoc_stream_t *) stream, &iov, 1u, 0, &error); + ssize_t const res = _mongoc_stream_writev_full ((mongoc_stream_t *) stream, &iov, 1u, 0, &error); ASSERT_CMPSSIZE_T (res, ==, 0); - ASSERT_WITH_MSG ( - stream->is_set, - "expected _writev_timeout_stream_writev() to be invoked"); + ASSERT_WITH_MSG (stream->is_set, "expected _writev_timeout_stream_writev() to be invoked"); ASSERT_CMPINT32 (stream->timeout_msec, ==, 0); mongoc_stream_destroy ((mongoc_stream_t *) stream); @@ -266,12 +238,9 @@ test_stream_writev_timeout (void) writev_timeout_stream_t *const stream = _writev_timeout_stream_new (); - ssize_t const res = _mongoc_stream_writev_full ( - (mongoc_stream_t *) stream, &iov, 1u, -1, &error); + ssize_t const res = _mongoc_stream_writev_full ((mongoc_stream_t *) stream, &iov, 1u, -1, &error); ASSERT_CMPSSIZE_T (res, ==, 0); - ASSERT_WITH_MSG ( - stream->is_set, - "expected _writev_timeout_stream_writev() to be invoked"); + ASSERT_WITH_MSG (stream->is_set, "expected _writev_timeout_stream_writev() to be invoked"); ASSERT_CMPINT32 (stream->timeout_msec, ==, default_timeout_msec); mongoc_stream_destroy ((mongoc_stream_t *) stream); diff --git a/src/libmongoc/tests/test-mongoc-streamable-hello.c b/src/libmongoc/tests/test-mongoc-streamable-hello.c index e4f376d320..ba985d3ac4 100644 --- a/src/libmongoc/tests/test-mongoc-streamable-hello.c +++ b/src/libmongoc/tests/test-mongoc-streamable-hello.c @@ -14,10 +14,8 @@ #undef MONGOC_LOG_DOMAIN #define MONGOC_LOG_DOMAIN "streamable-hello" -#define TV1 \ - "{ 'processId': { '$oid': 'AABBAABBAABBAABBAABBAABB' }, 'counter': 1 }" -#define TV2 \ - "{ 'processId': { '$oid': 'AABBAABBAABBAABBAABBAABB' }, 'counter': 2 }" +#define TV1 "{ 'processId': { '$oid': 'AABBAABBAABBAABBAABBAABB' }, 'counter': 1 }" +#define TV2 "{ 'processId': { '$oid': 'AABBAABBAABBAABBAABBAABB' }, 'counter': 2 }" static mongoc_server_description_t * _force_scan (mongoc_client_t *client, mock_server_t *server, const char *hello) @@ -31,8 +29,7 @@ _force_scan (mongoc_client_t *client, mock_server_t *server, const char *hello) /* Mark the topology as "stale" to trigger a scan. */ client->topology->stale = true; - future = - future_client_select_server (client, true /* for writes */, NULL, &error); + future = future_client_select_server (client, true /* for writes */, NULL, &error); request = mock_server_receives_any_hello (server); reply_to_request_simple (request, hello); sd = future_get_mongoc_server_description_ptr (future); @@ -53,8 +50,7 @@ test_topology_version_update (void) server = mock_server_new (); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); /* Override minHeartbeatFrequencyMS so test does not wait for 500ms when a * scan is needed. */ client->topology->min_heartbeat_frequency_msec = 1; @@ -126,9 +122,7 @@ _single_to_double (const char *in) } static void -_assert_topology_version_compare (const char *tv1, - const char *tv2, - int expected) +_assert_topology_version_compare (const char *tv1, const char *tv2, int expected) { int actual; bson_t *tv1_bson; @@ -137,12 +131,10 @@ _assert_topology_version_compare (const char *tv1, char *tv1_quoted = _single_to_double (tv1); char *tv2_quoted = _single_to_double (tv2); - tv1_bson = bson_new_from_json ( - (const uint8_t *) tv1_quoted, strlen (tv1_quoted), &error); + tv1_bson = bson_new_from_json ((const uint8_t *) tv1_quoted, strlen (tv1_quoted), &error); ASSERT_OR_PRINT (tv1_bson, error); - tv2_bson = bson_new_from_json ( - (const uint8_t *) tv2_quoted, strlen (tv2_quoted), &error); + tv2_bson = bson_new_from_json ((const uint8_t *) tv2_quoted, strlen (tv2_quoted), &error); ASSERT_OR_PRINT (tv2_bson, error); actual = mongoc_server_description_topology_version_cmp (tv1_bson, tv2_bson); @@ -157,45 +149,31 @@ _assert_topology_version_compare (const char *tv1, static void test_topology_version_compare (void) { - _assert_topology_version_compare ( - "{ 'processId': { '$oid': 'AABBAABBAABBAABBAABBAABB' }, 'counter': 1 }", - "{ 'processId': { '$oid': 'AABBAABBAABBAABBAABBAABB' }, 'counter': 2 }", - -1); - _assert_topology_version_compare ( - "{ 'processId': { '$oid': 'AABBAABBAABBAABBAABBAABB' }, 'counter': 1 }", - "{ 'processId': { '$oid': 'AABBAABBAABBAABBAABBAABB' }, 'counter': 1 }", - 0); - _assert_topology_version_compare ( - "{ 'processId': { '$oid': 'AABBAABBAABBAABBAABBAABB' }, 'counter': 2 }", - "{ 'processId': { '$oid': 'AABBAABBAABBAABBAABBAABB' }, 'counter': 1 }", - 1); + _assert_topology_version_compare ("{ 'processId': { '$oid': 'AABBAABBAABBAABBAABBAABB' }, 'counter': 1 }", + "{ 'processId': { '$oid': 'AABBAABBAABBAABBAABBAABB' }, 'counter': 2 }", + -1); + _assert_topology_version_compare ("{ 'processId': { '$oid': 'AABBAABBAABBAABBAABBAABB' }, 'counter': 1 }", + "{ 'processId': { '$oid': 'AABBAABBAABBAABBAABBAABB' }, 'counter': 1 }", + 0); + _assert_topology_version_compare ("{ 'processId': { '$oid': 'AABBAABBAABBAABBAABBAABB' }, 'counter': 2 }", + "{ 'processId': { '$oid': 'AABBAABBAABBAABBAABBAABB' }, 'counter': 1 }", + 1); /* Different process IDs always compare less. */ - _assert_topology_version_compare ( - "{ 'processId': { '$oid': 'AABBAABBAABBAABBAABBAABB' }, 'counter': 1 }", - "{ 'processId': { '$oid': 'CCCCCCCCCCCCCCCCCCCCCCCC' }, 'counter': 1 }", - -1); + _assert_topology_version_compare ("{ 'processId': { '$oid': 'AABBAABBAABBAABBAABBAABB' }, 'counter': 1 }", + "{ 'processId': { '$oid': 'CCCCCCCCCCCCCCCCCCCCCCCC' }, 'counter': 1 }", + -1); /* Missing fields or malformed always compare less. */ _assert_topology_version_compare ( - "{ 'processId': { '$oid': 'AABBAABBAABBAABBAABBAABB' }, 'counter': 1 }", - "{ }", - -1); + "{ 'processId': { '$oid': 'AABBAABBAABBAABBAABBAABB' }, 'counter': 1 }", "{ }", -1); _assert_topology_version_compare ( - "{ }", - "{ 'processId': { '$oid': 'AABBAABBAABBAABBAABBAABB' }, 'counter': 1 }", - -1); + "{ }", "{ 'processId': { '$oid': 'AABBAABBAABBAABBAABBAABB' }, 'counter': 1 }", -1); _assert_topology_version_compare ( - "{ 'counter': 2 }", - "{ 'processId': { '$oid': 'AABBAABBAABBAABBAABBAABB' }, 'counter': 1 }", - -1); + "{ 'counter': 2 }", "{ 'processId': { '$oid': 'AABBAABBAABBAABBAABBAABB' }, 'counter': 1 }", -1); } void test_streamable_hello_install (TestSuite *suite) { - TestSuite_AddMockServerTest (suite, - "/streamable/topology_version/update", - test_topology_version_update); - TestSuite_Add (suite, - "/streamable/topology_version/compare", - test_topology_version_compare); + TestSuite_AddMockServerTest (suite, "/streamable/topology_version/update", test_topology_version_update); + TestSuite_Add (suite, "/streamable/topology_version/compare", test_topology_version_compare); } diff --git a/src/libmongoc/tests/test-mongoc-thread.c b/src/libmongoc/tests/test-mongoc-thread.c index ea741e1813..e2e2356198 100644 --- a/src/libmongoc/tests/test-mongoc-thread.c +++ b/src/libmongoc/tests/test-mongoc-thread.c @@ -21,8 +21,7 @@ test_cond_wait (void) bson_mutex_unlock (&mutex); if (!((50 * 1000 < duration_usec) && (150 * 1000 > duration_usec))) { - test_error ("expected to wait 100ms, waited %" PRId64 "\n", - duration_usec / 1000); + test_error ("expected to wait 100ms, waited %" PRId64 "\n", duration_usec / 1000); } mongoc_cond_destroy (&cond); diff --git a/src/libmongoc/tests/test-mongoc-timeout.c b/src/libmongoc/tests/test-mongoc-timeout.c index 51f4b1cf8e..5682e0d27a 100644 --- a/src/libmongoc/tests/test-mongoc-timeout.c +++ b/src/libmongoc/tests/test-mongoc-timeout.c @@ -59,9 +59,7 @@ test_mongoc_timeout_new (void) } void -_test_mongoc_timeout_set_failure (mongoc_timeout_t *timeout, - int64_t try, - const char *err_msg) +_test_mongoc_timeout_set_failure (mongoc_timeout_t *timeout, int64_t try, const char *err_msg) { capture_logs (true); BSON_ASSERT (!mongoc_timeout_set_timeout_ms (timeout, try)); @@ -87,10 +85,8 @@ test_mongoc_timeout_set (void) timeout = mongoc_timeout_new (); BSON_ASSERT (!mongoc_timeout_is_set (timeout)); - _test_mongoc_timeout_set_failure ( - timeout, -1, "timeout must not be negative"); - _test_mongoc_timeout_set_failure ( - timeout, INT64_MIN, "timeout must not be negative"); + _test_mongoc_timeout_set_failure (timeout, -1, "timeout must not be negative"); + _test_mongoc_timeout_set_failure (timeout, INT64_MIN, "timeout must not be negative"); _test_mongoc_timeout_set_success (timeout, 0); _test_mongoc_timeout_set_success (timeout, 1); @@ -124,12 +120,10 @@ _test_mongoc_timeout_copy (mongoc_timeout_t *expected) /* assert different memory addresses */ BSON_ASSERT (expected != actual); - BSON_ASSERT (mongoc_timeout_is_set (actual) == - mongoc_timeout_is_set (expected)); + BSON_ASSERT (mongoc_timeout_is_set (actual) == mongoc_timeout_is_set (expected)); if (mongoc_timeout_is_set (actual)) { - BSON_ASSERT (mongoc_timeout_get_timeout_ms (actual) == - mongoc_timeout_get_timeout_ms (expected)); + BSON_ASSERT (mongoc_timeout_get_timeout_ms (actual) == mongoc_timeout_get_timeout_ms (expected)); } mongoc_timeout_destroy (actual); diff --git a/src/libmongoc/tests/test-mongoc-topology-description.c b/src/libmongoc/tests/test-mongoc-topology-description.c index 7159a23613..4351416a8f 100644 --- a/src/libmongoc/tests/test-mongoc-topology-description.c +++ b/src/libmongoc/tests/test-mongoc-topology-description.c @@ -43,8 +43,7 @@ _test_has_readable_writable_server (bool pooled) client = mongoc_client_pool_pop (pool); } - r = mongoc_client_command_simple ( - client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); + r = mongoc_client_command_simple (client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); ASSERT_OR_PRINT (r, error); mc_tpld_renew_ref (&td, topology); @@ -123,19 +122,11 @@ test_get_servers (void) /* servers "a" and "c" are mongos, but "b" remains unknown */ sd_a = _sd_for_host (tdmod.new_td, "a"); mongoc_topology_description_handle_hello ( - tdmod.new_td, - sd_a->id, - tmp_bson ("{'ok': 1, 'msg': 'isdbgrid'}"), - 100, - NULL); + tdmod.new_td, sd_a->id, tmp_bson ("{'ok': 1, 'msg': 'isdbgrid'}"), 100, NULL); sd_c = _sd_for_host (tdmod.new_td, "c"); mongoc_topology_description_handle_hello ( - tdmod.new_td, - sd_c->id, - tmp_bson ("{'ok': 1, 'msg': 'isdbgrid'}"), - 100, - NULL); + tdmod.new_td, sd_c->id, tmp_bson ("{'ok': 1, 'msg': 'isdbgrid'}"), 100, NULL); sds = mongoc_topology_description_get_servers (tdmod.new_td, &n); ASSERT_CMPSIZE_T ((size_t) 2, ==, n); @@ -155,10 +146,8 @@ test_get_servers (void) mongoc_uri_destroy (uri); } -#define TV_1 \ - "{ 'processId': { '$oid': 'AABBAABBAABBAABBAABBAABB' }, 'counter': 1 }" -#define TV_2 \ - "{ 'processId': { '$oid': 'AABBAABBAABBAABBAABBAABB' }, 'counter': 2 }" +#define TV_1 "{ 'processId': { '$oid': 'AABBAABBAABBAABBAABBAABB' }, 'counter': 1 }" +#define TV_2 "{ 'processId': { '$oid': 'AABBAABBAABBAABBAABBAABB' }, 'counter': 2 }" void _topology_changed (const mongoc_apm_topology_changed_t *event) @@ -186,27 +175,18 @@ test_topology_version_equal (void) callbacks = mongoc_apm_callbacks_new (); mongoc_apm_set_topology_changed_cb (callbacks, _topology_changed); - mongoc_topology_set_apm_callbacks ( - topology, tdmod.new_td, callbacks, &num_calls); + mongoc_topology_set_apm_callbacks (topology, tdmod.new_td, callbacks, &num_calls); sd = _sd_for_host (tdmod.new_td, "host"); mongoc_topology_description_handle_hello ( - tdmod.new_td, - sd->id, - tmp_bson ("{'ok': 1, 'topologyVersion': " TV_2 " }"), - 100, - NULL); + tdmod.new_td, sd->id, tmp_bson ("{'ok': 1, 'topologyVersion': " TV_2 " }"), 100, NULL); ASSERT_CMPINT (num_calls, ==, 1); /* The subsequent hello has a topologyVersion that compares less, so the * hello skips. */ mongoc_topology_description_handle_hello ( - tdmod.new_td, - sd->id, - tmp_bson ("{'ok': 1, 'topologyVersion': " TV_1 " }"), - 100, - NULL); + tdmod.new_td, sd->id, tmp_bson ("{'ok': 1, 'topologyVersion': " TV_1 " }"), 100, NULL); ASSERT_CMPINT (num_calls, ==, 1); @@ -237,19 +217,11 @@ test_topology_description_new_copy (void) /* servers "a" and "c" are mongos, but "b" remains unknown */ sd_a = _sd_for_host (tdmod.new_td, "a"); mongoc_topology_description_handle_hello ( - tdmod.new_td, - sd_a->id, - tmp_bson ("{'ok': 1, 'msg': 'isdbgrid'}"), - 100, - NULL); + tdmod.new_td, sd_a->id, tmp_bson ("{'ok': 1, 'msg': 'isdbgrid'}"), 100, NULL); sd_c = _sd_for_host (tdmod.new_td, "c"); mongoc_topology_description_handle_hello ( - tdmod.new_td, - sd_c->id, - tmp_bson ("{'ok': 1, 'msg': 'isdbgrid'}"), - 100, - NULL); + tdmod.new_td, sd_c->id, tmp_bson ("{'ok': 1, 'msg': 'isdbgrid'}"), 100, NULL); /* td was copied before original was updated */ sds = mongoc_topology_description_get_servers (td_copy, &n); @@ -286,24 +258,11 @@ test_topology_pool_clear (void) topology = mongoc_topology_new (uri, true); tdmod = mc_tpld_modify_begin (topology); - ASSERT_CMPUINT32 (0, - ==, - _mongoc_topology_get_connection_pool_generation ( - tdmod.new_td, 1, &kZeroServiceId)); - ASSERT_CMPUINT32 (0, - ==, - _mongoc_topology_get_connection_pool_generation ( - tdmod.new_td, 2, &kZeroServiceId)); - _mongoc_topology_description_clear_connection_pool ( - tdmod.new_td, 1, &kZeroServiceId); - ASSERT_CMPUINT32 (1, - ==, - _mongoc_topology_get_connection_pool_generation ( - tdmod.new_td, 1, &kZeroServiceId)); - ASSERT_CMPUINT32 (0, - ==, - _mongoc_topology_get_connection_pool_generation ( - tdmod.new_td, 2, &kZeroServiceId)); + ASSERT_CMPUINT32 (0, ==, _mongoc_topology_get_connection_pool_generation (tdmod.new_td, 1, &kZeroServiceId)); + ASSERT_CMPUINT32 (0, ==, _mongoc_topology_get_connection_pool_generation (tdmod.new_td, 2, &kZeroServiceId)); + _mongoc_topology_description_clear_connection_pool (tdmod.new_td, 1, &kZeroServiceId); + ASSERT_CMPUINT32 (1, ==, _mongoc_topology_get_connection_pool_generation (tdmod.new_td, 1, &kZeroServiceId)); + ASSERT_CMPUINT32 (0, ==, _mongoc_topology_get_connection_pool_generation (tdmod.new_td, 2, &kZeroServiceId)); mongoc_uri_destroy (uri); mc_tpld_modify_drop (tdmod); @@ -326,23 +285,11 @@ test_topology_pool_clear_by_serviceid (void) bson_oid_init_from_string (&oid_b, "BBBBBBBBBBBBBBBBBBBBBBBB"); tdmod = mc_tpld_modify_begin (topology); - ASSERT_CMPUINT32 (0, - ==, - _mongoc_topology_get_connection_pool_generation ( - tdmod.new_td, 1, &oid_a)); - ASSERT_CMPUINT32 (0, - ==, - _mongoc_topology_get_connection_pool_generation ( - tdmod.new_td, 1, &oid_b)); + ASSERT_CMPUINT32 (0, ==, _mongoc_topology_get_connection_pool_generation (tdmod.new_td, 1, &oid_a)); + ASSERT_CMPUINT32 (0, ==, _mongoc_topology_get_connection_pool_generation (tdmod.new_td, 1, &oid_b)); _mongoc_topology_description_clear_connection_pool (tdmod.new_td, 1, &oid_a); - ASSERT_CMPUINT32 (1, - ==, - _mongoc_topology_get_connection_pool_generation ( - tdmod.new_td, 1, &oid_a)); - ASSERT_CMPUINT32 (0, - ==, - _mongoc_topology_get_connection_pool_generation ( - tdmod.new_td, 1, &oid_b)); + ASSERT_CMPUINT32 (1, ==, _mongoc_topology_get_connection_pool_generation (tdmod.new_td, 1, &oid_a)); + ASSERT_CMPUINT32 (0, ==, _mongoc_topology_get_connection_pool_generation (tdmod.new_td, 1, &oid_b)); mongoc_uri_destroy (uri); mc_tpld_modify_drop (tdmod); @@ -352,22 +299,11 @@ test_topology_pool_clear_by_serviceid (void) void test_topology_description_install (TestSuite *suite) { - TestSuite_AddLive (suite, - "/TopologyDescription/readable_writable/single", - test_has_readable_writable_server_single); - TestSuite_AddLive (suite, - "/TopologyDescription/readable_writable/pooled", - test_has_readable_writable_server_pooled); + TestSuite_AddLive (suite, "/TopologyDescription/readable_writable/single", test_has_readable_writable_server_single); + TestSuite_AddLive (suite, "/TopologyDescription/readable_writable/pooled", test_has_readable_writable_server_pooled); TestSuite_Add (suite, "/TopologyDescription/get_servers", test_get_servers); - TestSuite_Add (suite, - "/TopologyDescription/topology_version_equal", - test_topology_version_equal); - TestSuite_Add (suite, - "/TopologyDescription/new_copy", - test_topology_description_new_copy); - TestSuite_Add ( - suite, "/TopologyDescription/pool_clear", test_topology_pool_clear); - TestSuite_Add (suite, - "/TopologyDescription/pool_clear_by_serviceid", - test_topology_pool_clear_by_serviceid); + TestSuite_Add (suite, "/TopologyDescription/topology_version_equal", test_topology_version_equal); + TestSuite_Add (suite, "/TopologyDescription/new_copy", test_topology_description_new_copy); + TestSuite_Add (suite, "/TopologyDescription/pool_clear", test_topology_pool_clear); + TestSuite_Add (suite, "/TopologyDescription/pool_clear_by_serviceid", test_topology_pool_clear_by_serviceid); } diff --git a/src/libmongoc/tests/test-mongoc-topology-reconcile.c b/src/libmongoc/tests/test-mongoc-topology-reconcile.c index 3af05c2346..6fe9c1bf0b 100644 --- a/src/libmongoc/tests/test-mongoc-topology-reconcile.c +++ b/src/libmongoc/tests/test-mongoc-topology-reconcile.c @@ -39,8 +39,7 @@ get_node (mongoc_topology_t *topology, const char *host_and_port) static bool -has_server_description (const mongoc_topology_t *topology, - const char *host_and_port) +has_server_description (const mongoc_topology_t *topology, const char *host_and_port) { mc_shared_tpld td = mc_tpld_take_ref (topology); const mongoc_set_t *servers = mc_tpld_servers_const (td.ptr); @@ -61,9 +60,7 @@ has_server_description (const mongoc_topology_t *topology, bool -selects_server (mongoc_client_t *client, - mongoc_read_prefs_t *read_prefs, - mock_server_t *server) +selects_server (mongoc_client_t *client, mongoc_read_prefs_t *read_prefs, mock_server_t *server) { bson_error_t error; mongoc_server_description_t *sd; @@ -71,16 +68,14 @@ selects_server (mongoc_client_t *client, ASSERT (client); - sd = mongoc_topology_select ( - client->topology, MONGOC_SS_READ, read_prefs, NULL, &error); + sd = mongoc_topology_select (client->topology, MONGOC_SS_READ, read_prefs, NULL, &error); if (!sd) { fprintf (stderr, "%s\n", error.message); return false; } - result = (0 == strcmp (mongoc_server_description_host (sd)->host_and_port, - mock_server_get_host_and_port (server))); + result = (0 == strcmp (mongoc_server_description_host (sd)->host_and_port, mock_server_get_host_and_port (server))); mongoc_server_description_destroy (sd); @@ -108,15 +103,12 @@ _test_topology_reconcile_rs (bool pooled) mock_server_run (server1); /* secondary, no tags */ - RS_RESPONSE_TO_HELLO ( - server0, WIRE_VERSION_MIN, false, false, server0, server1); + RS_RESPONSE_TO_HELLO (server0, WIRE_VERSION_MIN, false, false, server0, server1); /* primary, no tags */ - RS_RESPONSE_TO_HELLO ( - server1, WIRE_VERSION_MIN, true, false, server0, server1); + RS_RESPONSE_TO_HELLO (server1, WIRE_VERSION_MIN, true, false, server0, server1); /* provide secondary in seed list */ - uri_str = bson_strdup_printf ("mongodb://%s/?replicaSet=rs", - mock_server_get_host_and_port (server0)); + uri_str = bson_strdup_printf ("mongodb://%s/?replicaSet=rs", mock_server_get_host_and_port (server0)); uri = mongoc_uri_new (uri_str); @@ -141,8 +133,7 @@ _test_topology_reconcile_rs (bool pooled) */ BSON_ASSERT (selects_server (client, secondary_read_prefs, server0)); if (!pooled) { - BSON_ASSERT ( - get_node (client->topology, mock_server_get_host_and_port (server1))); + BSON_ASSERT (get_node (client->topology, mock_server_get_host_and_port (server1))); } /* @@ -153,8 +144,7 @@ _test_topology_reconcile_rs (bool pooled) /* * remove server1 from set. server0 is the primary, with tags. */ - RS_RESPONSE_TO_HELLO ( - server0, WIRE_VERSION_MIN, true, true, server0); /* server1 absent */ + RS_RESPONSE_TO_HELLO (server0, WIRE_VERSION_MIN, true, true, server0); /* server1 absent */ BSON_ASSERT (selects_server (client, tag_read_prefs, server0)); BSON_ASSERT (!client->topology->stale); @@ -166,10 +156,8 @@ _test_topology_reconcile_rs (bool pooled) /* * server1 returns as a secondary. its scanner node is un-retired. */ - RS_RESPONSE_TO_HELLO ( - server0, WIRE_VERSION_MIN, true, true, server0, server1); - RS_RESPONSE_TO_HELLO ( - server1, WIRE_VERSION_MIN, false, false, server0, server1); + RS_RESPONSE_TO_HELLO (server0, WIRE_VERSION_MIN, true, true, server0, server1); + RS_RESPONSE_TO_HELLO (server1, WIRE_VERSION_MIN, false, false, server0, server1); BSON_ASSERT (selects_server (client, secondary_read_prefs, server1)); @@ -232,9 +220,8 @@ _test_topology_reconcile_sharded (bool pooled) mock_server_run (secondary); /* provide both servers in seed list */ - uri_str = bson_strdup_printf ("mongodb://%s,%s", - mock_server_get_host_and_port (mongos), - mock_server_get_host_and_port (secondary)); + uri_str = bson_strdup_printf ( + "mongodb://%s,%s", mock_server_get_host_and_port (mongos), mock_server_get_host_and_port (secondary)); uri = mongoc_uri_new (uri_str); @@ -246,8 +233,7 @@ _test_topology_reconcile_sharded (bool pooled) } primary_read_prefs = mongoc_read_prefs_new (MONGOC_READ_PRIMARY); - future = future_topology_select ( - client->topology, MONGOC_SS_READ, primary_read_prefs, NULL, &error); + future = future_topology_select (client->topology, MONGOC_SS_READ, primary_read_prefs, NULL, &error); /* mongos */ request = mock_server_receives_any_hello (mongos); @@ -267,18 +253,17 @@ _test_topology_reconcile_sharded (bool pooled) /* replica set secondary - topology removes it */ request = mock_server_receives_any_hello (secondary); - secondary_response = - bson_strdup_printf ("{'ok': 1, " - " 'setName': 'rs'," - " 'isWritablePrimary': false," - " 'secondary': true," - " 'minWireVersion': %d," - " 'maxWireVersion': %d," - " 'hosts': ['%s', '%s']}", - WIRE_VERSION_MIN, - WIRE_VERSION_MAX, - mock_server_get_host_and_port (mongos), - mock_server_get_host_and_port (secondary)); + secondary_response = bson_strdup_printf ("{'ok': 1, " + " 'setName': 'rs'," + " 'isWritablePrimary': false," + " 'secondary': true," + " 'minWireVersion': %d," + " 'maxWireVersion': %d," + " 'hosts': ['%s', '%s']}", + WIRE_VERSION_MIN, + WIRE_VERSION_MAX, + mock_server_get_host_and_port (mongos), + mock_server_get_host_and_port (secondary)); reply_to_request_simple (request, secondary_response); @@ -288,12 +273,10 @@ _test_topology_reconcile_sharded (bool pooled) * mongos is selected, secondary is removed. */ sd = future_get_mongoc_server_description_ptr (future); - ASSERT_CMPSTR (sd->host.host_and_port, - mock_server_get_host_and_port (mongos)); + ASSERT_CMPSTR (sd->host.host_and_port, mock_server_get_host_and_port (mongos)); if (!pooled) { - BSON_ASSERT (!get_node (client->topology, - mock_server_get_host_and_port (secondary))); + BSON_ASSERT (!get_node (client->topology, mock_server_get_host_and_port (secondary))); } mongoc_server_description_destroy (sd); @@ -375,8 +358,7 @@ test_topology_reconcile_from_handshake (void *ctx) /* single seed - not the full test_framework_get_uri */ host_and_port = test_framework_get_host_and_port (); replset_name = test_framework_replset_name (); - uri_str = bson_strdup_printf ( - "mongodb://%s/?replicaSet=%s", host_and_port, replset_name); + uri_str = bson_strdup_printf ("mongodb://%s/?replicaSet=%s", host_and_port, replset_name); uri = mongoc_uri_new (uri_str); pool = test_framework_client_pool_new_from_uri (uri, NULL); @@ -393,14 +375,13 @@ test_topology_reconcile_from_handshake (void *ctx) client = mongoc_client_pool_pop (pool); /* command in the foreground (hello, just because it doesn't need auth) */ - r = mongoc_client_read_command_with_opts ( - client, - "admin", - tmp_bson ("{'" HANDSHAKE_CMD_LEGACY_HELLO "': 1}"), - NULL, - tmp_bson ("{'serverId': 1}"), - NULL, - &error); + r = mongoc_client_read_command_with_opts (client, + "admin", + tmp_bson ("{'" HANDSHAKE_CMD_LEGACY_HELLO "': 1}"), + NULL, + tmp_bson ("{'serverId': 1}"), + NULL, + &error); ASSERT_OR_PRINT (r, error); @@ -420,21 +401,13 @@ test_topology_reconcile_from_handshake (void *ctx) ASSERT_CMPINT (count, ==, 0); /* allow pool to start scanner thread */ - bson_atomic_int_exchange (&topology->scanner_state, - MONGOC_TOPOLOGY_SCANNER_OFF, - bson_memory_order_seq_cst); + bson_atomic_int_exchange (&topology->scanner_state, MONGOC_TOPOLOGY_SCANNER_OFF, bson_memory_order_seq_cst); mongoc_client_pool_push (pool, client); client = mongoc_client_pool_pop (pool); /* no serverId, waits for topology scan */ r = mongoc_client_read_command_with_opts ( - client, - "admin", - tmp_bson ("{'" HANDSHAKE_CMD_LEGACY_HELLO "': 1}"), - NULL, - NULL, - NULL, - &error); + client, "admin", tmp_bson ("{'" HANDSHAKE_CMD_LEGACY_HELLO "': 1}"), NULL, NULL, NULL, &error); ASSERT_OR_PRINT (r, error); bson_mutex_lock (&data.mutex); @@ -491,18 +464,15 @@ test_topology_reconcile_retire_single (void) mock_server_run (secondary); mock_server_run (primary); - RS_RESPONSE_TO_HELLO ( - primary, WIRE_VERSION_MIN, true, false, secondary, primary); - RS_RESPONSE_TO_HELLO ( - secondary, WIRE_VERSION_MIN, false, false, secondary, primary); + RS_RESPONSE_TO_HELLO (primary, WIRE_VERSION_MIN, true, false, secondary, primary); + RS_RESPONSE_TO_HELLO (secondary, WIRE_VERSION_MIN, false, false, secondary, primary); /* selection timeout must be > MONGOC_TOPOLOGY_MIN_HEARTBEAT_FREQUENCY_MS, * otherwise we skip second scan in pooled mode and don't hit the assert */ - uri_str = bson_strdup_printf ( - "mongodb://%s,%s/?replicaSet=rs" - "&serverSelectionTimeoutMS=600&heartbeatFrequencyMS=999999999", - mock_server_get_host_and_port (primary), - mock_server_get_host_and_port (secondary)); + uri_str = bson_strdup_printf ("mongodb://%s,%s/?replicaSet=rs" + "&serverSelectionTimeoutMS=600&heartbeatFrequencyMS=999999999", + mock_server_get_host_and_port (primary), + mock_server_get_host_and_port (secondary)); uri = mongoc_uri_new (uri_str); @@ -531,35 +501,29 @@ test_topology_reconcile_retire_single (void) /* step 3: run "ping" on primary, triggering a connection and handshake, thus * step 4 & 5: the primary tells the scanner to retire the secondary node */ - future = future_client_read_command_with_opts ( - client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, NULL, &error); - request = mock_server_receives_msg ( - primary, MONGOC_QUERY_NONE, tmp_bson ("{'ping': 1}")); + future = future_client_read_command_with_opts (client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, NULL, &error); + request = mock_server_receives_msg (primary, MONGOC_QUERY_NONE, tmp_bson ("{'ping': 1}")); reply_to_request_with_ok_and_destroy (request); ASSERT_OR_PRINT (future_get_bool (future), error); - BSON_ASSERT (!has_server_description ( - topology, mock_server_get_host_and_port (secondary))); + BSON_ASSERT (!has_server_description (topology, mock_server_get_host_and_port (secondary))); /* server removed from topology description. in pooled mode, the scanner node * is untouched, in single mode mongoc_cluster_fetch_stream_single scans and * updates topology */ - BSON_ASSERT ( - !get_node (topology, mock_server_get_host_and_port (secondary))); + BSON_ASSERT (!get_node (topology, mock_server_get_host_and_port (secondary))); /* step 7: trigger a scan by selecting with an unsatisfiable read preference. * should not crash with BSON_ASSERT. */ tag_read_prefs = mongoc_read_prefs_new (MONGOC_READ_NEAREST); mongoc_read_prefs_add_tag (tag_read_prefs, tmp_bson ("{'key': 'value'}")); - BSON_ASSERT ( - !mongoc_client_select_server (client, false, tag_read_prefs, NULL)); + BSON_ASSERT (!mongoc_client_select_server (client, false, tag_read_prefs, NULL)); - BSON_ASSERT ( - !get_node (topology, mock_server_get_host_and_port (secondary))); + BSON_ASSERT (!get_node (topology, mock_server_get_host_and_port (secondary))); mongoc_client_destroy (client); @@ -612,16 +576,14 @@ test_topology_reconcile_add_single (void) /* omit secondary from primary's hello, to start with */ RS_RESPONSE_TO_HELLO (primary, WIRE_VERSION_MIN, true, false, primary); - RS_RESPONSE_TO_HELLO ( - secondary, WIRE_VERSION_MIN, false, false, secondary, primary); + RS_RESPONSE_TO_HELLO (secondary, WIRE_VERSION_MIN, false, false, secondary, primary); /* selection timeout must be > MONGOC_TOPOLOGY_MIN_HEARTBEAT_FREQUENCY_MS, * otherwise we skip second scan in pooled mode and don't hit the assert */ - uri_str = bson_strdup_printf ( - "mongodb://%s,%s/?replicaSet=rs" - "&serverSelectionTimeoutMS=600&heartbeatFrequencyMS=999999999", - mock_server_get_host_and_port (primary), - mock_server_get_host_and_port (secondary)); + uri_str = bson_strdup_printf ("mongodb://%s,%s/?replicaSet=rs" + "&serverSelectionTimeoutMS=600&heartbeatFrequencyMS=999999999", + mock_server_get_host_and_port (primary), + mock_server_get_host_and_port (secondary)); uri = mongoc_uri_new (uri_str); @@ -633,8 +595,7 @@ test_topology_reconcile_add_single (void) BSON_ASSERT (selects_server (client, primary_read_prefs, primary)); /* add secondary to primary's config */ - RS_RESPONSE_TO_HELLO ( - primary, WIRE_VERSION_MIN, true, false, primary, secondary); + RS_RESPONSE_TO_HELLO (primary, WIRE_VERSION_MIN, true, false, primary, secondary); /* step 2: cluster opens new stream to primary - force new stream in single * mode by disconnecting primary scanner node */ @@ -646,16 +607,13 @@ test_topology_reconcile_add_single (void) /* step 3: run "ping" on primary, triggering a connection and handshake, thus * step 4 & 5: we add the secondary to the topology description */ - future = future_client_read_command_with_opts ( - client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, NULL, &error); - request = mock_server_receives_msg ( - primary, MONGOC_QUERY_NONE, tmp_bson ("{'ping': 1}")); + future = future_client_read_command_with_opts (client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, NULL, &error); + request = mock_server_receives_msg (primary, MONGOC_QUERY_NONE, tmp_bson ("{'ping': 1}")); reply_to_request_with_ok_and_destroy (request); ASSERT_OR_PRINT (future_get_bool (future), error); /* added server description */ - BSON_ASSERT (has_server_description ( - topology, mock_server_get_host_and_port (secondary))); + BSON_ASSERT (has_server_description (topology, mock_server_get_host_and_port (secondary))); node = get_node (topology, mock_server_get_host_and_port (secondary)); @@ -679,32 +637,20 @@ test_topology_reconcile_add_single (void) void test_topology_reconcile_install (TestSuite *suite) { - TestSuite_AddMockServerTest (suite, - "/TOPOLOGY/reconcile/rs/pooled", - test_topology_reconcile_rs_pooled, - test_framework_skip_if_slow); - TestSuite_AddMockServerTest (suite, - "/TOPOLOGY/reconcile/rs/single", - test_topology_reconcile_rs_single, - test_framework_skip_if_slow); - TestSuite_AddMockServerTest (suite, - "/TOPOLOGY/reconcile/sharded/pooled", - test_topology_reconcile_sharded_pooled); - TestSuite_AddMockServerTest (suite, - "/TOPOLOGY/reconcile/sharded/single", - test_topology_reconcile_sharded_single); + TestSuite_AddMockServerTest ( + suite, "/TOPOLOGY/reconcile/rs/pooled", test_topology_reconcile_rs_pooled, test_framework_skip_if_slow); + TestSuite_AddMockServerTest ( + suite, "/TOPOLOGY/reconcile/rs/single", test_topology_reconcile_rs_single, test_framework_skip_if_slow); + TestSuite_AddMockServerTest (suite, "/TOPOLOGY/reconcile/sharded/pooled", test_topology_reconcile_sharded_pooled); + TestSuite_AddMockServerTest (suite, "/TOPOLOGY/reconcile/sharded/single", test_topology_reconcile_sharded_single); TestSuite_AddFull (suite, "/TOPOLOGY/reconcile/from_handshake", test_topology_reconcile_from_handshake, NULL, NULL, test_framework_skip_if_not_replset); - TestSuite_AddMockServerTest (suite, - "/TOPOLOGY/reconcile/retire/single", - test_topology_reconcile_retire_single, - test_framework_skip_if_slow); - TestSuite_AddMockServerTest (suite, - "/TOPOLOGY/reconcile/add/single", - test_topology_reconcile_add_single, - test_framework_skip_if_slow); + TestSuite_AddMockServerTest ( + suite, "/TOPOLOGY/reconcile/retire/single", test_topology_reconcile_retire_single, test_framework_skip_if_slow); + TestSuite_AddMockServerTest ( + suite, "/TOPOLOGY/reconcile/add/single", test_topology_reconcile_add_single, test_framework_skip_if_slow); } diff --git a/src/libmongoc/tests/test-mongoc-topology-scanner.c b/src/libmongoc/tests/test-mongoc-topology-scanner.c index 4ac03a4c64..5a29637579 100644 --- a/src/libmongoc/tests/test-mongoc-topology-scanner.c +++ b/src/libmongoc/tests/test-mongoc-topology-scanner.c @@ -22,11 +22,8 @@ #define NSERVERS 10 static void -test_topology_scanner_helper (uint32_t id, - const bson_t *bson, - int64_t rtt_msec, - void *data, - const bson_error_t *error /* IN */) +test_topology_scanner_helper ( + uint32_t id, const bson_t *bson, int64_t rtt_msec, void *data, const bson_error_t *error /* IN */) { bson_iter_t iter; int *finished = (int *) data; @@ -62,8 +59,7 @@ _test_topology_scanner (bool with_ssl) mongoc_ssl_opt_t copt = {0}; #endif - topology_scanner = mongoc_topology_scanner_new ( - NULL, NULL, &test_topology_scanner_helper, &finished, TIMEOUT); + topology_scanner = mongoc_topology_scanner_new (NULL, NULL, &test_topology_scanner_helper, &finished, TIMEOUT); #ifdef MONGOC_ENABLE_SSL if (with_ssl) { @@ -91,10 +87,7 @@ _test_topology_scanner (bool with_ssl) mock_server_run (servers[i]); mongoc_topology_scanner_add ( - topology_scanner, - mongoc_uri_get_hosts (mock_server_get_uri (servers[i])), - (uint32_t) i, - false); + topology_scanner, mongoc_uri_get_hosts (mock_server_get_uri (servers[i])), (uint32_t) i, false); } for (i = 0; i < 3; i++) { @@ -153,38 +146,34 @@ test_topology_scanner_discovery (void) mock_server_run (primary); mock_server_run (secondary); - primary_response = - bson_strdup_printf ("{'ok': 1, " - " 'isWritablePrimary': true," - " 'setName': 'rs'," - " 'minWireVersion': %d," - " 'maxWireVersion': %d," - " 'hosts': ['%s', '%s']}", - WIRE_VERSION_MIN, - WIRE_VERSION_MAX, - mock_server_get_host_and_port (primary), - mock_server_get_host_and_port (secondary)); - - secondary_response = - bson_strdup_printf ("{'ok': 1, " - " 'isWritablePrimary': false," - " 'secondary': true," - " 'setName': 'rs'," - " 'minWireVersion': %d," - " 'maxWireVersion': %d," - " 'hosts': ['%s', '%s']}", - WIRE_VERSION_MIN, - WIRE_VERSION_MAX, - mock_server_get_host_and_port (primary), - mock_server_get_host_and_port (secondary)); - - uri_str = bson_strdup_printf ("mongodb://%s/?" MONGOC_URI_REPLICASET "=rs", - mock_server_get_host_and_port (primary)); + primary_response = bson_strdup_printf ("{'ok': 1, " + " 'isWritablePrimary': true," + " 'setName': 'rs'," + " 'minWireVersion': %d," + " 'maxWireVersion': %d," + " 'hosts': ['%s', '%s']}", + WIRE_VERSION_MIN, + WIRE_VERSION_MAX, + mock_server_get_host_and_port (primary), + mock_server_get_host_and_port (secondary)); + + secondary_response = bson_strdup_printf ("{'ok': 1, " + " 'isWritablePrimary': false," + " 'secondary': true," + " 'setName': 'rs'," + " 'minWireVersion': %d," + " 'maxWireVersion': %d," + " 'hosts': ['%s', '%s']}", + WIRE_VERSION_MIN, + WIRE_VERSION_MAX, + mock_server_get_host_and_port (primary), + mock_server_get_host_and_port (secondary)); + + uri_str = bson_strdup_printf ("mongodb://%s/?" MONGOC_URI_REPLICASET "=rs", mock_server_get_host_and_port (primary)); client = test_framework_client_new (uri_str, NULL); secondary_pref = mongoc_read_prefs_new (MONGOC_READ_SECONDARY_PREFERRED); - future = future_topology_select ( - client->topology, MONGOC_SS_READ, secondary_pref, NULL, &error); + future = future_topology_select (client->topology, MONGOC_SS_READ, secondary_pref, NULL, &error); /* a single scan discovers *and* checks the secondary */ request = mock_server_receives_any_hello (primary); @@ -199,11 +188,9 @@ test_topology_scanner_discovery (void) reply_to_request_simple (request, secondary_response); /* scan completes */ - ASSERT_OR_PRINT ((sd = future_get_mongoc_server_description_ptr (future)), - error); + ASSERT_OR_PRINT ((sd = future_get_mongoc_server_description_ptr (future)), error); - ASSERT_CMPSTR (sd->host.host_and_port, - mock_server_get_host_and_port (secondary)); + ASSERT_CMPSTR (sd->host.host_and_port, mock_server_get_host_and_port (secondary)); mongoc_server_description_destroy (sd); future_destroy (future); @@ -240,31 +227,27 @@ test_topology_scanner_oscillate (void) mock_server_run (server1); /* server 0 says it's primary, but only server 1 is in the set */ - server0_response = - bson_strdup_printf ("{'ok': 1, " - " 'isWritablePrimary': true," - " 'setName': 'rs'," - " 'hosts': ['%s']}", - mock_server_get_host_and_port (server1)); + server0_response = bson_strdup_printf ("{'ok': 1, " + " 'isWritablePrimary': true," + " 'setName': 'rs'," + " 'hosts': ['%s']}", + mock_server_get_host_and_port (server1)); /* the opposite */ - server1_response = - bson_strdup_printf ("{'ok': 1, " - " 'isWritablePrimary': true," - " 'setName': 'rs'," - " 'hosts': ['%s']}", - mock_server_get_host_and_port (server0)); + server1_response = bson_strdup_printf ("{'ok': 1, " + " 'isWritablePrimary': true," + " 'setName': 'rs'," + " 'hosts': ['%s']}", + mock_server_get_host_and_port (server0)); /* start with server 0 */ - uri_str = bson_strdup_printf ("mongodb://%s/?" MONGOC_URI_REPLICASET "=rs", - mock_server_get_host_and_port (server0)); + uri_str = bson_strdup_printf ("mongodb://%s/?" MONGOC_URI_REPLICASET "=rs", mock_server_get_host_and_port (server0)); client = test_framework_client_new (uri_str, NULL); scanner = client->topology->scanner; primary_pref = mongoc_read_prefs_new (MONGOC_READ_PRIMARY); BSON_ASSERT (!scanner->async->ncmds); - future = future_topology_select ( - client->topology, MONGOC_SS_READ, primary_pref, NULL, &error); + future = future_topology_select (client->topology, MONGOC_SS_READ, primary_pref, NULL, &error); /* a single scan discovers servers 0 and 1 */ request = mock_server_receives_any_hello (server0); @@ -304,8 +287,7 @@ test_topology_scanner_connection_error (void) /* assuming nothing is listening on this port */ client = test_framework_client_new ("mongodb://localhost:9876", NULL); - ASSERT (!mongoc_client_command_simple ( - client, "db", tmp_bson ("{'foo': 1}"), NULL, NULL, &error)); + ASSERT (!mongoc_client_command_simple (client, "db", tmp_bson ("{'foo': 1}"), NULL, NULL, &error)); ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_SERVER_SELECTION, @@ -333,18 +315,13 @@ test_topology_scanner_socket_timeout (void) mongoc_uri_set_option_as_int32 (uri, MONGOC_URI_CONNECTTIMEOUTMS, 10); client = test_framework_client_new_from_uri (uri, NULL); - ASSERT (!mongoc_client_command_simple ( - client, "db", tmp_bson ("{'foo': 1}"), NULL, NULL, &error)); + ASSERT (!mongoc_client_command_simple (client, "db", tmp_bson ("{'foo': 1}"), NULL, NULL, &error)); /* the mock server did accept connection, but never replied */ expected_msg = - bson_strdup_printf ("socket timeout calling hello on '%s'", - mongoc_uri_get_hosts (uri)->host_and_port); + bson_strdup_printf ("socket timeout calling hello on '%s'", mongoc_uri_get_hosts (uri)->host_and_port); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_SERVER_SELECTION, - MONGOC_ERROR_SERVER_SELECTION_FAILURE, - expected_msg); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_SERVER_SELECTION, MONGOC_ERROR_SERVER_SELECTION_FAILURE, expected_msg); bson_free (expected_msg); mongoc_client_destroy (client); @@ -360,10 +337,7 @@ typedef struct { static mongoc_stream_t * -slow_initiator (const mongoc_uri_t *uri, - const mongoc_host_list_t *host, - void *user_data, - bson_error_t *err) +slow_initiator (const mongoc_uri_t *uri, const mongoc_host_list_t *host, void *user_data, bson_error_t *err) { initiator_data_t *data; @@ -402,12 +376,7 @@ test_topology_scanner_blocking_initiator (void) mongoc_client_set_stream_initiator (client, slow_initiator, &data); ASSERT_OR_PRINT (mongoc_client_command_simple ( - client, - "admin", - tmp_bson ("{'" HANDSHAKE_CMD_LEGACY_HELLO "': 1}"), - NULL, - NULL, - &error), + client, "admin", tmp_bson ("{'" HANDSHAKE_CMD_LEGACY_HELLO "': 1}"), NULL, NULL, &error), error); mongoc_client_destroy (client); @@ -466,11 +435,8 @@ typedef struct dns_testcase { } dns_testcase_t; static void -_test_topology_scanner_dns_helper (uint32_t id, - const bson_t *bson, - int64_t rtt_msec, - void *data, - const bson_error_t *error /* IN */) +_test_topology_scanner_dns_helper ( + uint32_t id, const bson_t *bson, int64_t rtt_msec, void *data, const bson_error_t *error /* IN */) { dns_testcase_t *testcase = (dns_testcase_t *) data; @@ -482,10 +448,7 @@ _test_topology_scanner_dns_helper (uint32_t id, ASSERT_OR_PRINT (!error->code, (*error)); } else { ASSERT (error->code); - ASSERT_ERROR_CONTAINS ((*error), - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_CONNECT, - "connection refused"); + ASSERT_ERROR_CONTAINS ((*error), MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_CONNECT, "connection refused"); } } @@ -500,10 +463,8 @@ test_topology_scanner_dns_testcase (dns_testcase_t *testcase) mongoc_topology_scanner_node_t *node; server = _mock_server_listening_on (testcase->server_bind_to); - ts = mongoc_topology_scanner_new ( - NULL, NULL, &_test_topology_scanner_dns_helper, testcase, TIMEOUT); - host_str = bson_strdup_printf ( - "%s:%d", testcase->client_hostname, mock_server_get_port (server)); + ts = mongoc_topology_scanner_new (NULL, NULL, &_test_topology_scanner_dns_helper, testcase, TIMEOUT); + host_str = bson_strdup_printf ("%s:%d", testcase->client_hostname, mock_server_get_port (server)); BSON_ASSERT (_mongoc_host_list_from_string (&host, host_str)); /* we should only have one host. */ BSON_ASSERT (!host.next); @@ -518,16 +479,13 @@ test_topology_scanner_dns_testcase (dns_testcase_t *testcase) /* check the socket that the scanner found. */ if (testcase->should_succeed) { ASSERT (node->stream->type == MONGOC_STREAM_SOCKET); - sock = mongoc_stream_socket_get_socket ( - (mongoc_stream_socket_t *) node->stream); + sock = mongoc_stream_socket_get_socket ((mongoc_stream_socket_t *) node->stream); if (strcmp ("ipv4", testcase->expected_client_bind_to) == 0) { ASSERT (sock->domain == AF_INET); } else if (strcmp ("ipv6", testcase->expected_client_bind_to) == 0) { ASSERT (sock->domain == AF_INET6); } else if (strcmp ("either", testcase->expected_client_bind_to) != 0) { - fprintf (stderr, - "bad value for testcase->expected_client_bind_to=%s\n", - testcase->expected_client_bind_to); + fprintf (stderr, "bad value for testcase->expected_client_bind_to=%s\n", testcase->expected_client_bind_to); ASSERT (false); } } @@ -554,12 +512,10 @@ test_topology_scanner_dns (void) /* these tests require a hostname mapping to both IPv4 and IPv6 local. * this can be localhost normally, but some configurations may have localhost * only mapping to 127.0.0.1, not ::1. */ - dns_testcase_t tests_with_ipv4_and_ipv6_uri[] = { - {"ipv4", "", true, 2, "ipv4"}, - {"ipv6", "", true, 2, "ipv6"}, - {"both", "", true, 2, "either"}}; - char *ipv4_and_ipv6_host = - test_framework_getenv ("MONGOC_TEST_IPV4_AND_IPV6_HOST"); + dns_testcase_t tests_with_ipv4_and_ipv6_uri[] = {{"ipv4", "", true, 2, "ipv4"}, + {"ipv6", "", true, 2, "ipv6"}, + {"both", "", true, 2, "either"}}; + char *ipv4_and_ipv6_host = test_framework_getenv ("MONGOC_TEST_IPV4_AND_IPV6_HOST"); ntests = sizeof (tests) / sizeof (dns_testcase_t); for (i = 0; i < ntests; ++i) { @@ -577,11 +533,8 @@ test_topology_scanner_dns (void) } static void -_retired_fails_to_initiate_cb (uint32_t id, - const bson_t *bson, - int64_t rtt_msec, - void *data, - const bson_error_t *error /* IN */) +_retired_fails_to_initiate_cb ( + uint32_t id, const bson_t *bson, int64_t rtt_msec, void *data, const bson_error_t *error /* IN */) { BSON_UNUSED (id); BSON_UNUSED (bson); @@ -615,11 +568,9 @@ test_topology_retired_fails_to_initiate (void) server = mock_server_with_auto_hello (WIRE_VERSION_MAX); mock_server_run (server); - scanner = mongoc_topology_scanner_new ( - NULL, NULL, &_retired_fails_to_initiate_cb, NULL, TIMEOUT); + scanner = mongoc_topology_scanner_new (NULL, NULL, &_retired_fails_to_initiate_cb, NULL, TIMEOUT); - BSON_ASSERT (_mongoc_host_list_from_string ( - &host_list, mock_server_get_host_and_port (server))); + BSON_ASSERT (_mongoc_host_list_from_string (&host_list, mock_server_get_host_and_port (server))); mongoc_topology_scanner_add (scanner, &host_list, 1, false); mongoc_topology_scanner_start (scanner, false); @@ -644,8 +595,7 @@ static void heartbeat_failed (const mongoc_apm_server_heartbeat_failed_t *event) { bson_error_t error; - bool *failed = - (bool *) mongoc_apm_server_heartbeat_failed_get_context (event); + bool *failed = (bool *) mongoc_apm_server_heartbeat_failed_get_context (event); mongoc_apm_server_heartbeat_failed_get_error (event, &error); @@ -688,14 +638,12 @@ _test_topology_scanner_does_not_renegotiate (bool pooled) } /* ensure connection */ - r = mongoc_client_command_simple ( - client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); + r = mongoc_client_command_simple (client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); ASSERT_OR_PRINT (r, error); _mongoc_usleep (1500 * 1000); /* 1.5 seconds */ - r = mongoc_client_command_simple ( - client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); + r = mongoc_client_command_simple (client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); ASSERT_OR_PRINT (r, error); /* no heartbeats failed */ @@ -731,32 +679,18 @@ test_topology_scanner_does_not_renegotiate_pooled (void *ctx) void test_topology_scanner_install (TestSuite *suite) { - TestSuite_AddMockServerTest ( - suite, "/TOPOLOGY/scanner", test_topology_scanner); + TestSuite_AddMockServerTest (suite, "/TOPOLOGY/scanner", test_topology_scanner); #ifdef MONGOC_ENABLE_SSL_OPENSSL - TestSuite_AddMockServerTest ( - suite, "/TOPOLOGY/scanner_ssl", test_topology_scanner_ssl); + TestSuite_AddMockServerTest (suite, "/TOPOLOGY/scanner_ssl", test_topology_scanner_ssl); #endif + TestSuite_AddMockServerTest (suite, "/TOPOLOGY/scanner_discovery", test_topology_scanner_discovery); + TestSuite_AddMockServerTest (suite, "/TOPOLOGY/scanner_oscillate", test_topology_scanner_oscillate); + TestSuite_Add (suite, "/TOPOLOGY/scanner_connection_error", test_topology_scanner_connection_error); + TestSuite_AddMockServerTest (suite, "/TOPOLOGY/scanner_socket_timeout", test_topology_scanner_socket_timeout); + TestSuite_AddMockServerTest (suite, "/TOPOLOGY/blocking_initiator", test_topology_scanner_blocking_initiator); TestSuite_AddMockServerTest ( - suite, "/TOPOLOGY/scanner_discovery", test_topology_scanner_discovery); - TestSuite_AddMockServerTest ( - suite, "/TOPOLOGY/scanner_oscillate", test_topology_scanner_oscillate); - TestSuite_Add (suite, - "/TOPOLOGY/scanner_connection_error", - test_topology_scanner_connection_error); - TestSuite_AddMockServerTest (suite, - "/TOPOLOGY/scanner_socket_timeout", - test_topology_scanner_socket_timeout); - TestSuite_AddMockServerTest (suite, - "/TOPOLOGY/blocking_initiator", - test_topology_scanner_blocking_initiator); - TestSuite_AddMockServerTest (suite, - "/TOPOLOGY/dns", - test_topology_scanner_dns, - test_framework_skip_if_no_dual_ip_hostname); - TestSuite_AddMockServerTest (suite, - "/TOPOLOGY/retired_fails_to_initiate", - test_topology_retired_fails_to_initiate); + suite, "/TOPOLOGY/dns", test_topology_scanner_dns, test_framework_skip_if_no_dual_ip_hostname); + TestSuite_AddMockServerTest (suite, "/TOPOLOGY/retired_fails_to_initiate", test_topology_retired_fails_to_initiate); TestSuite_AddFull (suite, "/TOPOLOGY/scanner/renegotiate/single", test_topology_scanner_does_not_renegotiate_single, diff --git a/src/libmongoc/tests/test-mongoc-topology.c b/src/libmongoc/tests/test-mongoc-topology.c index f9e7713971..f60485306c 100644 --- a/src/libmongoc/tests/test-mongoc-topology.c +++ b/src/libmongoc/tests/test-mongoc-topology.c @@ -180,12 +180,10 @@ test_topology_client_creation (void) BSON_ASSERT (topology_a->scanner_state == MONGOC_TOPOLOGY_SCANNER_OFF); /* ensure that we are sharing streams with the client */ - server_stream = mongoc_cluster_stream_for_reads ( - &client_a->cluster, NULL, NULL, NULL, NULL, &error); + server_stream = mongoc_cluster_stream_for_reads (&client_a->cluster, NULL, NULL, NULL, NULL, &error); ASSERT_OR_PRINT (server_stream, error); - node = mongoc_topology_scanner_get_node (client_a->topology->scanner, - server_stream->sd->id); + node = mongoc_topology_scanner_get_node (client_a->topology->scanner, server_stream->sd->id); BSON_ASSERT (node); topology_stream = node->stream; BSON_ASSERT (topology_stream); @@ -198,8 +196,7 @@ test_topology_client_creation (void) } static void -assert_topology_state (mongoc_topology_t *topology, - mongoc_topology_scanner_state_t state) +assert_topology_state (mongoc_topology_t *topology, mongoc_topology_scanner_state_t state) { ASSERT (topology); ASSERT (topology->scanner_state == state); @@ -273,9 +270,8 @@ test_topology_client_pool_creation (void) static void test_server_selection_try_once_option (void *ctx) { - const char *uri_strings[3] = {"mongodb://a", - "mongodb://a/?serverSelectionTryOnce=true", - "mongodb://a/?serverSelectionTryOnce=false"}; + const char *uri_strings[3] = { + "mongodb://a", "mongodb://a/?serverSelectionTryOnce=true", "mongodb://a/?serverSelectionTryOnce=false"}; unsigned long i; mongoc_client_t *client; @@ -330,28 +326,26 @@ _test_server_selection (bool try_once) server = mock_server_new (); mock_server_run (server); - secondary_response = - bson_strdup_printf ("{'ok': 1, " - " 'isWritablePrimary': false," - " 'secondary': true," - " 'setName': 'rs'," - " 'minWireVersion': %d," - " 'maxWireVersion': %d," - " 'hosts': ['%s']}", - WIRE_VERSION_MIN, - WIRE_VERSION_MAX, - mock_server_get_host_and_port (server)); - - primary_response = - bson_strdup_printf ("{'ok': 1, " - " 'isWritablePrimary': true," - " 'setName': 'rs'," - " 'minWireVersion': %d," - " 'maxWireVersion': %d," - " 'hosts': ['%s']}", - WIRE_VERSION_MIN, - WIRE_VERSION_MAX, - mock_server_get_host_and_port (server)); + secondary_response = bson_strdup_printf ("{'ok': 1, " + " 'isWritablePrimary': false," + " 'secondary': true," + " 'setName': 'rs'," + " 'minWireVersion': %d," + " 'maxWireVersion': %d," + " 'hosts': ['%s']}", + WIRE_VERSION_MIN, + WIRE_VERSION_MAX, + mock_server_get_host_and_port (server)); + + primary_response = bson_strdup_printf ("{'ok': 1, " + " 'isWritablePrimary': true," + " 'setName': 'rs'," + " 'minWireVersion': %d," + " 'maxWireVersion': %d," + " 'hosts': ['%s']}", + WIRE_VERSION_MIN, + WIRE_VERSION_MAX, + mock_server_get_host_and_port (server)); uri = mongoc_uri_copy (mock_server_get_uri (server)); mongoc_uri_set_option_as_utf8 (uri, "replicaSet", "rs"); @@ -366,8 +360,7 @@ _test_server_selection (bool try_once) primary_pref = mongoc_read_prefs_new (MONGOC_READ_PRIMARY); /* no primary, selection fails after one try */ - future = future_topology_select ( - client->topology, MONGOC_SS_READ, primary_pref, NULL, &error); + future = future_topology_select (client->topology, MONGOC_SS_READ, primary_pref, NULL, &error); request = mock_server_receives_any_hello (server); BSON_ASSERT (request); reply_to_request_simple (request, secondary_response); @@ -397,8 +390,7 @@ _test_server_selection (bool try_once) _mongoc_usleep (510 * 1000); /* one heartbeat, plus a few milliseconds */ /* second selection, now we try hello again */ - future = future_topology_select ( - client->topology, MONGOC_SS_READ, primary_pref, NULL, &error); + future = future_topology_select (client->topology, MONGOC_SS_READ, primary_pref, NULL, &error); request = mock_server_receives_any_hello (server); BSON_ASSERT (request); @@ -436,19 +428,12 @@ test_server_selection_try_once_false (void *ctx) } static void -host_list_init (mongoc_host_list_t *host_list, - int family, - const char *host, - uint16_t port) +host_list_init (mongoc_host_list_t *host_list, int family, const char *host, uint16_t port) { memset (host_list, 0, sizeof *host_list); host_list->family = family; bson_snprintf (host_list->host, sizeof host_list->host, "%s", host); - bson_snprintf (host_list->host_and_port, - sizeof host_list->host_and_port, - "%s:%hu", - host, - port); + bson_snprintf (host_list->host_and_port, sizeof host_list->host_and_port, "%s:%hu", host, port); } static void @@ -494,13 +479,11 @@ _test_topology_invalidate_server (bool pooled) } /* call explicitly */ - server_stream = mongoc_cluster_stream_for_reads ( - &client->cluster, NULL, NULL, NULL, NULL, &error); + server_stream = mongoc_cluster_stream_for_reads (&client->cluster, NULL, NULL, NULL, NULL, &error); ASSERT_OR_PRINT (server_stream, error); sd = server_stream->sd; id = server_stream->sd->id; - BSON_ASSERT (sd->type == MONGOC_SERVER_STANDALONE || - sd->type == MONGOC_SERVER_RS_PRIMARY || + BSON_ASSERT (sd->type == MONGOC_SERVER_STANDALONE || sd->type == MONGOC_SERVER_RS_PRIMARY || sd->type == MONGOC_SERVER_MONGOS); ASSERT_CMPINT64 (sd->round_trip_time_msec, !=, (int64_t) -1); @@ -517,17 +500,14 @@ _test_topology_invalidate_server (bool pooled) /* insert a 'fake' server description and ensure that it is invalidated by * driver */ host_list_init (&fake_host_list, AF_INET, "fakeaddress", 27033); - mongoc_server_description_init ( - fake_sd, fake_host_list.host_and_port, fake_id); + mongoc_server_description_init (fake_sd, fake_host_list.host_and_port, fake_id); fake_sd->type = MONGOC_SERVER_STANDALONE; tdmod = mc_tpld_modify_begin (client->topology); mongoc_set_add (mc_tpld_servers (tdmod.new_td), fake_id, fake_sd); - mongoc_topology_scanner_add ( - client->topology->scanner, &fake_host_list, fake_id, false); + mongoc_topology_scanner_add (client->topology->scanner, &fake_host_list, fake_id, false); mc_tpld_modify_commit (tdmod); - BSON_ASSERT (!mongoc_cluster_stream_for_server ( - &client->cluster, fake_id, true, NULL, NULL, &error)); + BSON_ASSERT (!mongoc_cluster_stream_for_server (&client->cluster, fake_id, true, NULL, NULL, &error)); mc_tpld_renew_ref (&td, client->topology); sd = mongoc_set_get_const (mc_tpld_servers_const (td.ptr), fake_id); @@ -601,8 +581,7 @@ test_invalid_cluster_node (void *ctx) cluster = &client->cluster; /* load stream into cluster */ - server_stream = mongoc_cluster_stream_for_reads ( - &client->cluster, NULL, NULL, NULL, NULL, &error); + server_stream = mongoc_cluster_stream_for_reads (&client->cluster, NULL, NULL, NULL, NULL, &error); ASSERT_OR_PRINT (server_stream, error); id = server_stream->sd->id; mongoc_server_stream_cleanup (server_stream); @@ -620,14 +599,12 @@ test_invalid_cluster_node (void *ctx) /* update the server's generation, simulating a connection pool clearing */ tdmod = mc_tpld_modify_begin (client->topology); - mc_tpl_sd_increment_generation ( - mongoc_topology_description_server_by_id (tdmod.new_td, id, &error), - &kZeroServiceId); + mc_tpl_sd_increment_generation (mongoc_topology_description_server_by_id (tdmod.new_td, id, &error), + &kZeroServiceId); mc_tpld_modify_commit (tdmod); /* cluster discards node and creates new one with the current generation */ - server_stream = mongoc_cluster_stream_for_server ( - &client->cluster, id, true, NULL, NULL, &error); + server_stream = mongoc_cluster_stream_for_server (&client->cluster, id, true, NULL, NULL, &error); ASSERT_OR_PRINT (server_stream, error); cluster_node = (mongoc_cluster_node_t *) mongoc_set_get (cluster->nodes, id); ASSERT_CMPINT64 (cluster_node->handshake_sd->generation, ==, 1); @@ -658,12 +635,8 @@ test_max_wire_version_race_condition (void *ctx) database = mongoc_client_get_database (client, "test"); (void) mongoc_database_remove_user (database, "pink", &error); - r = mongoc_database_add_user (database, - "pink", - "panther", - tmp_bson ("[{'role': 'read', 'db': 'test'}]"), - NULL, - &error); + r = mongoc_database_add_user ( + database, "pink", "panther", tmp_bson ("[{'role': 'read', 'db': 'test'}]"), NULL, &error); ASSERT_OR_PRINT (r, error); mongoc_database_destroy (database); @@ -674,8 +647,7 @@ test_max_wire_version_race_condition (void *ctx) client = mongoc_client_pool_pop (pool); /* load stream into cluster */ - server_stream = mongoc_cluster_stream_for_reads ( - &client->cluster, NULL, NULL, NULL, NULL, &error); + server_stream = mongoc_cluster_stream_for_reads (&client->cluster, NULL, NULL, NULL, NULL, &error); ASSERT_OR_PRINT (server_stream, error); id = server_stream->sd->id; mongoc_server_stream_cleanup (server_stream); @@ -689,8 +661,7 @@ test_max_wire_version_race_condition (void *ctx) mc_tpld_modify_commit (tdmod); /* new stream, ensure that we can still auth with cached wire version */ - server_stream = mongoc_cluster_stream_for_server ( - &client->cluster, id, true, NULL, NULL, &error); + server_stream = mongoc_cluster_stream_for_server (&client->cluster, id, true, NULL, NULL, &error); ASSERT_OR_PRINT (server_stream, error); BSON_ASSERT (server_stream); @@ -714,13 +685,11 @@ test_cooldown_standalone (void) server = mock_server_new (); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); primary_pref = mongoc_read_prefs_new (MONGOC_READ_PRIMARY); /* first hello fails, selection fails */ - future = future_topology_select ( - client->topology, MONGOC_SS_READ, primary_pref, NULL, &error); + future = future_topology_select (client->topology, MONGOC_SS_READ, primary_pref, NULL, &error); request = mock_server_receives_any_hello (server); BSON_ASSERT (request); reply_to_request_with_hang_up (request); @@ -730,8 +699,7 @@ test_cooldown_standalone (void) /* second selection doesn't try to call hello: we're in cooldown */ start = bson_get_monotonic_time (); - sd = mongoc_topology_select ( - client->topology, MONGOC_SS_READ, primary_pref, NULL, &error); + sd = mongoc_topology_select (client->topology, MONGOC_SS_READ, primary_pref, NULL, &error); BSON_ASSERT (!sd); /* waited less than 500ms (minHeartbeatFrequencyMS), in fact * didn't wait at all since all nodes are in cooldown */ @@ -744,15 +712,12 @@ test_cooldown_standalone (void) _mongoc_usleep (1000 * 1000); /* 1 second */ /* third selection doesn't try to call hello: we're still in cooldown */ - future = future_topology_select ( - client->topology, MONGOC_SS_READ, primary_pref, NULL, &error); + future = future_topology_select (client->topology, MONGOC_SS_READ, primary_pref, NULL, &error); mock_server_set_request_timeout_msec (server, 100); BSON_ASSERT (!mock_server_receives_any_hello (server)); /* no hello call */ BSON_ASSERT (!future_get_mongoc_server_description_ptr (future)); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_SERVER_SELECTION, - MONGOC_ERROR_SERVER_SELECTION_FAILURE, - "No suitable servers"); + ASSERT_ERROR_CONTAINS ( + error, MONGOC_ERROR_SERVER_SELECTION, MONGOC_ERROR_SERVER_SELECTION_FAILURE, "No suitable servers"); future_destroy (future); mock_server_set_request_timeout_msec (server, get_future_timeout_ms ()); @@ -760,8 +725,7 @@ test_cooldown_standalone (void) _mongoc_usleep (5100 * 1000); /* 5.1 seconds */ /* cooldown ends, now we try hello again, this time succeeding */ - future = future_topology_select ( - client->topology, MONGOC_SS_READ, primary_pref, NULL, &error); + future = future_topology_select (client->topology, MONGOC_SS_READ, primary_pref, NULL, &error); request = mock_server_receives_any_hello (server); /* not in cooldown now */ BSON_ASSERT (request); reply_to_request_simple (request, @@ -803,11 +767,10 @@ test_cooldown_rs (void) } { - char *uri_str = - bson_strdup_printf ("mongodb://localhost:%hu/?replicaSet=rs" - "&serverSelectionTimeoutMS=100" - "&connectTimeoutMS=100", - mock_server_get_port (servers[0])); + char *uri_str = bson_strdup_printf ("mongodb://localhost:%hu/?replicaSet=rs" + "&serverSelectionTimeoutMS=100" + "&connectTimeoutMS=100", + mock_server_get_port (servers[0])); mongoc_uri_t *const uri = mongoc_uri_new_with_error (uri_str, &error); ASSERT_OR_PRINT (uri, error); @@ -823,18 +786,17 @@ test_cooldown_rs (void) primary_pref = mongoc_read_prefs_new (MONGOC_READ_PRIMARY); - secondary_response = - bson_strdup_printf ("{'ok': 1," - " 'isWritablePrimary': false," - " 'minWireVersion': %d," - " 'maxWireVersion': %d, " - " 'secondary': true," - " 'setName': 'rs'," - " 'hosts': ['localhost:%hu', 'localhost:%hu']}", - WIRE_VERSION_MIN, - WIRE_VERSION_MAX, - mock_server_get_port (servers[0]), - mock_server_get_port (servers[1])); + secondary_response = bson_strdup_printf ("{'ok': 1," + " 'isWritablePrimary': false," + " 'minWireVersion': %d," + " 'maxWireVersion': %d, " + " 'secondary': true," + " 'setName': 'rs'," + " 'hosts': ['localhost:%hu', 'localhost:%hu']}", + WIRE_VERSION_MIN, + WIRE_VERSION_MAX, + mock_server_get_port (servers[0]), + mock_server_get_port (servers[1])); primary_response = bson_strdup_printf ("{'ok': 1," " 'isWritablePrimary': true," @@ -847,8 +809,7 @@ test_cooldown_rs (void) mock_server_get_port (servers[1])); /* server 0 is a secondary. */ - future = future_topology_select ( - client->topology, MONGOC_SS_READ, primary_pref, NULL, &error); + future = future_topology_select (client->topology, MONGOC_SS_READ, primary_pref, NULL, &error); request = mock_server_receives_any_hello (servers[0]); BSON_ASSERT (request); @@ -868,8 +829,7 @@ test_cooldown_rs (void) _mongoc_usleep (1000 * 1000); /* 1 second */ /* second selection doesn't try hello on server 1: it's in cooldown */ - future = future_topology_select ( - client->topology, MONGOC_SS_READ, primary_pref, NULL, &error); + future = future_topology_select (client->topology, MONGOC_SS_READ, primary_pref, NULL, &error); request = mock_server_receives_any_hello (servers[0]); BSON_ASSERT (request); @@ -887,8 +847,7 @@ test_cooldown_rs (void) _mongoc_usleep (5100 * 1000); /* 5.1 seconds. longer than 5 sec cooldown. */ /* cooldown ends, now we try hello on server 1, this time succeeding */ - future = future_topology_select ( - client->topology, MONGOC_SS_READ, primary_pref, NULL, &error); + future = future_topology_select (client->topology, MONGOC_SS_READ, primary_pref, NULL, &error); request = mock_server_receives_any_hello (servers[1]); BSON_ASSERT (request); @@ -928,13 +887,11 @@ test_cooldown_retry (void) server = mock_server_new (); mock_server_run (server); uri = mongoc_uri_copy (mock_server_get_uri (server)); - mongoc_uri_set_option_as_bool ( - uri, MONGOC_URI_SERVERSELECTIONTRYONCE, false); + mongoc_uri_set_option_as_bool (uri, MONGOC_URI_SERVERSELECTIONTRYONCE, false); client = test_framework_client_new_from_uri (uri, NULL); primary_pref = mongoc_read_prefs_new (MONGOC_READ_PRIMARY); - future = future_topology_select ( - client->topology, MONGOC_SS_READ, primary_pref, NULL, &error); + future = future_topology_select (client->topology, MONGOC_SS_READ, primary_pref, NULL, &error); /* first hello fails */ request = mock_server_receives_any_hello (server); @@ -1029,8 +986,7 @@ _test_select_succeed (bool try_once) /* start waiting for a primary (NULL read pref) */ start = bson_get_monotonic_time (); - future = future_topology_select ( - client->topology, MONGOC_SS_READ, NULL, NULL, &error); + future = future_topology_select (client->topology, MONGOC_SS_READ, NULL, NULL, &error); /* selection succeeds */ sd = future_get_mongoc_server_description_ptr (future); @@ -1078,8 +1034,7 @@ test_multiple_selection_errors (void) bson_error_t error; client = test_framework_client_new (uri, NULL); - mongoc_client_command_simple ( - client, "test", tmp_bson ("{'ping': 1}"), NULL, &reply, &error); + mongoc_client_command_simple (client, "test", tmp_bson ("{'ping': 1}"), NULL, &reply, &error); ASSERT_CMPINT (MONGOC_ERROR_SERVER_SELECTION, ==, error.domain); ASSERT_CMPINT (MONGOC_ERROR_SERVER_SELECTION_FAILURE, ==, error.code); @@ -1107,8 +1062,8 @@ test_invalid_server_id (void) client = test_framework_new_default_client (); - BSON_ASSERT (!mongoc_topology_description_server_by_id_const ( - mc_tpld_unsafe_get_const (client->topology), 99999, &error)); + BSON_ASSERT ( + !mongoc_topology_description_server_by_id_const (mc_tpld_unsafe_get_const (client->topology), 99999, &error)); ASSERT_STARTSWITH (error.message, "Could not find description for node"); mongoc_client_destroy (client); @@ -1173,14 +1128,11 @@ _test_server_removed_during_handshake (bool pooled) } /* initial connection, discover one-node replica set */ - r = mongoc_client_command_simple ( - client, "db", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); + r = mongoc_client_command_simple (client, "db", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); ASSERT_OR_PRINT (r, error); - ASSERT_CMPINT (_mongoc_topology_get_type (client->topology), - ==, - MONGOC_TOPOLOGY_RS_WITH_PRIMARY); + ASSERT_CMPINT (_mongoc_topology_get_type (client->topology), ==, MONGOC_TOPOLOGY_RS_WITH_PRIMARY); sd = mongoc_client_get_server_description (client, 1); ASSERT_CMPINT ((int) MONGOC_SERVER_RS_PRIMARY, ==, sd->type); mongoc_server_description_destroy (sd); @@ -1206,32 +1158,22 @@ _test_server_removed_during_handshake (bool pooled) /* opens new stream and runs hello again, discovers bad setName. */ capture_logs (true); - r = mongoc_client_command_simple ( - client, "db", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); + r = mongoc_client_command_simple (client, "db", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); ASSERT (!r); - ASSERT_CAPTURED_LOG ("topology", - MONGOC_LOG_LEVEL_WARNING, - "Last server removed from topology"); + ASSERT_CAPTURED_LOG ("topology", MONGOC_LOG_LEVEL_WARNING, "Last server removed from topology"); capture_logs (false); if (!pooled) { - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_NOT_ESTABLISHED, - "Could not find stream for node"); + ASSERT_ERROR_CONTAINS ( + error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_NOT_ESTABLISHED, "Could not find stream for node"); } else { - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_NOT_ESTABLISHED, - "removed from topology"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_NOT_ESTABLISHED, "removed from topology"); } sds = mongoc_client_get_server_descriptions (client, &n); ASSERT_CMPSIZE_T (n, ==, (size_t) 0); - ASSERT_CMPINT (_mongoc_topology_get_type (client->topology), - ==, - MONGOC_TOPOLOGY_RS_NO_PRIMARY); + ASSERT_CMPINT (_mongoc_topology_get_type (client->topology), ==, MONGOC_TOPOLOGY_RS_NO_PRIMARY); if (pooled) { mongoc_client_pool_push (pool, client); @@ -1280,10 +1222,8 @@ test_rtt (void *ctx) server = mock_server_new (); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); - future = future_client_command_simple ( - client, "db", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + future = future_client_command_simple (client, "db", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); request = mock_server_receives_any_hello (server); _mongoc_usleep (1000 * 1000); /* one second */ @@ -1293,26 +1233,20 @@ test_rtt (void *ctx) 0, 0, 1, - tmp_str ("{'ok': 1, 'minWireVersion': %d, 'maxWireVersion': %d}", - WIRE_VERSION_MIN, - WIRE_VERSION_MAX)); + tmp_str ("{'ok': 1, 'minWireVersion': %d, 'maxWireVersion': %d}", WIRE_VERSION_MIN, WIRE_VERSION_MAX)); request_destroy (request); - request = mock_server_receives_msg ( - server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', 'ping': 1}")); + request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', 'ping': 1}")); reply_to_request ( request, MONGOC_REPLY_NONE, 0, 0, 1, - tmp_str ("{'ok': 1, 'minWireVersion': %d, 'maxWireVersion': %d}", - WIRE_VERSION_MIN, - WIRE_VERSION_MAX)); + tmp_str ("{'ok': 1, 'minWireVersion': %d, 'maxWireVersion': %d}", WIRE_VERSION_MIN, WIRE_VERSION_MAX)); request_destroy (request); ASSERT_OR_PRINT (future_get_bool (future), error); - sd = mongoc_topology_description_server_by_id_const ( - mc_tpld_unsafe_get_const (client->topology), 1, NULL); + sd = mongoc_topology_description_server_by_id_const (mc_tpld_unsafe_get_const (client->topology), 1, NULL); ASSERT (sd); /* assert, with plenty of slack, that rtt was calculated in ms, not usec */ @@ -1360,18 +1294,15 @@ test_add_and_scan_failure (void) mongoc_uri_set_option_as_utf8 (uri, "replicaSet", "rs"); pool = test_framework_client_pool_new_from_uri (uri, NULL); client = mongoc_client_pool_pop (pool); - future = future_client_command_simple ( - client, "db", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); + future = future_client_command_simple (client, "db", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); - request = mock_server_receives_msg ( - server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', 'ping': 1}")); + request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', 'ping': 1}")); reply_to_request_with_ok_and_destroy (request); ASSERT_OR_PRINT (future_get_bool (future), error); { mc_shared_tpld shared_tpld = mc_tpld_take_ref (client->topology); - sd = mongoc_topology_description_server_by_id_const ( - shared_tpld.ptr, 1, NULL); + sd = mongoc_topology_description_server_by_id_const (shared_tpld.ptr, 1, NULL); ASSERT (sd); ASSERT_CMPSTR (mongoc_server_description_type (sd), "RSPrimary"); mc_tpld_drop_ref (&shared_tpld); @@ -1379,8 +1310,7 @@ test_add_and_scan_failure (void) { mc_shared_tpld shared_tpld = mc_tpld_take_ref (client->topology); - sd = mongoc_topology_description_server_by_id_const ( - mc_tpld_unsafe_get_const (client->topology), 2, NULL); + sd = mongoc_topology_description_server_by_id_const (mc_tpld_unsafe_get_const (client->topology), 2, NULL); ASSERT (sd); ASSERT_CMPSTR (mongoc_server_description_type (sd), "Unknown"); mc_tpld_drop_ref (&shared_tpld); @@ -1397,8 +1327,7 @@ test_add_and_scan_failure (void) static future_t * future_command (mongoc_client_t *client, bson_error_t *error) { - return future_client_command_simple ( - client, "admin", tmp_bson ("{'foo': 1}"), NULL, NULL, error); + return future_client_command_simple (client, "admin", tmp_bson ("{'foo': 1}"), NULL, NULL, error); } @@ -1408,8 +1337,7 @@ receives_command (mock_server_t *server, future_t *future) request_t *request; bson_error_t error; - request = mock_server_receives_msg ( - server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'admin', 'foo': 1}")); + request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'admin', 'foo': 1}")); reply_to_request_with_ok_and_destroy (request); ASSERT_OR_PRINT (future_get_bool (future), error); future_destroy (future); @@ -1709,22 +1637,16 @@ test_incompatible_error (void) /* trigger connection, fails due to incompatibility */ ASSERT (!mongoc_client_command_simple ( - client, - "admin", - tmp_bson ("{'" HANDSHAKE_CMD_LEGACY_HELLO "': 1}"), - NULL, - NULL, - &error)); + client, "admin", tmp_bson ("{'" HANDSHAKE_CMD_LEGACY_HELLO "': 1}"), NULL, NULL, &error)); - ASSERT_ERROR_CONTAINS ( - error, - MONGOC_ERROR_PROTOCOL, - MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION, - tmp_str ("reports wire version %d, but this version of libmongoc " - "requires at least %d (MongoDB %s)", - WIRE_VERSION_MIN - 1, - WIRE_VERSION_MIN, - _mongoc_wire_version_to_server_version (WIRE_VERSION_MIN))); + ASSERT_ERROR_CONTAINS (error, + MONGOC_ERROR_PROTOCOL, + MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION, + tmp_str ("reports wire version %d, but this version of libmongoc " + "requires at least %d (MongoDB %s)", + WIRE_VERSION_MIN - 1, + WIRE_VERSION_MIN, + _mongoc_wire_version_to_server_version (WIRE_VERSION_MIN))); mock_server_auto_hello (server, "{'ok': 1.0," @@ -1737,22 +1659,14 @@ test_incompatible_error (void) /* wait until it's time for next heartbeat */ _mongoc_usleep (600 * 1000); ASSERT (!mongoc_client_command_simple ( - client, - "admin", - tmp_bson ("{'" HANDSHAKE_CMD_LEGACY_HELLO "': 1}"), - NULL, - NULL, - &error)); + client, "admin", tmp_bson ("{'" HANDSHAKE_CMD_LEGACY_HELLO "': 1}"), NULL, NULL, &error)); msg = bson_strdup_printf ("requires wire version %d, but this version of " "libmongoc only supports up to %d", WIRE_VERSION_MAX + 1, WIRE_VERSION_MAX); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_PROTOCOL, - MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION, - msg); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_PROTOCOL, MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION, msg); bson_free (msg); mongoc_client_destroy (client); @@ -1781,25 +1695,17 @@ test_compatible_null_error_pointer (void) WIRE_VERSION_MIN - 1, WIRE_VERSION_MIN - 1); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); /* trigger connection, fails due to incompatibility */ ASSERT (!mongoc_client_command_simple ( - client, - "admin", - tmp_bson ("{'" HANDSHAKE_CMD_LEGACY_HELLO "': 1}"), - NULL, - NULL, - &error)); + client, "admin", tmp_bson ("{'" HANDSHAKE_CMD_LEGACY_HELLO "': 1}"), NULL, NULL, &error)); - ASSERT_ERROR_CONTAINS ( - error, MONGOC_ERROR_PROTOCOL, MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION, ""); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_PROTOCOL, MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION, ""); /* null error pointer is ok */ td = mc_tpld_unsafe_get_const (client->topology); - ASSERT (!mongoc_topology_compatible ( - td, NULL /* read prefs */, NULL /* error */)); + ASSERT (!mongoc_topology_compatible (td, NULL /* read prefs */, NULL /* error */)); mongoc_client_destroy (client); mock_server_destroy (server); @@ -1808,16 +1714,15 @@ test_compatible_null_error_pointer (void) static char * cluster_time_fmt (int t) { - return bson_strdup_printf ( - "{" - " 'clusterTime': {'$timestamp': {'t': %d, 'i': 1}}," - " 'signature': {" - " 'hash': {'$binary': {'subType': '0', 'base64': 'Yw=='}}," - " 'keyId': {'$numberLong': '6446735049323708417'}" - " }," - " 'operationTime': {'$timestamp': {'t': 1, 'i': 1}}" - "}", - t); + return bson_strdup_printf ("{" + " 'clusterTime': {'$timestamp': {'t': %d, 'i': 1}}," + " 'signature': {" + " 'hash': {'$binary': {'subType': '0', 'base64': 'Yw=='}}," + " 'keyId': {'$numberLong': '6446735049323708417'}" + " }," + " 'operationTime': {'$timestamp': {'t': 1, 'i': 1}}" + "}", + t); } static void @@ -1865,8 +1770,7 @@ test_cluster_time_updated_during_handshake (void) mongoc_server_description_destroy (sd); /* check the cluster time stored on the topology description. */ - ASSERT_MATCH (&mc_tpld_unsafe_get_const (client->topology)->cluster_time, - cluster_time); + ASSERT_MATCH (&mc_tpld_unsafe_get_const (client->topology)->cluster_time, cluster_time); bson_free (cluster_time); cluster_time = cluster_time_fmt (2); @@ -1888,12 +1792,10 @@ test_cluster_time_updated_during_handshake (void) mongoc_cluster_disconnect_node (&client->cluster, 1); /* opens new stream and does a hello handshake (in pooled mode only). */ - r = mongoc_client_command_simple ( - client, "db", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); + r = mongoc_client_command_simple (client, "db", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); ASSERT_OR_PRINT (r, error); - ASSERT_MATCH (&mc_tpld_unsafe_get_const (client->topology)->cluster_time, - cluster_time); + ASSERT_MATCH (&mc_tpld_unsafe_get_const (client->topology)->cluster_time, cluster_time); bson_free (cluster_time); mongoc_client_pool_push (pool, client); mongoc_client_pool_destroy (pool); @@ -1909,11 +1811,8 @@ test_cluster_time_updated_during_handshake (void) * topology as stale. */ static void -_test_request_scan_on_error (bool pooled, - const char *err_response, - bool should_scan, - bool should_mark_unknown, - const char *server_err) +_test_request_scan_on_error ( + bool pooled, const char *err_response, bool should_scan, bool should_mark_unknown, const char *server_err) { mock_server_t *primary, *secondary; char *uri_str; @@ -1934,9 +1833,7 @@ _test_request_scan_on_error (bool pooled, MONGOC_DEBUG ("pooled? %d", (int) pooled); MONGOC_DEBUG ("err_response %s", err_response); - MONGOC_DEBUG ("should_scan %d, should_mark_unknown: %d", - (int) should_scan, - (int) should_mark_unknown); + MONGOC_DEBUG ("should_scan %d, should_mark_unknown: %d", (int) should_scan, (int) should_mark_unknown); MONGOC_DEBUG ("server_error %s", server_err); checks_init (&checks); @@ -1947,16 +1844,13 @@ _test_request_scan_on_error (bool pooled, mock_server_run (primary); mock_server_run (secondary); - RS_RESPONSE_TO_HELLO ( - primary, WIRE_VERSION_MIN, true, false, primary, secondary); - RS_RESPONSE_TO_HELLO ( - secondary, WIRE_VERSION_MIN, false, false, primary, secondary); + RS_RESPONSE_TO_HELLO (primary, WIRE_VERSION_MIN, true, false, primary, secondary); + RS_RESPONSE_TO_HELLO (secondary, WIRE_VERSION_MIN, false, false, primary, secondary); /* set a high heartbeatFrequency. Only the first and requested scans run. */ - uri_str = bson_strdup_printf ( - "mongodb://%s,%s/?replicaSet=rs&heartbeatFrequencyMS=999999", - mock_server_get_host_and_port (primary), - mock_server_get_host_and_port (secondary)); + uri_str = bson_strdup_printf ("mongodb://%s,%s/?replicaSet=rs&heartbeatFrequencyMS=999999", + mock_server_get_host_and_port (primary), + mock_server_get_host_and_port (secondary)); uri = mongoc_uri_new (uri_str); bson_free (uri_str); @@ -1995,10 +1889,8 @@ _test_request_scan_on_error (bool pooled, mongoc_uri_destroy (uri); ping_started_usec = bson_get_monotonic_time (); /* run a ping command on the primary. */ - future = future_client_command_simple ( - client, "db", tmp_bson ("{'ping': 1}"), read_prefs, &reply, &error); - request = mock_server_receives_msg ( - primary, MONGOC_QUERY_NONE, tmp_bson ("{'ping': 1}")); + future = future_client_command_simple (client, "db", tmp_bson ("{'ping': 1}"), read_prefs, &reply, &error); + request = mock_server_receives_msg (primary, MONGOC_QUERY_NONE, tmp_bson ("{'ping': 1}")); /* Capture logs to swallow warnings about endSessions */ capture_logs (true); @@ -2027,8 +1919,7 @@ _test_request_scan_on_error (bool pooled, * have been marked as unknown. */ BSON_ASSERT (sd->type == MONGOC_SERVER_UNKNOWN); ASSERT_CMPINT64 (sd->last_update_time_usec, >=, ping_started_usec); - ASSERT_CMPINT64 ( - sd->last_update_time_usec, <=, bson_get_monotonic_time ()); + ASSERT_CMPINT64 (sd->last_update_time_usec, <=, bson_get_monotonic_time ()); /* check that the error on the server description matches the error * message in the response. */ if (server_err) { @@ -2051,16 +1942,13 @@ _test_request_scan_on_error (bool pooled, } else { /* a single threaded client may mark the topology as stale. if a scan * should occur, it won't be triggered until the next command. */ - future = future_client_command_simple ( - client, "db", tmp_bson ("{'ping': 1}"), read_prefs, &reply, &error); + future = future_client_command_simple (client, "db", tmp_bson ("{'ping': 1}"), read_prefs, &reply, &error); if (should_scan || !should_mark_unknown) { - request = mock_server_receives_msg ( - primary, MONGOC_QUERY_NONE, tmp_bson ("{'ping': 1}")); + request = mock_server_receives_msg (primary, MONGOC_QUERY_NONE, tmp_bson ("{'ping': 1}")); } else { /* if the primary was marked as UNKNOWN, and no scan occurred, the ping * goes to the secondary. */ - request = mock_server_receives_msg ( - secondary, MONGOC_QUERY_NONE, tmp_bson ("{'ping': 1}")); + request = mock_server_receives_msg (secondary, MONGOC_QUERY_NONE, tmp_bson ("{'ping': 1}")); } reply_to_request_simple (request, "{'ok': 1}"); request_destroy (request); @@ -2115,11 +2003,8 @@ test_last_server_removed_warning (void) mock_server_get_port (server)); capture_logs (true); - description = mongoc_topology_select ( - client->topology, MONGOC_SS_READ, read_prefs, NULL, &error); - ASSERT_CAPTURED_LOG ("topology", - MONGOC_LOG_LEVEL_WARNING, - "Last server removed from topology"); + description = mongoc_topology_select (client->topology, MONGOC_SS_READ, read_prefs, NULL, &error); + ASSERT_CAPTURED_LOG ("topology", MONGOC_LOG_LEVEL_WARNING, "Last server removed from topology"); capture_logs (false); mongoc_server_description_destroy (description); @@ -2133,19 +2018,15 @@ static void test_request_scan_on_error (void) { #define TEST_POOLED(msg, should_scan, should_mark_unknown, server_err) \ - _test_request_scan_on_error ( \ - true, msg, should_scan, should_mark_unknown, server_err) + _test_request_scan_on_error (true, msg, should_scan, should_mark_unknown, server_err) #define TEST_SINGLE(msg, should_scan, should_mark_unknown, server_err) \ - _test_request_scan_on_error ( \ - false, msg, should_scan, should_mark_unknown, server_err) + _test_request_scan_on_error (false, msg, should_scan, should_mark_unknown, server_err) #define TEST_BOTH(msg, should_scan, should_mark_unknown, server_err) \ TEST_POOLED (msg, should_scan, should_mark_unknown, server_err); \ TEST_SINGLE (msg, should_scan, should_mark_unknown, server_err) - TEST_BOTH ("{'ok': 0, 'errmsg': 'not master'}", - true /* should_scan */, - true /* should_mark_unknown */, - "not master"); + TEST_BOTH ( + "{'ok': 0, 'errmsg': 'not master'}", true /* should_scan */, true /* should_mark_unknown */, "not master"); /* "node is recovering" behaves differently for single and pooled clients. */ TEST_SINGLE ("{'ok': 0, 'errmsg': 'node is recovering'}", false /* should_scan */, @@ -2167,16 +2048,12 @@ test_request_scan_on_error (void) true /* should_scan */, true /* should_mark_unknown */, "not master or secondary"); - TEST_BOTH ("{'ok': 0, 'errmsg': 'random error'}", - false /* should_scan */, - false /* should_mark_unknown */, - "random error"); + TEST_BOTH ( + "{'ok': 0, 'errmsg': 'random error'}", false /* should_scan */, false /* should_mark_unknown */, "random error"); /* check the error code for NotPrimary, which should be considered a "not * primary" error. */ - TEST_BOTH ("{'ok': 0, 'code': 10107 }", - true /* should_scan */, - true /* should_mark_unknown */, - NULL /* server_err */); + TEST_BOTH ( + "{'ok': 0, 'code': 10107 }", true /* should_scan */, true /* should_mark_unknown */, NULL /* server_err */); /* for an unknown code, the message should not be checked. */ TEST_BOTH ("{'ok': 0, 'code': 12345, 'errmsg': 'not master'}", false /* should_scan */, @@ -2184,27 +2061,13 @@ test_request_scan_on_error (void) "not master"); /* check the error code for InterruptedAtShutdown, which behaves * much like a "node is recovering" error. */ - TEST_SINGLE ("{'ok': 0, 'code': 11600 }", - false /* should_scan */, - true /* should_mark_unknown */, - NULL /* server_err */); - TEST_POOLED ("{'ok': 0, 'code': 11600 }", - true /* should_scan */, - true /* should_mark_unknown */, - NULL /* server_err */); + TEST_SINGLE ( + "{'ok': 0, 'code': 11600 }", false /* should_scan */, true /* should_mark_unknown */, NULL /* server_err */); + TEST_POOLED ( + "{'ok': 0, 'code': 11600 }", true /* should_scan */, true /* should_mark_unknown */, NULL /* server_err */); /* write concern errors are also checked. */ - _test_request_scan_on_error ( - 1, - "{'ok': 1, 'writeConcernError': { 'errmsg': 'not master' }}", - 1, - 1, - "not master"); - _test_request_scan_on_error ( - 0, - "{'ok': 1, 'writeConcernError': { 'errmsg': 'not master' }}", - 1, - 1, - "not master"); + _test_request_scan_on_error (1, "{'ok': 1, 'writeConcernError': { 'errmsg': 'not master' }}", 1, 1, "not master"); + _test_request_scan_on_error (0, "{'ok': 1, 'writeConcernError': { 'errmsg': 'not master' }}", 1, 1, "not master"); TEST_BOTH ("{'ok': 1, 'writeConcernError': { 'code': 10107 }}", true, /* should_scan */ true /* should_mark_unknown */, @@ -2257,10 +2120,8 @@ test_slow_server_pooled (void) mock_server_get_host_and_port (secondary), WIRE_VERSION_MIN, WIRE_VERSION_MAX); - hello_primary = bson_strdup_printf ( - "%s, 'isWritablePrimary': true, 'secondary': false }", hello_common); - hello_secondary = bson_strdup_printf ( - "%s, 'isWritablePrimary': false, 'secondary': true }", hello_common); + hello_primary = bson_strdup_printf ("%s, 'isWritablePrimary': true, 'secondary': false }", hello_common); + hello_secondary = bson_strdup_printf ("%s, 'isWritablePrimary': false, 'secondary': true }", hello_common); /* Primary responds immediately, but secondary does not. */ mock_server_auto_hello (primary, hello_primary); @@ -2269,8 +2130,7 @@ test_slow_server_pooled (void) /* Do not connect as topology type Single, so the client pool discovers the * secondary. */ mongoc_uri_set_option_as_bool (uri, MONGOC_URI_DIRECTCONNECTION, false); - mongoc_uri_set_option_as_int32 ( - uri, MONGOC_URI_SERVERSELECTIONTIMEOUTMS, 500); + mongoc_uri_set_option_as_int32 (uri, MONGOC_URI_SERVERSELECTIONTIMEOUTMS, 500); pool = mongoc_client_pool_new (uri); callbacks = heartbeat_callbacks (); @@ -2290,18 +2150,13 @@ test_slow_server_pooled (void) request = mock_server_receives_legacy_hello (secondary, NULL); /* A command to the primary succeeds. */ - ret = mongoc_client_command_simple ( - client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); + ret = mongoc_client_command_simple (client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); ASSERT_OR_PRINT (ret, error); /* A command to the secondary fails. */ prefs_secondary = mongoc_read_prefs_new (MONGOC_READ_SECONDARY); - ret = mongoc_client_command_simple ( - client, "admin", tmp_bson ("{'ping': 1}"), prefs_secondary, NULL, &error); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_SERVER_SELECTION, - MONGOC_ERROR_SERVER_SELECTION_FAILURE, - "expired"); + ret = mongoc_client_command_simple (client, "admin", tmp_bson ("{'ping': 1}"), prefs_secondary, NULL, &error); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_SERVER_SELECTION, MONGOC_ERROR_SERVER_SELECTION_FAILURE, "expired"); BSON_ASSERT (!ret); /* Set up an auto responder so future hellos on the secondary do not @@ -2313,8 +2168,7 @@ test_slow_server_pooled (void) request_destroy (request); /* Now a command to the secondary succeeds. */ - ret = mongoc_client_command_simple ( - client, "admin", tmp_bson ("{'ping': 1}"), prefs_secondary, NULL, &error); + ret = mongoc_client_command_simple (client, "admin", tmp_bson ("{'ping': 1}"), prefs_secondary, NULL, &error); ASSERT_OR_PRINT (ret, error); mongoc_read_prefs_destroy (prefs_secondary); @@ -2355,22 +2209,20 @@ _test_hello_versioned_api (bool pooled) client = test_framework_client_new_from_uri (uri, api); } - char *const hello_reply = - bson_strdup_printf ("{'ok': 1," - " 'isWritablePrimary': true," - " 'setName': 'rs'," - " 'minWireVersion': %d," - " 'maxWireVersion': %d," - " 'hosts': ['%s']}", - WIRE_VERSION_MIN, - WIRE_VERSION_MAX, - mock_server_get_host_and_port (server)); + char *const hello_reply = bson_strdup_printf ("{'ok': 1," + " 'isWritablePrimary': true," + " 'setName': 'rs'," + " 'minWireVersion': %d," + " 'maxWireVersion': %d," + " 'hosts': ['%s']}", + WIRE_VERSION_MIN, + WIRE_VERSION_MAX, + mock_server_get_host_and_port (server)); /* For client pools, the first handshake happens when the client is popped. * For non-pooled clients, we send a ping command to trigger a handshake. */ if (!pooled) { - future = future_client_command_simple ( - client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); + future = future_client_command_simple (client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); } request = mock_server_receives_hello_op_msg (server); @@ -2384,8 +2236,7 @@ _test_hello_versioned_api (bool pooled) request_destroy (request); if (!pooled) { - request = mock_server_receives_msg ( - server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'admin', 'ping': 1}")); + request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'admin', 'ping': 1}")); reply_to_request_with_ok_and_destroy (request); BSON_ASSERT (future_get_bool (future)); @@ -2466,8 +2317,7 @@ _test_hello_ok (bool pooled) /* For client pools, the first handshake happens when the client is popped. * For non-pooled clients, send a ping command to trigger a handshake. */ if (!pooled) { - future = future_client_command_simple ( - client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); + future = future_client_command_simple (client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); } request = mock_server_receives_any_hello_with_match ( @@ -2479,8 +2329,7 @@ _test_hello_ok (bool pooled) /* For non-pooled clients, handle the ping */ if (!pooled) { - request = mock_server_receives_msg ( - server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'admin', 'ping': 1}")); + request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'admin', 'ping': 1}")); reply_to_request_with_ok_and_destroy (request); BSON_ASSERT (future_get_bool (future)); future_destroy (future); @@ -2488,8 +2337,7 @@ _test_hello_ok (bool pooled) /* Send off another ping for non-pooled clients, making sure to wait long * enough to require another heartbeat. */ _mongoc_usleep (600 * 1000); - future = future_client_command_simple ( - client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); + future = future_client_command_simple (client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); } /* Hang up to ensure that the next check runs legacy hello again */ @@ -2499,10 +2347,9 @@ _test_hello_ok (bool pooled) request_destroy (request); /* The previous failure will trigger another handshake using legacy hello */ - request = mock_server_receives_any_hello_with_match ( - server, - "{'" HANDSHAKE_CMD_HELLO "': 1, 'helloOk': true}", - "{'" HANDSHAKE_CMD_LEGACY_HELLO "': 1, 'helloOk': true}"); + request = mock_server_receives_any_hello_with_match (server, + "{'" HANDSHAKE_CMD_HELLO "': 1, 'helloOk': true}", + "{'" HANDSHAKE_CMD_LEGACY_HELLO "': 1, 'helloOk': true}"); BSON_ASSERT (request); reply_to_request_simple (request, hello_not_ok); @@ -2510,8 +2357,7 @@ _test_hello_ok (bool pooled) /* Once again, handle the ping */ if (!pooled) { - request = mock_server_receives_msg ( - server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'admin', 'ping': 1}")); + request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'admin', 'ping': 1}")); reply_to_request_with_ok_and_destroy (request); BSON_ASSERT (future_get_bool (future)); future_destroy (future); @@ -2519,16 +2365,14 @@ _test_hello_ok (bool pooled) /* Send off another ping for non-pooled clients, making sure to wait long * enough to require another heartbeat. */ _mongoc_usleep (600 * 1000); - future = future_client_command_simple ( - client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); + future = future_client_command_simple (client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); } /* Since we never responded with helloOk: true, we're expecting another * hello. */ - request = mock_server_receives_any_hello_with_match ( - server, - "{'" HANDSHAKE_CMD_HELLO "': 1, 'helloOk': true}", - "{'" HANDSHAKE_CMD_LEGACY_HELLO "': 1, 'helloOk': true}"); + request = mock_server_receives_any_hello_with_match (server, + "{'" HANDSHAKE_CMD_HELLO "': 1, 'helloOk': true}", + "{'" HANDSHAKE_CMD_LEGACY_HELLO "': 1, 'helloOk': true}"); BSON_ASSERT (request); reply_to_request_simple (request, hello_not_ok); @@ -2536,8 +2380,7 @@ _test_hello_ok (bool pooled) /* Once again, handle the ping */ if (!pooled) { - request = mock_server_receives_msg ( - server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'admin', 'ping': 1}")); + request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'admin', 'ping': 1}")); reply_to_request_with_ok_and_destroy (request); BSON_ASSERT (future_get_bool (future)); future_destroy (future); @@ -2570,19 +2413,13 @@ test_hello_ok_pooled (void) // initiator_fail is a stream initiator that always fails. static mongoc_stream_t * -initiator_fail (const mongoc_uri_t *uri, - const mongoc_host_list_t *host, - void *user_data, - bson_error_t *error) +initiator_fail (const mongoc_uri_t *uri, const mongoc_host_list_t *host, void *user_data, bson_error_t *error) { BSON_UNUSED (uri); BSON_UNUSED (host); BSON_UNUSED (user_data); - bson_set_error (error, - MONGOC_ERROR_STREAM, - MONGOC_ERROR_STREAM_CONNECT, - "failing in initiator"); + bson_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_CONNECT, "failing in initiator"); printf ("failing in initiator\n"); return false; @@ -2615,8 +2452,7 @@ test_failure_to_setup_after_retry (void) client->topology->min_heartbeat_frequency_msec = overridden_heartbeat_ms; } - future = future_client_command_simple ( - client, "test", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); + future = future_client_command_simple (client, "test", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); // The first command starts the first topology scan. // Expect legacy hello with handshake. @@ -2635,8 +2471,7 @@ test_failure_to_setup_after_retry (void) // Expect "ping" command. { - request_t *request = mock_server_receives_msg ( - server, MONGOC_MSG_NONE, tmp_bson ("{'ping': 1}")); + request_t *request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'ping': 1}")); reply_to_request_with_ok_and_destroy (request); ASSERT_OR_PRINT (future_get_bool (future), error); future_destroy (future); @@ -2646,8 +2481,7 @@ test_failure_to_setup_after_retry (void) _mongoc_usleep (overridden_heartbeat_ms * 1000); // Send another command. - future = future_client_command_simple ( - client, "test", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); + future = future_client_command_simple (client, "test", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); // Expect legacy hello with handshake. { @@ -2665,10 +2499,8 @@ test_failure_to_setup_after_retry (void) ASSERT (!future_get_bool (future)); future_destroy (future); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_SERVER_SELECTION, - MONGOC_ERROR_SERVER_SELECTION_FAILURE, - "No suitable servers found"); + ASSERT_ERROR_CONTAINS ( + error, MONGOC_ERROR_SERVER_SELECTION, MONGOC_ERROR_SERVER_SELECTION_FAILURE, "No suitable servers found"); mongoc_client_destroy (client); mongoc_uri_destroy (uri); @@ -2723,12 +2555,11 @@ test_detect_nongenuine_hosts (void) ASSERT (uri); mongoc_topology_t *const topology = mongoc_topology_new (uri, true); ASSERT (topology); - ASSERT_CAPTURED_LOG ( - cosmos_uris[i], - MONGOC_LOG_LEVEL_INFO, - "You appear to be connected to a CosmosDB cluster. For more " - "information regarding feature compatibility and support please visit " - "https://www.mongodb.com/supportability/cosmosdb"); + ASSERT_CAPTURED_LOG (cosmos_uris[i], + MONGOC_LOG_LEVEL_INFO, + "You appear to be connected to a CosmosDB cluster. For more " + "information regarding feature compatibility and support please visit " + "https://www.mongodb.com/supportability/cosmosdb"); mongoc_topology_destroy (topology); mongoc_uri_destroy (uri); } @@ -2739,18 +2570,16 @@ test_detect_nongenuine_hosts (void) ASSERT (uri); mongoc_topology_t *const topology = mongoc_topology_new (uri, true); ASSERT (topology); - ASSERT_CAPTURED_LOG ( - docdb_uris[i], - MONGOC_LOG_LEVEL_INFO, - "You appear to be connected to a DocumentDB cluster. For more " - "information regarding feature compatibility and support please visit " - "https://www.mongodb.com/supportability/documentdb"); + ASSERT_CAPTURED_LOG (docdb_uris[i], + MONGOC_LOG_LEVEL_INFO, + "You appear to be connected to a DocumentDB cluster. For more " + "information regarding feature compatibility and support please visit " + "https://www.mongodb.com/supportability/documentdb"); mongoc_topology_destroy (topology); mongoc_uri_destroy (uri); } - for (size_t i = 0u; i < sizeof (genuine_uris) / sizeof (*genuine_uris); - ++i) { + for (size_t i = 0u; i < sizeof (genuine_uris) / sizeof (*genuine_uris); ++i) { capture_logs (true); mongoc_uri_t *const uri = mongoc_uri_new (genuine_uris[i]); ASSERT (uri); @@ -2765,13 +2594,9 @@ test_detect_nongenuine_hosts (void) void test_topology_install (TestSuite *suite) { - TestSuite_AddLive ( - suite, "/Topology/client_creation", test_topology_client_creation); - TestSuite_AddLive (suite, - "/Topology/client_pool_creation", - test_topology_client_pool_creation); - TestSuite_AddLive ( - suite, "/Topology/start_stop", test_topology_thread_start_stop); + TestSuite_AddLive (suite, "/Topology/client_creation", test_topology_client_creation); + TestSuite_AddLive (suite, "/Topology/client_pool_creation", test_topology_client_pool_creation); + TestSuite_AddLive (suite, "/Topology/start_stop", test_topology_thread_start_stop); TestSuite_AddFull (suite, "/Topology/server_selection_try_once_option", test_server_selection_try_once_option, @@ -2814,55 +2639,24 @@ test_topology_install (TestSuite *suite) NULL, NULL, test_framework_skip_if_no_auth); - TestSuite_AddMockServerTest (suite, - "/Topology/cooldown/standalone", - test_cooldown_standalone, - NULL, - NULL, - test_framework_skip_if_slow); - TestSuite_AddMockServerTest (suite, - "/Topology/cooldown/rs", - test_cooldown_rs, - NULL, - NULL, - test_framework_skip_if_slow); - TestSuite_AddMockServerTest (suite, - "/Topology/cooldown/retry", - test_cooldown_retry, - NULL, - NULL, - test_framework_skip_if_slow); - TestSuite_Add (suite, - "/Topology/multiple_selection_errors", - test_multiple_selection_errors); TestSuite_AddMockServerTest ( - suite, "/Topology/connect_timeout/succeed", test_select_after_timeout); + suite, "/Topology/cooldown/standalone", test_cooldown_standalone, NULL, NULL, test_framework_skip_if_slow); TestSuite_AddMockServerTest ( - suite, "/Topology/try_once/succeed", test_select_after_try_once); - TestSuite_AddLive ( - suite, "/Topology/invalid_server_id", test_invalid_server_id); - TestSuite_AddMockServerTest (suite, - "/Topology/server_removed/single", - test_server_removed_during_handshake_single); - TestSuite_AddMockServerTest (suite, - "/Topology/server_removed/pooled", - test_server_removed_during_handshake_pooled); - TestSuite_AddFull (suite, - "/Topology/rtt", - test_rtt, - NULL, - NULL, - test_framework_skip_if_slow); + suite, "/Topology/cooldown/rs", test_cooldown_rs, NULL, NULL, test_framework_skip_if_slow); TestSuite_AddMockServerTest ( - suite, "/Topology/add_and_scan_failure", test_add_and_scan_failure); - TestSuite_AddMockServerTest (suite, - "/Topology/hello_retry/single/hangup", - test_hello_retry_single_hangup, - test_framework_skip_if_slow); - TestSuite_AddMockServerTest (suite, - "/Topology/hello_retry/single/timeout", - test_hello_retry_single_timeout, - test_framework_skip_if_slow); + suite, "/Topology/cooldown/retry", test_cooldown_retry, NULL, NULL, test_framework_skip_if_slow); + TestSuite_Add (suite, "/Topology/multiple_selection_errors", test_multiple_selection_errors); + TestSuite_AddMockServerTest (suite, "/Topology/connect_timeout/succeed", test_select_after_timeout); + TestSuite_AddMockServerTest (suite, "/Topology/try_once/succeed", test_select_after_try_once); + TestSuite_AddLive (suite, "/Topology/invalid_server_id", test_invalid_server_id); + TestSuite_AddMockServerTest (suite, "/Topology/server_removed/single", test_server_removed_during_handshake_single); + TestSuite_AddMockServerTest (suite, "/Topology/server_removed/pooled", test_server_removed_during_handshake_pooled); + TestSuite_AddFull (suite, "/Topology/rtt", test_rtt, NULL, NULL, test_framework_skip_if_slow); + TestSuite_AddMockServerTest (suite, "/Topology/add_and_scan_failure", test_add_and_scan_failure); + TestSuite_AddMockServerTest ( + suite, "/Topology/hello_retry/single/hangup", test_hello_retry_single_hangup, test_framework_skip_if_slow); + TestSuite_AddMockServerTest ( + suite, "/Topology/hello_retry/single/timeout", test_hello_retry_single_timeout, test_framework_skip_if_slow); TestSuite_AddMockServerTest (suite, "/Topology/hello_retry/single/hangup/fail", test_hello_retry_single_hangup_fail, @@ -2871,14 +2665,10 @@ test_topology_install (TestSuite *suite) "/Topology/hello_retry/single/timeout/fail", test_hello_retry_single_timeout_fail, test_framework_skip_if_slow); - TestSuite_AddMockServerTest (suite, - "/Topology/hello_retry/pooled/hangup", - test_hello_retry_pooled_hangup, - test_framework_skip_if_slow); - TestSuite_AddMockServerTest (suite, - "/Topology/hello_retry/pooled/timeout", - test_hello_retry_pooled_timeout, - test_framework_skip_if_slow); + TestSuite_AddMockServerTest ( + suite, "/Topology/hello_retry/pooled/hangup", test_hello_retry_pooled_hangup, test_framework_skip_if_slow); + TestSuite_AddMockServerTest ( + suite, "/Topology/hello_retry/pooled/timeout", test_hello_retry_pooled_timeout, test_framework_skip_if_slow); TestSuite_AddMockServerTest (suite, "/Topology/hello_retry/pooled/hangup/fail", test_hello_retry_pooled_hangup_fail, @@ -2887,39 +2677,23 @@ test_topology_install (TestSuite *suite) "/Topology/hello_retry/pooled/timeout/fail", test_hello_retry_pooled_timeout_fail, test_framework_skip_if_slow); - TestSuite_AddMockServerTest (suite, - "/Topology/incompatible_error", - test_incompatible_error, - test_framework_skip_if_slow); + TestSuite_AddMockServerTest ( + suite, "/Topology/incompatible_error", test_incompatible_error, test_framework_skip_if_slow); TestSuite_AddMockServerTest (suite, "/Topology/compatible_null_error_pointer", test_compatible_null_error_pointer, test_framework_skip_if_slow); - TestSuite_AddMockServerTest (suite, - "/Topology/handshake/updates_clustertime", - test_cluster_time_updated_during_handshake); TestSuite_AddMockServerTest ( - suite, "/Topology/request_scan_on_error", test_request_scan_on_error); - TestSuite_AddMockServerTest (suite, - "/Topology/last_server_removed_warning", - test_last_server_removed_warning); - TestSuite_AddMockServerTest ( - suite, "/Topology/slow_server/pooled", test_slow_server_pooled); - - TestSuite_AddMockServerTest (suite, - "/Topology/hello/versioned_api/single", - test_hello_versioned_api_single); - TestSuite_AddMockServerTest (suite, - "/Topology/hello/versioned_api/pooled", - test_hello_versioned_api_pooled); - - TestSuite_AddMockServerTest ( - suite, "/Topology/hello_ok/single", test_hello_ok_single); - TestSuite_AddMockServerTest ( - suite, "/Topology/hello_ok/pooled", test_hello_ok_pooled); - TestSuite_AddMockServerTest (suite, - "/Topology/failure_to_setup_after_retry", - test_failure_to_setup_after_retry); - TestSuite_Add ( - suite, "/Topology/detect_nongenuine_hosts", test_detect_nongenuine_hosts); + suite, "/Topology/handshake/updates_clustertime", test_cluster_time_updated_during_handshake); + TestSuite_AddMockServerTest (suite, "/Topology/request_scan_on_error", test_request_scan_on_error); + TestSuite_AddMockServerTest (suite, "/Topology/last_server_removed_warning", test_last_server_removed_warning); + TestSuite_AddMockServerTest (suite, "/Topology/slow_server/pooled", test_slow_server_pooled); + + TestSuite_AddMockServerTest (suite, "/Topology/hello/versioned_api/single", test_hello_versioned_api_single); + TestSuite_AddMockServerTest (suite, "/Topology/hello/versioned_api/pooled", test_hello_versioned_api_pooled); + + TestSuite_AddMockServerTest (suite, "/Topology/hello_ok/single", test_hello_ok_single); + TestSuite_AddMockServerTest (suite, "/Topology/hello_ok/pooled", test_hello_ok_pooled); + TestSuite_AddMockServerTest (suite, "/Topology/failure_to_setup_after_retry", test_failure_to_setup_after_retry); + TestSuite_Add (suite, "/Topology/detect_nongenuine_hosts", test_detect_nongenuine_hosts); } diff --git a/src/libmongoc/tests/test-mongoc-transactions.c b/src/libmongoc/tests/test-mongoc-transactions.c index e835ac1d1d..7c2a920291 100644 --- a/src/libmongoc/tests/test-mongoc-transactions.c +++ b/src/libmongoc/tests/test-mongoc-transactions.c @@ -21,8 +21,7 @@ _reset_server (json_test_ctx_t *ctx, const char *host_str) mongoc_client_t *client; bson_error_t error; bool res; - mongoc_uri_t *uri = _mongoc_uri_copy_and_replace_host_list ( - ctx->test_framework_uri, host_str); + mongoc_uri_t *uri = _mongoc_uri_copy_and_replace_host_list (ctx->test_framework_uri, host_str); client = test_framework_client_new_from_uri (uri, NULL); test_framework_set_ssl_opts (client); @@ -32,12 +31,7 @@ _reset_server (json_test_ctx_t *ctx, const char *host_str) * transactions from previous test failures. Ignore a command failure with * error code 11601 ("Interrupted") to work around SERVER-38335." */ - res = mongoc_client_command_simple (client, - "admin", - tmp_bson ("{'killAllSessions': []}"), - NULL, - NULL, - &error); + res = mongoc_client_command_simple (client, "admin", tmp_bson ("{'killAllSessions': []}"), NULL, NULL, &error); if (!res && error.code != 11601) { test_error ("Unexpected error: %s from killAllSessions\n", error.message); } @@ -47,16 +41,14 @@ _reset_server (json_test_ctx_t *ctx, const char *host_str) * created collection on all mongoses. For an explanation see, Why do tests * that run distinct sometimes fail with StaleDbVersion?" */ - ASSERT_OR_PRINT ( - mongoc_client_command_simple ( - client, - mongoc_database_get_name (ctx->db), - tmp_bson ("{'distinct': '%s', 'key': 'test', 'query': {}}", - mongoc_collection_get_name (ctx->collection)), - NULL /* read prefs */, - NULL /* reply */, - &error), - error); + ASSERT_OR_PRINT (mongoc_client_command_simple (client, + mongoc_database_get_name (ctx->db), + tmp_bson ("{'distinct': '%s', 'key': 'test', 'query': {}}", + mongoc_collection_get_name (ctx->collection)), + NULL /* read prefs */, + NULL /* reply */, + &error), + error); mongoc_client_destroy (client); mongoc_uri_destroy (uri); } @@ -67,32 +59,24 @@ _disable_failpoints (json_test_ctx_t *ctx, const char *host_str) mongoc_client_t *client; bson_error_t error; int i; - mongoc_uri_t *uri = _mongoc_uri_copy_and_replace_host_list ( - ctx->test_framework_uri, host_str); + mongoc_uri_t *uri = _mongoc_uri_copy_and_replace_host_list (ctx->test_framework_uri, host_str); /* Some transactions tests have a failCommand for "hello" repeat seven * times. Repeat this seven times. And set a reduced server selection timeout * so we don't hang on failed hello commands. */ - mongoc_uri_set_option_as_int32 ( - uri, MONGOC_URI_SERVERSELECTIONTIMEOUTMS, 500); + mongoc_uri_set_option_as_int32 (uri, MONGOC_URI_SERVERSELECTIONTIMEOUTMS, 500); for (i = 0; i < 7; i++) { bool ret; client = test_framework_client_new_from_uri (uri, NULL); ret = mongoc_client_command_simple ( - client, - "admin", - tmp_bson ("{'configureFailPoint': 'failCommand', 'mode': 'off'}"), - NULL, - NULL, - &error); + client, "admin", tmp_bson ("{'configureFailPoint': 'failCommand', 'mode': 'off'}"), NULL, NULL, &error); if (!ret) { /* Tests that fail with hello also fail to disable the failpoint * (since we run hello when opening the connection). Ignore those * errors. */ - BSON_ASSERT (NULL != - strstr (error.message, "No suitable servers found")); + BSON_ASSERT (NULL != strstr (error.message, "No suitable servers found")); } mongoc_client_destroy (client); } @@ -107,9 +91,7 @@ transactions_test_before_test (json_test_ctx_t *ctx, const bson_t *test) _reset_server (ctx, "localhost:27017"); - is_multi_mongos = - bson_iter_init_find (&test_iter, test, "useMultipleMongoses") && - bson_iter_as_bool (&test_iter); + is_multi_mongos = bson_iter_init_find (&test_iter, test, "useMultipleMongoses") && bson_iter_as_bool (&test_iter); if (is_multi_mongos) { _reset_server (ctx, "localhost:27018"); @@ -125,9 +107,7 @@ transactions_test_after_test (json_test_ctx_t *ctx, const bson_t *test) _disable_failpoints (ctx, "localhost:27017"); - is_multi_mongos = - bson_iter_init_find (&test_iter, test, "useMultipleMongoses") && - bson_iter_as_bool (&test_iter); + is_multi_mongos = bson_iter_init_find (&test_iter, test, "useMultipleMongoses") && bson_iter_as_bool (&test_iter); if (is_multi_mongos) { _disable_failpoints (ctx, "localhost:27018"); @@ -142,10 +122,7 @@ typedef struct _cb_ctx_t { static bool -with_transaction_callback_runner (mongoc_client_session_t *session, - void *ctx, - bson_t **reply, - bson_error_t *error) +with_transaction_callback_runner (mongoc_client_session_t *session, void *ctx, bson_t **reply, bson_error_t *error) { cb_ctx_t *cb_ctx = (cb_ctx_t *) ctx; bson_t operation; @@ -161,12 +138,7 @@ with_transaction_callback_runner (mongoc_client_session_t *session, if (bson_has_field (test, "operation")) { bson_lookup_doc (test, "operation", &operation); - res = json_test_operation (cb_ctx->ctx, - test, - &operation, - cb_ctx->ctx->collection, - session, - &local_reply); + res = json_test_operation (cb_ctx->ctx, test, &operation, cb_ctx->ctx->collection, session, &local_reply); } else { ASSERT (bson_has_field (test, "operations")); bson_lookup_doc (test, "operations", &operations); @@ -177,12 +149,7 @@ with_transaction_callback_runner (mongoc_client_session_t *session, while (bson_iter_next (&iter)) { bson_destroy (&local_reply); bson_iter_bson (&iter, &operation); - res = json_test_operation (cb_ctx->ctx, - test, - &operation, - cb_ctx->ctx->collection, - session, - &local_reply); + res = json_test_operation (cb_ctx->ctx, test, &operation, cb_ctx->ctx->collection, session, &local_reply); if (!res) { break; } @@ -196,9 +163,7 @@ with_transaction_callback_runner (mongoc_client_session_t *session, } static bool -transactions_test_run_operation (json_test_ctx_t *ctx, - const bson_t *test, - const bson_t *operation) +transactions_test_run_operation (json_test_ctx_t *ctx, const bson_t *test, const bson_t *operation) { mongoc_transaction_opt_t *opts = NULL; mongoc_client_session_t *session = NULL; @@ -223,12 +188,7 @@ transactions_test_run_operation (json_test_ctx_t *ctx, } res = mongoc_client_session_with_transaction ( - session, - with_transaction_callback_runner, - opts, - &cb_ctx, - &reply, - &error); + session, with_transaction_callback_runner, opts, &cb_ctx, &reply, &error); value_init_from_doc (&value, &reply); check_result (test, operation, res, &value, &error); @@ -237,15 +197,13 @@ transactions_test_run_operation (json_test_ctx_t *ctx, } else { /* If there is no 'callback' field, then run simply. */ if (bson_has_field (operation, "arguments.session")) { - session = session_from_name ( - ctx, bson_lookup_utf8 (operation, "arguments.session")); + session = session_from_name (ctx, bson_lookup_utf8 (operation, "arguments.session")); } /* expect some warnings from abortTransaction, but don't suppress others: * we want to know if any other tests log warnings */ capture_logs (true); - res = json_test_operation ( - ctx, test, operation, ctx->collection, session, &reply); + res = json_test_operation (ctx, test, operation, ctx->collection, session, &reply); assert_all_captured_logs_have_prefix ("Error in abortTransaction:"); capture_logs (false); } @@ -258,9 +216,7 @@ transactions_test_run_operation (json_test_ctx_t *ctx, static test_skip_t skips[] = { - {"callback is not retried after non-transient error (DuplicateKeyError)", - "Waiting on CDRIVER-4811"}, - {0}}; + {"callback is not retried after non-transient error (DuplicateKeyError)", "Waiting on CDRIVER-4811"}, {0}}; static void @@ -303,10 +259,8 @@ test_transactions_supported (void *ctx) db = mongoc_client_get_database (client, "transaction-tests"); /* drop and create collection outside of transaction */ - mongoc_database_write_command_with_opts ( - db, tmp_bson ("{'drop': 'test'}"), majority, NULL, NULL); - collection = - mongoc_database_create_collection (db, "test", majority, &error); + mongoc_database_write_command_with_opts (db, tmp_bson ("{'drop': 'test'}"), majority, NULL, NULL); + collection = mongoc_database_create_collection (db, "test", majority, &error); ASSERT_OR_PRINT (collection, error); session = mongoc_client_start_session (client, NULL, &error); @@ -316,8 +270,7 @@ test_transactions_supported (void *ctx) r = mongoc_client_session_append (session, &opts, &error); ASSERT_OR_PRINT (r, error); - r = mongoc_collection_insert_one ( - collection, tmp_bson ("{}"), &opts, NULL, &error); + r = mongoc_collection_insert_one (collection, tmp_bson ("{}"), &opts, NULL, &error); /* insert should fail if replset has no members */ BSON_ASSERT (r == test_framework_is_replset ()); @@ -358,10 +311,8 @@ test_in_transaction (void *ctx) mongoc_client_set_error_api (client, 2); db = mongoc_client_get_database (client, "transaction-tests"); /* drop and create collection outside of transaction */ - mongoc_database_write_command_with_opts ( - db, tmp_bson ("{'drop': 'test'}"), majority, NULL, NULL); - collection = - mongoc_database_create_collection (db, "test", majority, &error); + mongoc_database_write_command_with_opts (db, tmp_bson ("{'drop': 'test'}"), majority, NULL, NULL); + collection = mongoc_database_create_collection (db, "test", majority, &error); ASSERT_OR_PRINT (collection, error); session = mongoc_client_start_session (client, NULL, &error); @@ -369,68 +320,48 @@ test_in_transaction (void *ctx) r = mongoc_client_session_append (session, &opts, &error); ASSERT_OR_PRINT (r, error); BSON_ASSERT (!mongoc_client_session_in_transaction (session)); - ASSERT_CMPINT (mongoc_client_session_get_transaction_state (session), - ==, - MONGOC_TRANSACTION_NONE); + ASSERT_CMPINT (mongoc_client_session_get_transaction_state (session), ==, MONGOC_TRANSACTION_NONE); ASSERT_CMPINT (session->txn.state, ==, MONGOC_INTERNAL_TRANSACTION_NONE); /* commit an empty transaction */ r = mongoc_client_session_start_transaction (session, NULL, &error); ASSERT_OR_PRINT (r, error); BSON_ASSERT (mongoc_client_session_in_transaction (session)); - ASSERT_CMPINT (mongoc_client_session_get_transaction_state (session), - ==, - MONGOC_TRANSACTION_STARTING); + ASSERT_CMPINT (mongoc_client_session_get_transaction_state (session), ==, MONGOC_TRANSACTION_STARTING); ASSERT_CMPINT (session->txn.state, ==, MONGOC_INTERNAL_TRANSACTION_STARTING); r = mongoc_client_session_commit_transaction (session, NULL, &error); ASSERT_OR_PRINT (r, error); BSON_ASSERT (!mongoc_client_session_in_transaction (session)); - ASSERT_CMPINT (mongoc_client_session_get_transaction_state (session), - ==, - MONGOC_TRANSACTION_COMMITTED); - ASSERT_CMPINT ( - session->txn.state, ==, MONGOC_INTERNAL_TRANSACTION_COMMITTED_EMPTY); + ASSERT_CMPINT (mongoc_client_session_get_transaction_state (session), ==, MONGOC_TRANSACTION_COMMITTED); + ASSERT_CMPINT (session->txn.state, ==, MONGOC_INTERNAL_TRANSACTION_COMMITTED_EMPTY); /* commit a transaction with an insert */ r = mongoc_client_session_start_transaction (session, NULL, &error); ASSERT_OR_PRINT (r, error); BSON_ASSERT (mongoc_client_session_in_transaction (session)); - ASSERT_CMPINT (mongoc_client_session_get_transaction_state (session), - ==, - MONGOC_TRANSACTION_STARTING); + ASSERT_CMPINT (mongoc_client_session_get_transaction_state (session), ==, MONGOC_TRANSACTION_STARTING); ASSERT_CMPINT (session->txn.state, ==, MONGOC_INTERNAL_TRANSACTION_STARTING); - r = mongoc_collection_insert_one ( - collection, tmp_bson ("{}"), &opts, NULL, &error); - ASSERT_CMPINT (mongoc_client_session_get_transaction_state (session), - ==, - MONGOC_TRANSACTION_IN_PROGRESS); - ASSERT_CMPINT ( - session->txn.state, ==, MONGOC_INTERNAL_TRANSACTION_IN_PROGRESS); + r = mongoc_collection_insert_one (collection, tmp_bson ("{}"), &opts, NULL, &error); + ASSERT_CMPINT (mongoc_client_session_get_transaction_state (session), ==, MONGOC_TRANSACTION_IN_PROGRESS); + ASSERT_CMPINT (session->txn.state, ==, MONGOC_INTERNAL_TRANSACTION_IN_PROGRESS); ASSERT_OR_PRINT (r, error); r = mongoc_client_session_commit_transaction (session, NULL, &error); ASSERT_OR_PRINT (r, error); BSON_ASSERT (!mongoc_client_session_in_transaction (session)); - ASSERT_CMPINT (mongoc_client_session_get_transaction_state (session), - ==, - MONGOC_TRANSACTION_COMMITTED); - ASSERT_CMPINT ( - session->txn.state, ==, MONGOC_INTERNAL_TRANSACTION_COMMITTED); + ASSERT_CMPINT (mongoc_client_session_get_transaction_state (session), ==, MONGOC_TRANSACTION_COMMITTED); + ASSERT_CMPINT (session->txn.state, ==, MONGOC_INTERNAL_TRANSACTION_COMMITTED); /* abort a transaction */ r = mongoc_client_session_start_transaction (session, NULL, &error); ASSERT_OR_PRINT (r, error); BSON_ASSERT (mongoc_client_session_in_transaction (session)); - ASSERT_CMPINT (mongoc_client_session_get_transaction_state (session), - ==, - MONGOC_TRANSACTION_STARTING); + ASSERT_CMPINT (mongoc_client_session_get_transaction_state (session), ==, MONGOC_TRANSACTION_STARTING); ASSERT_CMPINT (session->txn.state, ==, MONGOC_INTERNAL_TRANSACTION_STARTING); ASSERT_OR_PRINT (r, error); r = mongoc_client_session_abort_transaction (session, &error); ASSERT_OR_PRINT (r, error); BSON_ASSERT (!mongoc_client_session_in_transaction (session)); - ASSERT_CMPINT (mongoc_client_session_get_transaction_state (session), - ==, - MONGOC_TRANSACTION_ABORTED); + ASSERT_CMPINT (mongoc_client_session_get_transaction_state (session), ==, MONGOC_TRANSACTION_ABORTED); ASSERT_CMPINT (session->txn.state, ==, MONGOC_INTERNAL_TRANSACTION_ABORTED); bson_destroy (&opts); @@ -479,15 +410,9 @@ _test_transient_txn_err (bool hangup) server = mock_server_new (); mock_server_run (server); - rs_response_to_hello (server, - WIRE_VERSION_4_0, - true /* primary */, - false /* tags */, - server, - NULL); - - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + rs_response_to_hello (server, WIRE_VERSION_4_0, true /* primary */, false /* tags */, server, NULL); + + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); /* allow fast reconnect */ client->topology->min_heartbeat_frequency_msec = 0; session = mongoc_client_start_session (client, NULL, &error); @@ -555,50 +480,34 @@ _test_transient_txn_err (bool hangup) b = tmp_bson ("{'x': 1}"); u = tmp_bson ("{'$inc': {'x': 1}}"); - TEST_CMD_ERR (mongoc_client_command_with_opts ( - client, "db", b, NULL, &opts, &reply, NULL)); - TEST_CMD_ERR (mongoc_client_read_command_with_opts ( - client, "db", b, NULL, &opts, &reply, NULL)); - TEST_CMD_ERR (mongoc_client_write_command_with_opts ( - client, "db", b, &opts, &reply, NULL)); - TEST_CMD_ERR (mongoc_client_read_write_command_with_opts ( - client, "db", b, NULL, &opts, &reply, NULL)); - TEST_CMD_ERR (0 < mongoc_collection_count_documents ( - collection, b, &opts, NULL, &reply, NULL)); + TEST_CMD_ERR (mongoc_client_command_with_opts (client, "db", b, NULL, &opts, &reply, NULL)); + TEST_CMD_ERR (mongoc_client_read_command_with_opts (client, "db", b, NULL, &opts, &reply, NULL)); + TEST_CMD_ERR (mongoc_client_write_command_with_opts (client, "db", b, &opts, &reply, NULL)); + TEST_CMD_ERR (mongoc_client_read_write_command_with_opts (client, "db", b, NULL, &opts, &reply, NULL)); + TEST_CMD_ERR (0 < mongoc_collection_count_documents (collection, b, &opts, NULL, &reply, NULL)); BEGIN_IGNORE_DEPRECATIONS - TEST_CMD_ERR (mongoc_collection_create_index_with_opts ( - collection, b, NULL, &opts, &reply, NULL)); + TEST_CMD_ERR (mongoc_collection_create_index_with_opts (collection, b, NULL, &opts, &reply, NULL)); END_IGNORE_DEPRECATIONS fam = mongoc_find_and_modify_opts_new (); mongoc_find_and_modify_opts_append (fam, &opts); - TEST_CMD_ERR (mongoc_collection_find_and_modify_with_opts ( - collection, b, fam, &reply, NULL)); - - TEST_WRITE_ERR ( - mongoc_collection_insert_one (collection, b, &opts, &reply, NULL)); - TEST_WRITE_ERR (mongoc_collection_insert_many ( - collection, (const bson_t **) &b, 1, &opts, &reply, NULL)); - TEST_WRITE_ERR ( - mongoc_collection_update_one (collection, b, u, &opts, &reply, NULL)); - TEST_WRITE_ERR ( - mongoc_collection_update_many (collection, b, u, &opts, &reply, NULL)); - TEST_WRITE_ERR ( - mongoc_collection_replace_one (collection, b, b, &opts, &reply, NULL)); - TEST_WRITE_ERR ( - mongoc_collection_delete_one (collection, b, &opts, &reply, NULL)); - TEST_WRITE_ERR ( - mongoc_collection_delete_many (collection, b, &opts, &reply, NULL)); + TEST_CMD_ERR (mongoc_collection_find_and_modify_with_opts (collection, b, fam, &reply, NULL)); + + TEST_WRITE_ERR (mongoc_collection_insert_one (collection, b, &opts, &reply, NULL)); + TEST_WRITE_ERR (mongoc_collection_insert_many (collection, (const bson_t **) &b, 1, &opts, &reply, NULL)); + TEST_WRITE_ERR (mongoc_collection_update_one (collection, b, u, &opts, &reply, NULL)); + TEST_WRITE_ERR (mongoc_collection_update_many (collection, b, u, &opts, &reply, NULL)); + TEST_WRITE_ERR (mongoc_collection_replace_one (collection, b, b, &opts, &reply, NULL)); + TEST_WRITE_ERR (mongoc_collection_delete_one (collection, b, &opts, &reply, NULL)); + TEST_WRITE_ERR (mongoc_collection_delete_many (collection, b, &opts, &reply, NULL)); bulk = mongoc_collection_create_bulk_operation_with_opts (collection, &opts); mongoc_bulk_operation_insert (bulk, b); TEST_WRITE_ERR (mongoc_bulk_operation_execute (bulk, &reply, NULL)); - TEST_CURSOR_ERR (mongoc_collection_aggregate ( - collection, MONGOC_QUERY_NONE, tmp_bson ("[{}]"), &opts, NULL)); - TEST_CURSOR_ERR ( - mongoc_collection_find_with_opts (collection, b, &opts, NULL)); + TEST_CURSOR_ERR (mongoc_collection_aggregate (collection, MONGOC_QUERY_NONE, tmp_bson ("[{}]"), &opts, NULL)); + TEST_CURSOR_ERR (mongoc_collection_find_with_opts (collection, b, &opts, NULL)); mongoc_find_and_modify_opts_destroy (fam); mongoc_bulk_operation_destroy (bulk); @@ -650,15 +559,9 @@ test_unknown_commit_result (void) server = mock_server_new (); mock_server_run (server); - rs_response_to_hello (server, - WIRE_VERSION_4_0, - true /* primary */, - false /* tags */, - server, - NULL); - - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + rs_response_to_hello (server, WIRE_VERSION_4_0, true /* primary */, false /* tags */, server, NULL); + + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); /* allow fast reconnect */ client->topology->min_heartbeat_frequency_msec = 0; session = mongoc_client_start_session (client, NULL, &error); @@ -668,10 +571,8 @@ test_unknown_commit_result (void) r = mongoc_client_session_append (session, &opts, &error); ASSERT_OR_PRINT (r, error); collection = mongoc_client_get_collection (client, "db", "collection"); - future = future_collection_insert_one ( - collection, tmp_bson ("{}"), &opts, NULL, &error); - request = mock_server_receives_msg ( - server, 0, tmp_bson ("{'insert': 'collection'}"), tmp_bson ("{}")); + future = future_collection_insert_one (collection, tmp_bson ("{}"), &opts, NULL, &error); + request = mock_server_receives_msg (server, 0, tmp_bson ("{'insert': 'collection'}"), tmp_bson ("{}")); reply_to_request_with_ok_and_destroy (request); ASSERT_OR_PRINT (future_get_bool (future), error); future_destroy (future); @@ -682,13 +583,11 @@ test_unknown_commit_result (void) BSON_ASSERT (!r); if (!mongoc_error_has_label (&reply, "UnknownTransactionCommitResult")) { - test_error ("Reply lacks UnknownTransactionCommitResult label: %s", - bson_as_json (&reply, NULL)); + test_error ("Reply lacks UnknownTransactionCommitResult label: %s", bson_as_json (&reply, NULL)); } if (mongoc_error_has_label (&reply, "TransientTransactionError")) { - test_error ("Reply shouldn't have TransientTransactionError label: %s", - bson_as_json (&reply, NULL)); + test_error ("Reply shouldn't have TransientTransactionError label: %s", bson_as_json (&reply, NULL)); } bson_destroy (&reply); @@ -731,8 +630,7 @@ test_cursor_primary_read_pref (void *ctx) read_prefs = mongoc_read_prefs_new (MONGOC_READ_PRIMARY); - cursor = mongoc_collection_find_with_opts ( - collection, tmp_bson ("{}"), &opts, read_prefs); + cursor = mongoc_collection_find_with_opts (collection, tmp_bson ("{}"), &opts, read_prefs); bson_destroy (&opts); mongoc_read_prefs_destroy (read_prefs); @@ -799,25 +697,20 @@ test_inherit_from_client (void *ctx) /* test that unacknowledged write concern is actually used, since it should * result in an error. */ ASSERT (!mongoc_client_session_start_transaction (session, NULL, &error)); - ASSERT_ERROR_CONTAINS ( - error, - MONGOC_ERROR_TRANSACTION, - MONGOC_ERROR_TRANSACTION_INVALID_STATE, - "Transactions do not support unacknowledged write concern"); + ASSERT_ERROR_CONTAINS (error, + MONGOC_ERROR_TRANSACTION, + MONGOC_ERROR_TRANSACTION_INVALID_STATE, + "Transactions do not support unacknowledged write concern"); returned_sopt = mongoc_client_session_get_opts (session); - returned_topt = - mongoc_session_opts_get_default_transaction_opts (returned_sopt); + returned_topt = mongoc_session_opts_get_default_transaction_opts (returned_sopt); returned_rc = mongoc_transaction_opts_get_read_concern (returned_topt); returned_rp = mongoc_transaction_opts_get_read_prefs (returned_topt); returned_wc = mongoc_transaction_opts_get_write_concern (returned_topt); - BSON_ASSERT (strcmp (mongoc_read_concern_get_level (returned_rc), - mongoc_read_concern_get_level (rc)) == 0); - BSON_ASSERT (mongoc_write_concern_get_w (returned_wc) == - mongoc_write_concern_get_w (wc)); - BSON_ASSERT (mongoc_read_prefs_get_mode (returned_rp) == - mongoc_read_prefs_get_mode (rp)); + BSON_ASSERT (strcmp (mongoc_read_concern_get_level (returned_rc), mongoc_read_concern_get_level (rc)) == 0); + BSON_ASSERT (mongoc_write_concern_get_w (returned_wc) == mongoc_write_concern_get_w (wc)); + BSON_ASSERT (mongoc_read_prefs_get_mode (returned_rp) == mongoc_read_prefs_get_mode (rp)); mongoc_read_concern_destroy (rc); mongoc_read_prefs_destroy (rp); @@ -845,8 +738,7 @@ test_transaction_fails_on_unsupported_version_or_sharded_cluster (void *ctx) r = mongoc_client_session_start_transaction (session, NULL, &error); if (!test_framework_max_wire_version_at_least (7) || - (test_framework_is_mongos () && - !test_framework_max_wire_version_at_least (8))) { + (test_framework_is_mongos () && !test_framework_max_wire_version_at_least (8))) { BSON_ASSERT (!r); ASSERT_CONTAINS (error.message, "Multi-document transactions are not supported by this " @@ -873,8 +765,7 @@ test_transaction_recovery_token_cleared (void *ctx) BSON_UNUSED (ctx); uri = test_framework_get_uri (); - ASSERT_OR_PRINT ( - mongoc_uri_upsert_host_and_port (uri, "localhost:27018", &error), error); + ASSERT_OR_PRINT (mongoc_uri_upsert_host_and_port (uri, "localhost:27018", &error), error); client = test_framework_client_new_from_uri (uri, NULL); test_framework_set_ssl_opts (client); mongoc_uri_destroy (uri); @@ -882,53 +773,35 @@ test_transaction_recovery_token_cleared (void *ctx) ASSERT_OR_PRINT (session, error); coll = get_test_collection (client, "transaction_test"); - mongoc_client_command_with_opts (client, - "admin", - tmp_bson ("{'killAllSessions': []}"), - NULL, - NULL, - NULL, - &error); + mongoc_client_command_with_opts (client, "admin", tmp_bson ("{'killAllSessions': []}"), NULL, NULL, NULL, &error); /* Create the collection by inserting a canary document. You cannot create * inside a transaction */ - ASSERT_OR_PRINT ( - mongoc_collection_insert_one (coll, tmp_bson ("{}"), NULL, NULL, &error), - error); + ASSERT_OR_PRINT (mongoc_collection_insert_one (coll, tmp_bson ("{}"), NULL, NULL, &error), error); bson_init (&txn_opts); - ASSERT_OR_PRINT (mongoc_client_session_append (session, &txn_opts, &error), - error); + ASSERT_OR_PRINT (mongoc_client_session_append (session, &txn_opts, &error), error); - ASSERT_OR_PRINT ( - mongoc_client_session_start_transaction (session, NULL, &error), error); + ASSERT_OR_PRINT (mongoc_client_session_start_transaction (session, NULL, &error), error); /* Initially no recovery token. */ BSON_ASSERT (!session->recovery_token); - mongoc_collection_insert_one ( - coll, tmp_bson ("{}"), &txn_opts, NULL, &error); + mongoc_collection_insert_one (coll, tmp_bson ("{}"), &txn_opts, NULL, &error); BSON_ASSERT (session->recovery_token); - ASSERT_OR_PRINT ( - mongoc_client_session_commit_transaction (session, NULL, &error), error); + ASSERT_OR_PRINT (mongoc_client_session_commit_transaction (session, NULL, &error), error); BSON_ASSERT (session->recovery_token); /* Starting a new transaction clears the recovery token. */ - ASSERT_OR_PRINT ( - mongoc_client_session_start_transaction (session, NULL, &error), error); + ASSERT_OR_PRINT (mongoc_client_session_start_transaction (session, NULL, &error), error); BSON_ASSERT (!session->recovery_token); - ASSERT_OR_PRINT (mongoc_collection_insert_one ( - coll, tmp_bson ("{}"), &txn_opts, NULL, &error), - error); + ASSERT_OR_PRINT (mongoc_collection_insert_one (coll, tmp_bson ("{}"), &txn_opts, NULL, &error), error); BSON_ASSERT (session->recovery_token); - ASSERT_OR_PRINT ( - mongoc_client_session_commit_transaction (session, NULL, &error), error); + ASSERT_OR_PRINT (mongoc_client_session_commit_transaction (session, NULL, &error), error); BSON_ASSERT (session->recovery_token); /* Transitioning to the "none" state (i.e. a new operation outside of a * transaction), clears the recovery token */ - ASSERT_OR_PRINT (mongoc_collection_insert_one ( - coll, tmp_bson ("{}"), &txn_opts, NULL, &error), - error); + ASSERT_OR_PRINT (mongoc_collection_insert_one (coll, tmp_bson ("{}"), &txn_opts, NULL, &error), error); BSON_ASSERT (!session->recovery_token); bson_destroy (&txn_opts); @@ -960,8 +833,7 @@ test_selected_server_is_pinned_to_mongos (void *ctx) BSON_UNUSED (ctx); uri = test_framework_get_uri (); - ASSERT_OR_PRINT ( - mongoc_uri_upsert_host_and_port (uri, "localhost:27018", &error), error); + ASSERT_OR_PRINT (mongoc_uri_upsert_host_and_port (uri, "localhost:27018", &error), error); client = test_framework_client_new_from_uri (uri, NULL); BSON_ASSERT (client); @@ -982,19 +854,16 @@ test_selected_server_is_pinned_to_mongos (void *ctx) ASSERT_OR_PRINT (r, error); BSON_ASSERT (0 == mongoc_client_session_get_server_id (session)); - expected_id = mongoc_topology_select_server_id ( - client->topology, MONGOC_SS_WRITE, NULL, NULL, NULL, &error); + expected_id = mongoc_topology_select_server_id (client->topology, MONGOC_SS_WRITE, NULL, NULL, NULL, &error); ASSERT_OR_PRINT (expected_id, error); /* session should still be unpinned */ BSON_ASSERT (0 == mongoc_client_session_get_server_id (session)); /* should pin to the expected server id */ - server_stream = mongoc_cluster_stream_for_server ( - &client->cluster, expected_id, true, session, NULL, &error); + server_stream = mongoc_cluster_stream_for_server (&client->cluster, expected_id, true, session, NULL, &error); ASSERT_OR_PRINT (server_stream, error); - ASSERT_CMPINT32 ( - expected_id, ==, mongoc_client_session_get_server_id (session)); + ASSERT_CMPINT32 (expected_id, ==, mongoc_client_session_get_server_id (session)); db = mongoc_client_get_database (client, "db"); coll = mongoc_database_create_collection (db, "coll", NULL, &error); @@ -1004,16 +873,14 @@ test_selected_server_is_pinned_to_mongos (void *ctx) ASSERT_OR_PRINT (r, error); /* this should not override the expected server id */ - r = mongoc_collection_insert_one ( - coll, tmp_bson ("{}"), insert_opts, NULL, &error); + r = mongoc_collection_insert_one (coll, tmp_bson ("{}"), insert_opts, NULL, &error); ASSERT_OR_PRINT (r, error); actual_id = mongoc_client_session_get_server_id (session); ASSERT_CMPINT32 (actual_id, ==, expected_id); /* get a valid server id that's different from the pinned server id */ - servers = - mc_tpld_servers_const (mc_tpld_unsafe_get_const (client->topology)); + servers = mc_tpld_servers_const (mc_tpld_unsafe_get_const (client->topology)); for (size_t i = 0; i < servers->items_len; i++) { sd = mongoc_set_get_item_const (servers, i); if (sd && sd->id != actual_id) { @@ -1028,18 +895,15 @@ test_selected_server_is_pinned_to_mongos (void *ctx) "db", tmp_bson ("{'ping': 1}"), NULL, - tmp_bson ("{'serverId': %d, 'sessionId': {'$numberLong': '%ld'}}", - sd->id, - session->client_session_id), + tmp_bson ("{'serverId': %d, 'sessionId': {'$numberLong': '%ld'}}", sd->id, session->client_session_id), &reply, &error); BSON_ASSERT (!r); - ASSERT_ERROR_CONTAINS ( - error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_SERVER_SELECTION_INVALID_ID, - "Requested server id does not matched pinned server id"); + ASSERT_ERROR_CONTAINS (error, + MONGOC_ERROR_COMMAND, + MONGOC_ERROR_SERVER_SELECTION_INVALID_ID, + "Requested server id does not matched pinned server id"); r = mongoc_client_session_abort_transaction (session, &error); ASSERT_OR_PRINT (r, error); @@ -1075,15 +939,9 @@ test_get_transaction_opts (void) server = mock_server_new (); mock_server_run (server); - rs_response_to_hello (server, - WIRE_VERSION_4_0, - true /* primary */, - false /* tags */, - server, - NULL); - - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + rs_response_to_hello (server, WIRE_VERSION_4_0, true /* primary */, false /* tags */, server, NULL); + + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); BSON_ASSERT (client); read_concern = mongoc_read_concern_new (); @@ -1099,8 +957,7 @@ test_get_transaction_opts (void) mongoc_transaction_opts_set_read_concern (expected_txn_opts, read_concern); mongoc_transaction_opts_set_write_concern (expected_txn_opts, write_concern); mongoc_transaction_opts_set_read_prefs (expected_txn_opts, read_prefs); - mongoc_transaction_opts_set_max_commit_time_ms (expected_txn_opts, - max_commit_time_ms); + mongoc_transaction_opts_set_max_commit_time_ms (expected_txn_opts, max_commit_time_ms); session_opts = mongoc_session_opts_new (); session = mongoc_client_start_session (client, session_opts, &error); @@ -1108,27 +965,21 @@ test_get_transaction_opts (void) /* outside of a txn this function should return NULL */ BSON_ASSERT (!mongoc_session_opts_get_transaction_opts (session)); - r = mongoc_client_session_start_transaction ( - session, expected_txn_opts, &error); + r = mongoc_client_session_start_transaction (session, expected_txn_opts, &error); ASSERT_OR_PRINT (r, error); actual_txn_opts = mongoc_session_opts_get_transaction_opts (session); BSON_ASSERT (actual_txn_opts); - BSON_ASSERT ( - 0 == bson_compare ( - _mongoc_read_concern_get_bson (actual_txn_opts->read_concern), - _mongoc_read_concern_get_bson (expected_txn_opts->read_concern))); + BSON_ASSERT (0 == bson_compare (_mongoc_read_concern_get_bson (actual_txn_opts->read_concern), + _mongoc_read_concern_get_bson (expected_txn_opts->read_concern))); - BSON_ASSERT (0 == bson_compare (_mongoc_write_concern_get_bson ( - actual_txn_opts->write_concern), - _mongoc_write_concern_get_bson ( - expected_txn_opts->write_concern))); + BSON_ASSERT (0 == bson_compare (_mongoc_write_concern_get_bson (actual_txn_opts->write_concern), + _mongoc_write_concern_get_bson (expected_txn_opts->write_concern))); BSON_ASSERT (mongoc_read_prefs_get_mode (actual_txn_opts->read_prefs) == mongoc_read_prefs_get_mode (expected_txn_opts->read_prefs)); - BSON_ASSERT (actual_txn_opts->max_commit_time_ms == - expected_txn_opts->max_commit_time_ms); + BSON_ASSERT (actual_txn_opts->max_commit_time_ms == expected_txn_opts->max_commit_time_ms); r = mongoc_client_session_abort_transaction (session, &error); ASSERT_OR_PRINT (r, error); @@ -1160,10 +1011,7 @@ test_max_commit_time_ms_is_reset (void *ctx) BSON_UNUSED (ctx); - rs = mock_rs_with_auto_hello (WIRE_VERSION_4_2, - true /* has primary */, - 2 /* secondaries */, - 0 /* arbiters */); + rs = mock_rs_with_auto_hello (WIRE_VERSION_4_2, true /* has primary */, 2 /* secondaries */, 0 /* arbiters */); mock_rs_run (rs); uri = mongoc_uri_copy (mock_rs_get_uri (rs)); @@ -1185,16 +1033,13 @@ test_max_commit_time_ms_is_reset (void *ctx) r = mongoc_client_session_abort_transaction (session, &error); ASSERT_OR_PRINT (r, error); - BSON_ASSERT (DEFAULT_MAX_COMMIT_TIME_MS == - session->txn.opts.max_commit_time_ms); + BSON_ASSERT (DEFAULT_MAX_COMMIT_TIME_MS == session->txn.opts.max_commit_time_ms); - mongoc_transaction_opts_set_max_commit_time_ms (txn_opts, - DEFAULT_MAX_COMMIT_TIME_MS); + mongoc_transaction_opts_set_max_commit_time_ms (txn_opts, DEFAULT_MAX_COMMIT_TIME_MS); r = mongoc_client_session_start_transaction (session, txn_opts, &error); ASSERT_OR_PRINT (r, error); - BSON_ASSERT (DEFAULT_MAX_COMMIT_TIME_MS == - session->txn.opts.max_commit_time_ms); + BSON_ASSERT (DEFAULT_MAX_COMMIT_TIME_MS == session->txn.opts.max_commit_time_ms); r = mongoc_client_session_abort_transaction (session, &error); ASSERT_OR_PRINT (r, error); @@ -1224,51 +1069,32 @@ test_transactions_install (TestSuite *suite) test_framework_skip_if_no_txns, test_framework_skip_if_slow); - TestSuite_AddFull (suite, - "/transactions/supported", - test_transactions_supported, - NULL, - NULL, - test_framework_skip_if_no_txns); - TestSuite_AddFull (suite, - "/transactions/in_transaction", - test_in_transaction, - NULL, - NULL, - test_framework_skip_if_no_txns); - TestSuite_AddMockServerTest (suite, - "/transactions/server_selection_err", - test_server_selection_error, - test_framework_skip_if_no_crypto); - TestSuite_AddMockServerTest (suite, - "/transactions/network_err", - test_network_error, - test_framework_skip_if_no_crypto); - TestSuite_AddMockServerTest (suite, - "/transactions/unknown_commit_result", - test_unknown_commit_result, - test_framework_skip_if_no_crypto); + TestSuite_AddFull ( + suite, "/transactions/supported", test_transactions_supported, NULL, NULL, test_framework_skip_if_no_txns); + TestSuite_AddFull ( + suite, "/transactions/in_transaction", test_in_transaction, NULL, NULL, test_framework_skip_if_no_txns); + TestSuite_AddMockServerTest ( + suite, "/transactions/server_selection_err", test_server_selection_error, test_framework_skip_if_no_crypto); + TestSuite_AddMockServerTest ( + suite, "/transactions/network_err", test_network_error, test_framework_skip_if_no_crypto); + TestSuite_AddMockServerTest ( + suite, "/transactions/unknown_commit_result", test_unknown_commit_result, test_framework_skip_if_no_crypto); TestSuite_AddFull (suite, "/transactions/cursor_primary_read_pref", test_cursor_primary_read_pref, NULL, NULL, test_framework_skip_if_no_txns); + TestSuite_AddFull ( + suite, "/transactions/inherit_from_client", test_inherit_from_client, NULL, NULL, test_framework_skip_if_no_txns); TestSuite_AddFull (suite, - "/transactions/inherit_from_client", - test_inherit_from_client, + "/transactions/" + "transaction_fails_on_unsupported_version_or_sharded_cluster", + test_transaction_fails_on_unsupported_version_or_sharded_cluster, NULL, NULL, - test_framework_skip_if_no_txns); - TestSuite_AddFull ( - suite, - "/transactions/" - "transaction_fails_on_unsupported_version_or_sharded_cluster", - test_transaction_fails_on_unsupported_version_or_sharded_cluster, - NULL, - NULL, - test_framework_skip_if_no_sessions, - test_framework_skip_if_no_crypto); + test_framework_skip_if_no_sessions, + test_framework_skip_if_no_crypto); TestSuite_AddFull (suite, "/transactions/recovery_token_cleared", test_transaction_recovery_token_cleared, @@ -1286,10 +1112,8 @@ test_transactions_install (TestSuite *suite) test_framework_skip_if_no_sessions, test_framework_skip_if_max_wire_version_less_than_8, test_framework_skip_if_not_mongos); - TestSuite_AddMockServerTest (suite, - "/transactions/get_transaction_opts", - test_get_transaction_opts, - test_framework_skip_if_no_crypto); + TestSuite_AddMockServerTest ( + suite, "/transactions/get_transaction_opts", test_get_transaction_opts, test_framework_skip_if_no_crypto); TestSuite_AddFull (suite, "/transactions/max_commit_time_ms_is_reset", test_max_commit_time_ms_is_reset, diff --git a/src/libmongoc/tests/test-mongoc-ts-pool.c b/src/libmongoc/tests/test-mongoc-ts-pool.c index 2b6c916562..b1f9c49dcd 100644 --- a/src/libmongoc/tests/test-mongoc-ts-pool.c +++ b/src/libmongoc/tests/test-mongoc-ts-pool.c @@ -6,8 +6,7 @@ static void test_ts_pool_empty (void) { - mongoc_ts_pool *pool = mongoc_ts_pool_new ( - (mongoc_ts_pool_params){.element_size = sizeof (int)}); + mongoc_ts_pool *pool = mongoc_ts_pool_new ((mongoc_ts_pool_params){.element_size = sizeof (int)}); BSON_ASSERT (mongoc_ts_pool_is_empty (pool)); mongoc_ts_pool_free (pool); } @@ -16,8 +15,7 @@ test_ts_pool_empty (void) static void test_ts_pool_simple (void) { - mongoc_ts_pool *pool = mongoc_ts_pool_new ( - (mongoc_ts_pool_params){.element_size = sizeof (int)}); + mongoc_ts_pool *pool = mongoc_ts_pool_new ((mongoc_ts_pool_params){.element_size = sizeof (int)}); int *item; int *item2; @@ -60,8 +58,7 @@ _set_int_to_7 (int *v, void *unused, bson_error_t *unused2) /* Declare a pool that contains `int`, sets each new int to seven, and drops * integers that are equal to 42. */ -MONGOC_DECL_SPECIAL_TS_POOL ( - int, int_pool, void, _set_int_to_7, NULL, _is_int_42) +MONGOC_DECL_SPECIAL_TS_POOL (int, int_pool, void, _set_int_to_7, NULL, _is_int_42) static void test_ts_pool_special (void) diff --git a/src/libmongoc/tests/test-mongoc-uri.c b/src/libmongoc/tests/test-mongoc-uri.c index d20a93e5c7..0910ef8dc5 100644 --- a/src/libmongoc/tests/test-mongoc-uri.c +++ b/src/libmongoc/tests/test-mongoc-uri.c @@ -39,12 +39,10 @@ test_mongoc_uri_new (void) ASSERT (!mongoc_uri_new ("mongodb://user%40DOMAIN.COM:password@localhost/" "?" MONGOC_URI_AUTHMECHANISM "=\x80")); ASSERT (!mongoc_uri_new ("mongodb://user%40DOMAIN.COM:password@localhost/" - "?" MONGOC_URI_AUTHMECHANISM - "=GSSAPI&" MONGOC_URI_AUTHMECHANISMPROPERTIES + "?" MONGOC_URI_AUTHMECHANISM "=GSSAPI&" MONGOC_URI_AUTHMECHANISMPROPERTIES "=SERVICE_NAME:\x80")); ASSERT (!mongoc_uri_new ("mongodb://user%40DOMAIN.COM:password@localhost/" - "?" MONGOC_URI_AUTHMECHANISM - "=GSSAPI&" MONGOC_URI_AUTHMECHANISMPROPERTIES + "?" MONGOC_URI_AUTHMECHANISM "=GSSAPI&" MONGOC_URI_AUTHMECHANISMPROPERTIES "=\x80:mongodb")); ASSERT (!mongoc_uri_new ("mongodb://::")); ASSERT (!mongoc_uri_new ("mongodb://[::1]::27017/")); @@ -73,8 +71,7 @@ test_mongoc_uri_new (void) ASSERT (!mongoc_uri_new ("mongodb://local1,local2/?directConnection=true")); ASSERT (!mongoc_uri_new ("mongodb+srv://local1/?directConnection=true")); - uri = mongoc_uri_new ( - "mongodb://[::1]:27888,[::2]:27999/?ipv6=true&" MONGOC_URI_SAFE "=true"); + uri = mongoc_uri_new ("mongodb://[::1]:27888,[::2]:27999/?ipv6=true&" MONGOC_URI_SAFE "=true"); BSON_ASSERT (uri); hosts = mongoc_uri_get_hosts (uri); BSON_ASSERT (hosts); @@ -144,13 +141,11 @@ test_mongoc_uri_new (void) mongoc_uri_destroy (uri); uri = mongoc_uri_new ("mongodb://localhost:27017/" - "?" MONGOC_URI_READPREFERENCE - "=secondaryPreferred&" MONGOC_URI_READPREFERENCETAGS + "?" MONGOC_URI_READPREFERENCE "=secondaryPreferred&" MONGOC_URI_READPREFERENCETAGS "=dc:ny&" MONGOC_URI_READPREFERENCETAGS "="); ASSERT (uri); read_prefs = mongoc_uri_get_read_prefs_t (uri); - ASSERT (mongoc_read_prefs_get_mode (read_prefs) == - MONGOC_READ_SECONDARY_PREFERRED); + ASSERT (mongoc_read_prefs_get_mode (read_prefs) == MONGOC_READ_SECONDARY_PREFERRED); ASSERT (read_prefs); read_prefs_tags = mongoc_read_prefs_get_tags (read_prefs); ASSERT (read_prefs_tags); @@ -169,8 +164,7 @@ test_mongoc_uri_new (void) ASSERT (!bson_iter_next (&iter)); mongoc_uri_destroy (uri); - uri = mongoc_uri_new ("mongodb://localhost/?" MONGOC_URI_SAFE - "=false&" MONGOC_URI_JOURNAL "=false"); + uri = mongoc_uri_new ("mongodb://localhost/?" MONGOC_URI_SAFE "=false&" MONGOC_URI_JOURNAL "=false"); options = mongoc_uri_get_options (uri); ASSERT (options); ASSERT_CMPINT (bson_count_keys (options), ==, 2); @@ -184,19 +178,15 @@ test_mongoc_uri_new (void) ASSERT (!bson_iter_next (&iter)); mongoc_uri_destroy (uri); - uri = mongoc_uri_new ( - "mongodb://%2Ftmp%2Fmongodb-27017.sock/?" MONGOC_URI_TLS "=false"); + uri = mongoc_uri_new ("mongodb://%2Ftmp%2Fmongodb-27017.sock/?" MONGOC_URI_TLS "=false"); ASSERT (uri); ASSERT_CMPSTR (mongoc_uri_get_hosts (uri)->host, "/tmp/mongodb-27017.sock"); mongoc_uri_destroy (uri); - uri = mongoc_uri_new ( - "mongodb://%2Ftmp%2Fmongodb-27017.sock,localhost:27017/?" MONGOC_URI_TLS - "=false"); + uri = mongoc_uri_new ("mongodb://%2Ftmp%2Fmongodb-27017.sock,localhost:27017/?" MONGOC_URI_TLS "=false"); ASSERT (uri); ASSERT_CMPSTR (mongoc_uri_get_hosts (uri)->host, "/tmp/mongodb-27017.sock"); - ASSERT_CMPSTR (mongoc_uri_get_hosts (uri)->next->host_and_port, - "localhost:27017"); + ASSERT_CMPSTR (mongoc_uri_get_hosts (uri)->next->host_and_port, "localhost:27017"); ASSERT (!mongoc_uri_get_hosts (uri)->next->next); mongoc_uri_destroy (uri); @@ -204,39 +194,28 @@ test_mongoc_uri_new (void) uri = mongoc_uri_new ("mongodb://host1,host2:30000/foo"); ASSERT (uri); ASSERT_CMPSTR (mongoc_uri_get_hosts (uri)->host_and_port, "host1:27017"); - ASSERT_CMPSTR (mongoc_uri_get_hosts (uri)->next->host_and_port, - "host2:30000"); + ASSERT_CMPSTR (mongoc_uri_get_hosts (uri)->next->host_and_port, "host2:30000"); mongoc_uri_destroy (uri); - uri = mongoc_uri_new ( - "mongodb://localhost:27017,%2Ftmp%2Fmongodb-27017.sock/?" MONGOC_URI_TLS - "=false"); + uri = mongoc_uri_new ("mongodb://localhost:27017,%2Ftmp%2Fmongodb-27017.sock/?" MONGOC_URI_TLS "=false"); ASSERT (uri); ASSERT_CMPSTR (mongoc_uri_get_hosts (uri)->host_and_port, "localhost:27017"); - ASSERT_CMPSTR (mongoc_uri_get_hosts (uri)->next->host, - "/tmp/mongodb-27017.sock"); + ASSERT_CMPSTR (mongoc_uri_get_hosts (uri)->next->host, "/tmp/mongodb-27017.sock"); ASSERT (!mongoc_uri_get_hosts (uri)->next->next); mongoc_uri_destroy (uri); - uri = mongoc_uri_new ("mongodb://localhost/?" MONGOC_URI_HEARTBEATFREQUENCYMS - "=600"); + uri = mongoc_uri_new ("mongodb://localhost/?" MONGOC_URI_HEARTBEATFREQUENCYMS "=600"); ASSERT (uri); - ASSERT_CMPINT32 ( - 600, - ==, - mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_HEARTBEATFREQUENCYMS, 0)); + ASSERT_CMPINT32 (600, ==, mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_HEARTBEATFREQUENCYMS, 0)); mongoc_uri_destroy (uri); /* heartbeat frequency too short */ - ASSERT (!mongoc_uri_new ( - "mongodb://localhost/?" MONGOC_URI_HEARTBEATFREQUENCYMS "=499")); + ASSERT (!mongoc_uri_new ("mongodb://localhost/?" MONGOC_URI_HEARTBEATFREQUENCYMS "=499")); /* should use the " MONGOC_URI_AUTHSOURCE " over db when both are specified */ - uri = mongoc_uri_new ( - "mongodb://christian:secret@localhost:27017/foo?" MONGOC_URI_AUTHSOURCE - "=abcd"); + uri = mongoc_uri_new ("mongodb://christian:secret@localhost:27017/foo?" MONGOC_URI_AUTHSOURCE "=abcd"); ASSERT (uri); ASSERT_CMPSTR (mongoc_uri_get_username (uri), "christian"); ASSERT_CMPSTR (mongoc_uri_get_password (uri), "secret"); @@ -280,21 +259,17 @@ test_mongoc_uri_new (void) capture_logs (true); uri = mongoc_uri_new ("mongodb://u%ser:pwd@localhost:27017"); ASSERT (!uri); - ASSERT_CAPTURED_LOG ( - "uri", MONGOC_LOG_LEVEL_WARNING, "Invalid % escape sequence"); + ASSERT_CAPTURED_LOG ("uri", MONGOC_LOG_LEVEL_WARNING, "Invalid % escape sequence"); uri = mongoc_uri_new ("mongodb://user:p%wd@localhost:27017"); ASSERT (!uri); - ASSERT_CAPTURED_LOG ( - "uri", MONGOC_LOG_LEVEL_WARNING, "Invalid % escape sequence"); + ASSERT_CAPTURED_LOG ("uri", MONGOC_LOG_LEVEL_WARNING, "Invalid % escape sequence"); uri = mongoc_uri_new ("mongodb://user:pwd@local% host:27017"); ASSERT (!uri); - ASSERT_CAPTURED_LOG ( - "uri", MONGOC_LOG_LEVEL_WARNING, "Invalid % escape sequence"); + ASSERT_CAPTURED_LOG ("uri", MONGOC_LOG_LEVEL_WARNING, "Invalid % escape sequence"); - uri = mongoc_uri_new ( - "mongodb://christian%40realm@localhost:27017/?replicaset=%20"); + uri = mongoc_uri_new ("mongodb://christian%40realm@localhost:27017/?replicaset=%20"); ASSERT (uri); options = mongoc_uri_get_options (uri); ASSERT (options); @@ -303,8 +278,7 @@ test_mongoc_uri_new (void) ASSERT_CMPSTR (bson_iter_utf8 (&iter, NULL), " "); mongoc_uri_destroy (uri); - uri = mongoc_uri_new ( - "mongodb://christian%40realm@[::6]:27017/?replicaset=%20"); + uri = mongoc_uri_new ("mongodb://christian%40realm@[::6]:27017/?replicaset=%20"); ASSERT (uri); options = mongoc_uri_get_options (uri); ASSERT (options); @@ -332,40 +306,33 @@ test_mongoc_uri_new (void) /* should not accept " MONGOC_URI_AUTHSOURCE " other than $external */ ASSERT (!mongoc_uri_new ("mongodb://user%40DOMAIN.COM:password@localhost/" - "foo?" MONGOC_URI_AUTHMECHANISM - "=GSSAPI&" MONGOC_URI_AUTHSOURCE "=bar")); + "foo?" MONGOC_URI_AUTHMECHANISM "=GSSAPI&" MONGOC_URI_AUTHSOURCE "=bar")); /* should accept MONGOC_URI_AUTHMECHANISMPROPERTIES */ uri = mongoc_uri_new ("mongodb://user%40DOMAIN.COM:password@localhost/" - "?" MONGOC_URI_AUTHMECHANISM - "=GSSAPI&" MONGOC_URI_AUTHMECHANISMPROPERTIES + "?" MONGOC_URI_AUTHMECHANISM "=GSSAPI&" MONGOC_URI_AUTHMECHANISMPROPERTIES "=SERVICE_NAME:other,CANONICALIZE_HOST_NAME:" "true"); ASSERT (uri); credentials = mongoc_uri_get_credentials (uri); ASSERT (credentials); ASSERT (mongoc_uri_get_mechanism_properties (uri, &properties)); - BSON_ASSERT (bson_iter_init_find_case (&iter, &properties, "SERVICE_NAME") && - BSON_ITER_HOLDS_UTF8 (&iter) && + BSON_ASSERT (bson_iter_init_find_case (&iter, &properties, "SERVICE_NAME") && BSON_ITER_HOLDS_UTF8 (&iter) && (0 == strcmp (bson_iter_utf8 (&iter, NULL), "other"))); - BSON_ASSERT ( - bson_iter_init_find_case (&iter, &properties, "CANONICALIZE_HOST_NAME") && - BSON_ITER_HOLDS_UTF8 (&iter) && - (0 == strcmp (bson_iter_utf8 (&iter, NULL), "true"))); + BSON_ASSERT (bson_iter_init_find_case (&iter, &properties, "CANONICALIZE_HOST_NAME") && + BSON_ITER_HOLDS_UTF8 (&iter) && (0 == strcmp (bson_iter_utf8 (&iter, NULL), "true"))); mongoc_uri_destroy (uri); /* reverse order of arguments to ensure parsing still succeeds */ - uri = mongoc_uri_new ( - "mongodb://user@localhost/?" MONGOC_URI_AUTHMECHANISMPROPERTIES - "=SERVICE_NAME:other&" MONGOC_URI_AUTHMECHANISM "=GSSAPI"); + uri = mongoc_uri_new ("mongodb://user@localhost/?" MONGOC_URI_AUTHMECHANISMPROPERTIES + "=SERVICE_NAME:other&" MONGOC_URI_AUTHMECHANISM "=GSSAPI"); ASSERT (uri); mongoc_uri_destroy (uri); /* MONGODB-CR */ /* should recognize this mechanism */ - uri = mongoc_uri_new ("mongodb://user@localhost/?" MONGOC_URI_AUTHMECHANISM - "=MONGODB-CR"); + uri = mongoc_uri_new ("mongodb://user@localhost/?" MONGOC_URI_AUTHMECHANISM "=MONGODB-CR"); ASSERT (uri); ASSERT_CMPSTR (mongoc_uri_get_auth_mechanism (uri), "MONGODB-CR"); mongoc_uri_destroy (uri); @@ -373,45 +340,36 @@ test_mongoc_uri_new (void) /* X509 */ /* should recognize this mechanism, and use $external as the source */ - uri = mongoc_uri_new ("mongodb://user@localhost/?" MONGOC_URI_AUTHMECHANISM - "=MONGODB-X509"); + uri = mongoc_uri_new ("mongodb://user@localhost/?" MONGOC_URI_AUTHMECHANISM "=MONGODB-X509"); ASSERT (uri); ASSERT_CMPSTR (mongoc_uri_get_auth_mechanism (uri), "MONGODB-X509"); /*ASSERT_CMPSTR(mongoc_uri_get_auth_source(uri), "$external");*/ mongoc_uri_destroy (uri); /* use $external as source when db is specified */ - uri = mongoc_uri_new ( - "mongodb://CN%3DmyName%2COU%3DmyOrgUnit%2CO%3DmyOrg%2CL%3DmyLocality" - "%2CST%3DmyState%2CC%3DmyCountry@localhost/foo" - "?" MONGOC_URI_AUTHMECHANISM "=MONGODB-X509"); + uri = mongoc_uri_new ("mongodb://CN%3DmyName%2COU%3DmyOrgUnit%2CO%3DmyOrg%2CL%3DmyLocality" + "%2CST%3DmyState%2CC%3DmyCountry@localhost/foo" + "?" MONGOC_URI_AUTHMECHANISM "=MONGODB-X509"); ASSERT (uri); ASSERT_CMPSTR (mongoc_uri_get_auth_source (uri), "$external"); mongoc_uri_destroy (uri); /* should not accept " MONGOC_URI_AUTHSOURCE " other than $external */ - ASSERT (!mongoc_uri_new ( - "mongodb://CN%3DmyName%2COU%3DmyOrgUnit%2CO%3DmyOrg%2CL%3DmyLocality" - "%2CST%3DmyState%2CC%3DmyCountry@localhost/foo" - "?" MONGOC_URI_AUTHMECHANISM "=MONGODB-X509&" MONGOC_URI_AUTHSOURCE - "=bar")); + ASSERT (!mongoc_uri_new ("mongodb://CN%3DmyName%2COU%3DmyOrgUnit%2CO%3DmyOrg%2CL%3DmyLocality" + "%2CST%3DmyState%2CC%3DmyCountry@localhost/foo" + "?" MONGOC_URI_AUTHMECHANISM "=MONGODB-X509&" MONGOC_URI_AUTHSOURCE "=bar")); /* should recognize the encoded username */ - uri = mongoc_uri_new ( - "mongodb://CN%3DmyName%2COU%3DmyOrgUnit%2CO%3DmyOrg%2CL%3DmyLocality" - "%2CST%3DmyState%2CC%3DmyCountry@localhost/?" MONGOC_URI_AUTHMECHANISM - "=MONGODB-X509"); + uri = mongoc_uri_new ("mongodb://CN%3DmyName%2COU%3DmyOrgUnit%2CO%3DmyOrg%2CL%3DmyLocality" + "%2CST%3DmyState%2CC%3DmyCountry@localhost/?" MONGOC_URI_AUTHMECHANISM "=MONGODB-X509"); ASSERT (uri); - ASSERT_CMPSTR ( - mongoc_uri_get_username (uri), - "CN=myName,OU=myOrgUnit,O=myOrg,L=myLocality,ST=myState,C=myCountry"); + ASSERT_CMPSTR (mongoc_uri_get_username (uri), "CN=myName,OU=myOrgUnit,O=myOrg,L=myLocality,ST=myState,C=myCountry"); mongoc_uri_destroy (uri); /* PLAIN */ /* should recognize this mechanism */ - uri = mongoc_uri_new ("mongodb://user@localhost/?" MONGOC_URI_AUTHMECHANISM - "=PLAIN"); + uri = mongoc_uri_new ("mongodb://user@localhost/?" MONGOC_URI_AUTHMECHANISM "=PLAIN"); ASSERT (uri); ASSERT_CMPSTR (mongoc_uri_get_auth_mechanism (uri), "PLAIN"); mongoc_uri_destroy (uri); @@ -419,8 +377,7 @@ test_mongoc_uri_new (void) /* SCRAM-SHA1 */ /* should recognize this mechanism */ - uri = mongoc_uri_new ("mongodb://user@localhost/?" MONGOC_URI_AUTHMECHANISM - "=SCRAM-SHA1"); + uri = mongoc_uri_new ("mongodb://user@localhost/?" MONGOC_URI_AUTHMECHANISM "=SCRAM-SHA1"); ASSERT (uri); ASSERT_CMPSTR (mongoc_uri_get_auth_mechanism (uri), "SCRAM-SHA1"); mongoc_uri_destroy (uri); @@ -436,8 +393,7 @@ test_mongoc_uri_authmechanismproperties (void) capture_logs (true); - uri = mongoc_uri_new ("mongodb://user@localhost/?" MONGOC_URI_AUTHMECHANISM - "=SCRAM-SHA1" + uri = mongoc_uri_new ("mongodb://user@localhost/?" MONGOC_URI_AUTHMECHANISM "=SCRAM-SHA1" "&" MONGOC_URI_AUTHMECHANISMPROPERTIES "=a:one,b:two"); ASSERT (uri); ASSERT_CMPSTR (mongoc_uri_get_auth_mechanism (uri), "SCRAM-SHA1"); @@ -448,8 +404,7 @@ test_mongoc_uri_authmechanismproperties (void) ASSERT_CMPSTR (mongoc_uri_get_auth_mechanism (uri), "MONGODB-CR"); /* prohibited */ - ASSERT (!mongoc_uri_set_option_as_utf8 ( - uri, MONGOC_URI_AUTHMECHANISM, "SCRAM-SHA1")); + ASSERT (!mongoc_uri_set_option_as_utf8 (uri, MONGOC_URI_AUTHMECHANISM, "SCRAM-SHA1")); ASSERT (!mongoc_uri_set_option_as_int32 (uri, MONGOC_URI_AUTHMECHANISM, 1)); ASSERT_CAPTURED_LOG ("setting authmechanism=1", @@ -457,11 +412,9 @@ test_mongoc_uri_authmechanismproperties (void) "Unsupported value for \"authmechanism\": 1," " \"authmechanism\" is not an int32 option"); - ASSERT (!mongoc_uri_set_option_as_utf8 ( - uri, MONGOC_URI_AUTHMECHANISMPROPERTIES, "a:three")); + ASSERT (!mongoc_uri_set_option_as_utf8 (uri, MONGOC_URI_AUTHMECHANISMPROPERTIES, "a:three")); - ASSERT ( - mongoc_uri_set_mechanism_properties (uri, tmp_bson ("{'a': 'four'}"))); + ASSERT (mongoc_uri_set_mechanism_properties (uri, tmp_bson ("{'a': 'four'}"))); ASSERT (mongoc_uri_get_mechanism_properties (uri, &props)); ASSERT_MATCH (&props, "{'a': 'four', 'b': {'$exists': false}}"); @@ -470,14 +423,12 @@ test_mongoc_uri_authmechanismproperties (void) /* deprecated gssapiServiceName option */ uri = mongoc_uri_new ("mongodb://christian%40realm.cc@localhost:27017/" - "?" MONGOC_URI_AUTHMECHANISM - "=GSSAPI&" MONGOC_URI_GSSAPISERVICENAME "=blah"); + "?" MONGOC_URI_AUTHMECHANISM "=GSSAPI&" MONGOC_URI_GSSAPISERVICENAME "=blah"); ASSERT (uri); options = mongoc_uri_get_options (uri); ASSERT (options); BSON_ASSERT (0 == strcmp (mongoc_uri_get_auth_mechanism (uri), "GSSAPI")); - BSON_ASSERT (0 == - strcmp (mongoc_uri_get_username (uri), "christian@realm.cc")); + BSON_ASSERT (0 == strcmp (mongoc_uri_get_username (uri), "christian@realm.cc")); ASSERT (mongoc_uri_get_mechanism_properties (uri, &props)); ASSERT_MATCH (&props, "{'SERVICE_NAME': 'blah'}"); mongoc_uri_destroy (uri); @@ -492,8 +443,7 @@ test_mongoc_uri_functions (void) mongoc_database_t *db; int32_t i; - uri = mongoc_uri_new ( - "mongodb://foo:bar@localhost:27017/baz?" MONGOC_URI_AUTHSOURCE "=source"); + uri = mongoc_uri_new ("mongodb://foo:bar@localhost:27017/baz?" MONGOC_URI_AUTHSOURCE "=source"); ASSERT_CMPSTR (mongoc_uri_get_username (uri), "foo"); ASSERT_CMPSTR (mongoc_uri_get_password (uri), "bar"); @@ -501,72 +451,49 @@ test_mongoc_uri_functions (void) ASSERT_CMPSTR (mongoc_uri_get_auth_source (uri), "source"); mongoc_uri_set_username (uri, "longer username that should work"); - ASSERT_CMPSTR (mongoc_uri_get_username (uri), - "longer username that should work"); + ASSERT_CMPSTR (mongoc_uri_get_username (uri), "longer username that should work"); mongoc_uri_set_password (uri, "longer password that should also work"); - ASSERT_CMPSTR (mongoc_uri_get_password (uri), - "longer password that should also work"); + ASSERT_CMPSTR (mongoc_uri_get_password (uri), "longer password that should also work"); mongoc_uri_set_database (uri, "longer database that should work"); - ASSERT_CMPSTR (mongoc_uri_get_database (uri), - "longer database that should work"); + ASSERT_CMPSTR (mongoc_uri_get_database (uri), "longer database that should work"); ASSERT_CMPSTR (mongoc_uri_get_auth_source (uri), "source"); mongoc_uri_set_auth_source (uri, "longer authsource that should work"); - ASSERT_CMPSTR (mongoc_uri_get_auth_source (uri), - "longer authsource that should work"); - ASSERT_CMPSTR (mongoc_uri_get_database (uri), - "longer database that should work"); + ASSERT_CMPSTR (mongoc_uri_get_auth_source (uri), "longer authsource that should work"); + ASSERT_CMPSTR (mongoc_uri_get_database (uri), "longer database that should work"); client = test_framework_client_new_from_uri (uri, NULL); mongoc_uri_destroy (uri); - ASSERT_CMPSTR (mongoc_uri_get_username (client->uri), - "longer username that should work"); - ASSERT_CMPSTR (mongoc_uri_get_password (client->uri), - "longer password that should also work"); - ASSERT_CMPSTR (mongoc_uri_get_database (client->uri), - "longer database that should work"); - ASSERT_CMPSTR (mongoc_uri_get_auth_source (client->uri), - "longer authsource that should work"); + ASSERT_CMPSTR (mongoc_uri_get_username (client->uri), "longer username that should work"); + ASSERT_CMPSTR (mongoc_uri_get_password (client->uri), "longer password that should also work"); + ASSERT_CMPSTR (mongoc_uri_get_database (client->uri), "longer database that should work"); + ASSERT_CMPSTR (mongoc_uri_get_auth_source (client->uri), "longer authsource that should work"); mongoc_client_destroy (client); - uri = mongoc_uri_new ( - "mongodb://localhost/?" MONGOC_URI_SERVERSELECTIONTIMEOUTMS "=3" - "&" MONGOC_URI_JOURNAL "=true" - "&" MONGOC_URI_WTIMEOUTMS "=42" - "&" MONGOC_URI_CANONICALIZEHOSTNAME "=false"); - - ASSERT_CMPINT ( - mongoc_uri_get_option_as_int32 (uri, "serverselectiontimeoutms", 18), - ==, - 3); - ASSERT ( - mongoc_uri_set_option_as_int32 (uri, "serverselectiontimeoutms", 18)); - ASSERT_CMPINT32 ( - mongoc_uri_get_option_as_int32 (uri, "serverselectiontimeoutms", 19), - ==, - 18); - - ASSERT_CMPINT32 ( - mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_WTIMEOUTMS, 18), ==, 42); - ASSERT_CMPINT64 ( - mongoc_uri_get_option_as_int64 (uri, MONGOC_URI_WTIMEOUTMS, 18), ==, 42); + uri = mongoc_uri_new ("mongodb://localhost/?" MONGOC_URI_SERVERSELECTIONTIMEOUTMS "=3" + "&" MONGOC_URI_JOURNAL "=true" + "&" MONGOC_URI_WTIMEOUTMS "=42" + "&" MONGOC_URI_CANONICALIZEHOSTNAME "=false"); + + ASSERT_CMPINT (mongoc_uri_get_option_as_int32 (uri, "serverselectiontimeoutms", 18), ==, 3); + ASSERT (mongoc_uri_set_option_as_int32 (uri, "serverselectiontimeoutms", 18)); + ASSERT_CMPINT32 (mongoc_uri_get_option_as_int32 (uri, "serverselectiontimeoutms", 19), ==, 18); + + ASSERT_CMPINT32 (mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_WTIMEOUTMS, 18), ==, 42); + ASSERT_CMPINT64 (mongoc_uri_get_option_as_int64 (uri, MONGOC_URI_WTIMEOUTMS, 18), ==, 42); ASSERT (mongoc_uri_set_option_as_int32 (uri, MONGOC_URI_WTIMEOUTMS, 18)); - ASSERT_CMPINT32 ( - mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_WTIMEOUTMS, 19), ==, 18); + ASSERT_CMPINT32 (mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_WTIMEOUTMS, 19), ==, 18); ASSERT (mongoc_uri_set_option_as_int64 (uri, MONGOC_URI_WTIMEOUTMS, 20)); - ASSERT_CMPINT64 ( - mongoc_uri_get_option_as_int64 (uri, MONGOC_URI_WTIMEOUTMS, 19), ==, 20); + ASSERT_CMPINT64 (mongoc_uri_get_option_as_int64 (uri, MONGOC_URI_WTIMEOUTMS, 19), ==, 20); - ASSERT (mongoc_uri_set_option_as_int32 ( - uri, MONGOC_URI_HEARTBEATFREQUENCYMS, 500)); + ASSERT (mongoc_uri_set_option_as_int32 (uri, MONGOC_URI_HEARTBEATFREQUENCYMS, 500)); - i = mongoc_uri_get_option_as_int32 ( - uri, MONGOC_URI_HEARTBEATFREQUENCYMS, 1000); + i = mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_HEARTBEATFREQUENCYMS, 1000); ASSERT_CMPINT32 (i, ==, 500); @@ -574,75 +501,49 @@ test_mongoc_uri_functions (void) /* Server Discovery and Monitoring Spec: "the driver MUST NOT permit users to * configure it less than minHeartbeatFrequencyMS (500ms)." */ - ASSERT (!mongoc_uri_set_option_as_int32 ( - uri, MONGOC_URI_HEARTBEATFREQUENCYMS, 499)); + ASSERT (!mongoc_uri_set_option_as_int32 (uri, MONGOC_URI_HEARTBEATFREQUENCYMS, 499)); - ASSERT_CAPTURED_LOG ( - "mongoc_uri_set_option_as_int32", - MONGOC_LOG_LEVEL_WARNING, - "Invalid \"heartbeatfrequencyms\" of 499: must be at least 500"); + ASSERT_CAPTURED_LOG ("mongoc_uri_set_option_as_int32", + MONGOC_LOG_LEVEL_WARNING, + "Invalid \"heartbeatfrequencyms\" of 499: must be at least 500"); /* socketcheckintervalms isn't set, return our fallback */ - ASSERT_CMPINT (mongoc_uri_get_option_as_int32 ( - uri, MONGOC_URI_SOCKETCHECKINTERVALMS, 123), - ==, - 123); - ASSERT (mongoc_uri_set_option_as_int32 ( - uri, MONGOC_URI_SOCKETCHECKINTERVALMS, 18)); - ASSERT_CMPINT (mongoc_uri_get_option_as_int32 ( - uri, MONGOC_URI_SOCKETCHECKINTERVALMS, 19), - ==, - 18); + ASSERT_CMPINT (mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_SOCKETCHECKINTERVALMS, 123), ==, 123); + ASSERT (mongoc_uri_set_option_as_int32 (uri, MONGOC_URI_SOCKETCHECKINTERVALMS, 18)); + ASSERT_CMPINT (mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_SOCKETCHECKINTERVALMS, 19), ==, 18); ASSERT (mongoc_uri_get_option_as_bool (uri, MONGOC_URI_JOURNAL, false)); - ASSERT (!mongoc_uri_get_option_as_bool ( - uri, MONGOC_URI_CANONICALIZEHOSTNAME, true)); + ASSERT (!mongoc_uri_get_option_as_bool (uri, MONGOC_URI_CANONICALIZEHOSTNAME, true)); /* tls isn't set, return out fallback */ ASSERT (mongoc_uri_get_option_as_bool (uri, MONGOC_URI_TLS, true)); client = test_framework_client_new_from_uri (uri, NULL); mongoc_uri_destroy (uri); - ASSERT ( - mongoc_uri_get_option_as_bool (client->uri, MONGOC_URI_JOURNAL, false)); - ASSERT (!mongoc_uri_get_option_as_bool ( - client->uri, MONGOC_URI_CANONICALIZEHOSTNAME, true)); + ASSERT (mongoc_uri_get_option_as_bool (client->uri, MONGOC_URI_JOURNAL, false)); + ASSERT (!mongoc_uri_get_option_as_bool (client->uri, MONGOC_URI_CANONICALIZEHOSTNAME, true)); /* tls isn't set, return out fallback */ ASSERT (mongoc_uri_get_option_as_bool (client->uri, MONGOC_URI_TLS, true)); mongoc_client_destroy (client); uri = mongoc_uri_new ("mongodb://localhost/"); - ASSERT_CMPSTR (mongoc_uri_get_option_as_utf8 (uri, "replicaset", "default"), - "default"); + ASSERT_CMPSTR (mongoc_uri_get_option_as_utf8 (uri, "replicaset", "default"), "default"); ASSERT (mongoc_uri_set_option_as_utf8 (uri, "replicaset", "value")); - ASSERT_CMPSTR (mongoc_uri_get_option_as_utf8 (uri, "replicaset", "default"), - "value"); + ASSERT_CMPSTR (mongoc_uri_get_option_as_utf8 (uri, "replicaset", "default"), "value"); mongoc_uri_destroy (uri); - uri = mongoc_uri_new ("mongodb://localhost/?" MONGOC_URI_SOCKETTIMEOUTMS - "=1&" MONGOC_URI_SOCKETCHECKINTERVALMS "=200"); - ASSERT_CMPINT ( - 1, - ==, - mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_SOCKETTIMEOUTMS, 0)); - ASSERT_CMPINT (200, - ==, - mongoc_uri_get_option_as_int32 ( - uri, MONGOC_URI_SOCKETCHECKINTERVALMS, 0)); + uri = + mongoc_uri_new ("mongodb://localhost/?" MONGOC_URI_SOCKETTIMEOUTMS "=1&" MONGOC_URI_SOCKETCHECKINTERVALMS "=200"); + ASSERT_CMPINT (1, ==, mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_SOCKETTIMEOUTMS, 0)); + ASSERT_CMPINT (200, ==, mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_SOCKETCHECKINTERVALMS, 0)); mongoc_uri_set_option_as_int32 (uri, MONGOC_URI_SOCKETTIMEOUTMS, 2); - ASSERT_CMPINT ( - 2, - ==, - mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_SOCKETTIMEOUTMS, 0)); + ASSERT_CMPINT (2, ==, mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_SOCKETTIMEOUTMS, 0)); mongoc_uri_set_option_as_int32 (uri, MONGOC_URI_SOCKETCHECKINTERVALMS, 202); - ASSERT_CMPINT (202, - ==, - mongoc_uri_get_option_as_int32 ( - uri, MONGOC_URI_SOCKETCHECKINTERVALMS, 0)); + ASSERT_CMPINT (202, ==, mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_SOCKETCHECKINTERVALMS, 0)); client = test_framework_client_new_from_uri (uri, NULL); @@ -666,17 +567,14 @@ test_mongoc_uri_functions (void) uri = mongoc_uri_new ("mongodb://%2Ftmp%2FMongoDB-27017.sock/"); ASSERT_CMPSTR (mongoc_uri_get_hosts (uri)->host, "/tmp/MongoDB-27017.sock"); - ASSERT_CMPSTR (mongoc_uri_get_hosts (uri)->host_and_port, - "/tmp/MongoDB-27017.sock"); + ASSERT_CMPSTR (mongoc_uri_get_hosts (uri)->host_and_port, "/tmp/MongoDB-27017.sock"); mongoc_uri_destroy (uri); capture_logs (true); uri = mongoc_uri_new ("mongodb://host/?foobar=1"); ASSERT (uri); - ASSERT_CAPTURED_LOG ("setting URI option foobar=1", - MONGOC_LOG_LEVEL_WARNING, - "Unsupported URI option \"foobar\""); + ASSERT_CAPTURED_LOG ("setting URI option foobar=1", MONGOC_LOG_LEVEL_WARNING, "Unsupported URI option \"foobar\""); mongoc_uri_destroy (uri); } @@ -694,52 +592,40 @@ test_mongoc_uri_new_with_error (void) mongoc_uri_destroy (uri); ASSERT (!mongoc_uri_new_with_error ("mongodb://", &error)); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Invalid host string in URI"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid host string in URI"); memset (&error, 0, sizeof (bson_error_t)); ASSERT (!mongoc_uri_new_with_error ("mongo://localhost", &error)); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Invalid URI Schema, expecting 'mongodb://'"); - - memset (&error, 0, sizeof (bson_error_t)); - ASSERT (!mongoc_uri_new_with_error ( - "mongodb://localhost/?readPreference=unknown", &error)); ASSERT_ERROR_CONTAINS ( - error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Unsupported readPreference value [readPreference=unknown]"); + error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid URI Schema, expecting 'mongodb://'"); memset (&error, 0, sizeof (bson_error_t)); - ASSERT (!mongoc_uri_new_with_error ( - "mongodb://localhost/" - "?appname=" - "WayTooLongAppnameToBeValidSoThisShouldResultInAnErrorWayToLongAppnameToB" - "eValidSoThisShouldResultInAnErrorWayToLongAppnameToBeValidSoThisShouldRe" - "sultInAnError", - &error)); + ASSERT (!mongoc_uri_new_with_error ("mongodb://localhost/?readPreference=unknown", &error)); ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, - "Unsupported value for \"appname\""); /* ... */ + "Unsupported readPreference value [readPreference=unknown]"); + + memset (&error, 0, sizeof (bson_error_t)); + ASSERT (!mongoc_uri_new_with_error ("mongodb://localhost/" + "?appname=" + "WayTooLongAppnameToBeValidSoThisShouldResultInAnErrorWayToLongAppnameToB" + "eValidSoThisShouldResultInAnErrorWayToLongAppnameToBeValidSoThisShouldRe" + "sultInAnError", + &error)); + ASSERT_ERROR_CONTAINS ( + error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Unsupported value for \"appname\""); /* ... */ uri = mongoc_uri_new ("mongodb://localhost"); - ASSERT (!mongoc_uri_set_option_as_utf8 ( - uri, - MONGOC_URI_APPNAME, - "WayTooLongAppnameToBeValidSoThisShouldResultInAnErrorWayToLongAppnameToB" - "eValidSoThisShouldResultInAnErrorWayToLongAppnameToBeValidSoThisShouldRe" - "sultInAnError")); + ASSERT (!mongoc_uri_set_option_as_utf8 (uri, + MONGOC_URI_APPNAME, + "WayTooLongAppnameToBeValidSoThisShouldResultInAnErrorWayToLongAppnameToB" + "eValidSoThisShouldResultInAnErrorWayToLongAppnameToBeValidSoThisShouldRe" + "sultInAnError")); mongoc_uri_destroy (uri); memset (&error, 0, sizeof (bson_error_t)); - ASSERT ( - !mongoc_uri_new_with_error ("mongodb://user%p:pass@localhost/", &error)); + ASSERT (!mongoc_uri_new_with_error ("mongodb://user%p:pass@localhost/", &error)); ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, @@ -748,108 +634,73 @@ test_mongoc_uri_new_with_error (void) memset (&error, 0, sizeof (bson_error_t)); ASSERT (!mongoc_uri_new_with_error ("mongodb://l%oc, alhost/", &error)); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Invalid host string in URI"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid host string in URI"); memset (&error, 0, sizeof (bson_error_t)); ASSERT (!mongoc_uri_new_with_error ("mongodb:///tmp/mongodb.sock", &error)); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Invalid host string in URI"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid host string in URI"); memset (&error, 0, sizeof (bson_error_t)); ASSERT (!mongoc_uri_new_with_error ("mongodb://localhost/db.na%me", &error)); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Invalid database name in URI"); + ASSERT_ERROR_CONTAINS ( + error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid database name in URI"); memset (&error, 0, sizeof (bson_error_t)); - ASSERT (!mongoc_uri_new_with_error ( - "mongodb://localhost/db?journal=true&w=0", &error)); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Journal conflicts with w value [w=0]"); + ASSERT (!mongoc_uri_new_with_error ("mongodb://localhost/db?journal=true&w=0", &error)); + ASSERT_ERROR_CONTAINS ( + error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Journal conflicts with w value [w=0]"); memset (&error, 0, sizeof (bson_error_t)); - ASSERT (!mongoc_uri_new_with_error ( - "mongodb://localhost/db?journal=true&w=-1", &error)); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Journal conflicts with w value [w=-1]"); + ASSERT (!mongoc_uri_new_with_error ("mongodb://localhost/db?journal=true&w=-1", &error)); + ASSERT_ERROR_CONTAINS ( + error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Journal conflicts with w value [w=-1]"); memset (&error, 0, sizeof (bson_error_t)); ASSERT (!mongoc_uri_new_with_error ("mongodb://localhost/db?w=-5", &error)); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Unsupported w value [w=-5]"); + + memset (&error, 0, sizeof (bson_error_t)); + ASSERT (!mongoc_uri_new_with_error ("mongodb://localhost/db?heartbeatfrequencyms=10", &error)); ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, - "Unsupported w value [w=-5]"); + "Invalid \"heartbeatfrequencyms\" of 10: must be at least 500"); memset (&error, 0, sizeof (bson_error_t)); - ASSERT (!mongoc_uri_new_with_error ( - "mongodb://localhost/db?heartbeatfrequencyms=10", &error)); - ASSERT_ERROR_CONTAINS ( - error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Invalid \"heartbeatfrequencyms\" of 10: must be at least 500"); - - memset (&error, 0, sizeof (bson_error_t)); - ASSERT (!mongoc_uri_new_with_error ( - "mongodb://localhost/db?zlibcompressionlevel=10", &error)); - ASSERT_ERROR_CONTAINS ( - error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Invalid \"zlibcompressionlevel\" of 10: must be between -1 and 9"); - - memset (&error, 0, sizeof (bson_error_t)); - ASSERT (!mongoc_uri_new_with_error ("mongodb+srv://", &error)); + ASSERT (!mongoc_uri_new_with_error ("mongodb://localhost/db?zlibcompressionlevel=10", &error)); ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, - "Missing service name in SRV URI"); + "Invalid \"zlibcompressionlevel\" of 10: must be between -1 and 9"); + + memset (&error, 0, sizeof (bson_error_t)); + ASSERT (!mongoc_uri_new_with_error ("mongodb+srv://", &error)); + ASSERT_ERROR_CONTAINS ( + error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Missing service name in SRV URI"); memset (&error, 0, sizeof (bson_error_t)); ASSERT (!mongoc_uri_new_with_error ("mongodb+srv://%", &error)); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Invalid service name in URI"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid service name in URI"); memset (&error, 0, sizeof (bson_error_t)); ASSERT (!mongoc_uri_new_with_error ("mongodb+srv://x", &error)); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Invalid service name in URI"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid service name in URI"); memset (&error, 0, sizeof (bson_error_t)); ASSERT (!mongoc_uri_new_with_error ("mongodb+srv://x.y", &error)); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Invalid service name in URI"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid service name in URI"); memset (&error, 0, sizeof (bson_error_t)); ASSERT (!mongoc_uri_new_with_error ("mongodb+srv://a.b.c,d.e.f", &error)); - ASSERT_ERROR_CONTAINS ( - error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Multiple service names are prohibited in an SRV URI"); - - memset (&error, 0, sizeof (bson_error_t)); - ASSERT (!mongoc_uri_new_with_error ("mongodb+srv://a.b.c:8000", &error)); ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, - "Port numbers are prohibited in an SRV URI"); + "Multiple service names are prohibited in an SRV URI"); + + memset (&error, 0, sizeof (bson_error_t)); + ASSERT (!mongoc_uri_new_with_error ("mongodb+srv://a.b.c:8000", &error)); + ASSERT_ERROR_CONTAINS ( + error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Port numbers are prohibited in an SRV URI"); } @@ -867,16 +718,13 @@ test_mongoc_uri_compound_setters (void) mongoc_write_concern_t *wc; const mongoc_write_concern_t *wc_result; - uri = mongoc_uri_new ("mongodb://localhost/?" MONGOC_URI_READPREFERENCE - "=nearest&" MONGOC_URI_READPREFERENCETAGS - "=dc:ny&" MONGOC_URI_READCONCERNLEVEL - "=majority&" MONGOC_URI_W "=3"); + uri = mongoc_uri_new ("mongodb://localhost/?" MONGOC_URI_READPREFERENCE "=nearest&" MONGOC_URI_READPREFERENCETAGS + "=dc:ny&" MONGOC_URI_READCONCERNLEVEL "=majority&" MONGOC_URI_W "=3"); prefs = mongoc_read_prefs_new (MONGOC_READ_SECONDARY); mongoc_uri_set_read_prefs_t (uri, prefs); prefs_result = mongoc_uri_get_read_prefs_t (uri); - ASSERT_CMPINT ( - mongoc_read_prefs_get_mode (prefs_result), ==, MONGOC_READ_SECONDARY); + ASSERT_CMPINT (mongoc_read_prefs_get_mode (prefs_result), ==, MONGOC_READ_SECONDARY); ASSERT (bson_empty (mongoc_read_prefs_get_tags (prefs_result))); rc = mongoc_read_concern_new (); @@ -906,46 +754,31 @@ test_mongoc_host_list_from_string (void) /* shouldn't be parsable */ capture_logs (true); ASSERT (!_mongoc_host_list_from_string (&host_list, ":27017")); - ASSERT_CAPTURED_LOG ("_mongoc_host_list_from_string", - MONGOC_LOG_LEVEL_ERROR, - "Could not parse address"); + ASSERT_CAPTURED_LOG ("_mongoc_host_list_from_string", MONGOC_LOG_LEVEL_ERROR, "Could not parse address"); capture_logs (true); ASSERT (!_mongoc_host_list_from_string (&host_list, "example.com:")); - ASSERT_CAPTURED_LOG ("_mongoc_host_list_from_string", - MONGOC_LOG_LEVEL_ERROR, - "Could not parse address"); + ASSERT_CAPTURED_LOG ("_mongoc_host_list_from_string", MONGOC_LOG_LEVEL_ERROR, "Could not parse address"); capture_logs (true); ASSERT (!_mongoc_host_list_from_string (&host_list, "localhost:999999999")); - ASSERT_CAPTURED_LOG ("_mongoc_host_list_from_string", - MONGOC_LOG_LEVEL_ERROR, - "Could not parse address"); + ASSERT_CAPTURED_LOG ("_mongoc_host_list_from_string", MONGOC_LOG_LEVEL_ERROR, "Could not parse address"); capture_logs (true); ASSERT (!_mongoc_host_list_from_string (&host_list, "::1234")); - ASSERT_CAPTURED_LOG ("_mongoc_host_list_from_string", - MONGOC_LOG_LEVEL_ERROR, - "Could not parse address"); + ASSERT_CAPTURED_LOG ("_mongoc_host_list_from_string", MONGOC_LOG_LEVEL_ERROR, "Could not parse address"); capture_logs (true); ASSERT (!_mongoc_host_list_from_string (&host_list, "]:1234")); - ASSERT_CAPTURED_LOG ("_mongoc_host_list_from_string", - MONGOC_LOG_LEVEL_ERROR, - "Could not parse address"); + ASSERT_CAPTURED_LOG ("_mongoc_host_list_from_string", MONGOC_LOG_LEVEL_ERROR, "Could not parse address"); capture_logs (true); ASSERT (!_mongoc_host_list_from_string (&host_list, "[]:1234")); - ASSERT_CAPTURED_LOG ("_mongoc_host_list_from_string", - MONGOC_LOG_LEVEL_ERROR, - "Could not parse address"); + ASSERT_CAPTURED_LOG ("_mongoc_host_list_from_string", MONGOC_LOG_LEVEL_ERROR, "Could not parse address"); capture_logs (true); ASSERT (!_mongoc_host_list_from_string (&host_list, "[::1] foo")); - ASSERT_CAPTURED_LOG ("_mongoc_host_list_from_string", - MONGOC_LOG_LEVEL_ERROR, - "Could not parse address"); + ASSERT_CAPTURED_LOG ("_mongoc_host_list_from_string", MONGOC_LOG_LEVEL_ERROR, "Could not parse address"); capture_logs (true); - ASSERT ( - !_mongoc_host_list_from_string (&host_list, "[::1]extra_chars:27017")); + ASSERT (!_mongoc_host_list_from_string (&host_list, "[::1]extra_chars:27017")); ASSERT_CAPTURED_LOG ("_mongoc_host_list_from_string", MONGOC_LOG_LEVEL_ERROR, "If present, port should immediately follow the \"]\"" @@ -1037,9 +870,7 @@ test_mongoc_uri_compressors (void) mongoc_uri_set_compressors (uri, "snappy,unknown"); ASSERT (bson_has_field (mongoc_uri_get_compressors (uri), "snappy")); ASSERT (!bson_has_field (mongoc_uri_get_compressors (uri), "unknown")); - ASSERT_CAPTURED_LOG ("mongoc_uri_set_compressors", - MONGOC_LOG_LEVEL_WARNING, - "Unsupported compressor: 'unknown'"); + ASSERT_CAPTURED_LOG ("mongoc_uri_set_compressors", MONGOC_LOG_LEVEL_WARNING, "Unsupported compressor: 'unknown'"); #endif @@ -1055,17 +886,13 @@ test_mongoc_uri_compressors (void) mongoc_uri_set_compressors (uri, "unknown"); ASSERT (!bson_has_field (mongoc_uri_get_compressors (uri), "snappy")); ASSERT (!bson_has_field (mongoc_uri_get_compressors (uri), "unknown")); - ASSERT_CAPTURED_LOG ("mongoc_uri_set_compressors", - MONGOC_LOG_LEVEL_WARNING, - "Unsupported compressor: 'unknown'"); + ASSERT_CAPTURED_LOG ("mongoc_uri_set_compressors", MONGOC_LOG_LEVEL_WARNING, "Unsupported compressor: 'unknown'"); #endif capture_logs (true); mongoc_uri_set_compressors (uri, ""); ASSERT (bson_empty (mongoc_uri_get_compressors (uri))); - ASSERT_CAPTURED_LOG ("mongoc_uri_set_compressors", - MONGOC_LOG_LEVEL_WARNING, - "Unsupported compressor: ''"); + ASSERT_CAPTURED_LOG ("mongoc_uri_set_compressors", MONGOC_LOG_LEVEL_WARNING, "Unsupported compressor: ''"); /* Disable compression */ @@ -1084,13 +911,11 @@ test_mongoc_uri_compressors (void) mongoc_uri_destroy (uri); capture_logs (true); - uri = - mongoc_uri_new ("mongodb://localhost/?compressors=snappy,somethingElse"); + uri = mongoc_uri_new ("mongodb://localhost/?compressors=snappy,somethingElse"); ASSERT (bson_has_field (mongoc_uri_get_compressors (uri), "snappy")); ASSERT (!bson_has_field (mongoc_uri_get_compressors (uri), "somethingElse")); - ASSERT_CAPTURED_LOG ("mongoc_uri_set_compressors", - MONGOC_LOG_LEVEL_WARNING, - "Unsupported compressor: 'somethingElse'"); + ASSERT_CAPTURED_LOG ( + "mongoc_uri_set_compressors", MONGOC_LOG_LEVEL_WARNING, "Unsupported compressor: 'somethingElse'"); mongoc_uri_destroy (uri); #endif @@ -1125,44 +950,31 @@ test_mongoc_uri_compressors (void) uri = mongoc_uri_new ("mongodb://localhost/?compressors=zlib,somethingElse"); ASSERT (bson_has_field (mongoc_uri_get_compressors (uri), "zlib")); ASSERT (!bson_has_field (mongoc_uri_get_compressors (uri), "somethingElse")); - ASSERT_CAPTURED_LOG ("mongoc_uri_set_compressors", - MONGOC_LOG_LEVEL_WARNING, - "Unsupported compressor: 'somethingElse'"); + ASSERT_CAPTURED_LOG ( + "mongoc_uri_set_compressors", MONGOC_LOG_LEVEL_WARNING, "Unsupported compressor: 'somethingElse'"); mongoc_uri_destroy (uri); - uri = mongoc_uri_new ( - "mongodb://localhost/?compressors=zlib&zlibCompressionLevel=-1"); + uri = mongoc_uri_new ("mongodb://localhost/?compressors=zlib&zlibCompressionLevel=-1"); ASSERT (bson_has_field (mongoc_uri_get_compressors (uri), "zlib")); - ASSERT_CMPINT32 ( - mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_ZLIBCOMPRESSIONLEVEL, 1), - ==, - -1); + ASSERT_CMPINT32 (mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_ZLIBCOMPRESSIONLEVEL, 1), ==, -1); mongoc_uri_destroy (uri); - uri = mongoc_uri_new ( - "mongodb://localhost/?compressors=zlib&zlibCompressionLevel=9"); - ASSERT_CMPINT32 ( - mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_ZLIBCOMPRESSIONLEVEL, 1), - ==, - 9); + uri = mongoc_uri_new ("mongodb://localhost/?compressors=zlib&zlibCompressionLevel=9"); + ASSERT_CMPINT32 (mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_ZLIBCOMPRESSIONLEVEL, 1), ==, 9); mongoc_uri_destroy (uri); capture_logs (true); - uri = mongoc_uri_new ( - "mongodb://localhost/?compressors=zlib&zlibCompressionLevel=-2"); - ASSERT_CAPTURED_LOG ( - "mongoc_uri_set_compressors", - MONGOC_LOG_LEVEL_WARNING, - "Invalid \"zlibcompressionlevel\" of -2: must be between -1 and 9"); + uri = mongoc_uri_new ("mongodb://localhost/?compressors=zlib&zlibCompressionLevel=-2"); + ASSERT_CAPTURED_LOG ("mongoc_uri_set_compressors", + MONGOC_LOG_LEVEL_WARNING, + "Invalid \"zlibcompressionlevel\" of -2: must be between -1 and 9"); mongoc_uri_destroy (uri); capture_logs (true); - uri = mongoc_uri_new ( - "mongodb://localhost/?compressors=zlib&zlibCompressionLevel=10"); - ASSERT_CAPTURED_LOG ( - "mongoc_uri_set_compressors", - MONGOC_LOG_LEVEL_WARNING, - "Invalid \"zlibcompressionlevel\" of 10: must be between -1 and 9"); + uri = mongoc_uri_new ("mongodb://localhost/?compressors=zlib&zlibCompressionLevel=10"); + ASSERT_CAPTURED_LOG ("mongoc_uri_set_compressors", + MONGOC_LOG_LEVEL_WARNING, + "Invalid \"zlibcompressionlevel\" of 10: must be between -1 and 9"); mongoc_uri_destroy (uri); #endif @@ -1177,14 +989,13 @@ test_mongoc_uri_unescape (void) ASSERT (!strcmp (str, _e)); \ bson_free (str); \ } while (0) -#define ASSERT_URIDECODE_FAIL(_s) \ - do { \ - char *str; \ - capture_logs (true); \ - str = mongoc_uri_unescape (_s); \ - ASSERT (!str); \ - ASSERT_CAPTURED_LOG ( \ - "uri", MONGOC_LOG_LEVEL_WARNING, "Invalid % escape sequence"); \ +#define ASSERT_URIDECODE_FAIL(_s) \ + do { \ + char *str; \ + capture_logs (true); \ + str = mongoc_uri_unescape (_s); \ + ASSERT (!str); \ + ASSERT_CAPTURED_LOG ("uri", MONGOC_LOG_LEVEL_WARNING, "Invalid % escape sequence"); \ } while (0) ASSERT_URIDECODE_STR ("", ""); @@ -1226,101 +1037,66 @@ test_mongoc_uri_read_prefs (void) int i; bson_t *tags_dcny = BCON_NEW ("0", "{", "dc", "ny", "}"); - bson_t *tags_dcny_empty = - BCON_NEW ("0", "{", "dc", "ny", "}", "1", "{", "}"); - bson_t *tags_dcnyusessd_dcsf_empty = BCON_NEW ("0", - "{", - "dc", - "ny", - "use", - "ssd", - "}", - "1", - "{", - "dc", - "sf", - "}", - "2", - "{", - "}"); + bson_t *tags_dcny_empty = BCON_NEW ("0", "{", "dc", "ny", "}", "1", "{", "}"); + bson_t *tags_dcnyusessd_dcsf_empty = + BCON_NEW ("0", "{", "dc", "ny", "use", "ssd", "}", "1", "{", "dc", "sf", "}", "2", "{", "}"); bson_t *tags_empty = BCON_NEW ("0", "{", "}"); const char *conflicts = "Invalid readPreferences"; const read_prefs_test tests[] = { {"mongodb://localhost/", true, MONGOC_READ_PRIMARY, NULL}, - {"mongodb://localhost/?" MONGOC_URI_READPREFERENCE "=primary", - true, - MONGOC_READ_PRIMARY, - NULL}, + {"mongodb://localhost/?" MONGOC_URI_READPREFERENCE "=primary", true, MONGOC_READ_PRIMARY, NULL}, {"mongodb://localhost/?" MONGOC_URI_READPREFERENCE "=primaryPreferred", true, MONGOC_READ_PRIMARY_PREFERRED, NULL}, - {"mongodb://localhost/?" MONGOC_URI_READPREFERENCE "=secondary", - true, - MONGOC_READ_SECONDARY, - NULL}, + {"mongodb://localhost/?" MONGOC_URI_READPREFERENCE "=secondary", true, MONGOC_READ_SECONDARY, NULL}, {"mongodb://localhost/?" MONGOC_URI_READPREFERENCE "=secondaryPreferred", true, MONGOC_READ_SECONDARY_PREFERRED, NULL}, - {"mongodb://localhost/?" MONGOC_URI_READPREFERENCE "=nearest", - true, - MONGOC_READ_NEAREST, - NULL}, + {"mongodb://localhost/?" MONGOC_URI_READPREFERENCE "=nearest", true, MONGOC_READ_NEAREST, NULL}, /* MONGOC_URI_READPREFERENCETAGS conflict with primary mode */ - {"mongodb://localhost/?" MONGOC_URI_READPREFERENCETAGS "=", - false, - MONGOC_READ_PRIMARY, - NULL, - conflicts}, - {"mongodb://localhost/?" MONGOC_URI_READPREFERENCE - "=primary&" MONGOC_URI_READPREFERENCETAGS "=", + {"mongodb://localhost/?" MONGOC_URI_READPREFERENCETAGS "=", false, MONGOC_READ_PRIMARY, NULL, conflicts}, + {"mongodb://localhost/?" MONGOC_URI_READPREFERENCE "=primary&" MONGOC_URI_READPREFERENCETAGS "=", false, MONGOC_READ_PRIMARY, NULL, conflicts}, {"mongodb://localhost/" - "?" MONGOC_URI_READPREFERENCE - "=secondaryPreferred&" MONGOC_URI_READPREFERENCETAGS "=", + "?" MONGOC_URI_READPREFERENCE "=secondaryPreferred&" MONGOC_URI_READPREFERENCETAGS "=", true, MONGOC_READ_SECONDARY_PREFERRED, tags_empty}, {"mongodb://localhost/" - "?" MONGOC_URI_READPREFERENCE - "=secondaryPreferred&" MONGOC_URI_READPREFERENCETAGS "=dc:ny", + "?" MONGOC_URI_READPREFERENCE "=secondaryPreferred&" MONGOC_URI_READPREFERENCETAGS "=dc:ny", true, MONGOC_READ_SECONDARY_PREFERRED, tags_dcny}, {"mongodb://localhost/" - "?" MONGOC_URI_READPREFERENCE "=nearest&" MONGOC_URI_READPREFERENCETAGS - "=dc:ny&" MONGOC_URI_READPREFERENCETAGS "=", + "?" MONGOC_URI_READPREFERENCE "=nearest&" MONGOC_URI_READPREFERENCETAGS "=dc:ny&" MONGOC_URI_READPREFERENCETAGS + "=", true, MONGOC_READ_NEAREST, tags_dcny_empty}, {"mongodb://localhost/" "?" MONGOC_URI_READPREFERENCE "=nearest&" MONGOC_URI_READPREFERENCETAGS - "=dc:ny,use:ssd&" MONGOC_URI_READPREFERENCETAGS - "=dc:sf&" MONGOC_URI_READPREFERENCETAGS "=", + "=dc:ny,use:ssd&" MONGOC_URI_READPREFERENCETAGS "=dc:sf&" MONGOC_URI_READPREFERENCETAGS "=", true, MONGOC_READ_NEAREST, tags_dcnyusessd_dcsf_empty}, - {"mongodb://localhost/?" MONGOC_URI_READPREFERENCE - "=nearest&" MONGOC_URI_READPREFERENCETAGS "=foo", + {"mongodb://localhost/?" MONGOC_URI_READPREFERENCE "=nearest&" MONGOC_URI_READPREFERENCETAGS "=foo", false, MONGOC_READ_NEAREST, NULL, "Unsupported value for \"" MONGOC_URI_READPREFERENCETAGS "\": \"foo\""}, - {"mongodb://localhost/?" MONGOC_URI_READPREFERENCE - "=nearest&" MONGOC_URI_READPREFERENCETAGS "=foo,bar", + {"mongodb://localhost/?" MONGOC_URI_READPREFERENCE "=nearest&" MONGOC_URI_READPREFERENCETAGS "=foo,bar", false, MONGOC_READ_NEAREST, NULL, - "Unsupported value for \"" MONGOC_URI_READPREFERENCETAGS - "\": \"foo,bar\""}, - {"mongodb://localhost/?" MONGOC_URI_READPREFERENCE - "=nearest&" MONGOC_URI_READPREFERENCETAGS "=1", + "Unsupported value for \"" MONGOC_URI_READPREFERENCETAGS "\": \"foo,bar\""}, + {"mongodb://localhost/?" MONGOC_URI_READPREFERENCE "=nearest&" MONGOC_URI_READPREFERENCETAGS "=1", false, MONGOC_READ_NEAREST, NULL, @@ -1381,61 +1157,31 @@ test_mongoc_uri_write_concern (void) const write_concern_test *t; int i; static const write_concern_test tests[] = { - {"mongodb://localhost/?" MONGOC_URI_SAFE "=false", - true, - MONGOC_WRITE_CONCERN_W_UNACKNOWLEDGED}, + {"mongodb://localhost/?" MONGOC_URI_SAFE "=false", true, MONGOC_WRITE_CONCERN_W_UNACKNOWLEDGED}, {"mongodb://localhost/?" MONGOC_URI_SAFE "=true", true, 1}, - {"mongodb://localhost/?" MONGOC_URI_W "=-1", - true, - MONGOC_WRITE_CONCERN_W_ERRORS_IGNORED}, - {"mongodb://localhost/?" MONGOC_URI_W "=0", - true, - MONGOC_WRITE_CONCERN_W_UNACKNOWLEDGED}, + {"mongodb://localhost/?" MONGOC_URI_W "=-1", true, MONGOC_WRITE_CONCERN_W_ERRORS_IGNORED}, + {"mongodb://localhost/?" MONGOC_URI_W "=0", true, MONGOC_WRITE_CONCERN_W_UNACKNOWLEDGED}, {"mongodb://localhost/?" MONGOC_URI_W "=1", true, 1}, {"mongodb://localhost/?" MONGOC_URI_W "=2", true, 2}, - {"mongodb://localhost/?" MONGOC_URI_W "=majority", - true, - MONGOC_WRITE_CONCERN_W_MAJORITY}, + {"mongodb://localhost/?" MONGOC_URI_W "=majority", true, MONGOC_WRITE_CONCERN_W_MAJORITY}, {"mongodb://localhost/?" MONGOC_URI_W "=10", true, 10}, - {"mongodb://localhost/?" MONGOC_URI_W "=", - true, - MONGOC_WRITE_CONCERN_W_DEFAULT}, - {"mongodb://localhost/?" MONGOC_URI_W "=mytag", - true, - MONGOC_WRITE_CONCERN_W_TAG, - "mytag"}, + {"mongodb://localhost/?" MONGOC_URI_W "=", true, MONGOC_WRITE_CONCERN_W_DEFAULT}, + {"mongodb://localhost/?" MONGOC_URI_W "=mytag", true, MONGOC_WRITE_CONCERN_W_TAG, "mytag"}, {"mongodb://localhost/?" MONGOC_URI_W "=mytag&" MONGOC_URI_SAFE "=false", true, MONGOC_WRITE_CONCERN_W_TAG, "mytag"}, - {"mongodb://localhost/?" MONGOC_URI_W "=1&" MONGOC_URI_SAFE "=false", - true, - 1}, - {"mongodb://localhost/?" MONGOC_URI_JOURNAL "=true", - true, - MONGOC_WRITE_CONCERN_W_DEFAULT}, - {"mongodb://localhost/?" MONGOC_URI_W "=1&" MONGOC_URI_JOURNAL "=true", - true, - 1}, - {"mongodb://localhost/?" MONGOC_URI_W "=2&" MONGOC_URI_WTIMEOUTMS "=1000", - true, - 2, - NULL, - 1000}, - {"mongodb://localhost/?" MONGOC_URI_W "=2&" MONGOC_URI_WTIMEOUTMS - "=2147483648", - true, - 2, - NULL, - 2147483648LL}, - {"mongodb://localhost/?" MONGOC_URI_W "=majority&" MONGOC_URI_WTIMEOUTMS - "=1000", + {"mongodb://localhost/?" MONGOC_URI_W "=1&" MONGOC_URI_SAFE "=false", true, 1}, + {"mongodb://localhost/?" MONGOC_URI_JOURNAL "=true", true, MONGOC_WRITE_CONCERN_W_DEFAULT}, + {"mongodb://localhost/?" MONGOC_URI_W "=1&" MONGOC_URI_JOURNAL "=true", true, 1}, + {"mongodb://localhost/?" MONGOC_URI_W "=2&" MONGOC_URI_WTIMEOUTMS "=1000", true, 2, NULL, 1000}, + {"mongodb://localhost/?" MONGOC_URI_W "=2&" MONGOC_URI_WTIMEOUTMS "=2147483648", true, 2, NULL, 2147483648LL}, + {"mongodb://localhost/?" MONGOC_URI_W "=majority&" MONGOC_URI_WTIMEOUTMS "=1000", true, MONGOC_WRITE_CONCERN_W_MAJORITY, NULL, 1000}, - {"mongodb://localhost/?" MONGOC_URI_W "=mytag&" MONGOC_URI_WTIMEOUTMS - "=1000", + {"mongodb://localhost/?" MONGOC_URI_W "=mytag&" MONGOC_URI_WTIMEOUTMS "=1000", true, MONGOC_WRITE_CONCERN_W_TAG, "mytag", @@ -1461,8 +1207,7 @@ test_mongoc_uri_write_concern (void) uri = mongoc_uri_new (t->uri); if (tests[i].log_msg) { - ASSERT_CAPTURED_LOG ( - tests[i].uri, MONGOC_LOG_LEVEL_WARNING, tests[i].log_msg); + ASSERT_CAPTURED_LOG (tests[i].uri, MONGOC_LOG_LEVEL_WARNING, tests[i].log_msg); } else { ASSERT_NO_CAPTURED_LOGS (tests[i].uri); } @@ -1482,13 +1227,11 @@ test_mongoc_uri_write_concern (void) BSON_ASSERT (t->w == mongoc_write_concern_get_w (wr)); if (t->wtag) { - BSON_ASSERT (0 == - strcmp (t->wtag, mongoc_write_concern_get_wtag (wr))); + BSON_ASSERT (0 == strcmp (t->wtag, mongoc_write_concern_get_wtag (wr))); } if (t->wtimeoutms) { - BSON_ASSERT (t->wtimeoutms == - mongoc_write_concern_get_wtimeout_int64 (wr)); + BSON_ASSERT (t->wtimeoutms == mongoc_write_concern_get_wtimeout_int64 (wr)); } mongoc_uri_destroy (uri); @@ -1501,42 +1244,36 @@ test_mongoc_uri_read_concern (void) const mongoc_read_concern_t *rc; mongoc_uri_t *uri; - uri = mongoc_uri_new ("mongodb://localhost/?" MONGOC_URI_READCONCERNLEVEL - "=majority"); + uri = mongoc_uri_new ("mongodb://localhost/?" MONGOC_URI_READCONCERNLEVEL "=majority"); rc = mongoc_uri_get_read_concern (uri); ASSERT_CMPSTR (mongoc_read_concern_get_level (rc), "majority"); mongoc_uri_destroy (uri); uri = mongoc_uri_new ("mongodb://localhost/" - "?" MONGOC_URI_READCONCERNLEVEL - "=" MONGOC_READ_CONCERN_LEVEL_MAJORITY); + "?" MONGOC_URI_READCONCERNLEVEL "=" MONGOC_READ_CONCERN_LEVEL_MAJORITY); rc = mongoc_uri_get_read_concern (uri); ASSERT_CMPSTR (mongoc_read_concern_get_level (rc), "majority"); mongoc_uri_destroy (uri); uri = mongoc_uri_new ("mongodb://localhost/" - "?" MONGOC_URI_READCONCERNLEVEL - "=" MONGOC_READ_CONCERN_LEVEL_LINEARIZABLE); + "?" MONGOC_URI_READCONCERNLEVEL "=" MONGOC_READ_CONCERN_LEVEL_LINEARIZABLE); rc = mongoc_uri_get_read_concern (uri); ASSERT_CMPSTR (mongoc_read_concern_get_level (rc), "linearizable"); mongoc_uri_destroy (uri); - uri = mongoc_uri_new ("mongodb://localhost/?" MONGOC_URI_READCONCERNLEVEL - "=local"); + uri = mongoc_uri_new ("mongodb://localhost/?" MONGOC_URI_READCONCERNLEVEL "=local"); rc = mongoc_uri_get_read_concern (uri); ASSERT_CMPSTR (mongoc_read_concern_get_level (rc), "local"); mongoc_uri_destroy (uri); - uri = mongoc_uri_new ("mongodb://localhost/?" MONGOC_URI_READCONCERNLEVEL - "=" MONGOC_READ_CONCERN_LEVEL_LOCAL); + uri = mongoc_uri_new ("mongodb://localhost/?" MONGOC_URI_READCONCERNLEVEL "=" MONGOC_READ_CONCERN_LEVEL_LOCAL); rc = mongoc_uri_get_read_concern (uri); ASSERT_CMPSTR (mongoc_read_concern_get_level (rc), "local"); mongoc_uri_destroy (uri); - uri = mongoc_uri_new ("mongodb://localhost/?" MONGOC_URI_READCONCERNLEVEL - "=randomstuff"); + uri = mongoc_uri_new ("mongodb://localhost/?" MONGOC_URI_READCONCERNLEVEL "=randomstuff"); rc = mongoc_uri_get_read_concern (uri); ASSERT_CMPSTR (mongoc_read_concern_get_level (rc), "randomstuff"); mongoc_uri_destroy (uri); @@ -1548,8 +1285,7 @@ test_mongoc_uri_read_concern (void) mongoc_uri_destroy (uri); - uri = - mongoc_uri_new ("mongodb://localhost/?" MONGOC_URI_READCONCERNLEVEL "="); + uri = mongoc_uri_new ("mongodb://localhost/?" MONGOC_URI_READCONCERNLEVEL "="); rc = mongoc_uri_get_read_concern (uri); ASSERT_CMPSTR (mongoc_read_concern_get_level (rc), ""); mongoc_uri_destroy (uri); @@ -1632,27 +1368,19 @@ test_mongoc_uri_tls_ssl (const char *tls, tlsAllowInvalidHostnames); uri = mongoc_uri_new (url_buffer); - ASSERT_CMPSTR ( - mongoc_uri_get_username (uri), - "CN=client,OU=kerneluser,O=10Gen,L=New York City,ST=New York,C=US"); + ASSERT_CMPSTR (mongoc_uri_get_username (uri), "CN=client,OU=kerneluser,O=10Gen,L=New York City,ST=New York,C=US"); ASSERT (!mongoc_uri_get_password (uri)); ASSERT (!mongoc_uri_get_database (uri)); ASSERT_CMPSTR (mongoc_uri_get_auth_source (uri), "$external"); ASSERT_CMPSTR (mongoc_uri_get_auth_mechanism (uri), "MONGODB-X509"); - ASSERT_CMPSTR (mongoc_uri_get_option_as_utf8 ( - uri, MONGOC_URI_TLSCERTIFICATEKEYFILE, "none"), + ASSERT_CMPSTR (mongoc_uri_get_option_as_utf8 (uri, MONGOC_URI_TLSCERTIFICATEKEYFILE, "none"), "tests/x509gen/ldaptest-client-key-and-cert.pem"); - ASSERT_CMPSTR (mongoc_uri_get_option_as_utf8 ( - uri, MONGOC_URI_TLSCERTIFICATEKEYFILEPASSWORD, "none"), - "none"); - ASSERT_CMPSTR ( - mongoc_uri_get_option_as_utf8 (uri, MONGOC_URI_TLSCAFILE, "none"), - "tests/x509gen/ldaptest-ca-cert.crt"); - ASSERT (!mongoc_uri_get_option_as_bool ( - uri, MONGOC_URI_TLSALLOWINVALIDCERTIFICATES, false)); - ASSERT (mongoc_uri_get_option_as_bool ( - uri, MONGOC_URI_TLSALLOWINVALIDHOSTNAMES, false)); + ASSERT_CMPSTR (mongoc_uri_get_option_as_utf8 (uri, MONGOC_URI_TLSCERTIFICATEKEYFILEPASSWORD, "none"), "none"); + ASSERT_CMPSTR (mongoc_uri_get_option_as_utf8 (uri, MONGOC_URI_TLSCAFILE, "none"), + "tests/x509gen/ldaptest-ca-cert.crt"); + ASSERT (!mongoc_uri_get_option_as_bool (uri, MONGOC_URI_TLSALLOWINVALIDCERTIFICATES, false)); + ASSERT (mongoc_uri_get_option_as_bool (uri, MONGOC_URI_TLSALLOWINVALIDHOSTNAMES, false)); mongoc_uri_destroy (uri); @@ -1664,48 +1392,25 @@ test_mongoc_uri_tls_ssl (const char *tls, tlsCAFile); uri = mongoc_uri_new (url_buffer); - ASSERT_CMPSTR (mongoc_uri_get_option_as_utf8 ( - uri, MONGOC_URI_SSLCLIENTCERTIFICATEKEYFILE, "none"), - "key.pem"); - ASSERT_CMPSTR (mongoc_uri_get_option_as_utf8 ( - uri, MONGOC_URI_TLSCERTIFICATEKEYFILE, "none"), - "key.pem"); - ASSERT_CMPSTR (mongoc_uri_get_option_as_utf8 ( - uri, MONGOC_URI_SSLCLIENTCERTIFICATEKEYPASSWORD, "none"), - "none"); - ASSERT_CMPSTR (mongoc_uri_get_option_as_utf8 ( - uri, MONGOC_URI_TLSCERTIFICATEKEYFILEPASSWORD, "none"), - "none"); - ASSERT_CMPSTR (mongoc_uri_get_option_as_utf8 ( - uri, MONGOC_URI_SSLCERTIFICATEAUTHORITYFILE, "none"), - "ca.pem"); - ASSERT_CMPSTR ( - mongoc_uri_get_option_as_utf8 (uri, MONGOC_URI_TLSCAFILE, "none"), - "ca.pem"); - ASSERT (!mongoc_uri_get_option_as_bool ( - uri, MONGOC_URI_TLSALLOWINVALIDCERTIFICATES, false)); - ASSERT (!mongoc_uri_get_option_as_bool ( - uri, MONGOC_URI_TLSALLOWINVALIDHOSTNAMES, false)); + ASSERT_CMPSTR (mongoc_uri_get_option_as_utf8 (uri, MONGOC_URI_SSLCLIENTCERTIFICATEKEYFILE, "none"), "key.pem"); + ASSERT_CMPSTR (mongoc_uri_get_option_as_utf8 (uri, MONGOC_URI_TLSCERTIFICATEKEYFILE, "none"), "key.pem"); + ASSERT_CMPSTR (mongoc_uri_get_option_as_utf8 (uri, MONGOC_URI_SSLCLIENTCERTIFICATEKEYPASSWORD, "none"), "none"); + ASSERT_CMPSTR (mongoc_uri_get_option_as_utf8 (uri, MONGOC_URI_TLSCERTIFICATEKEYFILEPASSWORD, "none"), "none"); + ASSERT_CMPSTR (mongoc_uri_get_option_as_utf8 (uri, MONGOC_URI_SSLCERTIFICATEAUTHORITYFILE, "none"), "ca.pem"); + ASSERT_CMPSTR (mongoc_uri_get_option_as_utf8 (uri, MONGOC_URI_TLSCAFILE, "none"), "ca.pem"); + ASSERT (!mongoc_uri_get_option_as_bool (uri, MONGOC_URI_TLSALLOWINVALIDCERTIFICATES, false)); + ASSERT (!mongoc_uri_get_option_as_bool (uri, MONGOC_URI_TLSALLOWINVALIDHOSTNAMES, false)); mongoc_uri_destroy (uri); - bson_snprintf ( - url_buffer, sizeof (url_buffer), "mongodb://localhost/?%s=true", tls); + bson_snprintf (url_buffer, sizeof (url_buffer), "mongodb://localhost/?%s=true", tls); uri = mongoc_uri_new (url_buffer); - ASSERT_CMPSTR (mongoc_uri_get_option_as_utf8 ( - uri, MONGOC_URI_TLSCERTIFICATEKEYFILE, "none"), - "none"); - ASSERT_CMPSTR (mongoc_uri_get_option_as_utf8 ( - uri, MONGOC_URI_TLSCERTIFICATEKEYFILEPASSWORD, "none"), - "none"); - ASSERT_CMPSTR ( - mongoc_uri_get_option_as_utf8 (uri, MONGOC_URI_TLSCAFILE, "none"), - "none"); - ASSERT (!mongoc_uri_get_option_as_bool ( - uri, MONGOC_URI_TLSALLOWINVALIDCERTIFICATES, false)); - ASSERT (!mongoc_uri_get_option_as_bool ( - uri, MONGOC_URI_TLSALLOWINVALIDHOSTNAMES, false)); + ASSERT_CMPSTR (mongoc_uri_get_option_as_utf8 (uri, MONGOC_URI_TLSCERTIFICATEKEYFILE, "none"), "none"); + ASSERT_CMPSTR (mongoc_uri_get_option_as_utf8 (uri, MONGOC_URI_TLSCERTIFICATEKEYFILEPASSWORD, "none"), "none"); + ASSERT_CMPSTR (mongoc_uri_get_option_as_utf8 (uri, MONGOC_URI_TLSCAFILE, "none"), "none"); + ASSERT (!mongoc_uri_get_option_as_bool (uri, MONGOC_URI_TLSALLOWINVALIDCERTIFICATES, false)); + ASSERT (!mongoc_uri_get_option_as_bool (uri, MONGOC_URI_TLSALLOWINVALIDHOSTNAMES, false)); mongoc_uri_destroy (uri); @@ -1717,155 +1422,96 @@ test_mongoc_uri_tls_ssl (const char *tls, tlsCertificateKeyFile); uri = mongoc_uri_new (url_buffer); - ASSERT_CMPSTR (mongoc_uri_get_option_as_utf8 ( - uri, MONGOC_URI_SSLCLIENTCERTIFICATEKEYFILE, "none"), - "encrypted.pem"); - ASSERT_CMPSTR (mongoc_uri_get_option_as_utf8 ( - uri, MONGOC_URI_TLSCERTIFICATEKEYFILE, "none"), - "encrypted.pem"); - ASSERT_CMPSTR (mongoc_uri_get_option_as_utf8 ( - uri, MONGOC_URI_SSLCLIENTCERTIFICATEKEYPASSWORD, "none"), - "pa$$word!"); - ASSERT_CMPSTR (mongoc_uri_get_option_as_utf8 ( - uri, MONGOC_URI_TLSCERTIFICATEKEYFILEPASSWORD, "none"), - "pa$$word!"); - ASSERT_CMPSTR (mongoc_uri_get_option_as_utf8 ( - uri, MONGOC_URI_SSLCERTIFICATEAUTHORITYFILE, "none"), - "none"); - ASSERT_CMPSTR ( - mongoc_uri_get_option_as_utf8 (uri, MONGOC_URI_TLSCAFILE, "none"), - "none"); - ASSERT (!mongoc_uri_get_option_as_bool ( - uri, MONGOC_URI_TLSALLOWINVALIDCERTIFICATES, false)); - ASSERT (!mongoc_uri_get_option_as_bool ( - uri, MONGOC_URI_TLSALLOWINVALIDHOSTNAMES, false)); + ASSERT_CMPSTR (mongoc_uri_get_option_as_utf8 (uri, MONGOC_URI_SSLCLIENTCERTIFICATEKEYFILE, "none"), "encrypted.pem"); + ASSERT_CMPSTR (mongoc_uri_get_option_as_utf8 (uri, MONGOC_URI_TLSCERTIFICATEKEYFILE, "none"), "encrypted.pem"); + ASSERT_CMPSTR (mongoc_uri_get_option_as_utf8 (uri, MONGOC_URI_SSLCLIENTCERTIFICATEKEYPASSWORD, "none"), "pa$$word!"); + ASSERT_CMPSTR (mongoc_uri_get_option_as_utf8 (uri, MONGOC_URI_TLSCERTIFICATEKEYFILEPASSWORD, "none"), "pa$$word!"); + ASSERT_CMPSTR (mongoc_uri_get_option_as_utf8 (uri, MONGOC_URI_SSLCERTIFICATEAUTHORITYFILE, "none"), "none"); + ASSERT_CMPSTR (mongoc_uri_get_option_as_utf8 (uri, MONGOC_URI_TLSCAFILE, "none"), "none"); + ASSERT (!mongoc_uri_get_option_as_bool (uri, MONGOC_URI_TLSALLOWINVALIDCERTIFICATES, false)); + ASSERT (!mongoc_uri_get_option_as_bool (uri, MONGOC_URI_TLSALLOWINVALIDHOSTNAMES, false)); mongoc_uri_destroy (uri); - bson_snprintf (url_buffer, - sizeof (url_buffer), - "mongodb://localhost/?%s=true&%s=true", - tls, - tlsAllowInvalidCertificates); + bson_snprintf ( + url_buffer, sizeof (url_buffer), "mongodb://localhost/?%s=true&%s=true", tls, tlsAllowInvalidCertificates); uri = mongoc_uri_new (url_buffer); - ASSERT_CMPSTR (mongoc_uri_get_option_as_utf8 ( - uri, MONGOC_URI_TLSCERTIFICATEKEYFILE, "none"), - "none"); - ASSERT_CMPSTR (mongoc_uri_get_option_as_utf8 ( - uri, MONGOC_URI_TLSCERTIFICATEKEYFILEPASSWORD, "none"), - "none"); - ASSERT_CMPSTR ( - mongoc_uri_get_option_as_utf8 (uri, MONGOC_URI_TLSCAFILE, "none"), - "none"); - ASSERT (mongoc_uri_get_option_as_bool ( - uri, MONGOC_URI_SSLALLOWINVALIDCERTIFICATES, false)); - ASSERT (mongoc_uri_get_option_as_bool ( - uri, MONGOC_URI_TLSALLOWINVALIDCERTIFICATES, false)); - ASSERT (!mongoc_uri_get_option_as_bool ( - uri, MONGOC_URI_SSLALLOWINVALIDHOSTNAMES, false)); - ASSERT (!mongoc_uri_get_option_as_bool ( - uri, MONGOC_URI_TLSALLOWINVALIDHOSTNAMES, false)); + ASSERT_CMPSTR (mongoc_uri_get_option_as_utf8 (uri, MONGOC_URI_TLSCERTIFICATEKEYFILE, "none"), "none"); + ASSERT_CMPSTR (mongoc_uri_get_option_as_utf8 (uri, MONGOC_URI_TLSCERTIFICATEKEYFILEPASSWORD, "none"), "none"); + ASSERT_CMPSTR (mongoc_uri_get_option_as_utf8 (uri, MONGOC_URI_TLSCAFILE, "none"), "none"); + ASSERT (mongoc_uri_get_option_as_bool (uri, MONGOC_URI_SSLALLOWINVALIDCERTIFICATES, false)); + ASSERT (mongoc_uri_get_option_as_bool (uri, MONGOC_URI_TLSALLOWINVALIDCERTIFICATES, false)); + ASSERT (!mongoc_uri_get_option_as_bool (uri, MONGOC_URI_SSLALLOWINVALIDHOSTNAMES, false)); + ASSERT (!mongoc_uri_get_option_as_bool (uri, MONGOC_URI_TLSALLOWINVALIDHOSTNAMES, false)); mongoc_uri_destroy (uri); - bson_snprintf (url_buffer, - sizeof (url_buffer), - "mongodb://localhost/?%s=foo.pem", - tlsCertificateKeyFile); + bson_snprintf (url_buffer, sizeof (url_buffer), "mongodb://localhost/?%s=foo.pem", tlsCertificateKeyFile); uri = mongoc_uri_new (url_buffer); ASSERT (mongoc_uri_get_ssl (uri)); ASSERT (mongoc_uri_get_tls (uri)); mongoc_uri_destroy (uri); - bson_snprintf (url_buffer, - sizeof (url_buffer), - "mongodb://localhost/?%s=foo.pem", - tlsCAFile); + bson_snprintf (url_buffer, sizeof (url_buffer), "mongodb://localhost/?%s=foo.pem", tlsCAFile); uri = mongoc_uri_new (url_buffer); ASSERT (mongoc_uri_get_ssl (uri)); ASSERT (mongoc_uri_get_tls (uri)); mongoc_uri_destroy (uri); - bson_snprintf (url_buffer, - sizeof (url_buffer), - "mongodb://localhost/?%s=true", - tlsAllowInvalidCertificates); + bson_snprintf (url_buffer, sizeof (url_buffer), "mongodb://localhost/?%s=true", tlsAllowInvalidCertificates); uri = mongoc_uri_new (url_buffer); ASSERT (mongoc_uri_get_ssl (uri)); ASSERT (mongoc_uri_get_tls (uri)); - ASSERT (mongoc_uri_get_option_as_bool ( - uri, MONGOC_URI_SSLALLOWINVALIDCERTIFICATES, false)); - ASSERT (mongoc_uri_get_option_as_bool ( - uri, MONGOC_URI_TLSALLOWINVALIDCERTIFICATES, false)); + ASSERT (mongoc_uri_get_option_as_bool (uri, MONGOC_URI_SSLALLOWINVALIDCERTIFICATES, false)); + ASSERT (mongoc_uri_get_option_as_bool (uri, MONGOC_URI_TLSALLOWINVALIDCERTIFICATES, false)); mongoc_uri_destroy (uri); - bson_snprintf (url_buffer, - sizeof (url_buffer), - "mongodb://localhost/?%s=true", - tlsAllowInvalidHostnames); + bson_snprintf (url_buffer, sizeof (url_buffer), "mongodb://localhost/?%s=true", tlsAllowInvalidHostnames); uri = mongoc_uri_new (url_buffer); ASSERT (mongoc_uri_get_ssl (uri)); ASSERT (mongoc_uri_get_tls (uri)); - ASSERT (mongoc_uri_get_option_as_bool ( - uri, MONGOC_URI_SSLALLOWINVALIDHOSTNAMES, false)); - ASSERT (mongoc_uri_get_option_as_bool ( - uri, MONGOC_URI_TLSALLOWINVALIDHOSTNAMES, false)); + ASSERT (mongoc_uri_get_option_as_bool (uri, MONGOC_URI_SSLALLOWINVALIDHOSTNAMES, false)); + ASSERT (mongoc_uri_get_option_as_bool (uri, MONGOC_URI_TLSALLOWINVALIDHOSTNAMES, false)); mongoc_uri_destroy (uri); - bson_snprintf (url_buffer, - sizeof (url_buffer), - "mongodb://localhost/?%s=false&%s=foo.pem", - tls, - tlsCertificateKeyFile); + bson_snprintf ( + url_buffer, sizeof (url_buffer), "mongodb://localhost/?%s=false&%s=foo.pem", tls, tlsCertificateKeyFile); uri = mongoc_uri_new (url_buffer); ASSERT (!mongoc_uri_get_ssl (uri)); ASSERT (!mongoc_uri_get_tls (uri)); mongoc_uri_destroy (uri); - bson_snprintf (url_buffer, - sizeof (url_buffer), - "mongodb://localhost/?%s=false&%s=foo.pem", - tls, - tlsCertificateKeyFile); + bson_snprintf ( + url_buffer, sizeof (url_buffer), "mongodb://localhost/?%s=false&%s=foo.pem", tls, tlsCertificateKeyFile); uri = mongoc_uri_new (url_buffer); ASSERT (!mongoc_uri_get_ssl (uri)); ASSERT (!mongoc_uri_get_tls (uri)); mongoc_uri_destroy (uri); - bson_snprintf (url_buffer, - sizeof (url_buffer), - "mongodb://localhost/?%s=false&%s=true", - tls, - tlsAllowInvalidCertificates); + bson_snprintf ( + url_buffer, sizeof (url_buffer), "mongodb://localhost/?%s=false&%s=true", tls, tlsAllowInvalidCertificates); uri = mongoc_uri_new (url_buffer); ASSERT (!mongoc_uri_get_ssl (uri)); ASSERT (!mongoc_uri_get_tls (uri)); - ASSERT (mongoc_uri_get_option_as_bool ( - uri, MONGOC_URI_SSLALLOWINVALIDCERTIFICATES, false)); - ASSERT (mongoc_uri_get_option_as_bool ( - uri, MONGOC_URI_TLSALLOWINVALIDCERTIFICATES, false)); + ASSERT (mongoc_uri_get_option_as_bool (uri, MONGOC_URI_SSLALLOWINVALIDCERTIFICATES, false)); + ASSERT (mongoc_uri_get_option_as_bool (uri, MONGOC_URI_TLSALLOWINVALIDCERTIFICATES, false)); mongoc_uri_destroy (uri); - bson_snprintf (url_buffer, - sizeof (url_buffer), - "mongodb://localhost/?%s=false&%s=false", - tls, - tlsAllowInvalidHostnames); + bson_snprintf ( + url_buffer, sizeof (url_buffer), "mongodb://localhost/?%s=false&%s=false", tls, tlsAllowInvalidHostnames); uri = mongoc_uri_new (url_buffer); ASSERT (!mongoc_uri_get_ssl (uri)); ASSERT (!mongoc_uri_get_tls (uri)); - ASSERT (!mongoc_uri_get_option_as_bool ( - uri, MONGOC_URI_SSLALLOWINVALIDHOSTNAMES, true)); - ASSERT (!mongoc_uri_get_option_as_bool ( - uri, MONGOC_URI_TLSALLOWINVALIDHOSTNAMES, true)); + ASSERT (!mongoc_uri_get_option_as_bool (uri, MONGOC_URI_SSLALLOWINVALIDHOSTNAMES, true)); + ASSERT (!mongoc_uri_get_option_as_bool (uri, MONGOC_URI_TLSALLOWINVALIDHOSTNAMES, true)); mongoc_uri_destroy (uri); if (!strcmp (tls, "ssl")) { @@ -1876,11 +1522,7 @@ test_mongoc_uri_tls_ssl (const char *tls, /* Mixing options okay so long as they match */ capture_logs (true); - bson_snprintf (url_buffer, - sizeof (url_buffer), - "mongodb://localhost/?%s=true&%s=true", - tls, - tlsalt); + bson_snprintf (url_buffer, sizeof (url_buffer), "mongodb://localhost/?%s=true&%s=true", tls, tlsalt); uri = mongoc_uri_new (url_buffer); ASSERT (mongoc_uri_get_option_as_bool (uri, tls, false)); ASSERT_NO_CAPTURED_LOGS (url_buffer); @@ -1888,31 +1530,19 @@ test_mongoc_uri_tls_ssl (const char *tls, /* Same option with different values okay, latter overrides */ capture_logs (true); - bson_snprintf (url_buffer, - sizeof (url_buffer), - "mongodb://localhost/?%s=true&%s=false", - tls, - tls); + bson_snprintf (url_buffer, sizeof (url_buffer), "mongodb://localhost/?%s=true&%s=false", tls, tls); uri = mongoc_uri_new (url_buffer); ASSERT (!mongoc_uri_get_option_as_bool (uri, tls, true)); if (strcmp (tls, "tls")) { - ASSERT_CAPTURED_LOG ("option: ssl", - MONGOC_LOG_LEVEL_WARNING, - "Overwriting previously provided value for 'ssl'"); + ASSERT_CAPTURED_LOG ("option: ssl", MONGOC_LOG_LEVEL_WARNING, "Overwriting previously provided value for 'ssl'"); } else { - ASSERT_CAPTURED_LOG ("option: tls", - MONGOC_LOG_LEVEL_WARNING, - "Overwriting previously provided value for 'tls'"); + ASSERT_CAPTURED_LOG ("option: tls", MONGOC_LOG_LEVEL_WARNING, "Overwriting previously provided value for 'tls'"); } mongoc_uri_destroy (uri); /* Mixing options not okay if values differ */ capture_logs (false); - bson_snprintf (url_buffer, - sizeof (url_buffer), - "mongodb://localhost/?%s=true&%s=false", - tls, - tlsalt); + bson_snprintf (url_buffer, sizeof (url_buffer), "mongodb://localhost/?%s=true&%s=false", tls, tlsalt); uri = mongoc_uri_new_with_error (url_buffer, &err); if (strcmp (tls, "tls")) { ASSERT_ERROR_CONTAINS (err, @@ -1931,24 +1561,19 @@ test_mongoc_uri_tls_ssl (const char *tls, /* No conflict appears with implicit tls=true via SRV */ capture_logs (false); - bson_snprintf (url_buffer, - sizeof (url_buffer), - "mongodb+srv://a.b.c/?%s=foo.pem", - tlsCAFile); + bson_snprintf (url_buffer, sizeof (url_buffer), "mongodb+srv://a.b.c/?%s=foo.pem", tlsCAFile); uri = mongoc_uri_new (url_buffer); ASSERT (mongoc_uri_get_option_as_bool (uri, tls, false)); mongoc_uri_destroy (uri); /* Set TLS options after creating mongoc_uri_t from connection string */ uri = mongoc_uri_new ("mongodb://localhost/"); - ASSERT (mongoc_uri_set_option_as_utf8 ( - uri, tlsCertificateKeyFile, "/path/to/pem")); + ASSERT (mongoc_uri_set_option_as_utf8 (uri, tlsCertificateKeyFile, "/path/to/pem")); ASSERT (mongoc_uri_get_tls (uri)); mongoc_uri_destroy (uri); uri = mongoc_uri_new ("mongodb://localhost/"); - ASSERT (mongoc_uri_set_option_as_utf8 ( - uri, tlsCertificateKeyPassword, "password")); + ASSERT (mongoc_uri_set_option_as_utf8 (uri, tlsCertificateKeyPassword, "password")); ASSERT (mongoc_uri_get_tls (uri)); mongoc_uri_destroy (uri); @@ -1958,8 +1583,7 @@ test_mongoc_uri_tls_ssl (const char *tls, mongoc_uri_destroy (uri); uri = mongoc_uri_new ("mongodb://localhost/"); - ASSERT ( - mongoc_uri_set_option_as_bool (uri, tlsAllowInvalidCertificates, false)); + ASSERT (mongoc_uri_set_option_as_bool (uri, tlsAllowInvalidCertificates, false)); ASSERT (mongoc_uri_get_tls (uri)); mongoc_uri_destroy (uri); @@ -2005,28 +1629,23 @@ test_mongoc_uri_tls (void) ASSERT (mongoc_uri_get_option_as_bool (uri, MONGOC_URI_TLSINSECURE, false)); mongoc_uri_destroy (uri); - ASSERT (!mongoc_uri_new_with_error ( - "mongodb://localhost/?tlsInsecure=true&tlsAllowInvalidHostnames=false", - &err)); - ASSERT_ERROR_CONTAINS ( - err, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "tlsinsecure may not be specified with " - "tlsallowinvalidcertificates, tlsallowinvalidhostnames, " - "tlsdisableocspendpointcheck, or tlsdisablecertificaterevocationcheck"); - - ASSERT (!mongoc_uri_new_with_error ( - "mongodb://localhost/" - "?tlsInsecure=true&tlsAllowInvalidCertificates=true", - &err)); - ASSERT_ERROR_CONTAINS ( - err, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "tlsinsecure may not be specified with " - "tlsallowinvalidcertificates, tlsallowinvalidhostnames, " - "tlsdisableocspendpointcheck, or tlsdisablecertificaterevocationcheck"); + ASSERT (!mongoc_uri_new_with_error ("mongodb://localhost/?tlsInsecure=true&tlsAllowInvalidHostnames=false", &err)); + ASSERT_ERROR_CONTAINS (err, + MONGOC_ERROR_COMMAND, + MONGOC_ERROR_COMMAND_INVALID_ARG, + "tlsinsecure may not be specified with " + "tlsallowinvalidcertificates, tlsallowinvalidhostnames, " + "tlsdisableocspendpointcheck, or tlsdisablecertificaterevocationcheck"); + + ASSERT (!mongoc_uri_new_with_error ("mongodb://localhost/" + "?tlsInsecure=true&tlsAllowInvalidCertificates=true", + &err)); + ASSERT_ERROR_CONTAINS (err, + MONGOC_ERROR_COMMAND, + MONGOC_ERROR_COMMAND_INVALID_ARG, + "tlsinsecure may not be specified with " + "tlsallowinvalidcertificates, tlsallowinvalidhostnames, " + "tlsdisableocspendpointcheck, or tlsdisablecertificaterevocationcheck"); } static void @@ -2068,36 +1687,27 @@ test_mongoc_uri_local_threshold_ms (void) uri = mongoc_uri_new ("mongodb://localhost/"); /* localthresholdms isn't set, return the default */ - ASSERT_CMPINT (mongoc_uri_get_local_threshold_option (uri), - ==, - MONGOC_TOPOLOGY_LOCAL_THRESHOLD_MS); - ASSERT ( - mongoc_uri_set_option_as_int32 (uri, MONGOC_URI_LOCALTHRESHOLDMS, 99)); + ASSERT_CMPINT (mongoc_uri_get_local_threshold_option (uri), ==, MONGOC_TOPOLOGY_LOCAL_THRESHOLD_MS); + ASSERT (mongoc_uri_set_option_as_int32 (uri, MONGOC_URI_LOCALTHRESHOLDMS, 99)); ASSERT_CMPINT (mongoc_uri_get_local_threshold_option (uri), ==, 99); mongoc_uri_destroy (uri); - uri = - mongoc_uri_new ("mongodb://localhost/?" MONGOC_URI_LOCALTHRESHOLDMS "=0"); + uri = mongoc_uri_new ("mongodb://localhost/?" MONGOC_URI_LOCALTHRESHOLDMS "=0"); ASSERT_CMPINT (mongoc_uri_get_local_threshold_option (uri), ==, 0); - ASSERT ( - mongoc_uri_set_option_as_int32 (uri, MONGOC_URI_LOCALTHRESHOLDMS, 99)); + ASSERT (mongoc_uri_set_option_as_int32 (uri, MONGOC_URI_LOCALTHRESHOLDMS, 99)); ASSERT_CMPINT (mongoc_uri_get_local_threshold_option (uri), ==, 99); mongoc_uri_destroy (uri); - uri = mongoc_uri_new ("mongodb://localhost/?" MONGOC_URI_LOCALTHRESHOLDMS - "=-1"); + uri = mongoc_uri_new ("mongodb://localhost/?" MONGOC_URI_LOCALTHRESHOLDMS "=-1"); /* localthresholdms is invalid, return the default */ capture_logs (true); - ASSERT_CMPINT (mongoc_uri_get_local_threshold_option (uri), - ==, - MONGOC_TOPOLOGY_LOCAL_THRESHOLD_MS); - ASSERT_CAPTURED_LOG ("mongoc_uri_get_local_threshold_option", - MONGOC_LOG_LEVEL_WARNING, - "Invalid localThresholdMS: -1"); + ASSERT_CMPINT (mongoc_uri_get_local_threshold_option (uri), ==, MONGOC_TOPOLOGY_LOCAL_THRESHOLD_MS); + ASSERT_CAPTURED_LOG ( + "mongoc_uri_get_local_threshold_option", MONGOC_LOG_LEVEL_WARNING, "Invalid localThresholdMS: -1"); mongoc_uri_destroy (uri); } @@ -2105,13 +1715,9 @@ test_mongoc_uri_local_threshold_ms (void) #define INVALID(_uri, _host) \ BSON_ASSERT (!mongoc_uri_upsert_host ((_uri), (_host), 1, &error)); \ - ASSERT_ERROR_CONTAINS (error, \ - MONGOC_ERROR_STREAM, \ - MONGOC_ERROR_STREAM_NAME_RESOLUTION, \ - "must be subdomain") + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_NAME_RESOLUTION, "must be subdomain") -#define VALID(_uri, _host) \ - ASSERT_OR_PRINT (mongoc_uri_upsert_host ((_uri), (_host), 1, &error), error) +#define VALID(_uri, _host) ASSERT_OR_PRINT (mongoc_uri_upsert_host ((_uri), (_host), 1, &error), error) static void @@ -2192,18 +1798,16 @@ test_mongoc_uri_srv (void) } -#define PROHIBITED(_key, _value, _type, _where) \ - do { \ - const char *option = _key "=" #_value; \ - char *lkey = bson_strdup (_key); \ - mongoc_lowercase (lkey, lkey); \ - mongoc_uri_parse_options (uri, option, true /* from dns */, &error); \ - ASSERT_ERROR_CONTAINS (error, \ - MONGOC_ERROR_COMMAND, \ - MONGOC_ERROR_COMMAND_INVALID_ARG, \ - "prohibited in TXT record"); \ - BSON_ASSERT (!bson_has_field (mongoc_uri_get_##_where (uri), lkey)); \ - bson_free (lkey); \ +#define PROHIBITED(_key, _value, _type, _where) \ + do { \ + const char *option = _key "=" #_value; \ + char *lkey = bson_strdup (_key); \ + mongoc_lowercase (lkey, lkey); \ + mongoc_uri_parse_options (uri, option, true /* from dns */, &error); \ + ASSERT_ERROR_CONTAINS ( \ + error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "prohibited in TXT record"); \ + BSON_ASSERT (!bson_has_field (mongoc_uri_get_##_where (uri), lkey)); \ + bson_free (lkey); \ } while (0) @@ -2216,13 +1820,9 @@ test_mongoc_uri_dns_options (void) uri = mongoc_uri_new ("mongodb+srv://a.b.c"); BSON_ASSERT (uri); - BSON_ASSERT (!mongoc_uri_parse_options ( - uri, "tls=false", true /* from dsn */, &error)); + BSON_ASSERT (!mongoc_uri_parse_options (uri, "tls=false", true /* from dsn */, &error)); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "prohibited in TXT record"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "prohibited in TXT record"); ASSERT_MATCH (mongoc_uri_get_options (uri), "{'tls': true}"); @@ -2237,19 +1837,13 @@ test_mongoc_uri_dns_options (void) /* test that URI string overrides TXT record options */ mongoc_uri_destroy (uri); - uri = mongoc_uri_new ( - "mongodb+srv://user@a.b.c/?authSource=db1&replicaSet=rs1"); + uri = mongoc_uri_new ("mongodb+srv://user@a.b.c/?authSource=db1&replicaSet=rs1"); capture_logs (true); /* parse_options returns true, but logs warnings */ - BSON_ASSERT (mongoc_uri_parse_options ( - uri, "authSource=db2&replicaSet=db2", true, NULL)); - ASSERT_CAPTURED_LOG ("parsing TXT record", - MONGOC_LOG_LEVEL_WARNING, - "Cannot override URI option \"authSource\""); - ASSERT_CAPTURED_LOG ("parsing TXT record", - MONGOC_LOG_LEVEL_WARNING, - "Cannot override URI option \"replicaSet\""); + BSON_ASSERT (mongoc_uri_parse_options (uri, "authSource=db2&replicaSet=db2", true, NULL)); + ASSERT_CAPTURED_LOG ("parsing TXT record", MONGOC_LOG_LEVEL_WARNING, "Cannot override URI option \"authSource\""); + ASSERT_CAPTURED_LOG ("parsing TXT record", MONGOC_LOG_LEVEL_WARNING, "Cannot override URI option \"replicaSet\""); capture_logs (false); ASSERT_MATCH (mongoc_uri_get_credentials (uri), "{'authsource': 'db1'}"); ASSERT_MATCH (mongoc_uri_get_options (uri), "{'replicaset': 'rs1'}"); @@ -2266,25 +1860,16 @@ test_mongoc_uri_utf8 (void) /* start of 3-byte character, but it's incomplete */ BSON_ASSERT (!mongoc_uri_new_with_error ("mongodb://\xe8\x03", &err)); - ASSERT_ERROR_CONTAINS (err, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Invalid UTF-8 in URI"); + ASSERT_ERROR_CONTAINS (err, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid UTF-8 in URI"); /* start of 6-byte CESU-8 character, but it's incomplete */ BSON_ASSERT (!mongoc_uri_new_with_error ("mongodb://\xfa", &err)); - ASSERT_ERROR_CONTAINS (err, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Invalid UTF-8 in URI"); + ASSERT_ERROR_CONTAINS (err, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid UTF-8 in URI"); /* "az" with NIL expressed as two-byte sequence */ BSON_ASSERT (!mongoc_uri_new_with_error ("mongodb://a\xc0\x80z", &err)); - ASSERT_ERROR_CONTAINS (err, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Invalid UTF-8 in URI"); + ASSERT_ERROR_CONTAINS (err, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid UTF-8 in URI"); } @@ -2301,19 +1886,16 @@ test_mongoc_uri_duplicates (void) const mongoc_read_prefs_t *rp; bson_iter_t iter = {0}; -#define RECREATE_URI(opts) \ - if (1) { \ - mongoc_uri_destroy (uri); \ - uri = mongoc_uri_new_with_error ( \ - "mongodb://user:pwd@localhost/test?" opts, &err); \ - ASSERT_OR_PRINT (uri, err); \ - } else \ +#define RECREATE_URI(opts) \ + if (1) { \ + mongoc_uri_destroy (uri); \ + uri = mongoc_uri_new_with_error ("mongodb://user:pwd@localhost/test?" opts, &err); \ + ASSERT_OR_PRINT (uri, err); \ + } else \ (void) 0 -#define ASSERT_LOG_DUPE(opt) \ - ASSERT_CAPTURED_LOG ("option: " opt, \ - MONGOC_LOG_LEVEL_WARNING, \ - "Overwriting previously provided value for '" opt "'") +#define ASSERT_LOG_DUPE(opt) \ + ASSERT_CAPTURED_LOG ("option: " opt, MONGOC_LOG_LEVEL_WARNING, "Overwriting previously provided value for '" opt "'") /* iterate iter to key, and check that no other occurrences exist. */ #define BSON_ITER_UNIQUE(key) \ @@ -2342,111 +1924,83 @@ test_mongoc_uri_duplicates (void) BSON_ITER_UNIQUE (MONGOC_URI_AUTHMECHANISM); BSON_ASSERT (strcmp (bson_iter_utf8 (&iter, NULL), "b") == 0); - RECREATE_URI (MONGOC_URI_AUTHMECHANISMPROPERTIES - "=a:x&" MONGOC_URI_AUTHMECHANISMPROPERTIES "=b:y"); + RECREATE_URI (MONGOC_URI_AUTHMECHANISMPROPERTIES "=a:x&" MONGOC_URI_AUTHMECHANISMPROPERTIES "=b:y"); ASSERT_LOG_DUPE (MONGOC_URI_AUTHMECHANISMPROPERTIES); bson = mongoc_uri_get_credentials (uri); - BSON_ASSERT ( - bson_compare ( - bson, tmp_bson ("{'authmechanismproperties': {'b': 'y' }}")) == 0); + BSON_ASSERT (bson_compare (bson, tmp_bson ("{'authmechanismproperties': {'b': 'y' }}")) == 0); RECREATE_URI (MONGOC_URI_AUTHSOURCE "=a&" MONGOC_URI_AUTHSOURCE "=b"); ASSERT_LOG_DUPE (MONGOC_URI_AUTHSOURCE); str = mongoc_uri_get_auth_source (uri); BSON_ASSERT (strcmp (str, "b") == 0); - RECREATE_URI (MONGOC_URI_CANONICALIZEHOSTNAME - "=false&" MONGOC_URI_CANONICALIZEHOSTNAME "=true"); + RECREATE_URI (MONGOC_URI_CANONICALIZEHOSTNAME "=false&" MONGOC_URI_CANONICALIZEHOSTNAME "=true"); ASSERT_LOG_DUPE (MONGOC_URI_CANONICALIZEHOSTNAME); - BSON_ASSERT (mongoc_uri_get_option_as_bool ( - uri, MONGOC_URI_CANONICALIZEHOSTNAME, false)); + BSON_ASSERT (mongoc_uri_get_option_as_bool (uri, MONGOC_URI_CANONICALIZEHOSTNAME, false)); - RECREATE_URI (MONGOC_URI_CONNECTTIMEOUTMS "=1&" MONGOC_URI_CONNECTTIMEOUTMS - "=2"); + RECREATE_URI (MONGOC_URI_CONNECTTIMEOUTMS "=1&" MONGOC_URI_CONNECTTIMEOUTMS "=2"); ASSERT_LOG_DUPE (MONGOC_URI_CONNECTTIMEOUTMS); - BSON_ASSERT (mongoc_uri_get_option_as_int32 ( - uri, MONGOC_URI_CONNECTTIMEOUTMS, 0) == 2); + BSON_ASSERT (mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_CONNECTTIMEOUTMS, 0) == 2); -#if defined(MONGOC_ENABLE_COMPRESSION_SNAPPY) && \ - defined(MONGOC_ENABLE_COMPRESSION_ZLIB) - RECREATE_URI (MONGOC_URI_COMPRESSORS "=snappy&" MONGOC_URI_COMPRESSORS - "=zlib"); +#if defined(MONGOC_ENABLE_COMPRESSION_SNAPPY) && defined(MONGOC_ENABLE_COMPRESSION_ZLIB) + RECREATE_URI (MONGOC_URI_COMPRESSORS "=snappy&" MONGOC_URI_COMPRESSORS "=zlib"); ASSERT_LOG_DUPE (MONGOC_URI_COMPRESSORS); bson = mongoc_uri_get_compressors (uri); BSON_ASSERT (bson_compare (bson, tmp_bson ("{'zlib': 'yes'}")) == 0); #endif /* exception: GSSAPISERVICENAME does not overwrite. */ - RECREATE_URI (MONGOC_URI_GSSAPISERVICENAME "=a&" MONGOC_URI_GSSAPISERVICENAME - "=b"); - ASSERT_CAPTURED_LOG ( - "option: " MONGOC_URI_GSSAPISERVICENAME, - MONGOC_LOG_LEVEL_WARNING, - "Overwriting previously provided value for 'gssapiservicename'"); + RECREATE_URI (MONGOC_URI_GSSAPISERVICENAME "=a&" MONGOC_URI_GSSAPISERVICENAME "=b"); + ASSERT_CAPTURED_LOG ("option: " MONGOC_URI_GSSAPISERVICENAME, + MONGOC_LOG_LEVEL_WARNING, + "Overwriting previously provided value for 'gssapiservicename'"); bson = mongoc_uri_get_credentials (uri); - BSON_ASSERT ( - bson_compare ( - bson, - tmp_bson ("{'authmechanismproperties': {'SERVICE_NAME': 'b' }}")) == - 0); - - RECREATE_URI (MONGOC_URI_HEARTBEATFREQUENCYMS - "=500&" MONGOC_URI_HEARTBEATFREQUENCYMS "=501"); + BSON_ASSERT (bson_compare (bson, tmp_bson ("{'authmechanismproperties': {'SERVICE_NAME': 'b' }}")) == 0); + + RECREATE_URI (MONGOC_URI_HEARTBEATFREQUENCYMS "=500&" MONGOC_URI_HEARTBEATFREQUENCYMS "=501"); ASSERT_LOG_DUPE (MONGOC_URI_HEARTBEATFREQUENCYMS); - BSON_ASSERT (mongoc_uri_get_option_as_int32 ( - uri, MONGOC_URI_HEARTBEATFREQUENCYMS, 0) == 501); + BSON_ASSERT (mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_HEARTBEATFREQUENCYMS, 0) == 501); RECREATE_URI (MONGOC_URI_JOURNAL "=false&" MONGOC_URI_JOURNAL "=true"); ASSERT_LOG_DUPE (MONGOC_URI_JOURNAL); BSON_ASSERT (mongoc_uri_get_option_as_bool (uri, MONGOC_URI_JOURNAL, false)); - RECREATE_URI (MONGOC_URI_LOCALTHRESHOLDMS "=1&" MONGOC_URI_LOCALTHRESHOLDMS - "=2"); + RECREATE_URI (MONGOC_URI_LOCALTHRESHOLDMS "=1&" MONGOC_URI_LOCALTHRESHOLDMS "=2"); ASSERT_LOG_DUPE (MONGOC_URI_LOCALTHRESHOLDMS); - BSON_ASSERT (mongoc_uri_get_option_as_int32 ( - uri, MONGOC_URI_LOCALTHRESHOLDMS, 0) == 2); + BSON_ASSERT (mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_LOCALTHRESHOLDMS, 0) == 2); RECREATE_URI (MONGOC_URI_MAXIDLETIMEMS "=1&" MONGOC_URI_MAXIDLETIMEMS "=2"); ASSERT_LOG_DUPE (MONGOC_URI_MAXIDLETIMEMS); - BSON_ASSERT ( - mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_MAXIDLETIMEMS, 0) == 2); + BSON_ASSERT (mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_MAXIDLETIMEMS, 0) == 2); RECREATE_URI (MONGOC_URI_MAXPOOLSIZE "=1&" MONGOC_URI_MAXPOOLSIZE "=2"); ASSERT_LOG_DUPE (MONGOC_URI_MAXPOOLSIZE); - BSON_ASSERT ( - mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_MAXPOOLSIZE, 0) == 2); + BSON_ASSERT (mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_MAXPOOLSIZE, 0) == 2); - RECREATE_URI (MONGOC_URI_READPREFERENCE - "=secondary&" MONGOC_URI_MAXSTALENESSSECONDS - "=1&" MONGOC_URI_MAXSTALENESSSECONDS "=2"); + RECREATE_URI (MONGOC_URI_READPREFERENCE "=secondary&" MONGOC_URI_MAXSTALENESSSECONDS + "=1&" MONGOC_URI_MAXSTALENESSSECONDS "=2"); ASSERT_LOG_DUPE (MONGOC_URI_MAXSTALENESSSECONDS); - BSON_ASSERT (mongoc_uri_get_option_as_int32 ( - uri, MONGOC_URI_MAXSTALENESSSECONDS, 0) == 2); + BSON_ASSERT (mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_MAXSTALENESSSECONDS, 0) == 2); RECREATE_URI (MONGOC_URI_MINPOOLSIZE "=1&" MONGOC_URI_MINPOOLSIZE "=2"); ASSERT_LOG_DUPE (MONGOC_URI_MINPOOLSIZE); - BSON_ASSERT ( - mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_MINPOOLSIZE, 0) == 2); + BSON_ASSERT (mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_MINPOOLSIZE, 0) == 2); - RECREATE_URI (MONGOC_URI_READCONCERNLEVEL - "=local&" MONGOC_URI_READCONCERNLEVEL "=majority"); + RECREATE_URI (MONGOC_URI_READCONCERNLEVEL "=local&" MONGOC_URI_READCONCERNLEVEL "=majority"); ASSERT_LOG_DUPE (MONGOC_URI_READCONCERNLEVEL); rc = mongoc_uri_get_read_concern (uri); BSON_ASSERT (strcmp (mongoc_read_concern_get_level (rc), "majority") == 0); - RECREATE_URI (MONGOC_URI_READPREFERENCE - "=secondary&" MONGOC_URI_READPREFERENCE "=primary"); + RECREATE_URI (MONGOC_URI_READPREFERENCE "=secondary&" MONGOC_URI_READPREFERENCE "=primary"); ASSERT_LOG_DUPE (MONGOC_URI_READPREFERENCE); rp = mongoc_uri_get_read_prefs_t (uri); BSON_ASSERT (mongoc_read_prefs_get_mode (rp) == MONGOC_READ_PRIMARY); /* exception: read preference tags get appended. */ - RECREATE_URI (MONGOC_URI_READPREFERENCE - "=secondary&" MONGOC_URI_READPREFERENCETAGS - "=a:x&" MONGOC_URI_READPREFERENCETAGS "=b:y"); + RECREATE_URI (MONGOC_URI_READPREFERENCE "=secondary&" MONGOC_URI_READPREFERENCETAGS + "=a:x&" MONGOC_URI_READPREFERENCETAGS "=b:y"); bson = mongoc_uri_get_read_prefs (uri); - BSON_ASSERT (bson_compare ( - bson, tmp_bson ("{'0': {'a': 'x'}, '1': {'b': 'y'}}")) == 0); + BSON_ASSERT (bson_compare (bson, tmp_bson ("{'0': {'a': 'x'}, '1': {'b': 'y'}}")) == 0); RECREATE_URI (MONGOC_URI_REPLICASET "=a&" MONGOC_URI_REPLICASET "=b"); ASSERT_LOG_DUPE (MONGOC_URI_REPLICASET); @@ -2455,59 +2009,44 @@ test_mongoc_uri_duplicates (void) RECREATE_URI (MONGOC_URI_RETRYREADS "=false&" MONGOC_URI_RETRYREADS "=true"); ASSERT_LOG_DUPE (MONGOC_URI_RETRYREADS); - BSON_ASSERT ( - mongoc_uri_get_option_as_bool (uri, MONGOC_URI_RETRYREADS, false)); + BSON_ASSERT (mongoc_uri_get_option_as_bool (uri, MONGOC_URI_RETRYREADS, false)); - RECREATE_URI (MONGOC_URI_RETRYWRITES "=false&" MONGOC_URI_RETRYWRITES - "=true"); + RECREATE_URI (MONGOC_URI_RETRYWRITES "=false&" MONGOC_URI_RETRYWRITES "=true"); ASSERT_LOG_DUPE (MONGOC_URI_RETRYWRITES); - BSON_ASSERT ( - mongoc_uri_get_option_as_bool (uri, MONGOC_URI_RETRYWRITES, false)); + BSON_ASSERT (mongoc_uri_get_option_as_bool (uri, MONGOC_URI_RETRYWRITES, false)); RECREATE_URI (MONGOC_URI_SAFE "=false&" MONGOC_URI_SAFE "=true"); ASSERT_LOG_DUPE (MONGOC_URI_SAFE); BSON_ASSERT (mongoc_uri_get_option_as_bool (uri, MONGOC_URI_SAFE, false)); - RECREATE_URI (MONGOC_URI_SERVERSELECTIONTIMEOUTMS - "=1&" MONGOC_URI_SERVERSELECTIONTIMEOUTMS "=2"); + RECREATE_URI (MONGOC_URI_SERVERSELECTIONTIMEOUTMS "=1&" MONGOC_URI_SERVERSELECTIONTIMEOUTMS "=2"); ASSERT_LOG_DUPE (MONGOC_URI_SERVERSELECTIONTIMEOUTMS); - BSON_ASSERT (mongoc_uri_get_option_as_int32 ( - uri, MONGOC_URI_SERVERSELECTIONTIMEOUTMS, 0) == 2); + BSON_ASSERT (mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_SERVERSELECTIONTIMEOUTMS, 0) == 2); - RECREATE_URI (MONGOC_URI_SERVERSELECTIONTRYONCE - "=false&" MONGOC_URI_SERVERSELECTIONTRYONCE "=true"); + RECREATE_URI (MONGOC_URI_SERVERSELECTIONTRYONCE "=false&" MONGOC_URI_SERVERSELECTIONTRYONCE "=true"); ASSERT_LOG_DUPE (MONGOC_URI_SERVERSELECTIONTRYONCE); - BSON_ASSERT (mongoc_uri_get_option_as_bool ( - uri, MONGOC_URI_SERVERSELECTIONTRYONCE, false)); + BSON_ASSERT (mongoc_uri_get_option_as_bool (uri, MONGOC_URI_SERVERSELECTIONTRYONCE, false)); - RECREATE_URI (MONGOC_URI_SOCKETCHECKINTERVALMS - "=1&" MONGOC_URI_SOCKETCHECKINTERVALMS "=2"); + RECREATE_URI (MONGOC_URI_SOCKETCHECKINTERVALMS "=1&" MONGOC_URI_SOCKETCHECKINTERVALMS "=2"); ASSERT_LOG_DUPE (MONGOC_URI_SOCKETCHECKINTERVALMS); - BSON_ASSERT (mongoc_uri_get_option_as_int32 ( - uri, MONGOC_URI_SOCKETCHECKINTERVALMS, 0) == 2); + BSON_ASSERT (mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_SOCKETCHECKINTERVALMS, 0) == 2); - RECREATE_URI (MONGOC_URI_SOCKETTIMEOUTMS "=1&" MONGOC_URI_SOCKETTIMEOUTMS - "=2"); + RECREATE_URI (MONGOC_URI_SOCKETTIMEOUTMS "=1&" MONGOC_URI_SOCKETTIMEOUTMS "=2"); ASSERT_LOG_DUPE (MONGOC_URI_SOCKETTIMEOUTMS); - BSON_ASSERT ( - mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_SOCKETTIMEOUTMS, 0) == 2); + BSON_ASSERT (mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_SOCKETTIMEOUTMS, 0) == 2); RECREATE_URI (MONGOC_URI_TLS "=false&" MONGOC_URI_TLS "=true"); ASSERT_LOG_DUPE (MONGOC_URI_TLS); BSON_ASSERT (mongoc_uri_get_tls (uri)); - RECREATE_URI (MONGOC_URI_TLSCERTIFICATEKEYFILE - "=a&" MONGOC_URI_TLSCERTIFICATEKEYFILE "=b"); + RECREATE_URI (MONGOC_URI_TLSCERTIFICATEKEYFILE "=a&" MONGOC_URI_TLSCERTIFICATEKEYFILE "=b"); ASSERT_LOG_DUPE (MONGOC_URI_TLSCERTIFICATEKEYFILE); - str = - mongoc_uri_get_option_as_utf8 (uri, MONGOC_URI_TLSCERTIFICATEKEYFILE, ""); + str = mongoc_uri_get_option_as_utf8 (uri, MONGOC_URI_TLSCERTIFICATEKEYFILE, ""); BSON_ASSERT (strcmp (str, "b") == 0); - RECREATE_URI (MONGOC_URI_TLSCERTIFICATEKEYFILEPASSWORD - "=a&" MONGOC_URI_TLSCERTIFICATEKEYFILEPASSWORD "=b"); + RECREATE_URI (MONGOC_URI_TLSCERTIFICATEKEYFILEPASSWORD "=a&" MONGOC_URI_TLSCERTIFICATEKEYFILEPASSWORD "=b"); ASSERT_LOG_DUPE (MONGOC_URI_TLSCERTIFICATEKEYFILEPASSWORD); - str = mongoc_uri_get_option_as_utf8 ( - uri, MONGOC_URI_TLSCERTIFICATEKEYFILEPASSWORD, ""); + str = mongoc_uri_get_option_as_utf8 (uri, MONGOC_URI_TLSCERTIFICATEKEYFILEPASSWORD, ""); BSON_ASSERT (strcmp (str, "b") == 0); RECREATE_URI (MONGOC_URI_TLSCAFILE "=a&" MONGOC_URI_TLSCAFILE "=b"); @@ -2515,11 +2054,9 @@ test_mongoc_uri_duplicates (void) str = mongoc_uri_get_option_as_utf8 (uri, MONGOC_URI_TLSCAFILE, ""); BSON_ASSERT (strcmp (str, "b") == 0); - RECREATE_URI (MONGOC_URI_TLSALLOWINVALIDCERTIFICATES - "=false&" MONGOC_URI_TLSALLOWINVALIDCERTIFICATES "=true"); + RECREATE_URI (MONGOC_URI_TLSALLOWINVALIDCERTIFICATES "=false&" MONGOC_URI_TLSALLOWINVALIDCERTIFICATES "=true"); ASSERT_LOG_DUPE (MONGOC_URI_TLSALLOWINVALIDCERTIFICATES); - BSON_ASSERT (mongoc_uri_get_option_as_bool ( - uri, MONGOC_URI_TLSALLOWINVALIDCERTIFICATES, false)); + BSON_ASSERT (mongoc_uri_get_option_as_bool (uri, MONGOC_URI_TLSALLOWINVALIDCERTIFICATES, false)); RECREATE_URI (MONGOC_URI_W "=1&" MONGOC_URI_W "=0"); ASSERT_LOG_DUPE (MONGOC_URI_W); @@ -2530,33 +2067,24 @@ test_mongoc_uri_duplicates (void) RECREATE_URI (MONGOC_URI_W "=majority&" MONGOC_URI_W "=0"); ASSERT_LOG_DUPE (MONGOC_URI_W); wc = mongoc_uri_get_write_concern (uri); - BSON_ASSERT (mongoc_write_concern_get_w (wc) == - MONGOC_WRITE_CONCERN_W_MAJORITY); + BSON_ASSERT (mongoc_write_concern_get_w (wc) == MONGOC_WRITE_CONCERN_W_MAJORITY); - RECREATE_URI (MONGOC_URI_WAITQUEUEMULTIPLE "=1&" MONGOC_URI_WAITQUEUEMULTIPLE - "=2"); + RECREATE_URI (MONGOC_URI_WAITQUEUEMULTIPLE "=1&" MONGOC_URI_WAITQUEUEMULTIPLE "=2"); ASSERT_LOG_DUPE (MONGOC_URI_WAITQUEUEMULTIPLE); - BSON_ASSERT (mongoc_uri_get_option_as_int32 ( - uri, MONGOC_URI_WAITQUEUEMULTIPLE, 0) == 2); + BSON_ASSERT (mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_WAITQUEUEMULTIPLE, 0) == 2); - RECREATE_URI (MONGOC_URI_WAITQUEUETIMEOUTMS - "=1&" MONGOC_URI_WAITQUEUETIMEOUTMS "=2"); + RECREATE_URI (MONGOC_URI_WAITQUEUETIMEOUTMS "=1&" MONGOC_URI_WAITQUEUETIMEOUTMS "=2"); ASSERT_LOG_DUPE (MONGOC_URI_WAITQUEUETIMEOUTMS); - BSON_ASSERT (mongoc_uri_get_option_as_int32 ( - uri, MONGOC_URI_WAITQUEUETIMEOUTMS, 0) == 2); + BSON_ASSERT (mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_WAITQUEUETIMEOUTMS, 0) == 2); RECREATE_URI (MONGOC_URI_WTIMEOUTMS "=1&" MONGOC_URI_WTIMEOUTMS "=2"); ASSERT_LOG_DUPE (MONGOC_URI_WTIMEOUTMS); - BSON_ASSERT ( - mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_WTIMEOUTMS, 0) == 2); - BSON_ASSERT ( - mongoc_uri_get_option_as_int64 (uri, MONGOC_URI_WTIMEOUTMS, 0) == 2); + BSON_ASSERT (mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_WTIMEOUTMS, 0) == 2); + BSON_ASSERT (mongoc_uri_get_option_as_int64 (uri, MONGOC_URI_WTIMEOUTMS, 0) == 2); - RECREATE_URI (MONGOC_URI_ZLIBCOMPRESSIONLEVEL - "=1&" MONGOC_URI_ZLIBCOMPRESSIONLEVEL "=2"); + RECREATE_URI (MONGOC_URI_ZLIBCOMPRESSIONLEVEL "=1&" MONGOC_URI_ZLIBCOMPRESSIONLEVEL "=2"); ASSERT_LOG_DUPE (MONGOC_URI_ZLIBCOMPRESSIONLEVEL); - BSON_ASSERT (mongoc_uri_get_option_as_int32 ( - uri, MONGOC_URI_ZLIBCOMPRESSIONLEVEL, 0) == 2); + BSON_ASSERT (mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_ZLIBCOMPRESSIONLEVEL, 0) == 2); mongoc_uri_destroy (uri); } @@ -2574,112 +2102,66 @@ test_mongoc_uri_int_options (void) /* Set an int64 option as int64 succeeds */ ASSERT (mongoc_uri_set_option_as_int64 (uri, MONGOC_URI_WTIMEOUTMS, 10)); - ASSERT_CMPINT32 ( - mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_WTIMEOUTMS, 0), ==, 10); - ASSERT_CMPINT64 ( - mongoc_uri_get_option_as_int64 (uri, MONGOC_URI_WTIMEOUTMS, 0), ==, 10); + ASSERT_CMPINT32 (mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_WTIMEOUTMS, 0), ==, 10); + ASSERT_CMPINT64 (mongoc_uri_get_option_as_int64 (uri, MONGOC_URI_WTIMEOUTMS, 0), ==, 10); /* Set an int64 option as int32 succeeds */ ASSERT (mongoc_uri_set_option_as_int32 (uri, MONGOC_URI_WTIMEOUTMS, 15)); - ASSERT_CMPINT32 ( - mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_WTIMEOUTMS, 0), ==, 15); - ASSERT_CMPINT64 ( - mongoc_uri_get_option_as_int64 (uri, MONGOC_URI_WTIMEOUTMS, 0), ==, 15); + ASSERT_CMPINT32 (mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_WTIMEOUTMS, 0), ==, 15); + ASSERT_CMPINT64 (mongoc_uri_get_option_as_int64 (uri, MONGOC_URI_WTIMEOUTMS, 0), ==, 15); /* Setting an int32 option through _as_int64 succeeds for 32-bit values but * emits a warning */ - ASSERT ( - mongoc_uri_set_option_as_int64 (uri, MONGOC_URI_ZLIBCOMPRESSIONLEVEL, 9)); + ASSERT (mongoc_uri_set_option_as_int64 (uri, MONGOC_URI_ZLIBCOMPRESSIONLEVEL, 9)); ASSERT_CAPTURED_LOG ("option: " MONGOC_URI_ZLIBCOMPRESSIONLEVEL, MONGOC_LOG_LEVEL_WARNING, "Setting value for 32-bit option " "\"zlibcompressionlevel\" through 64-bit method"); - ASSERT_CMPINT32 ( - mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_ZLIBCOMPRESSIONLEVEL, 0), - ==, - 9); - ASSERT_CMPINT64 ( - mongoc_uri_get_option_as_int64 (uri, MONGOC_URI_ZLIBCOMPRESSIONLEVEL, 0), - ==, - 9); + ASSERT_CMPINT32 (mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_ZLIBCOMPRESSIONLEVEL, 0), ==, 9); + ASSERT_CMPINT64 (mongoc_uri_get_option_as_int64 (uri, MONGOC_URI_ZLIBCOMPRESSIONLEVEL, 0), ==, 9); clear_captured_logs (); - ASSERT (!mongoc_uri_set_option_as_int64 ( - uri, MONGOC_URI_CONNECTTIMEOUTMS, 2147483648LL)); - ASSERT_CAPTURED_LOG ( - "option: " MONGOC_URI_CONNECTTIMEOUTMS, - MONGOC_LOG_LEVEL_WARNING, - "Unsupported value for \"connecttimeoutms\": 2147483648," - " \"connecttimeoutms\" is not an int64 option"); - ASSERT_CMPINT32 ( - mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_CONNECTTIMEOUTMS, 0), - ==, - 0); - ASSERT_CMPINT64 ( - mongoc_uri_get_option_as_int64 (uri, MONGOC_URI_CONNECTTIMEOUTMS, 0), - ==, - 0); + ASSERT (!mongoc_uri_set_option_as_int64 (uri, MONGOC_URI_CONNECTTIMEOUTMS, 2147483648LL)); + ASSERT_CAPTURED_LOG ("option: " MONGOC_URI_CONNECTTIMEOUTMS, + MONGOC_LOG_LEVEL_WARNING, + "Unsupported value for \"connecttimeoutms\": 2147483648," + " \"connecttimeoutms\" is not an int64 option"); + ASSERT_CMPINT32 (mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_CONNECTTIMEOUTMS, 0), ==, 0); + ASSERT_CMPINT64 (mongoc_uri_get_option_as_int64 (uri, MONGOC_URI_CONNECTTIMEOUTMS, 0), ==, 0); clear_captured_logs (); /* Setting an int32 option as int32 succeeds */ - ASSERT ( - mongoc_uri_set_option_as_int32 (uri, MONGOC_URI_ZLIBCOMPRESSIONLEVEL, 9)); - ASSERT_CMPINT32 ( - mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_ZLIBCOMPRESSIONLEVEL, 0), - ==, - 9); - ASSERT_CMPINT64 ( - mongoc_uri_get_option_as_int64 (uri, MONGOC_URI_ZLIBCOMPRESSIONLEVEL, 0), - ==, - 9); + ASSERT (mongoc_uri_set_option_as_int32 (uri, MONGOC_URI_ZLIBCOMPRESSIONLEVEL, 9)); + ASSERT_CMPINT32 (mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_ZLIBCOMPRESSIONLEVEL, 0), ==, 9); + ASSERT_CMPINT64 (mongoc_uri_get_option_as_int64 (uri, MONGOC_URI_ZLIBCOMPRESSIONLEVEL, 0), ==, 9); /* Truncating a 64-bit value when fetching as 32-bit emits a warning */ - ASSERT (mongoc_uri_set_option_as_int64 ( - uri, MONGOC_URI_WTIMEOUTMS, 2147483648LL)); - ASSERT_CMPINT32 ( - mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_WTIMEOUTMS, 5), ==, 5); - ASSERT_CAPTURED_LOG ( - "option: " MONGOC_URI_WTIMEOUTMS " with 64-bit value", - MONGOC_LOG_LEVEL_WARNING, - "Cannot read 64-bit value for \"wtimeoutms\": 2147483648"); - ASSERT_CMPINT64 ( - mongoc_uri_get_option_as_int64 (uri, MONGOC_URI_WTIMEOUTMS, 5), - ==, - 2147483648LL); + ASSERT (mongoc_uri_set_option_as_int64 (uri, MONGOC_URI_WTIMEOUTMS, 2147483648LL)); + ASSERT_CMPINT32 (mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_WTIMEOUTMS, 5), ==, 5); + ASSERT_CAPTURED_LOG ("option: " MONGOC_URI_WTIMEOUTMS " with 64-bit value", + MONGOC_LOG_LEVEL_WARNING, + "Cannot read 64-bit value for \"wtimeoutms\": 2147483648"); + ASSERT_CMPINT64 (mongoc_uri_get_option_as_int64 (uri, MONGOC_URI_WTIMEOUTMS, 5), ==, 2147483648LL); clear_captured_logs (); - ASSERT (mongoc_uri_set_option_as_int64 ( - uri, MONGOC_URI_WTIMEOUTMS, -2147483649LL)); - ASSERT_CMPINT32 ( - mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_WTIMEOUTMS, 5), ==, 5); - ASSERT_CAPTURED_LOG ( - "option: " MONGOC_URI_WTIMEOUTMS " with 64-bit value", - MONGOC_LOG_LEVEL_WARNING, - "Cannot read 64-bit value for \"wtimeoutms\": -2147483649"); - ASSERT_CMPINT64 ( - mongoc_uri_get_option_as_int64 (uri, MONGOC_URI_WTIMEOUTMS, 5), - ==, - -2147483649LL); + ASSERT (mongoc_uri_set_option_as_int64 (uri, MONGOC_URI_WTIMEOUTMS, -2147483649LL)); + ASSERT_CMPINT32 (mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_WTIMEOUTMS, 5), ==, 5); + ASSERT_CAPTURED_LOG ("option: " MONGOC_URI_WTIMEOUTMS " with 64-bit value", + MONGOC_LOG_LEVEL_WARNING, + "Cannot read 64-bit value for \"wtimeoutms\": -2147483649"); + ASSERT_CMPINT64 (mongoc_uri_get_option_as_int64 (uri, MONGOC_URI_WTIMEOUTMS, 5), ==, -2147483649LL); clear_captured_logs (); /* Setting a INT_MAX and INT_MIN values doesn't cause truncation errors */ - ASSERT ( - mongoc_uri_set_option_as_int64 (uri, MONGOC_URI_WTIMEOUTMS, INT32_MAX)); - ASSERT_CMPINT32 ( - mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_WTIMEOUTMS, 0), - ==, - INT32_MAX); + ASSERT (mongoc_uri_set_option_as_int64 (uri, MONGOC_URI_WTIMEOUTMS, INT32_MAX)); + ASSERT_CMPINT32 (mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_WTIMEOUTMS, 0), ==, INT32_MAX); ASSERT_NO_CAPTURED_LOGS ("INT_MAX"); - ASSERT ( - mongoc_uri_set_option_as_int64 (uri, MONGOC_URI_WTIMEOUTMS, INT32_MIN)); - ASSERT_CMPINT32 ( - mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_WTIMEOUTMS, 0), - ==, - INT32_MIN); + ASSERT (mongoc_uri_set_option_as_int64 (uri, MONGOC_URI_WTIMEOUTMS, INT32_MIN)); + ASSERT_CMPINT32 (mongoc_uri_get_option_as_int32 (uri, MONGOC_URI_WTIMEOUTMS, 0), ==, INT32_MIN); ASSERT_NO_CAPTURED_LOGS ("INT_MIN"); mongoc_uri_destroy (uri); @@ -2702,8 +2184,7 @@ test_one_tls_option_enables_tls (void) MONGOC_URI_SSLALLOWINVALIDCERTIFICATES "=true", MONGOC_URI_SSLALLOWINVALIDHOSTNAMES "=true", MONGOC_URI_TLSDISABLEOCSPENDPOINTCHECK "=true", - MONGOC_URI_TLSDISABLECERTIFICATEREVOCATIONCHECK - "=true"}; + MONGOC_URI_TLSDISABLECERTIFICATEREVOCATIONCHECK "=true"}; int i; for (i = 0; i < sizeof (opts) / sizeof (opts[0]); i++) { @@ -2711,15 +2192,12 @@ test_one_tls_option_enables_tls (void) bson_error_t error; char *uri_string; - uri_string = - bson_strdup_printf ("mongodb://localhost:27017/?%s", opts[i]); + uri_string = bson_strdup_printf ("mongodb://localhost:27017/?%s", opts[i]); uri = mongoc_uri_new_with_error (uri_string, &error); bson_free (uri_string); ASSERT_OR_PRINT (uri, error); if (!mongoc_uri_get_tls (uri)) { - test_error ( - "unexpected tls not enabled when following option set: %s\n", - opts[i]); + test_error ("unexpected tls not enabled when following option set: %s\n", opts[i]); } mongoc_uri_destroy (uri); } @@ -2734,10 +2212,7 @@ test_casing_options (void) uri = mongoc_uri_new ("mongodb://localhost:27017/"); mongoc_uri_set_option_as_bool (uri, "TLS", true); mongoc_uri_parse_options (uri, "ssl=false", false, &error); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "conflicts"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "conflicts"); mongoc_uri_destroy (uri); } @@ -2787,17 +2262,13 @@ test_parses_long_ipv6 (void) capture_logs (true); mongoc_uri_t *uri = mongoc_uri_new_with_error (uri_string, &error); // Expect error parsing IPv6 literal is logged. - ASSERT_CAPTURED_LOG ("parsing IPv6", - MONGOC_LOG_LEVEL_ERROR, - "IPv6 literal provided in URI is too long"); + ASSERT_CAPTURED_LOG ("parsing IPv6", MONGOC_LOG_LEVEL_ERROR, "IPv6 literal provided in URI is too long"); capture_logs (false); // Expect a generic parsing error is also returned. ASSERT (!uri); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Invalid host string in URI"); + ASSERT_ERROR_CONTAINS ( + error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid host string in URI"); mongoc_uri_destroy (uri); bson_free (uri_string); @@ -2811,34 +2282,26 @@ test_uri_install (TestSuite *suite) { TestSuite_Add (suite, "/Uri/new", test_mongoc_uri_new); TestSuite_Add (suite, "/Uri/new_with_error", test_mongoc_uri_new_with_error); - TestSuite_Add ( - suite, "/Uri/new_for_host_port", test_mongoc_uri_new_for_host_port); + TestSuite_Add (suite, "/Uri/new_for_host_port", test_mongoc_uri_new_for_host_port); TestSuite_Add (suite, "/Uri/compressors", test_mongoc_uri_compressors); TestSuite_Add (suite, "/Uri/unescape", test_mongoc_uri_unescape); TestSuite_Add (suite, "/Uri/read_prefs", test_mongoc_uri_read_prefs); TestSuite_Add (suite, "/Uri/read_concern", test_mongoc_uri_read_concern); TestSuite_Add (suite, "/Uri/write_concern", test_mongoc_uri_write_concern); - TestSuite_Add ( - suite, "/HostList/from_string", test_mongoc_host_list_from_string); - TestSuite_Add (suite, - "/Uri/auth_mechanism_properties", - test_mongoc_uri_authmechanismproperties); + TestSuite_Add (suite, "/HostList/from_string", test_mongoc_host_list_from_string); + TestSuite_Add (suite, "/Uri/auth_mechanism_properties", test_mongoc_uri_authmechanismproperties); TestSuite_Add (suite, "/Uri/functions", test_mongoc_uri_functions); TestSuite_Add (suite, "/Uri/ssl", test_mongoc_uri_ssl); TestSuite_Add (suite, "/Uri/tls", test_mongoc_uri_tls); - TestSuite_Add ( - suite, "/Uri/compound_setters", test_mongoc_uri_compound_setters); + TestSuite_Add (suite, "/Uri/compound_setters", test_mongoc_uri_compound_setters); TestSuite_Add (suite, "/Uri/long_hostname", test_mongoc_uri_long_hostname); - TestSuite_Add ( - suite, "/Uri/local_threshold_ms", test_mongoc_uri_local_threshold_ms); + TestSuite_Add (suite, "/Uri/local_threshold_ms", test_mongoc_uri_local_threshold_ms); TestSuite_Add (suite, "/Uri/srv", test_mongoc_uri_srv); TestSuite_Add (suite, "/Uri/dns_options", test_mongoc_uri_dns_options); TestSuite_Add (suite, "/Uri/utf8", test_mongoc_uri_utf8); TestSuite_Add (suite, "/Uri/duplicates", test_mongoc_uri_duplicates); TestSuite_Add (suite, "/Uri/int_options", test_mongoc_uri_int_options); - TestSuite_Add (suite, - "/Uri/one_tls_option_enables_tls", - test_one_tls_option_enables_tls); + TestSuite_Add (suite, "/Uri/one_tls_option_enables_tls", test_one_tls_option_enables_tls); TestSuite_Add (suite, "/Uri/options_casing", test_casing_options); TestSuite_Add (suite, "/Uri/parses_long_ipv6", test_parses_long_ipv6); } diff --git a/src/libmongoc/tests/test-mongoc-usleep.c b/src/libmongoc/tests/test-mongoc-usleep.c index 024a54ea13..96be7da225 100644 --- a/src/libmongoc/tests/test-mongoc-usleep.c +++ b/src/libmongoc/tests/test-mongoc-usleep.c @@ -40,8 +40,7 @@ test_mongoc_usleep_custom (void) mongoc_uri_t *uri = mongoc_uri_copy (mock_server_get_uri (server)); // Tell single-threaded clients to reconnect if an error occcurs. - mongoc_uri_set_option_as_bool ( - uri, MONGOC_URI_SERVERSELECTIONTRYONCE, false); + mongoc_uri_set_option_as_bool (uri, MONGOC_URI_SERVERSELECTIONTRYONCE, false); mongoc_client_t *client = test_framework_client_new_from_uri (uri, NULL); ASSERT (client); @@ -56,12 +55,8 @@ test_mongoc_usleep_custom (void) mongoc_client_set_usleep_impl (client, custom_usleep_impl, &last_sleep_dur); bson_error_t error; - future_t *future = future_client_command_simple (client, - "db", - tmp_bson ("{'ping': 1}"), - NULL /* read prefs */, - NULL, - &error); + future_t *future = + future_client_command_simple (client, "db", tmp_bson ("{'ping': 1}"), NULL /* read prefs */, NULL, &error); // Client sends initial `isMaster`. { @@ -77,12 +72,11 @@ test_mongoc_usleep_custom (void) { request_t *req = mock_server_receives_any_hello (server); ASSERT (req); - reply_to_request_simple ( - req, - tmp_str ("{ 'minWireVersion': %d, 'maxWireVersion' : %d, " - "'isWritablePrimary': true}", - WIRE_VERSION_MIN, - WIRE_VERSION_MAX)); + reply_to_request_simple (req, + tmp_str ("{ 'minWireVersion': %d, 'maxWireVersion' : %d, " + "'isWritablePrimary': true}", + WIRE_VERSION_MIN, + WIRE_VERSION_MAX)); request_destroy (req); } @@ -91,8 +85,7 @@ test_mongoc_usleep_custom (void) // Client sends "ping". { - request_t *req = mock_server_receives_msg ( - server, MONGOC_MSG_NONE, tmp_bson ("{'ping': 1}")); + request_t *req = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'ping': 1}")); ASSERT (req); reply_to_request_with_ok_and_destroy (req); } @@ -110,6 +103,5 @@ void test_usleep_install (TestSuite *suite) { TestSuite_Add (suite, "/Sleep/basic", test_mongoc_usleep_basic); - TestSuite_AddMockServerTest ( - suite, "/Sleep/custom", test_mongoc_usleep_custom); + TestSuite_AddMockServerTest (suite, "/Sleep/custom", test_mongoc_usleep_custom); } diff --git a/src/libmongoc/tests/test-mongoc-util.c b/src/libmongoc/tests/test-mongoc-util.c index b43f2f3943..a98befd63b 100644 --- a/src/libmongoc/tests/test-mongoc-util.c +++ b/src/libmongoc/tests/test-mongoc-util.c @@ -76,20 +76,16 @@ test_wire_server_versions (void) /* Bumping WIRE_VERSION_MAX must be accompanied by an update to * `_mongoc_wire_version_to_server_version`. */ - ASSERT_WITH_MSG ( - strcmp (_mongoc_wire_version_to_server_version (WIRE_VERSION_MAX), - "Unknown"), - "WIRE_VERSION_MAX must have a corresponding server version defined in " - "_mongoc_wire_version_to_server_version"); + ASSERT_WITH_MSG (strcmp (_mongoc_wire_version_to_server_version (WIRE_VERSION_MAX), "Unknown"), + "WIRE_VERSION_MAX must have a corresponding server version defined in " + "_mongoc_wire_version_to_server_version"); /* Unlikely given the minimum version should always be a value older than the * maximum version, but nevertheless important to assert so warning/error * messages remain valid. */ - ASSERT_WITH_MSG ( - strcmp (_mongoc_wire_version_to_server_version (WIRE_VERSION_MIN), - "Unknown"), - "WIRE_VERSION_MIN must have a corresponding server version defined in " - "_mongoc_wire_version_to_server_version"); + ASSERT_WITH_MSG (strcmp (_mongoc_wire_version_to_server_version (WIRE_VERSION_MIN), "Unknown"), + "WIRE_VERSION_MIN must have a corresponding server version defined in " + "_mongoc_wire_version_to_server_version"); } static void @@ -122,8 +118,7 @@ test_util_install (TestSuite *suite) TestSuite_Add (suite, "/Util/command_name", test_command_name); TestSuite_Add (suite, "/Util/rand_simple", test_rand_simple); TestSuite_Add (suite, "/Util/lowercase_utf8", test_lowercase_utf8); - TestSuite_Add ( - suite, "/Util/wire_server_versions", test_wire_server_versions); + TestSuite_Add (suite, "/Util/wire_server_versions", test_wire_server_versions); TestSuite_Add (suite, "/Util/bin_to_hex", test_bin_to_hex); TestSuite_Add (suite, "/Util/hex_to_bin", test_hex_to_bin); } diff --git a/src/libmongoc/tests/test-mongoc-version.c b/src/libmongoc/tests/test-mongoc-version.c index 51d93daa96..0007c14aa0 100644 --- a/src/libmongoc/tests/test-mongoc-version.c +++ b/src/libmongoc/tests/test-mongoc-version.c @@ -10,11 +10,9 @@ test_mongoc_version (void) ASSERT_CMPINT (mongoc_get_micro_version (), ==, MONGOC_MICRO_VERSION); ASSERT_CMPSTR (mongoc_get_version (), MONGOC_VERSION_S); - ASSERT (mongoc_check_version ( - MONGOC_MAJOR_VERSION, MONGOC_MINOR_VERSION, MONGOC_MICRO_VERSION)); + ASSERT (mongoc_check_version (MONGOC_MAJOR_VERSION, MONGOC_MINOR_VERSION, MONGOC_MICRO_VERSION)); - ASSERT (!mongoc_check_version ( - MONGOC_MAJOR_VERSION, MONGOC_MINOR_VERSION + 1, MONGOC_MICRO_VERSION)); + ASSERT (!mongoc_check_version (MONGOC_MAJOR_VERSION, MONGOC_MINOR_VERSION + 1, MONGOC_MICRO_VERSION)); } void diff --git a/src/libmongoc/tests/test-mongoc-versioned-api.c b/src/libmongoc/tests/test-mongoc-versioned-api.c index 09f72cfd92..fd0aa7d87f 100644 --- a/src/libmongoc/tests/test-mongoc-versioned-api.c +++ b/src/libmongoc/tests/test-mongoc-versioned-api.c @@ -85,10 +85,8 @@ _test_mongoc_server_api_client (void) /* Cannot change server API once it is set */ ASSERT (!mongoc_client_set_server_api (client, api, &error)); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_CLIENT, - MONGOC_ERROR_CLIENT_API_ALREADY_SET, - "Cannot set server api more than once"); + ASSERT_ERROR_CONTAINS ( + error, MONGOC_ERROR_CLIENT, MONGOC_ERROR_CLIENT_API_ALREADY_SET, "Cannot set server api more than once"); /* client gets its own internal copy */ mongoc_server_api_destroy (api); @@ -111,15 +109,12 @@ _test_mongoc_server_api_client_pool (void) api = mongoc_server_api_new (MONGOC_SERVER_API_V1); - ASSERT_OR_PRINT (mongoc_client_pool_set_server_api (pool, api, &error), - error); + ASSERT_OR_PRINT (mongoc_client_pool_set_server_api (pool, api, &error), error); /* Cannot change server API once it is set */ ASSERT (!mongoc_client_pool_set_server_api (pool, api, &error)); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_POOL, - MONGOC_ERROR_POOL_API_ALREADY_SET, - "Cannot set server api more than once"); + ASSERT_ERROR_CONTAINS ( + error, MONGOC_ERROR_POOL, MONGOC_ERROR_POOL_API_ALREADY_SET, "Cannot set server api more than once"); /* Clients popped from pool have matching API */ client = mongoc_client_pool_pop (pool); @@ -127,11 +122,10 @@ _test_mongoc_server_api_client_pool (void) BSON_ASSERT (client->api->version == MONGOC_SERVER_API_V1); ASSERT (!mongoc_client_set_server_api (client, api, &error)); - ASSERT_ERROR_CONTAINS ( - error, - MONGOC_ERROR_CLIENT, - MONGOC_ERROR_CLIENT_API_FROM_POOL, - "Cannot set server api on a client checked out from a pool"); + ASSERT_ERROR_CONTAINS (error, + MONGOC_ERROR_CLIENT, + MONGOC_ERROR_CLIENT_API_FROM_POOL, + "Cannot set server api on a client checked out from a pool"); mongoc_client_pool_push (pool, client); mongoc_client_pool_destroy (pool); @@ -158,18 +152,16 @@ _test_mongoc_server_api_client_pool_once (void) /* Cannot change server API once a client has been popped. */ ASSERT (!mongoc_client_pool_set_server_api (pool, api, &error)); - ASSERT_ERROR_CONTAINS ( - error, - MONGOC_ERROR_POOL, - MONGOC_ERROR_POOL_API_TOO_LATE, - "Cannot set server api after a client has been created"); + ASSERT_ERROR_CONTAINS (error, + MONGOC_ERROR_POOL, + MONGOC_ERROR_POOL_API_TOO_LATE, + "Cannot set server api after a client has been created"); ASSERT (!mongoc_client_set_server_api (client, api, &error)); - ASSERT_ERROR_CONTAINS ( - error, - MONGOC_ERROR_CLIENT, - MONGOC_ERROR_CLIENT_API_FROM_POOL, - "Cannot set server api on a client checked out from a pool"); + ASSERT_ERROR_CONTAINS (error, + MONGOC_ERROR_CLIENT, + MONGOC_ERROR_CLIENT_API_FROM_POOL, + "Cannot set server api on a client checked out from a pool"); mongoc_client_pool_push (pool, client); mongoc_client_pool_destroy (pool); @@ -217,17 +209,10 @@ test_client_versioned_api_install (TestSuite *suite) { run_unified_tests (suite, JSON_DIR, "versioned_api"); - TestSuite_Add ( - suite, "/VersionedApi/client", _test_mongoc_server_api_client); - TestSuite_Add ( - suite, "/VersionedApi/client_pool", _test_mongoc_server_api_client_pool); - TestSuite_Add (suite, - "/VersionedApi/client_pool_once", - _test_mongoc_server_api_client_pool_once); + TestSuite_Add (suite, "/VersionedApi/client", _test_mongoc_server_api_client); + TestSuite_Add (suite, "/VersionedApi/client_pool", _test_mongoc_server_api_client_pool); + TestSuite_Add (suite, "/VersionedApi/client_pool_once", _test_mongoc_server_api_client_pool_once); TestSuite_Add (suite, "/VersionedApi/copy", _test_mongoc_server_api_copy); - TestSuite_Add ( - suite, "/VersionedApi/setters", _test_mongoc_server_api_setters); - TestSuite_Add (suite, - "/VersionedApi/private/client_uses_server_api", - _test_mongoc_client_uses_server_api); + TestSuite_Add (suite, "/VersionedApi/setters", _test_mongoc_server_api_setters); + TestSuite_Add (suite, "/VersionedApi/private/client_uses_server_api", _test_mongoc_client_uses_server_api); } diff --git a/src/libmongoc/tests/test-mongoc-with-transaction.c b/src/libmongoc/tests/test-mongoc-with-transaction.c index 22fbaf9199..40a118f900 100644 --- a/src/libmongoc/tests/test-mongoc-with-transaction.c +++ b/src/libmongoc/tests/test-mongoc-with-transaction.c @@ -9,10 +9,7 @@ * since it shares the same test runner with the transactions test runner. */ static bool -with_transaction_fail_transient_txn (mongoc_client_session_t *session, - void *ctx, - bson_t **reply, - bson_error_t *error) +with_transaction_fail_transient_txn (mongoc_client_session_t *session, void *ctx, bson_t **reply, bson_error_t *error) { bson_array_builder_t *labels; @@ -30,10 +27,7 @@ with_transaction_fail_transient_txn (mongoc_client_session_t *session, } static bool -with_transaction_do_nothing (mongoc_client_session_t *session, - void *ctx, - bson_t **reply, - bson_error_t *error) +with_transaction_do_nothing (mongoc_client_session_t *session, void *ctx, bson_t **reply, bson_error_t *error) { BSON_UNUSED (session); BSON_UNUSED (ctx); @@ -62,24 +56,22 @@ test_with_transaction_timeout (void *ctx) /* Test Case 1: Test that if the callback returns an error with the TransientTransactionError label and we have exceeded the timeout, withTransaction fails. */ - res = mongoc_client_session_with_transaction ( - session, with_transaction_fail_transient_txn, NULL, NULL, NULL, &error); + res = + mongoc_client_session_with_transaction (session, with_transaction_fail_transient_txn, NULL, NULL, NULL, &error); ASSERT (!res); /* Test Case 2: If committing returns an error with the UnknownTransactionCommitResult label and we have exceeded the timeout, withTransaction fails. */ session->fail_commit_label = UNKNOWN_COMMIT_RESULT; - res = mongoc_client_session_with_transaction ( - session, with_transaction_do_nothing, NULL, NULL, NULL, &error); + res = mongoc_client_session_with_transaction (session, with_transaction_do_nothing, NULL, NULL, NULL, &error); ASSERT (!res); /* Test Case 3: If committing returns an error with the TransientTransactionError label and we have exceeded the timeout, withTransaction fails. */ session->fail_commit_label = TRANSIENT_TXN_ERR; - res = mongoc_client_session_with_transaction ( - session, with_transaction_do_nothing, NULL, NULL, NULL, &error); + res = mongoc_client_session_with_transaction (session, with_transaction_do_nothing, NULL, NULL, NULL, &error); ASSERT (!res); mongoc_client_session_destroy (session); diff --git a/src/libmongoc/tests/test-mongoc-write-commands.c b/src/libmongoc/tests/test-mongoc-write-commands.c index 5134add6d4..29e9143222 100644 --- a/src/libmongoc/tests/test-mongoc-write-commands.c +++ b/src/libmongoc/tests/test-mongoc-write-commands.c @@ -47,32 +47,18 @@ test_split_insert (void) _mongoc_write_result_init (&result); - _mongoc_write_command_init_insert ( - &command, docs[0], NULL, write_flags, ++client->cluster.operation_id); + _mongoc_write_command_init_insert (&command, docs[0], NULL, write_flags, ++client->cluster.operation_id); for (i = 1; i < 3000; i++) { _mongoc_write_command_insert_append (&command, docs[i]); } - server_stream = mongoc_cluster_stream_for_writes ( - &client->cluster, NULL, NULL, NULL, &error); + server_stream = mongoc_cluster_stream_for_writes (&client->cluster, NULL, NULL, NULL, &error); ASSERT_OR_PRINT (server_stream, error); - _mongoc_write_command_execute (&command, - client, - server_stream, - collection->db, - collection->collection, - NULL, - 0, - NULL, - &result); - - r = MONGOC_WRITE_RESULT_COMPLETE (&result, - 2, - collection->write_concern, - (mongoc_error_domain_t) 0, - &reply, - &error); + _mongoc_write_command_execute ( + &command, client, server_stream, collection->db, collection->collection, NULL, 0, NULL, &result); + + r = MONGOC_WRITE_RESULT_COMPLETE (&result, 2, collection->write_concern, (mongoc_error_domain_t) 0, &reply, &error); ASSERT_OR_PRINT (r, error); BSON_ASSERT (result.nInserted == 3000); @@ -122,28 +108,14 @@ test_invalid_write_concern (void) doc = BCON_NEW ("_id", BCON_INT32 (0)); - _mongoc_write_command_init_insert ( - &command, doc, NULL, write_flags, ++client->cluster.operation_id); + _mongoc_write_command_init_insert (&command, doc, NULL, write_flags, ++client->cluster.operation_id); _mongoc_write_result_init (&result); - server_stream = mongoc_cluster_stream_for_writes ( - &client->cluster, NULL, NULL, NULL, &error); + server_stream = mongoc_cluster_stream_for_writes (&client->cluster, NULL, NULL, NULL, &error); ASSERT_OR_PRINT (server_stream, error); - _mongoc_write_command_execute (&command, - client, - server_stream, - collection->db, - collection->collection, - write_concern, - 0, - NULL, - &result); - - r = MONGOC_WRITE_RESULT_COMPLETE (&result, - 2, - collection->write_concern, - (mongoc_error_domain_t) 0, - &reply, - &error); + _mongoc_write_command_execute ( + &command, client, server_stream, collection->db, collection->collection, write_concern, 0, NULL, &result); + + r = MONGOC_WRITE_RESULT_COMPLETE (&result, 2, collection->write_concern, (mongoc_error_domain_t) 0, &reply, &error); BSON_ASSERT (!r); ASSERT_CMPINT (error.domain, ==, MONGOC_ERROR_COMMAND); @@ -188,10 +160,8 @@ test_bypass_validation (void *context) collection = mongoc_database_get_collection (database, collname); BSON_ASSERT (collection); - options = tmp_bson ( - "{'validator': {'number': {'$gte': 5}}, 'validationAction': 'error'}"); - collection2 = - mongoc_database_create_collection (database, collname, options, &error); + options = tmp_bson ("{'validator': {'number': {'$gte': 5}}, 'validationAction': 'error'}"); + collection2 = mongoc_database_create_collection (database, collname, options, &error); ASSERT_OR_PRINT (collection2, error); mongoc_collection_destroy (collection2); @@ -206,8 +176,7 @@ test_bypass_validation (void *context) bson_destroy (&reply); ASSERT (!r); - ASSERT_ERROR_CONTAINS ( - error, MONGOC_ERROR_COMMAND, 121, "Document failed validation"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, 121, "Document failed validation"); mongoc_bulk_operation_destroy (bulk); /* }}} */ @@ -223,8 +192,7 @@ test_bypass_validation (void *context) bson_destroy (&reply); ASSERT (!r); - ASSERT_ERROR_CONTAINS ( - error, MONGOC_ERROR_COMMAND, 121, "Document failed validation"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, 121, "Document failed validation"); mongoc_bulk_operation_destroy (bulk); /* }}} */ @@ -256,11 +224,10 @@ test_bypass_validation (void *context) r = mongoc_bulk_operation_execute (bulk, &reply, &error); bson_destroy (&reply); ASSERT_OR_PRINT (!r, error); - ASSERT_ERROR_CONTAINS ( - error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Cannot set bypassDocumentValidation for unacknowledged writes"); + ASSERT_ERROR_CONTAINS (error, + MONGOC_ERROR_COMMAND, + MONGOC_ERROR_COMMAND_INVALID_ARG, + "Cannot set bypassDocumentValidation for unacknowledged writes"); mongoc_bulk_operation_destroy (bulk); mongoc_write_concern_destroy (wr); /* }}} */ @@ -277,8 +244,7 @@ test_bypass_validation (void *context) static void test_bypass_command_started (const mongoc_apm_command_started_t *event) { - ASSERT_HAS_NOT_FIELD (mongoc_apm_command_started_get_command (event), - "bypassDocumentValidation"); + ASSERT_HAS_NOT_FIELD (mongoc_apm_command_started_get_command (event), "bypassDocumentValidation"); } static void @@ -340,8 +306,7 @@ test_bypass_not_sent (void) mongoc_find_and_modify_opts_set_update (opts, update); bson_destroy (update); query = BCON_NEW ("x", BCON_INT32 (31)); - r = mongoc_collection_find_and_modify_with_opts ( - collection, query, opts, &reply, &error); + r = mongoc_collection_find_and_modify_with_opts (collection, query, opts, &reply, &error); bson_destroy (&reply); ASSERT_OR_PRINT (r, error); bson_destroy (query); @@ -352,8 +317,7 @@ test_bypass_not_sent (void) /* aggregate match */ pipeline = BCON_NEW ("pipeline", "[", "]"); - cursor = mongoc_collection_aggregate ( - collection, MONGOC_QUERY_NONE, pipeline, agg_opts, NULL); + cursor = mongoc_collection_aggregate (collection, MONGOC_QUERY_NONE, pipeline, agg_opts, NULL); bson_destroy (pipeline); bson_destroy (agg_opts); @@ -403,13 +367,11 @@ test_disconnect_mid_batch (void) docs[i] = BCON_NEW ("_id", BCON_INT64 (i)); } - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); mongoc_client_set_error_api (client, MONGOC_ERROR_API_VERSION_2); coll = mongoc_client_get_collection (client, "db", "coll"); - future = future_collection_insert_many ( - coll, (const bson_t **) docs, n_docs, NULL, NULL, &error); + future = future_collection_insert_many (coll, (const bson_t **) docs, n_docs, NULL, NULL, &error); /* Mock server recieves first insert. */ request = mock_server_receives_request (server); BSON_ASSERT (request); @@ -418,8 +380,7 @@ test_disconnect_mid_batch (void) BSON_ASSERT (!future_get_bool (future)); future_destroy (future); - ASSERT_ERROR_CONTAINS ( - error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "socket error"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "socket error"); for (i = 0; i < n_docs; i++) { bson_destroy (docs[i]); @@ -431,9 +392,7 @@ test_disconnect_mid_batch (void) } static void -_configure_failpoint (mongoc_client_t *client, - const char *mode, - const char *data) +_configure_failpoint (mongoc_client_t *client, const char *mode, const char *data) { bool ret; bson_error_t error; @@ -443,9 +402,7 @@ _configure_failpoint (mongoc_client_t *client, ret = mongoc_client_command_simple ( client, "admin", - tmp_bson ("{'configureFailPoint': 'failCommand', 'mode': %s, 'data': %s}", - mode, - data), + tmp_bson ("{'configureFailPoint': 'failCommand', 'mode': %s, 'data': %s}", mode, data), NULL, NULL, &error); @@ -473,8 +430,7 @@ _test_invalid_wc_server_error (void *unused) "'writeConcernError': {'code' : " "91.0, 'errmsg': 'Replication is " "being shut down' }}"); - ret = mongoc_collection_insert_one ( - coll, tmp_bson ("{'x':1}"), NULL /* opts */, &reply, &error); + ret = mongoc_collection_insert_one (coll, tmp_bson ("{'x':1}"), NULL /* opts */, &reply, &error); BSON_ASSERT (!ret); ASSERT_MATCH (&reply, "{'writeConcernErrors': [{'code': 91, 'errmsg': " @@ -491,19 +447,11 @@ void test_write_command_install (TestSuite *suite) { TestSuite_AddLive (suite, "/WriteCommand/split_insert", test_split_insert); - TestSuite_AddLive ( - suite, "/WriteCommand/bypass_not_sent", test_bypass_not_sent); - TestSuite_AddLive ( - suite, "/WriteCommand/invalid_write_concern", test_invalid_write_concern); - TestSuite_AddFull (suite, - "/WriteCommand/bypass_validation", - test_bypass_validation, - NULL, - NULL, - TestSuite_CheckLive); - TestSuite_AddMockServerTest (suite, - "/WriteCommand/insert_disconnect_mid_batch", - test_disconnect_mid_batch); + TestSuite_AddLive (suite, "/WriteCommand/bypass_not_sent", test_bypass_not_sent); + TestSuite_AddLive (suite, "/WriteCommand/invalid_write_concern", test_invalid_write_concern); + TestSuite_AddFull ( + suite, "/WriteCommand/bypass_validation", test_bypass_validation, NULL, NULL, TestSuite_CheckLive); + TestSuite_AddMockServerTest (suite, "/WriteCommand/insert_disconnect_mid_batch", test_disconnect_mid_batch); TestSuite_AddFull (suite, "/WriteCommand/invalid_wc_server_error", _test_invalid_wc_server_error, diff --git a/src/libmongoc/tests/test-mongoc-write-concern.c b/src/libmongoc/tests/test-mongoc-write-concern.c index 54db242fbc..b19d653da3 100644 --- a/src/libmongoc/tests/test-mongoc-write-concern.c +++ b/src/libmongoc/tests/test-mongoc-write-concern.c @@ -32,8 +32,7 @@ test_write_concern_append (void) mongoc_write_concern_set_w (wc, 1); BSON_ASSERT (mongoc_write_concern_append (wc, cmd)); - assert_match_bson ( - cmd, tmp_bson ("{'foo': 1, 'writeConcern': {'w': 1}}"), true); + assert_match_bson (cmd, tmp_bson ("{'foo': 1, 'writeConcern': {'w': 1}}"), true); mongoc_write_concern_destroy (wc); } @@ -55,8 +54,7 @@ test_write_concern_basic (void) ASSERT (write_concern); ASSERT (!mongoc_write_concern_get_fsync (write_concern)); ASSERT (!mongoc_write_concern_get_journal (write_concern)); - ASSERT (mongoc_write_concern_get_w (write_concern) == - MONGOC_WRITE_CONCERN_W_DEFAULT); + ASSERT (mongoc_write_concern_get_w (write_concern) == MONGOC_WRITE_CONCERN_W_DEFAULT); ASSERT (!mongoc_write_concern_get_wtimeout_int64 (write_concern)); ASSERT (!mongoc_write_concern_get_wmajority (write_concern)); @@ -83,11 +81,9 @@ test_write_concern_basic (void) mongoc_write_concern_set_wtimeout (write_concern, 0); ASSERT (!mongoc_write_concern_get_wtimeout (write_concern)); mongoc_write_concern_set_wtimeout_int64 (write_concern, INT64_MAX); - ASSERT (mongoc_write_concern_get_wtimeout_int64 (write_concern) == - INT64_MAX); + ASSERT (mongoc_write_concern_get_wtimeout_int64 (write_concern) == INT64_MAX); mongoc_write_concern_set_w (write_concern, MONGOC_WRITE_CONCERN_W_DEFAULT); - ASSERT (mongoc_write_concern_get_w (write_concern) == - MONGOC_WRITE_CONCERN_W_DEFAULT); + ASSERT (mongoc_write_concern_get_w (write_concern) == MONGOC_WRITE_CONCERN_W_DEFAULT); mongoc_write_concern_set_w (write_concern, 3); ASSERT (mongoc_write_concern_get_w (write_concern) == 3); @@ -99,12 +95,9 @@ test_write_concern_basic (void) bson = _mongoc_write_concern_get_bson (write_concern); ASSERT (bson); - ASSERT (bson_iter_init_find (&iter, bson, "fsync") && - BSON_ITER_HOLDS_BOOL (&iter) && bson_iter_bool (&iter)); - ASSERT (bson_iter_init_find (&iter, bson, "j") && - BSON_ITER_HOLDS_BOOL (&iter) && bson_iter_bool (&iter)); - ASSERT (bson_iter_init_find (&iter, bson, "w") && - BSON_ITER_HOLDS_INT32 (&iter) && bson_iter_int32 (&iter) == 3); + ASSERT (bson_iter_init_find (&iter, bson, "fsync") && BSON_ITER_HOLDS_BOOL (&iter) && bson_iter_bool (&iter)); + ASSERT (bson_iter_init_find (&iter, bson, "j") && BSON_ITER_HOLDS_BOOL (&iter) && bson_iter_bool (&iter)); + ASSERT (bson_iter_init_find (&iter, bson, "w") && BSON_ITER_HOLDS_INT32 (&iter) && bson_iter_int32 (&iter) == 3); mongoc_write_concern_destroy (write_concern); @@ -153,10 +146,8 @@ test_write_concern_bson_includes_false_fsync_and_journal (void) bson = _mongoc_write_concern_get_bson (write_concern); ASSERT (bson); - ASSERT (bson_iter_init_find (&iter, bson, "fsync") && - BSON_ITER_HOLDS_BOOL (&iter) && !bson_iter_bool (&iter)); - ASSERT (bson_iter_init_find (&iter, bson, "j") && - BSON_ITER_HOLDS_BOOL (&iter) && !bson_iter_bool (&iter)); + ASSERT (bson_iter_init_find (&iter, bson, "fsync") && BSON_ITER_HOLDS_BOOL (&iter) && !bson_iter_bool (&iter)); + ASSERT (bson_iter_init_find (&iter, bson, "j") && BSON_ITER_HOLDS_BOOL (&iter) && !bson_iter_bool (&iter)); ASSERT (!bson_iter_init_find (&iter, bson, "w")); mongoc_write_concern_destroy (write_concern); @@ -185,8 +176,7 @@ test_write_concern_fsync_and_journal_w1_and_validity (void) ASSERT (!mongoc_write_concern_journal_is_set (write_concern)); /* w=0 does not need GLE and is valid */ - mongoc_write_concern_set_w (write_concern, - MONGOC_WRITE_CONCERN_W_UNACKNOWLEDGED); + mongoc_write_concern_set_w (write_concern, MONGOC_WRITE_CONCERN_W_UNACKNOWLEDGED); ASSERT (!mongoc_write_concern_is_acknowledged (write_concern)); ASSERT (mongoc_write_concern_is_valid (write_concern)); ASSERT (!mongoc_write_concern_journal_is_set (write_concern)); @@ -206,8 +196,7 @@ test_write_concern_fsync_and_journal_w1_and_validity (void) mongoc_write_concern_set_journal (write_concern, false); /* w=-1 does not need GLE and is valid */ - mongoc_write_concern_set_w (write_concern, - MONGOC_WRITE_CONCERN_W_ERRORS_IGNORED); + mongoc_write_concern_set_w (write_concern, MONGOC_WRITE_CONCERN_W_ERRORS_IGNORED); ASSERT (!mongoc_write_concern_is_acknowledged (write_concern)); ASSERT (mongoc_write_concern_is_valid (write_concern)); ASSERT (mongoc_write_concern_journal_is_set (write_concern)); @@ -250,23 +239,20 @@ test_write_concern_wtimeout_validity (void) /* Test defaults */ ASSERT (write_concern); - ASSERT (mongoc_write_concern_get_w (write_concern) == - MONGOC_WRITE_CONCERN_W_DEFAULT); + ASSERT (mongoc_write_concern_get_w (write_concern) == MONGOC_WRITE_CONCERN_W_DEFAULT); ASSERT (mongoc_write_concern_get_wtimeout_int64 (write_concern) == 0); ASSERT (!mongoc_write_concern_get_wmajority (write_concern)); /* mongoc_write_concern_set_wtimeout_int64() ignores invalid wtimeout */ mongoc_write_concern_set_wtimeout_int64 (write_concern, -1); - ASSERT (mongoc_write_concern_get_w (write_concern) == - MONGOC_WRITE_CONCERN_W_DEFAULT); + ASSERT (mongoc_write_concern_get_w (write_concern) == MONGOC_WRITE_CONCERN_W_DEFAULT); ASSERT (mongoc_write_concern_get_wtimeout_int64 (write_concern) == 0); ASSERT (!mongoc_write_concern_get_wmajority (write_concern)); ASSERT (mongoc_write_concern_is_valid (write_concern)); /* mongoc_write_concern_set_wmajority() ignores invalid wtimeout */ mongoc_write_concern_set_wmajority (write_concern, -1); - ASSERT (mongoc_write_concern_get_w (write_concern) == - MONGOC_WRITE_CONCERN_W_MAJORITY); + ASSERT (mongoc_write_concern_get_w (write_concern) == MONGOC_WRITE_CONCERN_W_MAJORITY); ASSERT (mongoc_write_concern_get_wtimeout_int64 (write_concern) == 0); ASSERT (mongoc_write_concern_get_wmajority (write_concern)); ASSERT (mongoc_write_concern_is_valid (write_concern)); @@ -303,10 +289,7 @@ _test_write_concern_from_iterator (const char *swc, bool ok, bool is_default) mongoc_write_concern_destroy (wc); } else { BSON_ASSERT (!wc); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_COMMAND, - MONGOC_ERROR_COMMAND_INVALID_ARG, - "Invalid writeConcern"); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG, "Invalid writeConcern"); } } @@ -314,76 +297,40 @@ static void test_write_concern_from_iterator (void) { _test_write_concern_from_iterator ("{'writeConcern': {}}", true, true); - _test_write_concern_from_iterator ( - "{'writeConcern': {'w': 'majority'}}", true, false); - _test_write_concern_from_iterator ( - "{'writeConcern': {'w': 'majority', 'j': true}}", true, false); - _test_write_concern_from_iterator ( - "{'writeConcern': {'w': 'sometag'}}", true, false); - _test_write_concern_from_iterator ( - "{'writeConcern': {'w': 'sometag', 'j': true}}", true, false); - _test_write_concern_from_iterator ( - "{'writeConcern': {'w': 'sometag', 'j': false}}", true, false); - _test_write_concern_from_iterator ( - "{'writeConcern': {'w': 1, 'j': true}}", true, false); - _test_write_concern_from_iterator ( - "{'writeConcern': {'w': 1, 'j': false}}", true, false); - _test_write_concern_from_iterator ( - "{'writeConcern': {'w': 0, 'j': true}}", false, false); - _test_write_concern_from_iterator ( - "{'writeConcern': {'w': 0, 'j': false}}", true, false); - _test_write_concern_from_iterator ( - "{'writeConcern': {'w': 42}}", true, false); - _test_write_concern_from_iterator ( - "{'writeConcern': {'w': 1}}", true, false); - _test_write_concern_from_iterator ( - "{'writeConcern': {'j': true}}", true, false); - _test_write_concern_from_iterator ( - "{'writeConcern': {'j': false}}", true, false); - _test_write_concern_from_iterator ( - "{'writeConcern': {'w': -1}}", true, false); - _test_write_concern_from_iterator ( - "{'writeConcern': {'w': -2}}", false, false); - _test_write_concern_from_iterator ( - "{'writeConcern': {'w': -3}}", false, false); - _test_write_concern_from_iterator ( - "{'writeConcern': {'w': -4}}", false, false); - _test_write_concern_from_iterator ( - "{'writeConcern': {'w': -5}}", false, false); - _test_write_concern_from_iterator ( - "{'writeConcern': {'w': 'majority', 'wtimeout': 42}}", true, false); - _test_write_concern_from_iterator ( - "{'writeConcern': {'w': 'sometag', 'wtimeout': 42}}", true, false); - _test_write_concern_from_iterator ( - "{'writeConcern': {'wtimeout': 42}}", true, false); - _test_write_concern_from_iterator ( - "{'writeConcern': {'wtimeout': -42}}", false, false); - _test_write_concern_from_iterator ( - "{'writeConcern': {'wtimeout': {'$numberLong': '123'}}}", true, false); - _test_write_concern_from_iterator ( - "{'writeConcern': {'wtimeout': {'$numberLong': '2147483648'}}}", - true, - false); - _test_write_concern_from_iterator ( - "{'writeConcern': {'w': 1, 'wtimeout': 42}}", true, false); - _test_write_concern_from_iterator ( - "{'writeConcern': {'w': 0, 'wtimeout': 42}}", true, false); - _test_write_concern_from_iterator ( - "{'writeConcern': {'w': 1.0}}", false, false); - _test_write_concern_from_iterator ( - "{'writeConcern': {'w': {'some': 'stuff'}}}", false, false); - _test_write_concern_from_iterator ( - "{'writeConcern': {'w': []}}", false, false); - _test_write_concern_from_iterator ( - "{'writeConcern': {'wtimeout': 'never'}}", false, false); - _test_write_concern_from_iterator ( - "{'writeConcern': {'j': 'never'}}", false, false); - _test_write_concern_from_iterator ( - "{'writeConcern': {'j': 1.0}}", false, false); - _test_write_concern_from_iterator ( - "{'writeConcern': {'fsync': 1.0}}", false, false); - _test_write_concern_from_iterator ( - "{'writeConcern': {'fsync': true}}", true, false); + _test_write_concern_from_iterator ("{'writeConcern': {'w': 'majority'}}", true, false); + _test_write_concern_from_iterator ("{'writeConcern': {'w': 'majority', 'j': true}}", true, false); + _test_write_concern_from_iterator ("{'writeConcern': {'w': 'sometag'}}", true, false); + _test_write_concern_from_iterator ("{'writeConcern': {'w': 'sometag', 'j': true}}", true, false); + _test_write_concern_from_iterator ("{'writeConcern': {'w': 'sometag', 'j': false}}", true, false); + _test_write_concern_from_iterator ("{'writeConcern': {'w': 1, 'j': true}}", true, false); + _test_write_concern_from_iterator ("{'writeConcern': {'w': 1, 'j': false}}", true, false); + _test_write_concern_from_iterator ("{'writeConcern': {'w': 0, 'j': true}}", false, false); + _test_write_concern_from_iterator ("{'writeConcern': {'w': 0, 'j': false}}", true, false); + _test_write_concern_from_iterator ("{'writeConcern': {'w': 42}}", true, false); + _test_write_concern_from_iterator ("{'writeConcern': {'w': 1}}", true, false); + _test_write_concern_from_iterator ("{'writeConcern': {'j': true}}", true, false); + _test_write_concern_from_iterator ("{'writeConcern': {'j': false}}", true, false); + _test_write_concern_from_iterator ("{'writeConcern': {'w': -1}}", true, false); + _test_write_concern_from_iterator ("{'writeConcern': {'w': -2}}", false, false); + _test_write_concern_from_iterator ("{'writeConcern': {'w': -3}}", false, false); + _test_write_concern_from_iterator ("{'writeConcern': {'w': -4}}", false, false); + _test_write_concern_from_iterator ("{'writeConcern': {'w': -5}}", false, false); + _test_write_concern_from_iterator ("{'writeConcern': {'w': 'majority', 'wtimeout': 42}}", true, false); + _test_write_concern_from_iterator ("{'writeConcern': {'w': 'sometag', 'wtimeout': 42}}", true, false); + _test_write_concern_from_iterator ("{'writeConcern': {'wtimeout': 42}}", true, false); + _test_write_concern_from_iterator ("{'writeConcern': {'wtimeout': -42}}", false, false); + _test_write_concern_from_iterator ("{'writeConcern': {'wtimeout': {'$numberLong': '123'}}}", true, false); + _test_write_concern_from_iterator ("{'writeConcern': {'wtimeout': {'$numberLong': '2147483648'}}}", true, false); + _test_write_concern_from_iterator ("{'writeConcern': {'w': 1, 'wtimeout': 42}}", true, false); + _test_write_concern_from_iterator ("{'writeConcern': {'w': 0, 'wtimeout': 42}}", true, false); + _test_write_concern_from_iterator ("{'writeConcern': {'w': 1.0}}", false, false); + _test_write_concern_from_iterator ("{'writeConcern': {'w': {'some': 'stuff'}}}", false, false); + _test_write_concern_from_iterator ("{'writeConcern': {'w': []}}", false, false); + _test_write_concern_from_iterator ("{'writeConcern': {'wtimeout': 'never'}}", false, false); + _test_write_concern_from_iterator ("{'writeConcern': {'j': 'never'}}", false, false); + _test_write_concern_from_iterator ("{'writeConcern': {'j': 1.0}}", false, false); + _test_write_concern_from_iterator ("{'writeConcern': {'fsync': 1.0}}", false, false); + _test_write_concern_from_iterator ("{'writeConcern': {'fsync': true}}", true, false); } @@ -397,30 +344,24 @@ test_write_concern_always_mutable (void) ASSERT (write_concern); mongoc_write_concern_set_fsync (write_concern, true); - ASSERT_MATCH (_mongoc_write_concern_get_bson (write_concern), - "{'fsync': true}"); + ASSERT_MATCH (_mongoc_write_concern_get_bson (write_concern), "{'fsync': true}"); mongoc_write_concern_set_journal (write_concern, true); - ASSERT_MATCH (_mongoc_write_concern_get_bson (write_concern), - "{'fsync': true, 'j': true}"); + ASSERT_MATCH (_mongoc_write_concern_get_bson (write_concern), "{'fsync': true, 'j': true}"); mongoc_write_concern_set_w (write_concern, 2); - ASSERT_MATCH (_mongoc_write_concern_get_bson (write_concern), - "{'w': 2, 'fsync': true, 'j': true}"); + ASSERT_MATCH (_mongoc_write_concern_get_bson (write_concern), "{'w': 2, 'fsync': true, 'j': true}"); mongoc_write_concern_set_wtimeout_int64 (write_concern, 100); - ASSERT_MATCH (_mongoc_write_concern_get_bson (write_concern), - "{'w': 2, 'fsync': true, 'j': true, 'wtimeout': 100}"); + ASSERT_MATCH (_mongoc_write_concern_get_bson (write_concern), "{'w': 2, 'fsync': true, 'j': true, 'wtimeout': 100}"); mongoc_write_concern_set_wmajority (write_concern, 200); - ASSERT_MATCH ( - _mongoc_write_concern_get_bson (write_concern), - "{'w': 'majority', 'fsync': true, 'j': true, 'wtimeout': 200}"); + ASSERT_MATCH (_mongoc_write_concern_get_bson (write_concern), + "{'w': 'majority', 'fsync': true, 'j': true, 'wtimeout': 200}"); mongoc_write_concern_set_wtag (write_concern, "MultipleDC"); - ASSERT_MATCH ( - _mongoc_write_concern_get_bson (write_concern), - "{'w': 'MultipleDC', 'fsync': true, 'j': true, 'wtimeout': 200}"); + ASSERT_MATCH (_mongoc_write_concern_get_bson (write_concern), + "{'w': 'MultipleDC', 'fsync': true, 'j': true, 'wtimeout': 200}"); mongoc_write_concern_destroy (write_concern); } @@ -433,10 +374,7 @@ _test_wc_request (future_t *future, mock_server_t *server, bson_error_t *error) BSON_UNUSED (error); - request = mock_server_receives_msg ( - server, - MONGOC_MSG_NONE, - tmp_bson ("{'$db': 'db', 'writeConcern': {'w': 2}}")); + request = mock_server_receives_msg (server, MONGOC_MSG_NONE, tmp_bson ("{'$db': 'db', 'writeConcern': {'w': 2}}")); reply_to_request_with_ok_and_destroy (request); BSON_ASSERT (future_get_bool (future)); @@ -458,25 +396,19 @@ test_write_concern (void) opts = tmp_bson ("{'writeConcern': {'w': 2}}"); server = mock_server_with_auto_hello (WIRE_VERSION_MIN); mock_server_run (server); - client = - test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); + client = test_framework_client_new_from_uri (mock_server_get_uri (server), NULL); collection = mongoc_client_get_collection (client, "db", "collection"); /* * aggregate with $out */ - cursor = mongoc_collection_aggregate (collection, - MONGOC_QUERY_NONE, - tmp_bson ("[{'$out': 'foo'}]"), - opts, - NULL); + cursor = mongoc_collection_aggregate (collection, MONGOC_QUERY_NONE, tmp_bson ("[{'$out': 'foo'}]"), opts, NULL); ASSERT_OR_PRINT (!mongoc_cursor_error (cursor, &error), error); /* * generic mongoc_client_write_command_with_opts */ - future = future_client_write_command_with_opts ( - client, "db", tmp_bson ("{'foo': 1}"), opts, NULL, &error); + future = future_client_write_command_with_opts (client, "db", tmp_bson ("{'foo': 1}"), opts, NULL, &error); _test_wc_request (future, server, &error); /* @@ -518,8 +450,7 @@ test_write_concern_unacknowledged (void) /* In this insert_one with w:0, we write an OP_MSG on the socket, but don't * read a reply. Before CDRIVER-2902 was fixed, since we forget to set * moreToCome, the server still sends a reply. */ - r = mongoc_collection_insert_one ( - coll, tmp_bson ("{}"), &opts, &reply, &error); + r = mongoc_collection_insert_one (coll, tmp_bson ("{}"), &opts, &reply, &error); ASSERT_OR_PRINT (r, error); ASSERT (bson_empty (&reply)); bson_destroy (&reply); @@ -578,8 +509,7 @@ write_concern_count (const mongoc_apm_command_started_t *event) bson_iter_t iter, iter_rec; if (bson_iter_init (&iter, command)) { - int *sent_collection_w = - (int *) mongoc_apm_command_started_get_context (event); + int *sent_collection_w = (int *) mongoc_apm_command_started_get_context (event); if (bson_iter_find_descendant (&iter, "writeConcern.w", &iter_rec)) { *sent_collection_w = bson_iter_int32 (&iter_rec); } else { @@ -643,8 +573,7 @@ test_write_concern_inheritance_fam_txn (bool in_session, bool in_txn) } mongoc_find_and_modify_opts_set_update (opts, update); - success = mongoc_collection_find_and_modify_with_opts ( - collection, &query, opts, NULL, &error); + success = mongoc_collection_find_and_modify_with_opts (collection, &query, opts, NULL, &error); if (in_txn) { /* check that the sent write concern is not inherited */ @@ -662,14 +591,12 @@ test_write_concern_inheritance_fam_txn (bool in_session, bool in_txn) mongoc_collection_set_write_concern (collection, wc); sent_w = MONGOC_WRITE_CONCERN_W_DEFAULT; - success = mongoc_collection_find_and_modify_with_opts ( - collection, &query, opts, NULL, &error); + success = mongoc_collection_find_and_modify_with_opts (collection, &query, opts, NULL, &error); if (in_txn) { /* check that the sent write concern is not inherited */ BSON_ASSERT (sent_w == MONGOC_WRITE_CONCERN_W_DEFAULT); - success = - mongoc_client_session_commit_transaction (session, NULL, &error); + success = mongoc_client_session_commit_transaction (session, NULL, &error); ASSERT_OR_PRINT (success, error); } else if (!in_session) { /* assert that write concern is inherited */ @@ -720,34 +647,20 @@ test_write_concern_install (TestSuite *suite) { TestSuite_Add (suite, "/WriteConcern/append", test_write_concern_append); TestSuite_Add (suite, "/WriteConcern/basic", test_write_concern_basic); - TestSuite_Add (suite, - "/WriteConcern/bson_omits_defaults", - test_write_concern_bson_omits_defaults); + TestSuite_Add (suite, "/WriteConcern/bson_omits_defaults", test_write_concern_bson_omits_defaults); TestSuite_Add (suite, "/WriteConcern/bson_includes_false_fsync_and_journal", test_write_concern_bson_includes_false_fsync_and_journal); - TestSuite_Add (suite, - "/WriteConcern/fsync_and_journal_gle_and_validity", - test_write_concern_fsync_and_journal_w1_and_validity); - TestSuite_Add (suite, - "/WriteConcern/wtimeout_validity", - test_write_concern_wtimeout_validity); TestSuite_Add ( - suite, "/WriteConcern/from_iterator", test_write_concern_from_iterator); - TestSuite_Add ( - suite, "/WriteConcern/always_mutable", test_write_concern_always_mutable); - TestSuite_Add (suite, - "/WriteConcern/wtimeout_preserved", - test_write_concern_wtimeout_preserved); + suite, "/WriteConcern/fsync_and_journal_gle_and_validity", test_write_concern_fsync_and_journal_w1_and_validity); + TestSuite_Add (suite, "/WriteConcern/wtimeout_validity", test_write_concern_wtimeout_validity); + TestSuite_Add (suite, "/WriteConcern/from_iterator", test_write_concern_from_iterator); + TestSuite_Add (suite, "/WriteConcern/always_mutable", test_write_concern_always_mutable); + TestSuite_Add (suite, "/WriteConcern/wtimeout_preserved", test_write_concern_wtimeout_preserved); TestSuite_AddMockServerTest (suite, "/WriteConcern", test_write_concern); - TestSuite_AddLive ( - suite, "/WriteConcern/unacknowledged", test_write_concern_unacknowledged); - TestSuite_AddFull (suite, - "/WriteConcern/inherited_fam", - test_fam_no_session_no_txn, - NULL, - NULL, - TestSuite_CheckLive); + TestSuite_AddLive (suite, "/WriteConcern/unacknowledged", test_write_concern_unacknowledged); + TestSuite_AddFull ( + suite, "/WriteConcern/inherited_fam", test_fam_no_session_no_txn, NULL, NULL, TestSuite_CheckLive); TestSuite_AddFull (suite, "/WriteConcern/inherited_fam_session_no_txn", test_fam_session_no_txn, diff --git a/src/libmongoc/tests/test-mongoc-x509.c b/src/libmongoc/tests/test-mongoc-x509.c index 0a1c6d36a0..400baffd10 100644 --- a/src/libmongoc/tests/test-mongoc-x509.c +++ b/src/libmongoc/tests/test-mongoc-x509.c @@ -15,14 +15,11 @@ test_extract_subject (void) char *subject; subject = mongoc_ssl_extract_subject (CERT_SERVER, NULL); - ASSERT_CMPSTR ( - subject, - "C=US,ST=New York,L=New York City,O=MongoDB,OU=Drivers,CN=localhost"); + ASSERT_CMPSTR (subject, "C=US,ST=New York,L=New York City,O=MongoDB,OU=Drivers,CN=localhost"); bson_free (subject); subject = mongoc_ssl_extract_subject (CERT_CLIENT, NULL); - ASSERT_CMPSTR ( - subject, "C=US,ST=New York,L=New York City,O=MDB,OU=Drivers,CN=client"); + ASSERT_CMPSTR (subject, "C=US,ST=New York,L=New York City,O=MDB,OU=Drivers,CN=client"); bson_free (subject); } #endif diff --git a/src/libmongoc/tests/test-service-gcp.c b/src/libmongoc/tests/test-service-gcp.c index 29f98cacd9..cad2ddc3f6 100644 --- a/src/libmongoc/tests/test-service-gcp.c +++ b/src/libmongoc/tests/test-service-gcp.c @@ -10,41 +10,24 @@ _test_gcp_parse (void) gcp_service_account_token token; // server output must be json data - ASSERT (!gcp_access_token_try_parse_from_json ( - &token, "invalid json", -1, &error)); + ASSERT (!gcp_access_token_try_parse_from_json (&token, "invalid json", -1, &error)); ASSERT_CMPUINT32 (error.domain, ==, BSON_ERROR_JSON); // server output must contain access_token ASSERT (!gcp_access_token_try_parse_from_json (&token, "{}", -1, &error)); - ASSERT_ERROR_CONTAINS ( - error, MONGOC_ERROR_GCP, MONGOC_ERROR_KMS_SERVER_BAD_JSON, ""); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_GCP, MONGOC_ERROR_KMS_SERVER_BAD_JSON, ""); // server output must contain a value for access_token - ASSERT (!gcp_access_token_try_parse_from_json ( - &token, BSON_STR ({"access_token" : null}), -1, &error)); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_GCP, - MONGOC_ERROR_KMS_SERVER_BAD_JSON, - "One or more required JSON"); + ASSERT (!gcp_access_token_try_parse_from_json (&token, BSON_STR ({"access_token" : null}), -1, &error)); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_GCP, MONGOC_ERROR_KMS_SERVER_BAD_JSON, "One or more required JSON"); // server output must contain token_type - ASSERT (!gcp_access_token_try_parse_from_json ( - &token, BSON_STR ({"access_token" : "helloworld"}), -1, &error)); - ASSERT_ERROR_CONTAINS (error, - MONGOC_ERROR_GCP, - MONGOC_ERROR_KMS_SERVER_BAD_JSON, - "One or more required JSON"); + ASSERT (!gcp_access_token_try_parse_from_json (&token, BSON_STR ({"access_token" : "helloworld"}), -1, &error)); + ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_GCP, MONGOC_ERROR_KMS_SERVER_BAD_JSON, "One or more required JSON"); // can successfully parse JSON datat into a gcp_service_account_token - ASSERT ( - gcp_access_token_try_parse_from_json (&token, - BSON_STR ({ - "access_token" : "helloworld", - "token_type" : "bearer", - "expires_in" : "3788" - }), - -1, - &error)); + ASSERT (gcp_access_token_try_parse_from_json ( + &token, BSON_STR ({"access_token" : "helloworld", "token_type" : "bearer", "expires_in" : "3788"}), -1, &error)); ASSERT_ERROR_CONTAINS (error, 0, 0, ""); ASSERT_CMPSTR (token.access_token, "helloworld"); ASSERT_CMPSTR (token.token_type, "bearer"); @@ -61,14 +44,13 @@ _test_gcp_http_request (void) gcp_request_init (&req, "helloworld.com", 1234, NULL); bson_string_t *req_str = _mongoc_http_render_request_head (&req.req); gcp_request_destroy (&req); - ASSERT_CMPSTR ( - req_str->str, - "GET " - "/computeMetadata/v1/instance/service-accounts/default/token HTTP/1.0\r\n" - "Host: helloworld.com:1234\r\n" - "Connection: close\r\n" - "Metadata-Flavor: Google\r\n" - "\r\n"); + ASSERT_CMPSTR (req_str->str, + "GET " + "/computeMetadata/v1/instance/service-accounts/default/token HTTP/1.0\r\n" + "Host: helloworld.com:1234\r\n" + "Connection: close\r\n" + "Metadata-Flavor: Google\r\n" + "\r\n"); bson_string_free (req_str, true); } @@ -90,14 +72,11 @@ _run_http_test_case (const char *case_, ASSERT_ERROR_CONTAINS (error, 0, 0, ""); gcp_service_account_token token = {0}; - char *const header = - bson_strdup_printf ("X-MongoDB-HTTP-TestParams: case=%s\r\n", case_); - gcp_access_token_from_gcp_server ( - &token, host.host, host.port, header, &error); + char *const header = bson_strdup_printf ("X-MongoDB-HTTP-TestParams: case=%s\r\n", case_); + gcp_access_token_from_gcp_server (&token, host.host, host.port, header, &error); bson_free (header); gcp_access_token_destroy (&token); - ASSERT_ERROR_CONTAINS ( - error, expect_domain, expect_code, expect_error_message); + ASSERT_ERROR_CONTAINS (error, expect_domain, expect_code, expect_error_message); } static void @@ -105,16 +84,11 @@ _test_with_mock_server (void *ctx) { BSON_UNUSED (ctx); _run_http_test_case ("", 0, 0, ""); // (No error) - _run_http_test_case ( - "404", MONGOC_ERROR_GCP, MONGOC_ERROR_KMS_SERVER_HTTP, ""); - _run_http_test_case ( - "slow", MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "Timeout"); - _run_http_test_case ( - "empty-json", MONGOC_ERROR_GCP, MONGOC_ERROR_KMS_SERVER_BAD_JSON, ""); - _run_http_test_case ( - "bad-json", MONGOC_ERROR_CLIENT, MONGOC_ERROR_STREAM_INVALID_TYPE, ""); - _run_http_test_case ( - "giant", MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "too large"); + _run_http_test_case ("404", MONGOC_ERROR_GCP, MONGOC_ERROR_KMS_SERVER_HTTP, ""); + _run_http_test_case ("slow", MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "Timeout"); + _run_http_test_case ("empty-json", MONGOC_ERROR_GCP, MONGOC_ERROR_KMS_SERVER_BAD_JSON, ""); + _run_http_test_case ("bad-json", MONGOC_ERROR_CLIENT, MONGOC_ERROR_STREAM_INVALID_TYPE, ""); + _run_http_test_case ("giant", MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, "too large"); } static int @@ -129,10 +103,5 @@ test_service_gcp_install (TestSuite *suite) { TestSuite_Add (suite, "/gcp/http/parse", _test_gcp_parse); TestSuite_Add (suite, "/gcp/http/request", _test_gcp_http_request); - TestSuite_AddFull (suite, - "/gcp/http/talk", - _test_with_mock_server, - NULL, - NULL, - have_mock_server_env); + TestSuite_AddFull (suite, "/gcp/http/talk", _test_with_mock_server, NULL, NULL, have_mock_server_env); } diff --git a/src/libmongoc/tests/unified/entity-map.c b/src/libmongoc/tests/unified/entity-map.c index 8ffcd35b5c..697ec89f57 100644 --- a/src/libmongoc/tests/unified/entity-map.c +++ b/src/libmongoc/tests/unified/entity-map.c @@ -98,8 +98,7 @@ uri_apply_options (mongoc_uri_t *uri, bson_t *opts, bson_error_t *error) } else if (0 == strcmp ("appname", key)) { mongoc_uri_set_appname (uri, bson_iter_utf8 (&iter, NULL)); } else { - test_set_error ( - error, "Unimplemented test runner support for URI option: %s", key); + test_set_error (error, "Unimplemented test runner support for URI option: %s", key); goto done; } } @@ -179,8 +178,7 @@ should_ignore_event (entity_t *client_entity, event_t *event) } { - observe_event_t *const begin = - (observe_event_t *) client_entity->observe_events.data; + observe_event_t *const begin = (observe_event_t *) client_entity->observe_events.data; observe_event_t *const end = begin + client_entity->observe_events.len; bool is_observed = false; @@ -197,8 +195,7 @@ should_ignore_event (entity_t *client_entity, event_t *event) } } - if (client_entity->observe_sensitive_commands && - *client_entity->observe_sensitive_commands) { + if (client_entity->observe_sensitive_commands && *client_entity->observe_sensitive_commands) { return false; } @@ -233,10 +230,7 @@ typedef struct command_callback_funcs_t { static void -observe_event (entity_t *entity, - command_callback_funcs_t funcs, - const char *type, - const void *apm_command) +observe_event (entity_t *entity, command_callback_funcs_t funcs, const char *type, const void *apm_command) { BSON_ASSERT_PARAM (type); BSON_ASSERT_PARAM (apm_command); @@ -256,8 +250,7 @@ observe_event (entity_t *entity, event->command_name = bson_strdup (funcs.get_command_name (apm_command)); if (funcs.get_database_name) { - event->database_name = - bson_strdup (funcs.get_database_name (apm_command)); + event->database_name = bson_strdup (funcs.get_database_name (apm_command)); } BSON_ASSERT (funcs.get_service_id); @@ -279,45 +272,28 @@ observe_event (entity_t *entity, static void -store_event_serialize_started (bson_t *doc, - const mongoc_apm_command_started_t *apm_command) +store_event_serialize_started (bson_t *doc, const mongoc_apm_command_started_t *apm_command) { // Spec: The test runner MAY omit the command field for CommandStartedEvent // and reply field for CommandSucceededEvent. // BSON_APPEND_DOCUMENT ( // doc, "command", mongoc_apm_command_started_get_command (apm_command)); - BSON_APPEND_UTF8 ( - doc, - "databaseName", - mongoc_apm_command_started_get_database_name (apm_command)); + BSON_APPEND_UTF8 (doc, "databaseName", mongoc_apm_command_started_get_database_name (apm_command)); - BSON_APPEND_UTF8 (doc, - "commandName", - mongoc_apm_command_started_get_command_name (apm_command)); + BSON_APPEND_UTF8 (doc, "commandName", mongoc_apm_command_started_get_command_name (apm_command)); - BSON_APPEND_INT64 (doc, - "requestId", - mongoc_apm_command_started_get_request_id (apm_command)); + BSON_APPEND_INT64 (doc, "requestId", mongoc_apm_command_started_get_request_id (apm_command)); - BSON_APPEND_INT64 ( - doc, - "operationId", - mongoc_apm_command_started_get_operation_id (apm_command)); + BSON_APPEND_INT64 (doc, "operationId", mongoc_apm_command_started_get_operation_id (apm_command)); - BSON_APPEND_UTF8 ( - doc, - "connectionId", - mongoc_apm_command_started_get_host (apm_command)->host_and_port); + BSON_APPEND_UTF8 (doc, "connectionId", mongoc_apm_command_started_get_host (apm_command)->host_and_port); BSON_APPEND_INT64 ( - doc, - "serverConnectionId", - mongoc_apm_command_started_get_server_connection_id_int64 (apm_command)); + doc, "serverConnectionId", mongoc_apm_command_started_get_server_connection_id_int64 (apm_command)); { - const bson_oid_t *const service_id = - mongoc_apm_command_started_get_service_id (apm_command); + const bson_oid_t *const service_id = mongoc_apm_command_started_get_service_id (apm_command); if (service_id) { BSON_APPEND_OID (doc, "serviceId", service_id); @@ -327,15 +303,11 @@ store_event_serialize_started (bson_t *doc, static void -store_event_serialize_failed (bson_t *doc, - const mongoc_apm_command_failed_t *apm_command) +store_event_serialize_failed (bson_t *doc, const mongoc_apm_command_failed_t *apm_command) { - BSON_APPEND_INT64 ( - doc, "duration", mongoc_apm_command_failed_get_duration (apm_command)); + BSON_APPEND_INT64 (doc, "duration", mongoc_apm_command_failed_get_duration (apm_command)); - BSON_APPEND_UTF8 (doc, - "commandName", - mongoc_apm_command_failed_get_command_name (apm_command)); + BSON_APPEND_UTF8 (doc, "commandName", mongoc_apm_command_failed_get_command_name (apm_command)); { bson_error_t error; @@ -343,26 +315,17 @@ store_event_serialize_failed (bson_t *doc, BSON_APPEND_UTF8 (doc, "failure", error.message); } - BSON_APPEND_INT64 ( - doc, "requestId", mongoc_apm_command_failed_get_request_id (apm_command)); + BSON_APPEND_INT64 (doc, "requestId", mongoc_apm_command_failed_get_request_id (apm_command)); - BSON_APPEND_INT64 (doc, - "operationId", - mongoc_apm_command_failed_get_operation_id (apm_command)); + BSON_APPEND_INT64 (doc, "operationId", mongoc_apm_command_failed_get_operation_id (apm_command)); - BSON_APPEND_UTF8 ( - doc, - "connectionId", - mongoc_apm_command_failed_get_host (apm_command)->host_and_port); + BSON_APPEND_UTF8 (doc, "connectionId", mongoc_apm_command_failed_get_host (apm_command)->host_and_port); BSON_APPEND_INT64 ( - doc, - "serverConnectionId", - mongoc_apm_command_failed_get_server_connection_id_int64 (apm_command)); + doc, "serverConnectionId", mongoc_apm_command_failed_get_server_connection_id_int64 (apm_command)); { - const bson_oid_t *const service_id = - mongoc_apm_command_failed_get_service_id (apm_command); + const bson_oid_t *const service_id = mongoc_apm_command_failed_get_service_id (apm_command); if (service_id) { BSON_APPEND_OID (doc, "serviceId", service_id); @@ -372,46 +335,28 @@ store_event_serialize_failed (bson_t *doc, static void -store_event_serialize_succeeded ( - bson_t *doc, const mongoc_apm_command_succeeded_t *apm_command) +store_event_serialize_succeeded (bson_t *doc, const mongoc_apm_command_succeeded_t *apm_command) { - BSON_APPEND_INT64 ( - doc, "duration", mongoc_apm_command_succeeded_get_duration (apm_command)); + BSON_APPEND_INT64 (doc, "duration", mongoc_apm_command_succeeded_get_duration (apm_command)); // Spec: The test runner MAY omit the command field for CommandStartedEvent // and reply field for CommandSucceededEvent. // BSON_APPEND_DOCUMENT ( // doc, "reply", mongoc_apm_command_succeeded_get_reply (apm_command)); - BSON_APPEND_UTF8 ( - doc, - "commandName", - mongoc_apm_command_succeeded_get_command_name (apm_command)); + BSON_APPEND_UTF8 (doc, "commandName", mongoc_apm_command_succeeded_get_command_name (apm_command)); - BSON_APPEND_INT64 ( - doc, - "requestId", - mongoc_apm_command_succeeded_get_request_id (apm_command)); + BSON_APPEND_INT64 (doc, "requestId", mongoc_apm_command_succeeded_get_request_id (apm_command)); - BSON_APPEND_INT64 ( - doc, - "operationId", - mongoc_apm_command_succeeded_get_operation_id (apm_command)); + BSON_APPEND_INT64 (doc, "operationId", mongoc_apm_command_succeeded_get_operation_id (apm_command)); - BSON_APPEND_UTF8 ( - doc, - "connectionId", - mongoc_apm_command_succeeded_get_host (apm_command)->host_and_port); + BSON_APPEND_UTF8 (doc, "connectionId", mongoc_apm_command_succeeded_get_host (apm_command)->host_and_port); BSON_APPEND_INT64 ( - doc, - "serverConnectionId", - mongoc_apm_command_succeeded_get_server_connection_id_int64 ( - apm_command)); + doc, "serverConnectionId", mongoc_apm_command_succeeded_get_server_connection_id_int64 (apm_command)); { - const bson_oid_t *const service_id = - mongoc_apm_command_succeeded_get_service_id (apm_command); + const bson_oid_t *const service_id = mongoc_apm_command_succeeded_get_service_id (apm_command); if (service_id) { BSON_APPEND_OID (doc, "serviceId", service_id); @@ -421,10 +366,7 @@ store_event_serialize_succeeded ( static void -store_event_to_entities (entity_t *entity, - command_callback_funcs_t funcs, - const char *type, - const void *apm_command) +store_event_to_entities (entity_t *entity, command_callback_funcs_t funcs, const char *type, const void *apm_command) { BSON_ASSERT_PARAM (entity); BSON_ASSERT_PARAM (type); @@ -443,8 +385,7 @@ store_event_to_entities (entity_t *entity, for (store_event_t *iter = begin; iter != end; ++iter) { if (bson_strcasecmp (iter->type, type) == 0) { - mongoc_array_t *arr = - entity_map_get_bson_array (em, iter->entity_id, &error); + mongoc_array_t *arr = entity_map_get_bson_array (em, iter->entity_id, &error); ASSERT_OR_PRINT (arr, error); bson_t *doc = bson_new (); @@ -466,9 +407,7 @@ store_event_to_entities (entity_t *entity, static void -apm_command_callback (command_callback_funcs_t funcs, - const char *type, - const void *apm_command) +apm_command_callback (command_callback_funcs_t funcs, const char *type, const void *apm_command) { BSON_ASSERT_PARAM (type); BSON_ASSERT_PARAM (apm_command); @@ -488,19 +427,13 @@ command_started (const mongoc_apm_command_started_t *started) .get_context = (apm_func_void_t) mongoc_apm_command_started_get_context, .get_command = (apm_func_bson_t) mongoc_apm_command_started_get_command, .get_reply = NULL, - .get_command_name = - (apm_func_utf8_t) mongoc_apm_command_started_get_command_name, - .get_database_name = - (apm_func_utf8_t) mongoc_apm_command_started_get_database_name, - .get_request_id = - (apm_func_int64_t) mongoc_apm_command_started_get_request_id, - .get_operation_id = - (apm_func_int64_t) mongoc_apm_command_started_get_operation_id, - .get_service_id = - (apm_func_bson_oid_t) mongoc_apm_command_started_get_service_id, + .get_command_name = (apm_func_utf8_t) mongoc_apm_command_started_get_command_name, + .get_database_name = (apm_func_utf8_t) mongoc_apm_command_started_get_database_name, + .get_request_id = (apm_func_int64_t) mongoc_apm_command_started_get_request_id, + .get_operation_id = (apm_func_int64_t) mongoc_apm_command_started_get_operation_id, + .get_service_id = (apm_func_bson_oid_t) mongoc_apm_command_started_get_service_id, .get_host = (apm_func_host_list_t) mongoc_apm_command_started_get_host, - .get_server_connection_id = (apm_func_int64_t) - mongoc_apm_command_started_get_server_connection_id_int64, + .get_server_connection_id = (apm_func_int64_t) mongoc_apm_command_started_get_server_connection_id_int64, .serialize = (apm_func_serialize_t) store_event_serialize_started, }; @@ -514,18 +447,13 @@ command_failed (const mongoc_apm_command_failed_t *failed) .get_context = (apm_func_void_t) mongoc_apm_command_failed_get_context, .get_command = NULL, .get_reply = (apm_func_bson_t) mongoc_apm_command_failed_get_reply, - .get_command_name = - (apm_func_utf8_t) mongoc_apm_command_failed_get_command_name, + .get_command_name = (apm_func_utf8_t) mongoc_apm_command_failed_get_command_name, .get_database_name = NULL, - .get_request_id = - (apm_func_int64_t) mongoc_apm_command_failed_get_request_id, - .get_operation_id = - (apm_func_int64_t) mongoc_apm_command_failed_get_operation_id, - .get_service_id = - (apm_func_bson_oid_t) mongoc_apm_command_failed_get_service_id, + .get_request_id = (apm_func_int64_t) mongoc_apm_command_failed_get_request_id, + .get_operation_id = (apm_func_int64_t) mongoc_apm_command_failed_get_operation_id, + .get_service_id = (apm_func_bson_oid_t) mongoc_apm_command_failed_get_service_id, .get_host = (apm_func_host_list_t) mongoc_apm_command_failed_get_host, - .get_server_connection_id = (apm_func_int64_t) - mongoc_apm_command_failed_get_server_connection_id_int64, + .get_server_connection_id = (apm_func_int64_t) mongoc_apm_command_failed_get_server_connection_id_int64, .serialize = (apm_func_serialize_t) store_event_serialize_failed, }; @@ -539,18 +467,13 @@ command_succeeded (const mongoc_apm_command_succeeded_t *succeeded) .get_context = (apm_func_void_t) mongoc_apm_command_succeeded_get_context, .get_command = NULL, .get_reply = (apm_func_bson_t) mongoc_apm_command_succeeded_get_reply, - .get_command_name = - (apm_func_utf8_t) mongoc_apm_command_succeeded_get_command_name, + .get_command_name = (apm_func_utf8_t) mongoc_apm_command_succeeded_get_command_name, .get_database_name = NULL, - .get_request_id = - (apm_func_int64_t) mongoc_apm_command_succeeded_get_request_id, - .get_operation_id = - (apm_func_int64_t) mongoc_apm_command_succeeded_get_operation_id, - .get_service_id = - (apm_func_bson_oid_t) mongoc_apm_command_succeeded_get_service_id, + .get_request_id = (apm_func_int64_t) mongoc_apm_command_succeeded_get_request_id, + .get_operation_id = (apm_func_int64_t) mongoc_apm_command_succeeded_get_operation_id, + .get_service_id = (apm_func_bson_oid_t) mongoc_apm_command_succeeded_get_service_id, .get_host = (apm_func_host_list_t) mongoc_apm_command_succeeded_get_host, - .get_server_connection_id = (apm_func_int64_t) - mongoc_apm_command_succeeded_get_server_connection_id_int64, + .get_server_connection_id = (apm_func_int64_t) mongoc_apm_command_succeeded_get_server_connection_id_int64, .serialize = (apm_func_serialize_t) store_event_serialize_succeeded, }; @@ -576,9 +499,7 @@ set_command_callback (mongoc_apm_callbacks_t *callbacks, const char *type) {.type = "commandStartedEvent", .set = (set_func_t) mongoc_apm_set_command_started_cb, .cb = (cb_t) command_started}, - {.type = "commandFailedEvent", - .set = (set_func_t) mongoc_apm_set_command_failed_cb, - .cb = (cb_t) command_failed}, + {.type = "commandFailedEvent", .set = (set_func_t) mongoc_apm_set_command_failed_cb, .cb = (cb_t) command_failed}, {.type = "commandSucceededEvent", .set = (set_func_t) mongoc_apm_set_command_succeeded_cb, .cb = (cb_t) command_succeeded}, @@ -637,131 +558,100 @@ entity_client_new (entity_map_t *em, bson_t *bson, bson_error_t *error) else (error ("A client 'id' string is required")), // Optional 'uriOptions' for the client find (key ("uriOptions"), - if (not(type (doc)), - then (error ("'uriOptions' must be a document value"))), + if (not(type (doc)), then (error ("'uriOptions' must be a document value"))), storeDocDupPtr (uri_options)), // Optional 'useMultipleMongoses' bool find (key ("useMultipleMongoses"), - if (not(type (bool)), - then (error ("'useMultipleMongoses' must be a bool value"))), + if (not(type (bool)), then (error ("'useMultipleMongoses' must be a bool value"))), do (use_multiple_mongoses_set = true), storeBool (use_multiple_mongoses)), // Events to observe: find (key ("observeEvents"), - if (not(type (array)), - then (error ("'observeEvents' must be an array"))), + if (not(type (array)), then (error ("'observeEvents' must be an array"))), visitEach (case ( // Ensure all elements are strings: - when (not(type (utf8)), - error ("Every 'observeEvents' element must be a string")), + when (not(type (utf8)), error ("Every 'observeEvents' element must be a string")), // Dispatch based on the event name: when (anyOf (iStrEqual ("commandStartedEvent"), iStrEqual ("commandFailedEvent"), iStrEqual ("commandSucceededEvent")), do ({ - const char *const type = - bson_iter_utf8 (&bsonVisitIter, NULL); + const char *const type = bson_iter_utf8 (&bsonVisitIter, NULL); set_command_callback (callbacks, type); add_observe_event (entity, type); })), // Unsupported (but known) event names: - when (eval (is_unsupported_event_type ( - bson_iter_utf8 (&bsonVisitIter, NULL))), - do (MONGOC_DEBUG ("Skipping unsupported event type '%s'", - bsonAs (cstr)))), + when (eval (is_unsupported_event_type (bson_iter_utf8 (&bsonVisitIter, NULL))), + do (MONGOC_DEBUG ("Skipping unsupported event type '%s'", bsonAs (cstr)))), // An unknown event name is a hard-error: - else (do ( - test_error ("Unknown event type '%s'", bsonAs (cstr))))))), + else (do (test_error ("Unknown event type '%s'", bsonAs (cstr))))))), // Command events to ignore - find ( - key ("ignoreCommandMonitoringEvents"), - if (not(type (array)), - then (error ("'ignoreCommandMonitoringEvents' must be an array"))), - visitEach (if (not(type (utf8)), - then (error ("Every 'ignoreCommandMonitoringEvents' " - "element must be a string")))), - storeDocDupPtr (entity->ignore_command_monitoring_events)), + find (key ("ignoreCommandMonitoringEvents"), + if (not(type (array)), then (error ("'ignoreCommandMonitoringEvents' must be an array"))), + visitEach (if (not(type (utf8)), + then (error ("Every 'ignoreCommandMonitoringEvents' " + "element must be a string")))), + storeDocDupPtr (entity->ignore_command_monitoring_events)), // Parse the serverApi, if present - find ( - key ("serverApi"), - if (not(type (doc)), then (error ("'serverApi' must be a document"))), - parse ( // The "version" string is required first: - find (keyWithType ("version", utf8), do ({ - mongoc_server_api_version_t ver; - if (!mongoc_server_api_version_from_string (bsonAs (cstr), - &ver)) { - bsonParseError = "Invalid serverApi.version string"; - } else { - api = mongoc_server_api_new (ver); - } - })), - else (error ("Missing 'version' property in 'serverApi' object")), - // Toggle strictness: - find (key ("strict"), - if (not(type (bool)), - then (error ("'serverApi.strict' must be a bool"))), - do (mongoc_server_api_strict (api, bsonAs (bool)))), - // Toggle deprecation errors: - find ( - key ("deprecationErrors"), - if (not(type (bool)), - then (error ("serverApi.deprecationErrors must be a bool"))), - do ( - mongoc_server_api_deprecation_errors (api, bsonAs (bool)))))), + find (key ("serverApi"), + if (not(type (doc)), then (error ("'serverApi' must be a document"))), + parse ( // The "version" string is required first: + find (keyWithType ("version", utf8), do ({ + mongoc_server_api_version_t ver; + if (!mongoc_server_api_version_from_string (bsonAs (cstr), &ver)) { + bsonParseError = "Invalid serverApi.version string"; + } else { + api = mongoc_server_api_new (ver); + } + })), + else (error ("Missing 'version' property in 'serverApi' object")), + // Toggle strictness: + find (key ("strict"), + if (not(type (bool)), then (error ("'serverApi.strict' must be a bool"))), + do (mongoc_server_api_strict (api, bsonAs (bool)))), + // Toggle deprecation errors: + find (key ("deprecationErrors"), + if (not(type (bool)), then (error ("serverApi.deprecationErrors must be a bool"))), + do (mongoc_server_api_deprecation_errors (api, bsonAs (bool)))))), // Toggle observation of sensitive commands find (key ("observeSensitiveCommands"), - if (not(type (bool)), - then (error ("'observeSensitiveCommands' must be a bool"))), + if (not(type (bool)), then (error ("'observeSensitiveCommands' must be a bool"))), do ({ - bool *p = entity->observe_sensitive_commands = - bson_malloc (sizeof (bool)); + bool *p = entity->observe_sensitive_commands = bson_malloc (sizeof (bool)); *p = bsonAs (bool); })), // Which events should be available as entities: - find ( - key ("storeEventsAsEntities"), - if (not(type (array)), - then (error ("'storeEventsAsEntities' must be an array"))), - visitEach (parse ( - find (keyWithType ("id", utf8), storeStrRef (store_entity_id), do ({ - if (!entity_map_add_bson_array ( - em, store_entity_id, error)) { - test_error ("failed to create storeEventsAsEntities " - "entity '%s': %s", - store_entity_id, - error->message); - } - })), - find (keyWithType ("events", array), - visitEach (case ( - when (not(type (utf8)), - error ("Every 'storeEventsAsEntities.events' " - "element must be a string")), - when (anyOf (iStrEqual ("commandStartedEvent"), - iStrEqual ("commandFailedEvent"), - iStrEqual ("commandSucceededEvent")), - do ({ - const char *const type = - bson_iter_utf8 (&bsonVisitIter, NULL); - set_command_callback (callbacks, type); - add_store_event (entity, type, store_entity_id); - })), - when (eval (is_unsupported_event_type ( - bson_iter_utf8 (&bsonVisitIter, NULL))), - do (MONGOC_DEBUG ( - "Skipping unsupported event type '%s'", - bsonAs (cstr)))), - else (do (test_error ("Unknown event type '%s'", - bsonAs (cstr))))))), - visitOthers ( - errorf (err, - "Unexpected field '%s' in storeEventsAsEntities", - bson_iter_key (&bsonVisitIter)))))), - visitOthers (dupPath (errpath), - errorf (err, - "At [%s]: Unknown key '%s' given in entity options", - errpath, - bson_iter_key (&bsonVisitIter)))); + find (key ("storeEventsAsEntities"), + if (not(type (array)), then (error ("'storeEventsAsEntities' must be an array"))), + visitEach (parse ( + find (keyWithType ("id", utf8), storeStrRef (store_entity_id), do ({ + if (!entity_map_add_bson_array (em, store_entity_id, error)) { + test_error ("failed to create storeEventsAsEntities " + "entity '%s': %s", + store_entity_id, + error->message); + } + })), + find (keyWithType ("events", array), + visitEach (case (when (not(type (utf8)), + error ("Every 'storeEventsAsEntities.events' " + "element must be a string")), + when (anyOf (iStrEqual ("commandStartedEvent"), + iStrEqual ("commandFailedEvent"), + iStrEqual ("commandSucceededEvent")), + do ({ + const char *const type = bson_iter_utf8 (&bsonVisitIter, NULL); + set_command_callback (callbacks, type); + add_store_event (entity, type, store_entity_id); + })), + when (eval (is_unsupported_event_type (bson_iter_utf8 (&bsonVisitIter, NULL))), + do (MONGOC_DEBUG ("Skipping unsupported event type '%s'", bsonAs (cstr)))), + else (do (test_error ("Unknown event type '%s'", bsonAs (cstr))))))), + visitOthers ( + errorf (err, "Unexpected field '%s' in storeEventsAsEntities", bson_iter_key (&bsonVisitIter)))))), + visitOthers ( + dupPath (errpath), + errorf (err, "At [%s]: Unknown key '%s' given in entity options", errpath, bson_iter_key (&bsonVisitIter)))); if (bsonParseError) { test_error ("Error while parsing entity object: %s", bsonParseError); @@ -786,8 +676,7 @@ entity_client_new (entity_map_t *em, bson_t *bson, bson_error_t *error) uri = test_framework_get_uri_multi_mongos_loadbalanced (); } } else if (use_multiple_mongoses_set) { - if (!test_framework_uri_apply_multi_mongos ( - uri, use_multiple_mongoses, error)) { + if (!test_framework_uri_apply_multi_mongos (uri, use_multiple_mongoses, error)) { goto done; } } @@ -804,8 +693,7 @@ entity_client_new (entity_map_t *em, bson_t *bson, bson_error_t *error) } if (can_reduce_heartbeat && em->reduced_heartbeat) { - mongoc_uri_set_option_as_int32 ( - uri, MONGOC_URI_HEARTBEATFREQUENCYMS, REDUCED_HEARTBEAT_FREQUENCY_MS); + mongoc_uri_set_option_as_int32 (uri, MONGOC_URI_HEARTBEATFREQUENCYMS, REDUCED_HEARTBEAT_FREQUENCY_MS); } client = test_framework_client_new_from_uri (uri, api); @@ -815,8 +703,7 @@ entity_client_new (entity_map_t *em, bson_t *bson, bson_error_t *error) mongoc_client_set_apm_callbacks (client, callbacks, entity); if (can_reduce_heartbeat && em->reduced_heartbeat) { - client->topology->min_heartbeat_frequency_msec = - REDUCED_MIN_HEARTBEAT_FREQUENCY_MS; + client->topology->min_heartbeat_frequency_msec = REDUCED_MIN_HEARTBEAT_FREQUENCY_MS; } ret = true; @@ -840,19 +727,15 @@ _entity_client_encryption_getenv (const char *name, bson_error_t *error) BSON_ASSERT_PARAM (name); if (!(res = _mongoc_getenv (name))) { - test_set_error ( - error, "missing required environment variable '%s'", name); + test_set_error (error, "missing required environment variable '%s'", name); } return res; } static bool -_append_kms_provider_value_or_getenv (bson_t *bson, - const char *key, - const char *value, - const char *env_name, - bson_error_t *error) +_append_kms_provider_value_or_getenv ( + bson_t *bson, const char *key, const char *value, const char *env_name, bson_error_t *error) { BSON_ASSERT_PARAM (bson); BSON_ASSERT_PARAM (env_name); @@ -890,8 +773,7 @@ _validate_string_or_placeholder (const bson_iter_t *iter, bson_error_t *error) /* Otherwise, must be a document with a single '$$placeholder' field. */ if (BSON_ITER_HOLDS_DOCUMENT (iter)) { bson_val_t *const bson_val = bson_val_from_iter (iter); - bson_val_t *const expected = - bson_val_from_json ("{'$$placeholder': { '$exists': true }}"); + bson_val_t *const expected = bson_val_from_json ("{'$$placeholder': { '$exists': true }}"); bool is_match = false; BSON_ASSERT (bson_val); @@ -913,11 +795,8 @@ _validate_string_or_placeholder (const bson_iter_t *iter, bson_error_t *error) } static bool -_parse_kms_provider_aws (bson_t *kms_providers, - bson_t *tls_opts, - const char *provider, - bson_t *kms_doc, - bson_error_t *error) +_parse_kms_provider_aws ( + bson_t *kms_providers, bson_t *tls_opts, const char *provider, bson_t *kms_doc, bson_error_t *error) { bson_t child; bson_iter_t iter; @@ -940,8 +819,7 @@ _parse_kms_provider_aws (bson_t *kms_providers, if (0 == strcmp (provider, "aws:name2")) { envvar = "MONGOC_TEST_AWSNAME2_ACCESS_KEY_ID"; } - if (!_append_kms_provider_value_or_getenv ( - &child, key, value, envvar, error)) { + if (!_append_kms_provider_value_or_getenv (&child, key, value, envvar, error)) { return false; } } else if (strcmp (key, "secretAccessKey") == 0) { @@ -949,8 +827,7 @@ _parse_kms_provider_aws (bson_t *kms_providers, if (0 == strcmp (provider, "aws:name2")) { envvar = "MONGOC_TEST_AWSNAME2_SECRET_ACCESS_KEY"; } - if (!_append_kms_provider_value_or_getenv ( - &child, key, value, envvar, error)) { + if (!_append_kms_provider_value_or_getenv (&child, key, value, envvar, error)) { return false; } } else { @@ -965,11 +842,8 @@ _parse_kms_provider_aws (bson_t *kms_providers, } static bool -_parse_kms_provider_azure (bson_t *kms_providers, - bson_t *tls_opts, - const char *provider, - bson_t *kms_doc, - bson_error_t *error) +_parse_kms_provider_azure ( + bson_t *kms_providers, bson_t *tls_opts, const char *provider, bson_t *kms_doc, bson_error_t *error) { bson_t child; bson_iter_t iter; @@ -988,18 +862,15 @@ _parse_kms_provider_azure (bson_t *kms_providers, } if (strcmp (key, "tenantId") == 0) { - if (!_append_kms_provider_value_or_getenv ( - &child, key, value, "MONGOC_TEST_AZURE_TENANT_ID", error)) { + if (!_append_kms_provider_value_or_getenv (&child, key, value, "MONGOC_TEST_AZURE_TENANT_ID", error)) { return false; } } else if (strcmp (key, "clientId") == 0) { - if (!_append_kms_provider_value_or_getenv ( - &child, key, value, "MONGOC_TEST_AZURE_CLIENT_ID", error)) { + if (!_append_kms_provider_value_or_getenv (&child, key, value, "MONGOC_TEST_AZURE_CLIENT_ID", error)) { return false; } } else if (strcmp (key, "clientSecret") == 0) { - if (!_append_kms_provider_value_or_getenv ( - &child, key, value, "MONGOC_TEST_AZURE_CLIENT_SECRET", error)) { + if (!_append_kms_provider_value_or_getenv (&child, key, value, "MONGOC_TEST_AZURE_CLIENT_SECRET", error)) { return false; } } else { @@ -1014,11 +885,8 @@ _parse_kms_provider_azure (bson_t *kms_providers, } static bool -_parse_kms_provider_gcp (bson_t *kms_providers, - bson_t *tls_opts, - const char *provider, - bson_t *kms_doc, - bson_error_t *error) +_parse_kms_provider_gcp ( + bson_t *kms_providers, bson_t *tls_opts, const char *provider, bson_t *kms_doc, bson_error_t *error) { bson_t child; bson_iter_t iter; @@ -1037,13 +905,11 @@ _parse_kms_provider_gcp (bson_t *kms_providers, } if (strcmp (key, "email") == 0) { - if (!_append_kms_provider_value_or_getenv ( - &child, key, value, "MONGOC_TEST_GCP_EMAIL", error)) { + if (!_append_kms_provider_value_or_getenv (&child, key, value, "MONGOC_TEST_GCP_EMAIL", error)) { return false; } } else if (strcmp (key, "privateKey") == 0) { - if (!_append_kms_provider_value_or_getenv ( - &child, key, value, "MONGOC_TEST_GCP_PRIVATEKEY", error)) { + if (!_append_kms_provider_value_or_getenv (&child, key, value, "MONGOC_TEST_GCP_PRIVATEKEY", error)) { return false; } } else if (strcmp (key, "endpoint") == 0) { @@ -1062,11 +928,8 @@ _parse_kms_provider_gcp (bson_t *kms_providers, } static bool -_parse_kms_provider_kmip (bson_t *kms_providers, - bson_t *tls_opts, - const char *provider, - bson_t *kms_doc, - bson_error_t *error) +_parse_kms_provider_kmip ( + bson_t *kms_providers, bson_t *tls_opts, const char *provider, bson_t *kms_doc, bson_error_t *error) { bson_t child; bson_iter_t iter; @@ -1093,22 +956,13 @@ _parse_kms_provider_kmip (bson_t *kms_providers, /* Configure tlsOptions to enable KMIP TLS connections. */ { bson_t tls_child; - BSON_ASSERT ( - BSON_APPEND_DOCUMENT_BEGIN (tls_opts, provider, &tls_child)); + BSON_ASSERT (BSON_APPEND_DOCUMENT_BEGIN (tls_opts, provider, &tls_child)); if (!_append_kms_provider_value_or_getenv ( - &tls_child, - "tlsCAFile", - NULL, - "MONGOC_TEST_CSFLE_TLS_CA_FILE", - error)) { + &tls_child, "tlsCAFile", NULL, "MONGOC_TEST_CSFLE_TLS_CA_FILE", error)) { return false; } if (!_append_kms_provider_value_or_getenv ( - &tls_child, - "tlsCertificateKeyFile", - NULL, - "MONGOC_TEST_CSFLE_TLS_CERTIFICATE_KEY_FILE", - error)) { + &tls_child, "tlsCertificateKeyFile", NULL, "MONGOC_TEST_CSFLE_TLS_CERTIFICATE_KEY_FILE", error)) { return false; } BSON_ASSERT (bson_append_document_end (tls_opts, &tls_child)); @@ -1125,11 +979,8 @@ _parse_kms_provider_kmip (bson_t *kms_providers, } static bool -_parse_kms_provider_local (bson_t *kms_providers, - bson_t *tls_opts, - const char *provider, - bson_t *kms_doc, - bson_error_t *error) +_parse_kms_provider_local ( + bson_t *kms_providers, bson_t *tls_opts, const char *provider, bson_t *kms_doc, bson_error_t *error) { bson_t child; bson_iter_t iter; @@ -1153,14 +1004,11 @@ _parse_kms_provider_local (bson_t *kms_providers, } else { /* LOCAL_MASTERKEY in base64 encoding as defined in Client Side * Encryption Tests spec. */ - const char local_masterkey[] = - "Mng0NCt4ZHVUYUJCa1kxNkVyNUR1QURhZ2h2UzR2d2RrZzh0cFBwM3R6N" - "mdWMDFBMUN3YkQ5aXRRMkhGRGdQV09wOGVNYUMxT2k3NjZKelhaQmRCZG" - "JkTXVyZG9uSjFk"; + const char local_masterkey[] = "Mng0NCt4ZHVUYUJCa1kxNkVyNUR1QURhZ2h2UzR2d2RrZzh0cFBwM3R6N" + "mdWMDFBMUN3YkQ5aXRRMkhGRGdQV09wOGVNYUMxT2k3NjZKelhaQmRCZG" + "JkTXVyZG9uSjFk"; uint8_t data[96]; - BSON_ASSERT (mcommon_b64_pton (local_masterkey, - data, - sizeof (local_masterkey)) == 96); + BSON_ASSERT (mcommon_b64_pton (local_masterkey, data, sizeof (local_masterkey)) == 96); BSON_APPEND_BINARY (&child, "key", BSON_SUBTYPE_BINARY, data, 96); } } else { @@ -1175,33 +1023,27 @@ _parse_kms_provider_local (bson_t *kms_providers, } static bool -_parse_and_set_kms_providers (mongoc_client_encryption_opts_t *ce_opts, - bson_t *kms_from_file, - bson_error_t *error) +_parse_and_set_kms_providers (mongoc_client_encryption_opts_t *ce_opts, bson_t *kms_from_file, bson_error_t *error) { /* Map provider to corresponding KMS parser. */ typedef struct _prov_map_t { const char *provider; - bool (*parse) (bson_t *kms_providers, - bson_t *tls_opts, - const char *provider, - bson_t *kms_doc, - bson_error_t *error); + bool (*parse) ( + bson_t *kms_providers, bson_t *tls_opts, const char *provider, bson_t *kms_doc, bson_error_t *error); } prov_map_t; - const prov_map_t prov_map[] = { - {.provider = "aws", .parse = _parse_kms_provider_aws}, - {.provider = "aws:name1", .parse = _parse_kms_provider_aws}, - {.provider = "aws:name2", .parse = _parse_kms_provider_aws}, - {.provider = "azure", .parse = _parse_kms_provider_azure}, - {.provider = "azure:name1", .parse = _parse_kms_provider_azure}, - {.provider = "gcp", .parse = _parse_kms_provider_gcp}, - {.provider = "gcp:name1", .parse = _parse_kms_provider_gcp}, - {.provider = "kmip", .parse = _parse_kms_provider_kmip}, - {.provider = "kmip:name1", .parse = _parse_kms_provider_kmip}, - {.provider = "local", .parse = _parse_kms_provider_local}, - {.provider = "local:name1", .parse = _parse_kms_provider_local}, - {.provider = "local:name2", .parse = _parse_kms_provider_local}}; + const prov_map_t prov_map[] = {{.provider = "aws", .parse = _parse_kms_provider_aws}, + {.provider = "aws:name1", .parse = _parse_kms_provider_aws}, + {.provider = "aws:name2", .parse = _parse_kms_provider_aws}, + {.provider = "azure", .parse = _parse_kms_provider_azure}, + {.provider = "azure:name1", .parse = _parse_kms_provider_azure}, + {.provider = "gcp", .parse = _parse_kms_provider_gcp}, + {.provider = "gcp:name1", .parse = _parse_kms_provider_gcp}, + {.provider = "kmip", .parse = _parse_kms_provider_kmip}, + {.provider = "kmip:name1", .parse = _parse_kms_provider_kmip}, + {.provider = "local", .parse = _parse_kms_provider_local}, + {.provider = "local:name1", .parse = _parse_kms_provider_local}, + {.provider = "local:name2", .parse = _parse_kms_provider_local}}; const size_t prov_map_size = sizeof (prov_map) / sizeof (prov_map[0]); @@ -1218,15 +1060,13 @@ _parse_and_set_kms_providers (mongoc_client_encryption_opts_t *ce_opts, bool found = false; if (!bson_init_from_value (&kms_doc, bson_iter_value (&iter))) { - test_set_error ( - error, "kmsProviders field '%s' is not a valid document", provider); + test_set_error (error, "kmsProviders field '%s' is not a valid document", provider); goto done; } for (i = 0u; i < prov_map_size; ++i) { if (strcmp (provider, prov_map[i].provider) == 0) { - found = prov_map[i].parse ( - &kms_providers, &tls_opts, provider, &kms_doc, error); + found = prov_map[i].parse (&kms_providers, &tls_opts, provider, &kms_doc, error); goto parsed; } } @@ -1254,14 +1094,11 @@ _parse_and_set_kms_providers (mongoc_client_encryption_opts_t *ce_opts, } entity_t * -entity_client_encryption_new (entity_map_t *entity_map, - bson_t *bson, - bson_error_t *error) +entity_client_encryption_new (entity_map_t *entity_map, bson_t *bson, bson_error_t *error) { entity_t *const entity = entity_new (entity_map, "clientEncryption"); bson_parser_t *const parser = bson_parser_new (); - mongoc_client_encryption_opts_t *const ce_opts = - mongoc_client_encryption_opts_new (); + mongoc_client_encryption_opts_t *const ce_opts = mongoc_client_encryption_opts_new (); bson_t *ce_opts_bson = NULL; @@ -1289,8 +1126,7 @@ entity_client_encryption_new (entity_map_t *entity_map, } { - entity_t *const client_entity = - entity_map_get (entity_map, client_id, error); + entity_t *const client_entity = entity_map_get (entity_map, client_id, error); mongoc_client_t *client = NULL; if (!client_entity) { @@ -1308,8 +1144,7 @@ entity_client_encryption_new (entity_map_t *entity_map, const char *coll = NULL; if (!dot) { - test_set_error ( - error, "keyVaultNamespace does not have required dot separator"); + test_set_error (error, "keyVaultNamespace does not have required dot separator"); goto ce_opts_done; } @@ -1318,13 +1153,11 @@ entity_client_encryption_new (entity_map_t *entity_map, coll = dot + 1; /* "datakeys" */ if (strchr (coll, '.') != NULL) { - test_set_error ( - error, "keyVaultNamespace contains more than one dot separator"); + test_set_error (error, "keyVaultNamespace contains more than one dot separator"); goto ce_opts_done; } - mongoc_client_encryption_opts_set_keyvault_namespace ( - ce_opts, db, coll); + mongoc_client_encryption_opts_set_keyvault_namespace (ce_opts, db, coll); } if (!_parse_and_set_kms_providers (ce_opts, kms, error)) { @@ -1401,9 +1234,7 @@ coll_or_db_opts_parse (coll_or_db_opts_t *opts, bson_t *in, bson_error_t *error) } entity_t * -entity_database_new (entity_map_t *entity_map, - bson_t *bson, - bson_error_t *error) +entity_database_new (entity_map_t *entity_map, bson_t *bson, bson_error_t *error) { bson_parser_t *parser = NULL; entity_t *entity = NULL; @@ -1467,9 +1298,7 @@ entity_database_new (entity_map_t *entity_map, } entity_t * -entity_collection_new (entity_map_t *entity_map, - bson_t *bson, - bson_error_t *error) +entity_collection_new (entity_map_t *entity_map, bson_t *bson, bson_error_t *error) { bson_parser_t *parser = NULL; entity_t *entity = NULL; @@ -1546,8 +1375,7 @@ session_opts_new (bson_t *bson, bson_error_t *error) bp = bson_parser_new (); bson_parser_bool_optional (bp, "causalConsistency", &causal_consistency); bson_parser_bool_optional (bp, "snapshot", &snapshot); - bson_parser_doc_optional ( - bp, "defaultTransactionOptions", &default_transaction_opts); + bson_parser_doc_optional (bp, "defaultTransactionOptions", &default_transaction_opts); if (!bson_parser_parse (bp, bson, error)) { goto done; } @@ -1699,8 +1527,7 @@ entity_bucket_new (entity_map_t *entity_map, bson_t *bson, bson_error_t *error) mongoc_write_concern_append (wc, opts); } - entity->value = - mongoc_gridfs_bucket_new (database, opts, NULL /* read prefs */, error); + entity->value = mongoc_gridfs_bucket_new (database, opts, NULL /* read prefs */, error); if (!entity->value) { goto done; } @@ -1751,10 +1578,7 @@ entity_map_create (entity_map_t *entity_map, bson_t *bson, bson_error_t *error) entity_type = bson_iter_key (&iter); bson_iter_bson (&iter, &entity_bson); if (bson_iter_next (&iter)) { - test_set_error (error, - "Extra field in entity: %s: %s", - bson_iter_key (&iter), - tmp_json (bson)); + test_set_error (error, "Extra field in entity: %s: %s", bson_iter_key (&iter), tmp_json (bson)); goto done; } @@ -1771,8 +1595,7 @@ entity_map_create (entity_map_t *entity_map, bson_t *bson, bson_error_t *error) } else if (0 == strcmp (entity_type, "bucket")) { entity = entity_bucket_new (entity_map, &entity_bson, error); } else { - test_set_error ( - error, "Unknown entity type: %s: %s", entity_type, tmp_json (bson)); + test_set_error (error, "Unknown entity type: %s: %s", entity_type, tmp_json (bson)); goto done; } @@ -1783,8 +1606,7 @@ entity_map_create (entity_map_t *entity_map, bson_t *bson, bson_error_t *error) LL_FOREACH (entity_map->entities, entity_iter) { if (0 == strcmp (entity_iter->id, entity->id)) { - test_set_error ( - error, "Attempting to create duplicate entity: '%s'", entity->id); + test_set_error (error, "Attempting to create duplicate entity: '%s'", entity->id); entity_destroy (entity); goto done; } @@ -1871,9 +1693,7 @@ entity_destroy (entity_t *entity) bson_free (v); } else { - test_error ("Attempting to destroy unrecognized entity type: %s, id: %s", - entity->type, - entity->id); + test_error ("Attempting to destroy unrecognized entity type: %s, id: %s", entity->type, entity->id); } LL_FOREACH_SAFE (entity->events, event, tmp) @@ -1922,10 +1742,7 @@ entity_map_delete (entity_map_t *em, const char *id, bson_error_t *error) } static entity_t * -_entity_map_get_by_type (entity_map_t *entity_map, - const char *id, - const char *type, - bson_error_t *error) +_entity_map_get_by_type (entity_map_t *entity_map, const char *id, const char *type, bson_error_t *error) { entity_t *entity = NULL; @@ -1935,19 +1752,14 @@ _entity_map_get_by_type (entity_map_t *entity_map, } if (0 != strcmp (entity->type, type)) { - test_set_error (error, - "Unexpected entity type. Expected: %s, got %s", - type, - entity->type); + test_set_error (error, "Unexpected entity type. Expected: %s, got %s", type, entity->type); return NULL; } return entity; } mongoc_client_t * -entity_map_get_client (entity_map_t *entity_map, - const char *id, - bson_error_t *error) +entity_map_get_client (entity_map_t *entity_map, const char *id, bson_error_t *error) { entity_t *entity = _entity_map_get_by_type (entity_map, id, "client", error); if (!entity) { @@ -1957,12 +1769,9 @@ entity_map_get_client (entity_map_t *entity_map, } mongoc_client_encryption_t * -entity_map_get_client_encryption (entity_map_t *entity_map, - const char *id, - bson_error_t *error) +entity_map_get_client_encryption (entity_map_t *entity_map, const char *id, bson_error_t *error) { - entity_t *entity = - _entity_map_get_by_type (entity_map, id, "clientEncryption", error); + entity_t *entity = _entity_map_get_by_type (entity_map, id, "clientEncryption", error); if (!entity) { return NULL; } @@ -1970,12 +1779,9 @@ entity_map_get_client_encryption (entity_map_t *entity_map, } mongoc_database_t * -entity_map_get_database (entity_map_t *entity_map, - const char *id, - bson_error_t *error) +entity_map_get_database (entity_map_t *entity_map, const char *id, bson_error_t *error) { - entity_t *entity = - _entity_map_get_by_type (entity_map, id, "database", error); + entity_t *entity = _entity_map_get_by_type (entity_map, id, "database", error); if (!entity) { return NULL; } @@ -1983,12 +1789,9 @@ entity_map_get_database (entity_map_t *entity_map, } mongoc_collection_t * -entity_map_get_collection (entity_map_t *entity_map, - const char *id, - bson_error_t *error) +entity_map_get_collection (entity_map_t *entity_map, const char *id, bson_error_t *error) { - entity_t *entity = - _entity_map_get_by_type (entity_map, id, "collection", error); + entity_t *entity = _entity_map_get_by_type (entity_map, id, "collection", error); if (!entity) { return NULL; } @@ -1996,12 +1799,9 @@ entity_map_get_collection (entity_map_t *entity_map, } mongoc_change_stream_t * -entity_map_get_changestream (entity_map_t *entity_map, - const char *id, - bson_error_t *error) +entity_map_get_changestream (entity_map_t *entity_map, const char *id, bson_error_t *error) { - entity_t *entity = - _entity_map_get_by_type (entity_map, id, "changestream", error); + entity_t *entity = _entity_map_get_by_type (entity_map, id, "changestream", error); if (!entity) { return NULL; } @@ -2009,12 +1809,9 @@ entity_map_get_changestream (entity_map_t *entity_map, } entity_findcursor_t * -entity_map_get_findcursor (entity_map_t *entity_map, - const char *id, - bson_error_t *error) +entity_map_get_findcursor (entity_map_t *entity_map, const char *id, bson_error_t *error) { - entity_t *entity = - _entity_map_get_by_type (entity_map, id, "findcursor", error); + entity_t *entity = _entity_map_get_by_type (entity_map, id, "findcursor", error); if (!entity) { return NULL; } @@ -2022,9 +1819,7 @@ entity_map_get_findcursor (entity_map_t *entity_map, } bson_val_t * -entity_map_get_bson (entity_map_t *entity_map, - const char *id, - bson_error_t *error) +entity_map_get_bson (entity_map_t *entity_map, const char *id, bson_error_t *error) { entity_t *entity = _entity_map_get_by_type (entity_map, id, "bson", error); if (!entity) { @@ -2034,12 +1829,9 @@ entity_map_get_bson (entity_map_t *entity_map, } mongoc_array_t * -entity_map_get_bson_array (entity_map_t *entity_map, - const char *id, - bson_error_t *error) +entity_map_get_bson_array (entity_map_t *entity_map, const char *id, bson_error_t *error) { - entity_t *entity = - _entity_map_get_by_type (entity_map, id, "bson_array", error); + entity_t *entity = _entity_map_get_by_type (entity_map, id, "bson_array", error); if (!entity) { return NULL; } @@ -2047,9 +1839,7 @@ entity_map_get_bson_array (entity_map_t *entity_map, } size_t * -entity_map_get_size_t (entity_map_t *entity_map, - const char *id, - bson_error_t *error) +entity_map_get_size_t (entity_map_t *entity_map, const char *id, bson_error_t *error) { entity_t *entity = _entity_map_get_by_type (entity_map, id, "size_t", error); if (!entity) { @@ -2059,20 +1849,14 @@ entity_map_get_size_t (entity_map_t *entity_map, } mongoc_client_session_t * -entity_map_get_session (entity_map_t *entity_map, - const char *id, - bson_error_t *error) +entity_map_get_session (entity_map_t *entity_map, const char *id, bson_error_t *error) { - entity_t *entity = - _entity_map_get_by_type (entity_map, id, "session", error); + entity_t *entity = _entity_map_get_by_type (entity_map, id, "session", error); if (!entity) { return NULL; } if (!entity->value) { - test_set_error ( - error, - "entity: %s is an ended session that is no longer valid to use", - id); + test_set_error (error, "entity: %s is an ended session that is no longer valid to use", id); return NULL; } return (mongoc_client_session_t *) entity->value; @@ -2088,19 +1872,14 @@ entity_map_get_lsid (entity_map_t *em, char *session_id, bson_error_t *error) return NULL; } if (!entity->lsid) { - test_set_error (error, - "entity %s of type %s does not have an lsid", - session_id, - entity->type); + test_set_error (error, "entity %s of type %s does not have an lsid", session_id, entity->type); return NULL; } return entity->lsid; } mongoc_gridfs_bucket_t * -entity_map_get_bucket (entity_map_t *entity_map, - const char *id, - bson_error_t *error) +entity_map_get_bucket (entity_map_t *entity_map, const char *id, bson_error_t *error) { entity_t *entity = _entity_map_get_by_type (entity_map, id, "bucket", error); if (!entity) { @@ -2110,11 +1889,7 @@ entity_map_get_bucket (entity_map_t *entity_map, } static bool -_entity_map_add (entity_map_t *em, - const char *id, - const char *type, - void *value, - bson_error_t *error) +_entity_map_add (entity_map_t *em, const char *id, const char *type, void *value, bson_error_t *error) { bson_error_t tmperr; entity_t *entity = NULL; @@ -2137,16 +1912,14 @@ entity_map_add_changestream (entity_map_t *em, mongoc_change_stream_t *changestream, bson_error_t *error) { - return _entity_map_add ( - em, id, "changestream", (void *) changestream, error); + return _entity_map_add (em, id, "changestream", (void *) changestream, error); } void -entity_findcursor_iterate_until_document_or_error ( - entity_findcursor_t *findcursor, - const bson_t **document, - bson_error_t *error, - const bson_t **error_document) +entity_findcursor_iterate_until_document_or_error (entity_findcursor_t *findcursor, + const bson_t **document, + bson_error_t *error, + const bson_t **error_document) { *document = NULL; @@ -2157,42 +1930,32 @@ entity_findcursor_iterate_until_document_or_error ( } while (!mongoc_cursor_next (findcursor->cursor, document)) { - if (mongoc_cursor_error_document ( - findcursor->cursor, error, error_document)) { + if (mongoc_cursor_error_document (findcursor->cursor, error, error_document)) { return; } } } bool -entity_map_add_findcursor (entity_map_t *em, - const char *id, - mongoc_cursor_t *cursor, - const bson_t *first_result, - bson_error_t *error) +entity_map_add_findcursor ( + entity_map_t *em, const char *id, mongoc_cursor_t *cursor, const bson_t *first_result, bson_error_t *error) { entity_findcursor_t *findcursor; - findcursor = - (entity_findcursor_t *) bson_malloc0 (sizeof (entity_findcursor_t)); + findcursor = (entity_findcursor_t *) bson_malloc0 (sizeof (entity_findcursor_t)); findcursor->cursor = cursor; findcursor->first_result = first_result; return _entity_map_add (em, id, "findcursor", (void *) findcursor, error); } bool -entity_map_add_bson (entity_map_t *em, - const char *id, - bson_val_t *val, - bson_error_t *error) +entity_map_add_bson (entity_map_t *em, const char *id, bson_val_t *val, bson_error_t *error) { return _entity_map_add (em, id, "bson", (void *) bson_val_copy (val), error); } bool -entity_map_add_bson_array (entity_map_t *em, - const char *id, - bson_error_t *error) +entity_map_add_bson_array (entity_map_t *em, const char *id, bson_error_t *error) { // Note: the specification states we should be storing a BSON object of array // type, but we use an array of BSON objects instead to make append and @@ -2203,10 +1966,7 @@ entity_map_add_bson_array (entity_map_t *em, } bool -entity_map_add_size_t (entity_map_t *em, - const char *id, - size_t *value, - bson_error_t *error) +entity_map_add_size_t (entity_map_t *em, const char *id, size_t *value, bson_error_t *error) { return _entity_map_add (em, id, "size_t", value, error); } @@ -2231,9 +1991,7 @@ special_session_lsid (bson_matcher_t *matcher, bson_iter_next (&iter); if (!BSON_ITER_HOLDS_UTF8 (&iter)) { - test_set_error (error, - "unexpected $$sessionLsid does not contain utf8: %s", - tmp_json (assertion)); + test_set_error (error, "unexpected $$sessionLsid does not contain utf8: %s", tmp_json (assertion)); goto done; } @@ -2274,9 +2032,7 @@ special_matches_entity (bson_matcher_t *matcher, BSON_ASSERT (bson_iter_next (&iter)); if (!BSON_ITER_HOLDS_UTF8 (&iter)) { - test_set_error (error, - "unexpected $$matchesEntity does not contain utf8: %s", - tmp_json (assertion)); + test_set_error (error, "unexpected $$matchesEntity does not contain utf8: %s", tmp_json (assertion)); goto done; } @@ -2296,22 +2052,16 @@ special_matches_entity (bson_matcher_t *matcher, } bool -entity_map_match (entity_map_t *em, - const bson_val_t *expected, - const bson_val_t *actual, - bool array_of_root_docs, - bson_error_t *error) +entity_map_match ( + entity_map_t *em, const bson_val_t *expected, const bson_val_t *actual, bool array_of_root_docs, bson_error_t *error) { bson_matcher_t *matcher; bool ret; matcher = bson_matcher_new (); - bson_matcher_add_special ( - matcher, "$$sessionLsid", special_session_lsid, em); - bson_matcher_add_special ( - matcher, "$$matchesEntity", special_matches_entity, em); - ret = bson_matcher_match ( - matcher, expected, actual, "", array_of_root_docs, error); + bson_matcher_add_special (matcher, "$$sessionLsid", special_session_lsid, em); + bson_matcher_add_special (matcher, "$$matchesEntity", special_matches_entity, em); + ret = bson_matcher_match (matcher, expected, actual, "", array_of_root_docs, error); bson_matcher_destroy (matcher); return ret; } @@ -2336,8 +2086,7 @@ event_list_to_string (event_t *events) bson_string_append_printf (str, " sent %s", tmp_json (eiter->command)); } if (eiter->reply) { - bson_string_append_printf ( - str, " received %s", tmp_json (eiter->reply)); + bson_string_append_printf (str, " received %s", tmp_json (eiter->reply)); } bson_string_append (str, "\n"); } @@ -2357,8 +2106,7 @@ entity_map_end_session (entity_map_t *em, char *session_id, bson_error_t *error) } if (0 != strcmp (entity->type, "session")) { - test_set_error ( - error, "expected session for %s but got %s", session_id, entity->type); + test_set_error (error, "expected session for %s but got %s", session_id, entity->type); goto done; } @@ -2370,9 +2118,7 @@ entity_map_end_session (entity_map_t *em, char *session_id, bson_error_t *error) } char * -entity_map_get_session_client_id (entity_map_t *em, - char *session_id, - bson_error_t *error) +entity_map_get_session_client_id (entity_map_t *em, char *session_id, bson_error_t *error) { char *ret = NULL; entity_t *entity = NULL; @@ -2383,8 +2129,7 @@ entity_map_get_session_client_id (entity_map_t *em, } if (0 != strcmp (entity->type, "session")) { - test_set_error ( - error, "expected session for %s but got %s", session_id, entity->type); + test_set_error (error, "expected session for %s but got %s", session_id, entity->type); goto done; } diff --git a/src/libmongoc/tests/unified/entity-map.h b/src/libmongoc/tests/unified/entity-map.h index 866e84c0ce..4b213a6293 100644 --- a/src/libmongoc/tests/unified/entity-map.h +++ b/src/libmongoc/tests/unified/entity-map.h @@ -90,30 +90,19 @@ entity_map_add_changestream (entity_map_t *em, /* Steals ownership of cursor. */ bool -entity_map_add_findcursor (entity_map_t *em, - const char *id, - mongoc_cursor_t *cursor, - const bson_t *first_result, - bson_error_t *error); +entity_map_add_findcursor ( + entity_map_t *em, const char *id, mongoc_cursor_t *cursor, const bson_t *first_result, bson_error_t *error); /* Copies val */ bool -entity_map_add_bson (entity_map_t *em, - const char *id, - bson_val_t *val, - bson_error_t *error); +entity_map_add_bson (entity_map_t *em, const char *id, bson_val_t *val, bson_error_t *error); bool -entity_map_add_bson_array (entity_map_t *em, - const char *id, - bson_error_t *error); +entity_map_add_bson_array (entity_map_t *em, const char *id, bson_error_t *error); /* Steals ownership of value. */ bool -entity_map_add_size_t (entity_map_t *em, - const char *id, - size_t *value, - bson_error_t *error); +entity_map_add_size_t (entity_map_t *em, const char *id, size_t *value, bson_error_t *error); /* Returns NULL and sets @error if @id does not map to an entry. */ entity_t * @@ -125,86 +114,56 @@ bool entity_map_delete (entity_map_t *em, const char *id, bson_error_t *error); mongoc_client_t * -entity_map_get_client (entity_map_t *entity_map, - const char *id, - bson_error_t *error); +entity_map_get_client (entity_map_t *entity_map, const char *id, bson_error_t *error); mongoc_client_encryption_t * -entity_map_get_client_encryption (entity_map_t *entity_map, - const char *id, - bson_error_t *error); +entity_map_get_client_encryption (entity_map_t *entity_map, const char *id, bson_error_t *error); mongoc_database_t * -entity_map_get_database (entity_map_t *entity_map, - const char *id, - bson_error_t *error); +entity_map_get_database (entity_map_t *entity_map, const char *id, bson_error_t *error); mongoc_collection_t * -entity_map_get_collection (entity_map_t *entity_map, - const char *id, - bson_error_t *error); +entity_map_get_collection (entity_map_t *entity_map, const char *id, bson_error_t *error); mongoc_change_stream_t * -entity_map_get_changestream (entity_map_t *entity_map, - const char *id, - bson_error_t *error); +entity_map_get_changestream (entity_map_t *entity_map, const char *id, bson_error_t *error); entity_findcursor_t * -entity_map_get_findcursor (entity_map_t *entity_map, - const char *id, - bson_error_t *error); +entity_map_get_findcursor (entity_map_t *entity_map, const char *id, bson_error_t *error); void -entity_findcursor_iterate_until_document_or_error ( - entity_findcursor_t *cursor, - const bson_t **document, - bson_error_t *error, - const bson_t **error_document); +entity_findcursor_iterate_until_document_or_error (entity_findcursor_t *cursor, + const bson_t **document, + bson_error_t *error, + const bson_t **error_document); mongoc_client_session_t * -entity_map_get_session (entity_map_t *entity_map, - const char *id, - bson_error_t *error); +entity_map_get_session (entity_map_t *entity_map, const char *id, bson_error_t *error); bson_val_t * -entity_map_get_bson (entity_map_t *entity_map, - const char *id, - bson_error_t *error); +entity_map_get_bson (entity_map_t *entity_map, const char *id, bson_error_t *error); mongoc_array_t * -entity_map_get_bson_array (entity_map_t *entity_map, - const char *id, - bson_error_t *error); +entity_map_get_bson_array (entity_map_t *entity_map, const char *id, bson_error_t *error); size_t * -entity_map_get_size_t (entity_map_t *entity_map, - const char *id, - bson_error_t *error); +entity_map_get_size_t (entity_map_t *entity_map, const char *id, bson_error_t *error); mongoc_gridfs_bucket_t * -entity_map_get_bucket (entity_map_t *entity_map, - const char *id, - bson_error_t *error); +entity_map_get_bucket (entity_map_t *entity_map, const char *id, bson_error_t *error); bool -entity_map_match (entity_map_t *em, - const bson_val_t *expected, - const bson_val_t *actual, - bool allow_extra, - bson_error_t *error); +entity_map_match ( + entity_map_t *em, const bson_val_t *expected, const bson_val_t *actual, bool allow_extra, bson_error_t *error); char * event_list_to_string (event_t *events); bool -entity_map_end_session (entity_map_t *em, - char *session_id, - bson_error_t *error); +entity_map_end_session (entity_map_t *em, char *session_id, bson_error_t *error); char * -entity_map_get_session_client_id (entity_map_t *em, - char *session_id, - bson_error_t *error); +entity_map_get_session_client_id (entity_map_t *em, char *session_id, bson_error_t *error); void entity_map_set_reduced_heartbeat (entity_map_t *em, bool val); diff --git a/src/libmongoc/tests/unified/operation.c b/src/libmongoc/tests/unified/operation.c index 371999597d..812a847782 100644 --- a/src/libmongoc/tests/unified/operation.c +++ b/src/libmongoc/tests/unified/operation.c @@ -59,10 +59,8 @@ operation_new (bson_t *bson, bson_error_t *error) bson_parser_doc_optional (op->parser, "arguments", &op->arguments); bson_parser_doc_optional (op->parser, "expectError", &op->expect_error); bson_parser_any_optional (op->parser, "expectResult", &op->expect_result); - bson_parser_bool_optional ( - op->parser, "ignoreResultAndError", &op->ignore_result_and_error); - bson_parser_utf8_optional ( - op->parser, "saveResultAsEntity", &op->save_result_as_entity); + bson_parser_bool_optional (op->parser, "ignoreResultAndError", &op->ignore_result_and_error); + bson_parser_utf8_optional (op->parser, "saveResultAsEntity", &op->save_result_as_entity); if (!bson_parser_parse (op->parser, bson, error)) { operation_destroy (op); return NULL; @@ -71,10 +69,7 @@ operation_new (bson_t *bson, bson_error_t *error) } static bool -operation_create_change_stream (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_create_change_stream (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { bool ret = false; entity_t *entity = NULL; @@ -121,10 +116,7 @@ operation_create_change_stream (test_t *test, result_from_val_and_reply (result, NULL, (bson_t *) op_reply, &op_error); if (op->save_result_as_entity) { - if (!entity_map_add_changestream (test->entity_map, - op->save_result_as_entity, - changestream, - error)) { + if (!entity_map_add_changestream (test->entity_map, op->save_result_as_entity, changestream, error)) { goto done; } else { // Successfully saved the changestream @@ -142,10 +134,7 @@ operation_create_change_stream (test_t *test, } static bool -operation_list_databases (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_list_databases (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { bool ret = false; mongoc_client_t *client = NULL; @@ -179,10 +168,7 @@ operation_list_databases (test_t *test, } static bool -operation_list_database_names (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_list_database_names (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { bool ret = false; mongoc_client_t *client = NULL; @@ -203,8 +189,7 @@ operation_list_database_names (test_t *test, goto done; } - char **names = - mongoc_client_get_database_names_with_opts (client, opts, error); + char **names = mongoc_client_get_database_names_with_opts (client, opts, error); { bson_val_t *val = NULL; @@ -237,10 +222,7 @@ operation_list_database_names (test_t *test, } static bool -operation_create_datakey (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_create_datakey (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { bson_parser_t *parser = bson_parser_new (); char *kms_provider = NULL; @@ -257,8 +239,7 @@ operation_create_datakey (test_t *test, goto done; } - if (!(ce = entity_map_get_client_encryption ( - test->entity_map, op->object, error))) { + if (!(ce = entity_map_get_client_encryption (test->entity_map, op->object, error))) { goto done; } @@ -280,8 +261,7 @@ operation_create_datakey (test_t *test, } if (master_key) { - mongoc_client_encryption_datakey_opts_set_masterkey (datakey_opts, - master_key); + mongoc_client_encryption_datakey_opts_set_masterkey (datakey_opts, master_key); } if (key_alt_names) { @@ -299,8 +279,7 @@ operation_create_datakey (test_t *test, BSON_ASSERT (bson_in_range_unsigned (uint32_t, arr.len)); - mongoc_client_encryption_datakey_opts_set_keyaltnames ( - datakey_opts, arr.data, (uint32_t) arr.len); + mongoc_client_encryption_datakey_opts_set_keyaltnames (datakey_opts, arr.data, (uint32_t) arr.len); _mongoc_array_destroy (&arr); } @@ -310,18 +289,13 @@ operation_create_datakey (test_t *test, BSON_ASSERT (value); - if (value->value_type != BSON_TYPE_BINARY || - value->value.v_binary.subtype != BSON_SUBTYPE_BINARY) { - test_set_error ( - error, - "expected field 'keyMaterial' to be binData with subtype 00"); + if (value->value_type != BSON_TYPE_BINARY || value->value.v_binary.subtype != BSON_SUBTYPE_BINARY) { + test_set_error (error, "expected field 'keyMaterial' to be binData with subtype 00"); goto opts_done; } mongoc_client_encryption_datakey_opts_set_keymaterial ( - datakey_opts, - value->value.v_binary.data, - value->value.v_binary.data_len); + datakey_opts, value->value.v_binary.data, value->value.v_binary.data_len); } success = true; @@ -335,8 +309,8 @@ operation_create_datakey (test_t *test, } { - const bool success = mongoc_client_encryption_create_datakey ( - ce, kms_provider, datakey_opts, &key_id_value, error); + const bool success = + mongoc_client_encryption_create_datakey (ce, kms_provider, datakey_opts, &key_id_value, error); bson_val_t *val = NULL; if (success) { @@ -359,10 +333,7 @@ operation_create_datakey (test_t *test, } static bool -operation_rewrap_many_datakey (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_rewrap_many_datakey (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { bson_parser_t *const parser = bson_parser_new (); mongoc_client_encryption_rewrap_many_datakey_result_t *const rmd_result = @@ -382,8 +353,7 @@ operation_rewrap_many_datakey (test_t *test, goto done; } - if (!(ce = entity_map_get_client_encryption ( - test->entity_map, op->object, error))) { + if (!(ce = entity_map_get_client_encryption (test->entity_map, op->object, error))) { goto done; } @@ -403,17 +373,14 @@ operation_rewrap_many_datakey (test_t *test, } } - if (mongoc_client_encryption_rewrap_many_datakey ( - ce, filter_doc, provider, master_key, rmd_result, error)) { + if (mongoc_client_encryption_rewrap_many_datakey (ce, filter_doc, provider, master_key, rmd_result, error)) { const bson_t *const bulk_write_result = - mongoc_client_encryption_rewrap_many_datakey_result_get_bulk_write_result ( - rmd_result); + mongoc_client_encryption_rewrap_many_datakey_result_get_bulk_write_result (rmd_result); bson_t doc = BSON_INITIALIZER; if (bulk_write_result) { - bson_t *const rewritten = - rewrite_bulk_write_result (bulk_write_result); + bson_t *const rewritten = rewrite_bulk_write_result (bulk_write_result); BSON_APPEND_DOCUMENT (&doc, "bulkWriteResult", rewritten); bson_destroy (rewritten); } @@ -441,10 +408,7 @@ operation_rewrap_many_datakey (test_t *test, } static bool -operation_delete_key (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_delete_key (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { bson_parser_t *const parser = bson_parser_new (); @@ -458,15 +422,13 @@ operation_delete_key (test_t *test, goto done; } - if (!(ce = entity_map_get_client_encryption ( - test->entity_map, op->object, error))) { + if (!(ce = entity_map_get_client_encryption (test->entity_map, op->object, error))) { goto done; } { bson_t reply; - const bool success = mongoc_client_encryption_delete_key ( - ce, bson_val_to_value (id_val), &reply, error); + const bool success = mongoc_client_encryption_delete_key (ce, bson_val_to_value (id_val), &reply, error); bson_val_t *const val = success ? bson_val_from_bson (&reply) : NULL; result_from_val_and_reply (result, val, NULL, error); @@ -484,10 +446,7 @@ operation_delete_key (test_t *test, } static bool -operation_get_key (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_get_key (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { bson_parser_t *const parser = bson_parser_new (); @@ -501,20 +460,16 @@ operation_get_key (test_t *test, goto done; } - if (!(ce = entity_map_get_client_encryption ( - test->entity_map, op->object, error))) { + if (!(ce = entity_map_get_client_encryption (test->entity_map, op->object, error))) { goto done; } { bson_t key_doc; - const bool success = mongoc_client_encryption_get_key ( - ce, bson_val_to_value (id_val), &key_doc, error); + const bool success = mongoc_client_encryption_get_key (ce, bson_val_to_value (id_val), &key_doc, error); const bson_value_t value = {.value_type = BSON_TYPE_NULL}; bson_val_t *const val = - success ? (bson_empty (&key_doc) ? bson_val_from_value (&value) - : bson_val_from_bson (&key_doc)) - : NULL; + success ? (bson_empty (&key_doc) ? bson_val_from_value (&value) : bson_val_from_bson (&key_doc)) : NULL; result_from_val_and_reply (result, val, NULL, error); @@ -531,10 +486,7 @@ operation_get_key (test_t *test, } static bool -operation_get_keys (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_get_keys (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { bson_parser_t *const parser = bson_parser_new (); @@ -545,14 +497,12 @@ operation_get_keys (test_t *test, goto done; } - if (!(ce = entity_map_get_client_encryption ( - test->entity_map, op->object, error))) { + if (!(ce = entity_map_get_client_encryption (test->entity_map, op->object, error))) { goto done; } { - mongoc_cursor_t *const cursor = - mongoc_client_encryption_get_keys (ce, error); + mongoc_cursor_t *const cursor = mongoc_client_encryption_get_keys (ce, error); if (cursor) { result_from_cursor (result, cursor); @@ -572,10 +522,7 @@ operation_get_keys (test_t *test, } static bool -operation_add_key_alt_name (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_add_key_alt_name (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { bson_parser_t *const parser = bson_parser_new (); @@ -591,20 +538,17 @@ operation_add_key_alt_name (test_t *test, goto done; } - if (!(ce = entity_map_get_client_encryption ( - test->entity_map, op->object, error))) { + if (!(ce = entity_map_get_client_encryption (test->entity_map, op->object, error))) { goto done; } { bson_t key_doc; - const bool success = mongoc_client_encryption_add_key_alt_name ( - ce, bson_val_to_value (id_val), alt_name, &key_doc, error); + const bool success = + mongoc_client_encryption_add_key_alt_name (ce, bson_val_to_value (id_val), alt_name, &key_doc, error); const bson_value_t value = {.value_type = BSON_TYPE_NULL}; bson_val_t *const val = - success ? (bson_empty (&key_doc) ? bson_val_from_value (&value) - : bson_val_from_bson (&key_doc)) - : NULL; + success ? (bson_empty (&key_doc) ? bson_val_from_value (&value) : bson_val_from_bson (&key_doc)) : NULL; result_from_val_and_reply (result, val, NULL, error); @@ -621,10 +565,7 @@ operation_add_key_alt_name (test_t *test, } static bool -operation_remove_key_alt_name (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_remove_key_alt_name (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { bson_parser_t *const parser = bson_parser_new (); @@ -640,20 +581,17 @@ operation_remove_key_alt_name (test_t *test, goto done; } - if (!(ce = entity_map_get_client_encryption ( - test->entity_map, op->object, error))) { + if (!(ce = entity_map_get_client_encryption (test->entity_map, op->object, error))) { goto done; } { bson_t key_doc; - const bool success = mongoc_client_encryption_remove_key_alt_name ( - ce, bson_val_to_value (id_val), alt_name, &key_doc, error); + const bool success = + mongoc_client_encryption_remove_key_alt_name (ce, bson_val_to_value (id_val), alt_name, &key_doc, error); const bson_value_t value = {.value_type = BSON_TYPE_NULL}; bson_val_t *const val = - success ? (bson_empty (&key_doc) ? bson_val_from_value (&value) - : bson_val_from_bson (&key_doc)) - : NULL; + success ? (bson_empty (&key_doc) ? bson_val_from_value (&value) : bson_val_from_bson (&key_doc)) : NULL; result_from_val_and_reply (result, val, NULL, error); @@ -670,10 +608,7 @@ operation_remove_key_alt_name (test_t *test, } static bool -operation_get_key_by_alt_name (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_get_key_by_alt_name (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { bson_parser_t *const parser = bson_parser_new (); @@ -687,20 +622,16 @@ operation_get_key_by_alt_name (test_t *test, goto done; } - if (!(ce = entity_map_get_client_encryption ( - test->entity_map, op->object, error))) { + if (!(ce = entity_map_get_client_encryption (test->entity_map, op->object, error))) { goto done; } { bson_t key_doc; - const bool success = mongoc_client_encryption_get_key_by_alt_name ( - ce, keyaltname, &key_doc, error); + const bool success = mongoc_client_encryption_get_key_by_alt_name (ce, keyaltname, &key_doc, error); const bson_value_t value = {.value_type = BSON_TYPE_NULL}; bson_val_t *const val = - success ? (bson_empty (&key_doc) ? bson_val_from_value (&value) - : bson_val_from_bson (&key_doc)) - : NULL; + success ? (bson_empty (&key_doc) ? bson_val_from_value (&value) : bson_val_from_bson (&key_doc)) : NULL; result_from_val_and_reply (result, val, NULL, error); @@ -717,15 +648,11 @@ operation_get_key_by_alt_name (test_t *test, } static bool -operation_encrypt (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_encrypt (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { bool ret = false; mongoc_client_encryption_t *ce = NULL; - mongoc_client_encryption_encrypt_opts_t *eo = - mongoc_client_encryption_encrypt_opts_new (); + mongoc_client_encryption_encrypt_opts_t *eo = mongoc_client_encryption_encrypt_opts_new (); bson_val_t *value = NULL; bson_t *opts = NULL; char *opts_keyaltname = NULL; @@ -768,28 +695,23 @@ operation_encrypt (test_t *test, } // Get ClientEncryption object. - if (!(ce = entity_map_get_client_encryption ( - test->entity_map, op->object, error))) { + if (!(ce = entity_map_get_client_encryption (test->entity_map, op->object, error))) { goto done; } // Encrypt. { if (opts_id) { - mongoc_client_encryption_encrypt_opts_set_keyid ( - eo, bson_val_to_value (opts_id)); + mongoc_client_encryption_encrypt_opts_set_keyid (eo, bson_val_to_value (opts_id)); } if (opts_keyaltname) { - mongoc_client_encryption_encrypt_opts_set_keyaltname (eo, - opts_keyaltname); + mongoc_client_encryption_encrypt_opts_set_keyaltname (eo, opts_keyaltname); } mongoc_client_encryption_encrypt_opts_set_algorithm (eo, opts_algorithm); bson_value_t ciphertext; - const bool success = mongoc_client_encryption_encrypt ( - ce, bson_val_to_value (value), eo, &ciphertext, error); - bson_val_t *const val = - success ? bson_val_from_value (&ciphertext) : NULL; + const bool success = mongoc_client_encryption_encrypt (ce, bson_val_to_value (value), eo, &ciphertext, error); + bson_val_t *const val = success ? bson_val_from_value (&ciphertext) : NULL; result_from_val_and_reply (result, val, NULL /* reply */, error); bson_value_destroy (&ciphertext); bson_val_destroy (val); @@ -810,10 +732,7 @@ operation_encrypt (test_t *test, } static bool -operation_decrypt (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_decrypt (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { bool ret = false; mongoc_client_encryption_t *ce = NULL; @@ -836,16 +755,14 @@ operation_decrypt (test_t *test, } // Get ClientEncryption object. - if (!(ce = entity_map_get_client_encryption ( - test->entity_map, op->object, error))) { + if (!(ce = entity_map_get_client_encryption (test->entity_map, op->object, error))) { goto done; } // Decrypt. { bson_value_t plaintext; - const bool success = mongoc_client_encryption_decrypt ( - ce, bson_val_to_value (value), &plaintext, error); + const bool success = mongoc_client_encryption_decrypt (ce, bson_val_to_value (value), &plaintext, error); bson_val_t *const val = success ? bson_val_from_value (&plaintext) : NULL; result_from_val_and_reply (result, val, NULL /* reply */, error); bson_value_destroy (&plaintext); @@ -862,10 +779,7 @@ operation_decrypt (test_t *test, } static bool -operation_create_collection (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_create_collection (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { bool ret = false; bson_parser_t *parser = NULL; @@ -907,10 +821,7 @@ operation_create_collection (test_t *test, } static bool -operation_drop_collection (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_drop_collection (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { bool ret = false; bson_parser_t *parser = NULL; @@ -959,10 +870,7 @@ operation_drop_collection (test_t *test, } static bool -operation_list_collections (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_list_collections (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { bool ret = false; mongoc_database_t *db = NULL; @@ -996,10 +904,7 @@ operation_list_collections (test_t *test, } static bool -operation_list_collection_names (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_list_collection_names (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { bool ret = false; mongoc_database_t *db = NULL; @@ -1021,8 +926,7 @@ operation_list_collection_names (test_t *test, goto done; } - op_ret = - mongoc_database_get_collection_names_with_opts (db, opts, &op_error); + op_ret = mongoc_database_get_collection_names_with_opts (db, opts, &op_error); result_from_ok (result); @@ -1035,10 +939,7 @@ operation_list_collection_names (test_t *test, } static bool -operation_list_indexes (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_list_indexes (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { bool ret = false; mongoc_collection_t *coll = NULL; @@ -1073,10 +974,7 @@ operation_list_indexes (test_t *test, } static bool -operation_run_command (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_run_command (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { bool ret = false; bson_parser_t *parser = NULL; @@ -1120,8 +1018,7 @@ operation_run_command (test_t *test, } bson_destroy (&op_reply); - mongoc_database_command_with_opts ( - db, command, rp, opts, &op_reply, &op_error); + mongoc_database_command_with_opts (db, command, rp, opts, &op_reply, &op_error); result_from_val_and_reply (result, NULL, &op_reply, &op_error); @@ -1134,10 +1031,7 @@ operation_run_command (test_t *test, } static bool -operation_modify_collection (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_modify_collection (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { bson_parser_t *const parser = bson_parser_new (); @@ -1165,8 +1059,7 @@ operation_modify_collection (test_t *test, { bson_t reply; - mongoc_database_write_command_with_opts ( - db, &command, NULL, &reply, error); + mongoc_database_write_command_with_opts (db, &command, NULL, &reply, error); result_from_val_and_reply (result, NULL, &reply, error); bson_destroy (&reply); @@ -1182,10 +1075,7 @@ operation_modify_collection (test_t *test, } static bool -operation_aggregate (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_aggregate (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { bool ret = false; entity_t *entity = NULL; @@ -1211,12 +1101,10 @@ operation_aggregate (test_t *test, entity = entity_map_get (test->entity_map, op->object, error); if (0 == strcmp (entity->type, "collection")) { mongoc_collection_t *coll = (mongoc_collection_t *) entity->value; - cursor = mongoc_collection_aggregate ( - coll, 0 /* query flags */, pipeline, opts, NULL /* read prefs */); + cursor = mongoc_collection_aggregate (coll, 0 /* query flags */, pipeline, opts, NULL /* read prefs */); } else if (0 == strcmp (entity->type, "database")) { mongoc_database_t *db = (mongoc_database_t *) entity->value; - cursor = - mongoc_database_aggregate (db, pipeline, opts, NULL /* read prefs */); + cursor = mongoc_database_aggregate (db, pipeline, opts, NULL /* read prefs */); } else { goto done; } @@ -1232,9 +1120,7 @@ operation_aggregate (test_t *test, } static bool -bulk_op_append (mongoc_bulk_operation_t *bulk, - bson_t *request, - bson_error_t *error) +bulk_op_append (mongoc_bulk_operation_t *bulk, bson_t *request, bson_error_t *error) { bool ret = false; bson_iter_t iter; @@ -1246,9 +1132,7 @@ bulk_op_append (mongoc_bulk_operation_t *bulk, bson_iter_init (&iter, request); bson_iter_next (&iter); if (!BSON_ITER_HOLDS_DOCUMENT (&iter)) { - test_set_error (error, - "Unexpected non-document in bulk write model: %s", - bson_iter_key (&iter)); + test_set_error (error, "Unexpected non-document in bulk write model: %s", bson_iter_key (&iter)); } op_type = bson_iter_key (&iter); bson_iter_bson (&iter, &request_doc); @@ -1263,8 +1147,7 @@ bulk_op_append (mongoc_bulk_operation_t *bulk, goto done; } - mongoc_bulk_operation_insert_with_opts ( - bulk, document, bson_parser_get_extra (parser), error); + mongoc_bulk_operation_insert_with_opts (bulk, document, bson_parser_get_extra (parser), error); } else if (0 == strcmp (op_type, "updateOne")) { bson_parser_doc (parser, "filter", &filter); bson_parser_array_or_doc (parser, "update", &update); @@ -1272,8 +1155,7 @@ bulk_op_append (mongoc_bulk_operation_t *bulk, goto done; } - mongoc_bulk_operation_update_one_with_opts ( - bulk, filter, update, bson_parser_get_extra (parser), error); + mongoc_bulk_operation_update_one_with_opts (bulk, filter, update, bson_parser_get_extra (parser), error); } else if (0 == strcmp (op_type, "updateMany")) { bson_parser_doc (parser, "filter", &filter); bson_parser_array_or_doc (parser, "update", &update); @@ -1281,8 +1163,7 @@ bulk_op_append (mongoc_bulk_operation_t *bulk, goto done; } - mongoc_bulk_operation_update_many_with_opts ( - bulk, filter, update, bson_parser_get_extra (parser), error); + mongoc_bulk_operation_update_many_with_opts (bulk, filter, update, bson_parser_get_extra (parser), error); } else if (0 == strcmp (op_type, "deleteOne")) { bson_parser_doc (parser, "filter", &filter); @@ -1290,16 +1171,14 @@ bulk_op_append (mongoc_bulk_operation_t *bulk, goto done; } - mongoc_bulk_operation_remove_one_with_opts ( - bulk, filter, bson_parser_get_extra (parser), error); + mongoc_bulk_operation_remove_one_with_opts (bulk, filter, bson_parser_get_extra (parser), error); } else if (0 == strcmp (op_type, "deleteMany")) { bson_parser_doc (parser, "filter", &filter); if (!bson_parser_parse (parser, &request_doc, error)) { goto done; } - mongoc_bulk_operation_remove_many_with_opts ( - bulk, filter, bson_parser_get_extra (parser), error); + mongoc_bulk_operation_remove_many_with_opts (bulk, filter, bson_parser_get_extra (parser), error); } else if (0 == strcmp (op_type, "replaceOne")) { bson_parser_doc (parser, "filter", &filter); bson_parser_doc (parser, "replacement", &replacement); @@ -1307,8 +1186,7 @@ bulk_op_append (mongoc_bulk_operation_t *bulk, goto done; } - mongoc_bulk_operation_replace_one_with_opts ( - bulk, filter, replacement, bson_parser_get_extra (parser), error); + mongoc_bulk_operation_replace_one_with_opts (bulk, filter, replacement, bson_parser_get_extra (parser), error); } ret = true; @@ -1318,10 +1196,7 @@ bulk_op_append (mongoc_bulk_operation_t *bulk, } static bool -operation_bulk_write (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_bulk_write (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { bool ret = false; mongoc_collection_t *coll = NULL; @@ -1393,10 +1268,7 @@ operation_bulk_write (test_t *test, } static bool -operation_count_documents (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_count_documents (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { bool ret = false; mongoc_collection_t *coll = NULL; @@ -1428,8 +1300,7 @@ operation_count_documents (test_t *test, } bson_destroy (&op_reply); - op_ret = mongoc_collection_count_documents ( - coll, filter, opts, NULL /* read prefs */, &op_reply, &op_error); + op_ret = mongoc_collection_count_documents (coll, filter, opts, NULL /* read prefs */, &op_reply, &op_error); if (op_ret != -1) { val = bson_val_from_int64 (op_ret); @@ -1447,10 +1318,7 @@ operation_count_documents (test_t *test, } static bool -operation_create_find_cursor (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_create_find_cursor (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { bool ret = false; mongoc_collection_t *coll = NULL; @@ -1481,8 +1349,7 @@ operation_create_find_cursor (test_t *test, } } - cursor = mongoc_collection_find_with_opts ( - coll, filter, opts, NULL /* read prefs */); + cursor = mongoc_collection_find_with_opts (coll, filter, opts, NULL /* read prefs */); mongoc_cursor_next (cursor, &first_result); @@ -1496,11 +1363,7 @@ operation_create_find_cursor (test_t *test, goto done; } - if (!entity_map_add_findcursor (test->entity_map, - op->save_result_as_entity, - cursor, - first_result, - error)) { + if (!entity_map_add_findcursor (test->entity_map, op->save_result_as_entity, cursor, first_result, error)) { goto done; } @@ -1511,10 +1374,7 @@ operation_create_find_cursor (test_t *test, } static bool -operation_create_index (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_create_index (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { bool ret = false; mongoc_collection_t *coll = NULL; @@ -1557,8 +1417,7 @@ operation_create_index (test_t *test, } im = mongoc_index_model_new (keys, index_opts); - mongoc_collection_create_indexes_with_opts ( - coll, &im, 1, opts, &op_reply, &op_error); + mongoc_collection_create_indexes_with_opts (coll, &im, 1, opts, &op_reply, &op_error); MONGOC_DEBUG ("running createIndexes: %s", tmp_json (create_indexes)); @@ -1579,10 +1438,7 @@ operation_create_index (test_t *test, } static bool -operation_delete_one (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_delete_one (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { bool ret = false; mongoc_collection_t *coll = NULL; @@ -1625,10 +1481,7 @@ operation_delete_one (test_t *test, } static bool -operation_delete_many (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_delete_many (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { bool ret = false; mongoc_collection_t *coll = NULL; @@ -1671,10 +1524,7 @@ operation_delete_many (test_t *test, } static bool -operation_distinct (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_distinct (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { bool ret = false; mongoc_collection_t *coll = NULL; @@ -1706,18 +1556,11 @@ operation_distinct (test_t *test, goto done; } - distinct = BCON_NEW ("distinct", - mongoc_collection_get_name (coll), - "key", - BCON_UTF8 (field_name), - "query", - "{", - &filter, - "}"); + distinct = BCON_NEW ( + "distinct", mongoc_collection_get_name (coll), "key", BCON_UTF8 (field_name), "query", "{", &filter, "}"); bson_destroy (&op_reply); - mongoc_collection_read_command_with_opts ( - coll, distinct, NULL /* read prefs */, opts, &op_reply, &op_error); + mongoc_collection_read_command_with_opts (coll, distinct, NULL /* read prefs */, opts, &op_reply, &op_error); result_from_distinct (result, &op_reply, &op_error); @@ -1731,10 +1574,7 @@ operation_distinct (test_t *test, } static bool -operation_estimated_document_count (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_estimated_document_count (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { bool ret = false; mongoc_collection_t *coll = NULL; @@ -1764,8 +1604,7 @@ operation_estimated_document_count (test_t *test, } bson_destroy (&op_reply); - op_ret = mongoc_collection_estimated_document_count ( - coll, opts, NULL /* read prefs */, &op_reply, &op_error); + op_ret = mongoc_collection_estimated_document_count (coll, opts, NULL /* read prefs */, &op_reply, &op_error); if (op_ret != -1) { val = bson_val_from_int64 (op_ret); @@ -1783,10 +1622,7 @@ operation_estimated_document_count (test_t *test, } static bool -operation_find (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_find (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { bool ret = false; mongoc_collection_t *coll = NULL; @@ -1814,8 +1650,7 @@ operation_find (test_t *test, } } - cursor = mongoc_collection_find_with_opts ( - coll, filter, opts, NULL /* read prefs */); + cursor = mongoc_collection_find_with_opts (coll, filter, opts, NULL /* read prefs */); result_from_cursor (result, cursor); @@ -1828,10 +1663,7 @@ operation_find (test_t *test, } static bool -operation_find_one_and_update (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_find_one_and_update (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { bool ret = false; mongoc_collection_t *coll = NULL; @@ -1873,8 +1705,7 @@ operation_find_one_and_update (test_t *test, mongoc_find_and_modify_opts_append (opts, session_opts); bson_destroy (&op_reply); - mongoc_collection_find_and_modify_with_opts ( - coll, filter, opts, &op_reply, &op_error); + mongoc_collection_find_and_modify_with_opts (coll, filter, opts, &op_reply, &op_error); if (bson_iter_init_find (&iter, &op_reply, "value")) { val = bson_val_from_iter (&iter); @@ -1892,10 +1723,7 @@ operation_find_one_and_update (test_t *test, } static bool -operation_find_one_and_replace (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_find_one_and_replace (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { bool ret = false; mongoc_collection_t *coll = NULL; @@ -1940,8 +1768,7 @@ operation_find_one_and_replace (test_t *test, mongoc_find_and_modify_opts_append (opts, session_opts); bson_destroy (&op_reply); - mongoc_collection_find_and_modify_with_opts ( - coll, filter, opts, &op_reply, &op_error); + mongoc_collection_find_and_modify_with_opts (coll, filter, opts, &op_reply, &op_error); if (bson_iter_init_find (&iter, &op_reply, "value")) { val = bson_val_from_iter (&iter); @@ -1959,10 +1786,7 @@ operation_find_one_and_replace (test_t *test, } static bool -operation_find_one_and_delete (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_find_one_and_delete (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { bool ret = false; mongoc_collection_t *coll = NULL; @@ -2000,8 +1824,7 @@ operation_find_one_and_delete (test_t *test, mongoc_find_and_modify_opts_append (opts, session_opts); bson_destroy (&op_reply); - mongoc_collection_find_and_modify_with_opts ( - coll, filter, opts, &op_reply, &op_error); + mongoc_collection_find_and_modify_with_opts (coll, filter, opts, &op_reply, &op_error); if (bson_iter_init_find (&iter, &op_reply, "value")) { val = bson_val_from_iter (&iter); @@ -2019,10 +1842,7 @@ operation_find_one_and_delete (test_t *test, } static bool -operation_insert_many (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_insert_many (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { bool ret = false; mongoc_collection_t *coll = NULL; @@ -2071,8 +1891,7 @@ operation_insert_many (test_t *test, } bson_destroy (&op_reply); - mongoc_collection_insert_many ( - coll, (const bson_t **) docs, n_docs, opts, &op_reply, &op_error); + mongoc_collection_insert_many (coll, (const bson_t **) docs, n_docs, opts, &op_reply, &op_error); result_from_insert_many (result, &op_reply, &op_error); ret = true; done: @@ -2089,10 +1908,7 @@ operation_insert_many (test_t *test, } static bool -operation_insert_one (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_insert_one (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { bool ret = false; mongoc_collection_t *coll = NULL; @@ -2135,10 +1951,7 @@ operation_insert_one (test_t *test, } static bool -operation_replace_one (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_replace_one (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { bool ret = false; mongoc_collection_t *coll = NULL; @@ -2170,8 +1983,7 @@ operation_replace_one (test_t *test, } bson_destroy (&op_reply); - mongoc_collection_replace_one ( - coll, filter, replacement, opts, &op_reply, &op_error); + mongoc_collection_replace_one (coll, filter, replacement, opts, &op_reply, &op_error); result_from_update_or_replace (result, &op_reply, &op_error); @@ -2184,10 +1996,7 @@ operation_replace_one (test_t *test, } static bool -operation_update_one (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_update_one (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { bool ret = false; mongoc_collection_t *coll = NULL; @@ -2219,8 +2028,7 @@ operation_update_one (test_t *test, } bson_destroy (&op_reply); - mongoc_collection_update_one ( - coll, filter, update, opts, &op_reply, &op_error); + mongoc_collection_update_one (coll, filter, update, opts, &op_reply, &op_error); result_from_update_or_replace (result, &op_reply, &op_error); @@ -2233,10 +2041,7 @@ operation_update_one (test_t *test, } static bool -operation_update_many (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_update_many (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { bool ret = false; mongoc_collection_t *coll = NULL; @@ -2268,8 +2073,7 @@ operation_update_many (test_t *test, } bson_destroy (&op_reply); - mongoc_collection_update_many ( - coll, filter, update, opts, &op_reply, &op_error); + mongoc_collection_update_many (coll, filter, update, opts, &op_reply, &op_error); result_from_update_or_replace (result, &op_reply, &op_error); @@ -2282,10 +2086,7 @@ operation_update_many (test_t *test, } static bool -operation_iterate_until_document_or_error (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_iterate_until_document_or_error (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { bool ret = false; mongoc_change_stream_t *changestream = NULL; @@ -2302,28 +2103,24 @@ operation_iterate_until_document_or_error (test_t *test, } if (strcmp ("changestream", entity->type) == 0) { - changestream = - entity_map_get_changestream (test->entity_map, op->object, error); + changestream = entity_map_get_changestream (test->entity_map, op->object, error); if (!changestream) { goto done; } /* Loop until error or document is returned. */ while (!mongoc_change_stream_next (changestream, &doc)) { - if (mongoc_change_stream_error_document ( - changestream, &op_error, &op_reply)) { + if (mongoc_change_stream_error_document (changestream, &op_error, &op_reply)) { break; } } } else { - findcursor = - entity_map_get_findcursor (test->entity_map, op->object, error); + findcursor = entity_map_get_findcursor (test->entity_map, op->object, error); if (!findcursor) { goto done; } - entity_findcursor_iterate_until_document_or_error ( - findcursor, &doc, &op_error, &op_reply); + entity_findcursor_iterate_until_document_or_error (findcursor, &doc, &op_error, &op_reply); } if (NULL != doc) { @@ -2339,10 +2136,7 @@ operation_iterate_until_document_or_error (test_t *test, } static bool -operation_close (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_close (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { bool ret = false; entity_t *entity; @@ -2351,10 +2145,8 @@ operation_close (test_t *test, goto done; } - if (0 != strcmp (entity->type, "findcursor") && - 0 != strcmp (entity->type, "changestream")) { - test_set_error ( - error, "attempting to close an unsupported entity: %s", entity->type); + if (0 != strcmp (entity->type, "findcursor") && 0 != strcmp (entity->type, "changestream")) { + test_set_error (error, "attempting to close an unsupported entity: %s", entity->type); goto done; } @@ -2368,10 +2160,7 @@ operation_close (test_t *test, } static bool -operation_drop_index (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_drop_index (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { bool ret = false; entity_t *entity; @@ -2411,10 +2200,7 @@ operation_drop_index (test_t *test, } static bool -operation_failpoint (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_failpoint (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { bool ret = false; bson_parser_t *bp = NULL; @@ -2441,16 +2227,11 @@ operation_failpoint (test_t *test, rp = mongoc_read_prefs_new (MONGOC_READ_PRIMARY); bson_destroy (&op_reply); - mongoc_client_command_simple ( - client, "admin", failpoint, rp, &op_reply, &op_error); + mongoc_client_command_simple (client, "admin", failpoint, rp, &op_reply, &op_error); result_from_val_and_reply (result, NULL /* value */, &op_reply, &op_error); /* Add failpoint to list of test_t's known failpoints */ - register_failpoint ( - test, - (char *) bson_lookup_utf8 (failpoint, "configureFailPoint"), - client_id, - 0); + register_failpoint (test, (char *) bson_lookup_utf8 (failpoint, "configureFailPoint"), client_id, 0); ret = true; done: @@ -2461,10 +2242,7 @@ operation_failpoint (test_t *test, } static bool -operation_targeted_failpoint (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_targeted_failpoint (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { bool ret = false; bson_parser_t *bp = NULL; @@ -2488,8 +2266,7 @@ operation_targeted_failpoint (test_t *test, goto done; } - client_id = entity_map_get_session_client_id ( - test->entity_map, op->session_id, error); + client_id = entity_map_get_session_client_id (test->entity_map, op->session_id, error); if (!client_id) { goto done; } @@ -2501,24 +2278,18 @@ operation_targeted_failpoint (test_t *test, server_id = mongoc_client_session_get_server_id (op->session); if (0 == server_id) { - test_set_error ( - error, "expected session %s to be pinned but was not", op->session_id); + test_set_error (error, "expected session %s to be pinned but was not", op->session_id); goto done; } rp = mongoc_read_prefs_new (MONGOC_READ_PRIMARY); bson_destroy (&op_reply); - mongoc_client_command_simple_with_server_id ( - client, "admin", failpoint, rp, server_id, &op_reply, &op_error); + mongoc_client_command_simple_with_server_id (client, "admin", failpoint, rp, server_id, &op_reply, &op_error); result_from_val_and_reply (result, NULL /* value */, &op_reply, &op_error); /* Add failpoint to list of test_t's known failpoints */ - register_failpoint ( - test, - (char *) bson_lookup_utf8 (failpoint, "configureFailPoint"), - client_id, - server_id); + register_failpoint (test, (char *) bson_lookup_utf8 (failpoint, "configureFailPoint"), client_id, server_id); ret = true; done: @@ -2529,10 +2300,7 @@ operation_targeted_failpoint (test_t *test, } static bool -operation_delete (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_delete (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { bool ret = false; mongoc_gridfs_bucket_t *bucket = NULL; @@ -2551,8 +2319,7 @@ operation_delete (test_t *test, goto done; } - mongoc_gridfs_bucket_delete_by_id ( - bucket, bson_val_to_value (id), &op_error); + mongoc_gridfs_bucket_delete_by_id (bucket, bson_val_to_value (id), &op_error); result_from_val_and_reply (result, NULL, NULL, &op_error); ret = true; @@ -2562,10 +2329,7 @@ operation_delete (test_t *test, } static bool -operation_download (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_download (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { bool ret = false; mongoc_gridfs_bucket_t *bucket = NULL; @@ -2590,12 +2354,10 @@ operation_download (test_t *test, goto done; } - stream = mongoc_gridfs_bucket_open_download_stream ( - bucket, bson_val_to_value (id), &op_error); + stream = mongoc_gridfs_bucket_open_download_stream (bucket, bson_val_to_value (id), &op_error); if (stream) { - while ((bytes_read = - mongoc_stream_read (stream, buf, sizeof (buf), 1, 0)) > 0) { + while ((bytes_read = mongoc_stream_read (stream, buf, sizeof (buf), 1, 0)) > 0) { ASSERT (bson_in_range_signed (uint32_t, bytes_read)); _mongoc_array_append_vals (&all_bytes, buf, (uint32_t) bytes_read); } @@ -2616,10 +2378,7 @@ operation_download (test_t *test, } static bool -operation_upload (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_upload (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { bool ret = false; mongoc_gridfs_bucket_t *bucket = NULL; @@ -2644,8 +2403,7 @@ operation_upload (test_t *test, goto done; } - stream = mongoc_gridfs_bucket_open_upload_stream ( - bucket, filename, bson_parser_get_extra (bp), &file_id, &op_error); + stream = mongoc_gridfs_bucket_open_upload_stream (bucket, filename, bson_parser_get_extra (bp), &file_id, &op_error); if (stream) { size_t total_written = 0u; @@ -2653,17 +2411,14 @@ operation_upload (test_t *test, uint32_t source_bytes_len; bson_iter_t iter; - if (!bson_iter_init_find (&iter, source, "$$hexBytes") || - !BSON_ITER_HOLDS_UTF8 (&iter)) { + if (!bson_iter_init_find (&iter, source, "$$hexBytes") || !BSON_ITER_HOLDS_UTF8 (&iter)) { test_set_error (error, "$$hexBytes not found in source data"); goto done; } - source_bytes = - hex_to_bin (bson_iter_utf8 (&iter, NULL), &source_bytes_len); + source_bytes = hex_to_bin (bson_iter_utf8 (&iter, NULL), &source_bytes_len); while (total_written < source_bytes_len) { - const ssize_t bytes_written = mongoc_stream_write ( - stream, source_bytes, source_bytes_len - total_written, 0); + const ssize_t bytes_written = mongoc_stream_write (stream, source_bytes, source_bytes_len - total_written, 0); if (bytes_written < 0) { break; } @@ -2685,11 +2440,7 @@ operation_upload (test_t *test, } static bool -assert_session_dirty_helper (test_t *test, - operation_t *op, - result_t *result, - bool check_dirty, - bson_error_t *error) +assert_session_dirty_helper (test_t *test, operation_t *op, result_t *result, bool check_dirty, bson_error_t *error) { bool ret = false; @@ -2701,9 +2452,7 @@ assert_session_dirty_helper (test_t *test, } if (check_dirty != mongoc_client_session_get_dirty (op->session)) { - test_set_error (error, - "expected session to%s be dirty but was not", - check_dirty ? "" : " not"); + test_set_error (error, "expected session to%s be dirty but was not", check_dirty ? "" : " not"); goto done; } @@ -2714,19 +2463,13 @@ assert_session_dirty_helper (test_t *test, return ret; } static bool -operation_assert_session_not_dirty (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_assert_session_not_dirty (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { return assert_session_dirty_helper (test, op, result, false, error); } static bool -operation_assert_session_dirty (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_assert_session_dirty (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { return assert_session_dirty_helper (test, op, result, true, error); } @@ -2746,11 +2489,7 @@ next_started_event (event_t *iter) } static bool -assert_lsid_on_last_two_commands (test_t *test, - operation_t *op, - result_t *result, - bool check_same, - bson_error_t *error) +assert_lsid_on_last_two_commands (test_t *test, operation_t *op, result_t *result, bool check_same, bson_error_t *error) { bool ret = false; bson_parser_t *bp = NULL; @@ -2788,27 +2527,19 @@ assert_lsid_on_last_two_commands (test_t *test, } if (NULL == a || NULL == b) { - test_set_error (error, - "unable to find two commandStartedEvents on client: %s", - client_id); + test_set_error (error, "unable to find two commandStartedEvents on client: %s", client_id); goto done; } if (!bson_iter_init_find (&iter, a->command, "lsid")) { - test_set_error ( - error, - "unable to find lsid in second to last commandStartedEvent: %s", - tmp_json (a->command)); + test_set_error (error, "unable to find lsid in second to last commandStartedEvent: %s", tmp_json (a->command)); goto done; } bson_iter_bson (&iter, &a_lsid); if (!bson_iter_init_find (&iter, b->command, "lsid")) { - test_set_error ( - error, - "unable to find lsid in second to last commandStartedEvent: %s", - tmp_json (b->command)); + test_set_error (error, "unable to find lsid in second to last commandStartedEvent: %s", tmp_json (b->command)); goto done; } @@ -2832,10 +2563,7 @@ assert_lsid_on_last_two_commands (test_t *test, } static bool -operation_assert_same_lsid_on_last_two_commands (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_assert_same_lsid_on_last_two_commands (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { return assert_lsid_on_last_two_commands (test, op, result, true, error); } @@ -2850,10 +2578,7 @@ operation_assert_different_lsid_on_last_two_commands (test_t *test, } static bool -operation_end_session (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_end_session (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { bool ret = false; @@ -2868,10 +2593,7 @@ operation_end_session (test_t *test, } static bool -operation_start_transaction (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_start_transaction (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { bool ret = false; mongoc_client_session_t *session = NULL; @@ -2934,10 +2656,7 @@ transaction_state_to_string (mongoc_transaction_state_t tstate) } static bool -operation_assert_session_transaction_state (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_assert_session_transaction_state (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { bool ret = false; bson_parser_t *bp = NULL; @@ -2961,8 +2680,7 @@ operation_assert_session_transaction_state (test_t *test, state = mongoc_client_session_get_transaction_state (op->session); actual = transaction_state_to_string (state); if (0 != strcmp (expected, actual)) { - test_set_error ( - error, "expected state: %s, got state: %s", expected, actual); + test_set_error (error, "expected state: %s, got state: %s", expected, actual); goto done; } @@ -2975,11 +2693,7 @@ operation_assert_session_transaction_state (test_t *test, } static bool -assert_collection_exists (test_t *test, - operation_t *op, - result_t *result, - bool expect_exist, - bson_error_t *error) +assert_collection_exists (test_t *test, operation_t *op, result_t *result, bool expect_exist, bson_error_t *error) { bool ret = false; bson_parser_t *bp = NULL; @@ -2997,8 +2711,7 @@ assert_collection_exists (test_t *test, goto done; } - db = mongoc_client_get_database ( - test->test_file->test_runner->internal_client, database_name); + db = mongoc_client_get_database (test->test_file->test_runner->internal_client, database_name); head = mongoc_database_get_collection_names_with_opts (db, NULL, &op_error); for (iter = head; *iter; iter++) { if (0 == strcmp (*iter, collection_name)) { @@ -3027,28 +2740,19 @@ assert_collection_exists (test_t *test, } static bool -operation_assert_collection_exists (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_assert_collection_exists (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { return assert_collection_exists (test, op, result, true, error); } static bool -operation_assert_collection_not_exists (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_assert_collection_not_exists (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { return assert_collection_exists (test, op, result, false, error); } static bool -operation_commit_transaction (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_commit_transaction (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { bool ret = false; mongoc_client_session_t *session = NULL; @@ -3071,10 +2775,7 @@ operation_commit_transaction (test_t *test, } static bool -operation_abort_transaction (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_abort_transaction (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { bool ret = false; mongoc_client_session_t *session = NULL; @@ -3094,11 +2795,7 @@ operation_abort_transaction (test_t *test, } static bool -assert_index_exists (test_t *test, - operation_t *op, - result_t *result, - bool expect_exist, - bson_error_t *error) +assert_index_exists (test_t *test, operation_t *op, result_t *result, bool expect_exist, bson_error_t *error) { bool ret = false; bson_parser_t *bp = NULL; @@ -3120,10 +2817,7 @@ assert_index_exists (test_t *test, goto done; } - coll = mongoc_client_get_collection ( - test->test_file->test_runner->internal_client, - database_name, - collection_name); + coll = mongoc_client_get_collection (test->test_file->test_runner->internal_client, database_name, collection_name); cursor = mongoc_collection_find_indexes_with_opts (coll, NULL); while (mongoc_cursor_next (cursor, &index)) { bson_iter_t iter; @@ -3166,19 +2860,13 @@ assert_index_exists (test_t *test, } static bool -operation_assert_index_exists (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_assert_index_exists (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { return assert_index_exists (test, op, result, true, error); } static bool -operation_assert_index_not_exists (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_assert_index_not_exists (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { return assert_index_exists (test, op, result, false, error); } @@ -3189,10 +2877,7 @@ typedef struct { } txn_ctx_t; static bool -with_transaction_cb (mongoc_client_session_t *session, - void *ctx, - bson_t **reply, - bson_error_t *error) +with_transaction_cb (mongoc_client_session_t *session, void *ctx, bson_t **reply, bson_error_t *error) { bool ret = false; bson_iter_t iter; @@ -3220,10 +2905,7 @@ with_transaction_cb (mongoc_client_session_t *session, } static bool -operation_with_transaction (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_with_transaction (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { bool ret = false; bson_parser_t *bp = NULL; @@ -3265,8 +2947,7 @@ operation_with_transaction (test_t *test, tctx.test = test; bson_destroy (&op_reply); - mongoc_client_session_with_transaction ( - session, with_transaction_cb, topts, &tctx, &op_reply, &op_error); + mongoc_client_session_with_transaction (session, with_transaction_cb, topts, &tctx, &op_reply, &op_error); result_from_val_and_reply (result, NULL, &op_reply, &op_error); @@ -3279,11 +2960,7 @@ operation_with_transaction (test_t *test, } static bool -assert_session_pinned (test_t *test, - operation_t *op, - result_t *result, - bool expect_pinned, - bson_error_t *error) +assert_session_pinned (test_t *test, operation_t *op, result_t *result, bool expect_pinned, bson_error_t *error) { bool ret = false; bool actual_pinned = false; @@ -3314,27 +2991,19 @@ assert_session_pinned (test_t *test, } static bool -operation_assert_session_pinned (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_assert_session_pinned (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { return assert_session_pinned (test, op, result, true, error); } static bool -operation_assert_session_unpinned (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_assert_session_unpinned (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { return assert_session_pinned (test, op, result, false, error); } static bool -create_loop_bson_array_entity (entity_map_t *em, - const char *id, - bson_error_t *error) +create_loop_bson_array_entity (entity_map_t *em, const char *id, bson_error_t *error) { BSON_ASSERT_PARAM (em); BSON_ASSERT (id || true); @@ -3362,16 +3031,13 @@ create_loop_bson_array_entity (entity_map_t *em, // If the entity exists and is of a different type, the test runner MUST // raise an error. else { - test_set_error ( - error, "loop entity %s exists but is not of type BSON array", id); + test_set_error (error, "loop entity %s exists but is not of type BSON array", id); return false; } } static bool -create_loop_size_t_entity (entity_map_t *em, - const char *id, - bson_error_t *error) +create_loop_size_t_entity (entity_map_t *em, const char *id, bson_error_t *error) { BSON_ASSERT_PARAM (em); BSON_ASSERT (id || true); @@ -3386,8 +3052,7 @@ create_loop_size_t_entity (entity_map_t *em, // If the entity of the specified name already exists, the test runner MUST // raise an error. if (entity) { - test_set_error ( - error, "loop entity %s already exists when it should not", id); + test_set_error (error, "loop entity %s already exists when it should not", id); return false; } @@ -3412,10 +3077,7 @@ increment_loop_counter (entity_map_t *em, const char *id) } static bool -append_loop_error (entity_map_t *em, - const char *id, - bson_error_t *op_error, - bson_error_t *error) +append_loop_error (entity_map_t *em, const char *id, bson_error_t *op_error, bson_error_t *error) { BSON_ASSERT_PARAM (em); BSON_ASSERT (id || true); @@ -3449,10 +3111,7 @@ append_loop_error (entity_map_t *em, volatile sig_atomic_t operation_loop_terminated = false; static bool -operation_loop (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_loop (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { bool ret = false; @@ -3462,8 +3121,7 @@ operation_loop (test_t *test, BSON_ASSERT_PARAM (error); if (test->loop_operation_executed) { - test_set_error (error, - "test should not contain more than one loop operation"); + test_set_error (error, "test should not contain more than one loop operation"); return false; } else { test->loop_operation_executed = true; @@ -3484,12 +3142,9 @@ operation_loop (test_t *test, bson_parser_array (parser, "operations", &operations); bson_parser_utf8_optional (parser, "storeErrorsAsEntity", &errors_as_entity); - bson_parser_utf8_optional ( - parser, "storeFailuresAsEntity", &failures_as_entity); - bson_parser_utf8_optional ( - parser, "storeSuccessesAsEntity", &successes_as_entity); - bson_parser_utf8_optional ( - parser, "storeIterationsAsEntity", &iterations_as_entity); + bson_parser_utf8_optional (parser, "storeFailuresAsEntity", &failures_as_entity); + bson_parser_utf8_optional (parser, "storeSuccessesAsEntity", &successes_as_entity); + bson_parser_utf8_optional (parser, "storeIterationsAsEntity", &iterations_as_entity); if (!bson_parser_parse (parser, op->arguments, error)) { goto done; @@ -3516,23 +3171,19 @@ operation_loop (test_t *test, } } - if (!create_loop_bson_array_entity ( - test->entity_map, errors_as_entity, error)) { + if (!create_loop_bson_array_entity (test->entity_map, errors_as_entity, error)) { goto done; } - if (!create_loop_bson_array_entity ( - test->entity_map, failures_as_entity, error)) { + if (!create_loop_bson_array_entity (test->entity_map, failures_as_entity, error)) { goto done; } - if (!create_loop_size_t_entity ( - test->entity_map, successes_as_entity, error)) { + if (!create_loop_size_t_entity (test->entity_map, successes_as_entity, error)) { goto done; } - if (!create_loop_size_t_entity ( - test->entity_map, iterations_as_entity, error)) { + if (!create_loop_size_t_entity (test->entity_map, iterations_as_entity, error)) { goto done; } @@ -3562,14 +3213,12 @@ operation_loop (test_t *test, } else { // Categorize errors triggered by a sub-operation as a "failure". // If this operation fails, categorize as an "error" instead. - (void) append_loop_error ( - test->entity_map, failures_as_entity, &op_error, error); + (void) append_loop_error (test->entity_map, failures_as_entity, &op_error, error); // If neither storeErrorsAsEntity nor storeFailuresAsEntity are // specified, the loop MUST terminate and raise the error/failure // (i.e. the error/failure will interrupt the test). - operation_loop_terminated = - operation_loop_terminated || should_propagate; + operation_loop_terminated = operation_loop_terminated || should_propagate; // If, in the course of executing sub-operations, a sub-operation // yields an error or failure, the test runner MUST NOT execute @@ -3584,15 +3233,12 @@ operation_loop (test_t *test, // We have a problem if we can't store errors without triggering a new // error. Terminate the test suite early instead of looping with an // irrecoverable state. - ASSERT_OR_PRINT (append_loop_error ( - test->entity_map, errors_as_entity, error, error), - (*error)); + ASSERT_OR_PRINT (append_loop_error (test->entity_map, errors_as_entity, error, error), (*error)); // If neither storeErrorsAsEntity nor storeFailuresAsEntity are // specified, the loop MUST terminate and raise the error/failure // (i.e. the error/failure will interrupt the test). - operation_loop_terminated = - operation_loop_terminated || should_propagate; + operation_loop_terminated = operation_loop_terminated || should_propagate; } } MONGOC_DEBUG ("running loop operations... done."); @@ -3607,10 +3253,7 @@ operation_loop (test_t *test, } static bool -operation_assert_number_connections_checked_out (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_assert_number_connections_checked_out (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { BSON_UNUSED (test); BSON_UNUSED (op); @@ -3623,10 +3266,7 @@ operation_assert_number_connections_checked_out (test_t *test, } static bool -operation_rename (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_rename (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { // First validate the arguments const char *object = op->object; @@ -3671,10 +3311,7 @@ operation_rename (test_t *test, } static bool -operation_createSearchIndex (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_createSearchIndex (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { bool ret = false; bson_parser_t *bp = bson_parser_new (); @@ -3696,13 +3333,10 @@ operation_createSearchIndex (test_t *test, } // Build command. - bsonBuildAppend (*cmd, - kv ("createSearchIndexes", cstr (coll->collection)), - kv ("indexes", array (bson (*model)))); + bsonBuildAppend (*cmd, kv ("createSearchIndexes", cstr (coll->collection)), kv ("indexes", array (bson (*model)))); ASSERT (!bsonBuildError); - mongoc_collection_command_simple ( - coll, cmd, NULL /* read_prefs */, NULL /* reply */, &op_error); + mongoc_collection_command_simple (coll, cmd, NULL /* read_prefs */, NULL /* reply */, &op_error); result_from_val_and_reply (result, NULL, &op_reply, &op_error); ret = true; done: @@ -3713,10 +3347,7 @@ operation_createSearchIndex (test_t *test, } static bool -operation_createSearchIndexes (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_createSearchIndexes (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { bool ret = false; bson_parser_t *bp = bson_parser_new (); @@ -3738,13 +3369,10 @@ operation_createSearchIndexes (test_t *test, } // Build command. - bsonBuildAppend (*cmd, - kv ("createSearchIndexes", cstr (coll->collection)), - kv ("indexes", bsonArray (*models))); + bsonBuildAppend (*cmd, kv ("createSearchIndexes", cstr (coll->collection)), kv ("indexes", bsonArray (*models))); ASSERT (!bsonBuildError); - mongoc_collection_command_simple ( - coll, cmd, NULL /* read_prefs */, NULL /* reply */, &op_error); + mongoc_collection_command_simple (coll, cmd, NULL /* read_prefs */, NULL /* reply */, &op_error); result_from_val_and_reply (result, NULL, &op_reply, &op_error); ret = true; done: @@ -3755,10 +3383,7 @@ operation_createSearchIndexes (test_t *test, } static bool -operation_dropSearchIndex (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_dropSearchIndex (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { bool ret = false; bson_parser_t *bp = bson_parser_new (); @@ -3780,13 +3405,10 @@ operation_dropSearchIndex (test_t *test, } // Build command. - bsonBuildAppend (*cmd, - kv ("dropSearchIndex", cstr (coll->collection)), - kv ("name", cstr (name))); + bsonBuildAppend (*cmd, kv ("dropSearchIndex", cstr (coll->collection)), kv ("name", cstr (name))); ASSERT (!bsonBuildError); - mongoc_collection_command_simple ( - coll, cmd, NULL /* read_prefs */, NULL /* reply */, &op_error); + mongoc_collection_command_simple (coll, cmd, NULL /* read_prefs */, NULL /* reply */, &op_error); result_from_val_and_reply (result, NULL, &op_reply, &op_error); ret = true; done: @@ -3797,10 +3419,7 @@ operation_dropSearchIndex (test_t *test, } static bool -operation_listSearchIndexes (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_listSearchIndexes (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { bool ret = false; bson_parser_t *bp = bson_parser_new (); @@ -3825,20 +3444,14 @@ operation_listSearchIndexes (test_t *test, } // Build command. - bsonBuildAppend ( - *pipeline, - kv ("pipeline", - array (doc (kv ("$listSearchIndexes", - if (name != NULL, - then (doc (kv ("name", cstr (name)))), - else (doc ()))))))); + bsonBuildAppend (*pipeline, + kv ("pipeline", + array (doc (kv ("$listSearchIndexes", + if (name != NULL, then (doc (kv ("name", cstr (name)))), else (doc ()))))))); ASSERT (!bsonBuildError); - cursor = mongoc_collection_aggregate (coll, - MONGOC_QUERY_NONE, - pipeline, - aggregateOptions /* opts */, - NULL /* read_prefs */); + cursor = mongoc_collection_aggregate ( + coll, MONGOC_QUERY_NONE, pipeline, aggregateOptions /* opts */, NULL /* read_prefs */); result_from_cursor (result, cursor); ret = true; @@ -3850,10 +3463,7 @@ operation_listSearchIndexes (test_t *test, } static bool -operation_updateSearchIndex (test_t *test, - operation_t *op, - result_t *result, - bson_error_t *error) +operation_updateSearchIndex (test_t *test, operation_t *op, result_t *result, bson_error_t *error) { bool ret = false; bson_parser_t *bp = bson_parser_new (); @@ -3883,8 +3493,7 @@ operation_updateSearchIndex (test_t *test, if (name != NULL, then (kv ("name", cstr (name))))); ASSERT (!bsonBuildError); - mongoc_collection_command_simple ( - coll, cmd, NULL /* read_prefs */, NULL /* reply */, &op_error); + mongoc_collection_command_simple (coll, cmd, NULL /* read_prefs */, NULL /* reply */, &op_error); result_from_val_and_reply (result, NULL, &op_reply, &op_error); ret = true; done: @@ -3960,8 +3569,7 @@ operation_run (test_t *test, bson_t *op_bson, bson_error_t *error) {"updateSearchIndex", operation_updateSearchIndex}, /* Change stream and cursor operations */ - {"iterateUntilDocumentOrError", - operation_iterate_until_document_or_error}, + {"iterateUntilDocumentOrError", operation_iterate_until_document_or_error}, {"close", operation_close}, {"dropIndex", operation_drop_index}, @@ -3970,12 +3578,9 @@ operation_run (test_t *test, bson_t *op_bson, bson_error_t *error) {"targetedFailPoint", operation_targeted_failpoint}, {"assertSessionDirty", operation_assert_session_dirty}, {"assertSessionNotDirty", operation_assert_session_not_dirty}, - {"assertSameLsidOnLastTwoCommands", - operation_assert_same_lsid_on_last_two_commands}, - {"assertDifferentLsidOnLastTwoCommands", - operation_assert_different_lsid_on_last_two_commands}, - {"assertSessionTransactionState", - operation_assert_session_transaction_state}, + {"assertSameLsidOnLastTwoCommands", operation_assert_same_lsid_on_last_two_commands}, + {"assertDifferentLsidOnLastTwoCommands", operation_assert_different_lsid_on_last_two_commands}, + {"assertSessionTransactionState", operation_assert_session_transaction_state}, {"assertCollectionNotExists", operation_assert_collection_not_exists}, {"assertCollectionExists", operation_assert_collection_exists}, {"assertIndexNotExists", operation_assert_index_not_exists}, @@ -3983,8 +3588,7 @@ operation_run (test_t *test, bson_t *op_bson, bson_error_t *error) {"assertSessionPinned", operation_assert_session_pinned}, {"assertSessionUnpinned", operation_assert_session_unpinned}, {"loop", operation_loop}, - {"assertNumberConnectionsCheckedOut", - operation_assert_number_connections_checked_out}, + {"assertNumberConnectionsCheckedOut", operation_assert_number_connections_checked_out}, /* GridFS operations */ {"delete", operation_delete}, @@ -4012,10 +3616,8 @@ operation_run (test_t *test, bson_t *op_bson, bson_error_t *error) bson_t copied; mongoc_client_session_t *session = NULL; - op->session_id = - bson_strdup (bson_lookup_utf8 (op->arguments, "session")); - session = - entity_map_get_session (test->entity_map, op->session_id, error); + op->session_id = bson_strdup (bson_lookup_utf8 (op->arguments, "session")); + session = entity_map_get_session (test->entity_map, op->session_id, error); if (!session) { goto done; @@ -4045,22 +3647,14 @@ operation_run (test_t *test, bson_t *op_bson, bson_error_t *error) if (!op_to_fn_map[i].fn (test, op, result, error)) { goto done; } - if (check_result && !result_check (result, - test->entity_map, - op->expect_result, - op->expect_error, - error)) { - test_diagnostics_error_info ( - "checking for result (%s) / error (%s)", - bson_val_to_json (op->expect_result), - tmp_json (op->expect_error)); + if (check_result && !result_check (result, test->entity_map, op->expect_result, op->expect_error, error)) { + test_diagnostics_error_info ("checking for result (%s) / error (%s)", + bson_val_to_json (op->expect_result), + tmp_json (op->expect_error)); goto done; } if (result_get_val (result) != NULL && op->save_result_as_entity) { - if (!entity_map_add_bson (test->entity_map, - op->save_result_as_entity, - result_get_val (result), - error)) { + if (!entity_map_add_bson (test->entity_map, op->save_result_as_entity, result_get_val (result), error)) { goto done; } } diff --git a/src/libmongoc/tests/unified/result.c b/src/libmongoc/tests/unified/result.c index ddc2bbaacb..de8c5fbb06 100644 --- a/src/libmongoc/tests/unified/result.c +++ b/src/libmongoc/tests/unified/result.c @@ -43,10 +43,7 @@ result_new (void) } static void -_result_init (result_t *result, - const bson_val_t *value, - const bson_t *reply, - const bson_error_t *error) +_result_init (result_t *result, const bson_val_t *value, const bson_t *reply, const bson_error_t *error) { bson_string_t *str; @@ -116,8 +113,7 @@ rewrite_upserted_ids (bson_t *mongoc_upserted_ids) bson_parser_int (el_bp, "index", &index); bson_parser_any (el_bp, "_id", &id); bson_parser_parse_or_assert (el_bp, &el); - bson_uint32_to_string ( - (uint32_t) *index, &key, storage, sizeof (storage)); + bson_uint32_to_string ((uint32_t) *index, &key, storage, sizeof (storage)); BSON_APPEND_VALUE (upserted_ids, key, bson_val_to_value (id)); bson_parser_destroy_with_parsed_fields (el_bp); } @@ -130,24 +126,21 @@ rewrite_bulk_write_result (const bson_t *bulk_write_result) { bson_t *const res = bson_new (); if (!bson_empty0 (bulk_write_result)) { - BCON_APPEND ( - res, - "insertedCount", - BCON_INT32 (bson_lookup_int32 (bulk_write_result, "nInserted")), - "deletedCount", - BCON_INT32 (bson_lookup_int32 (bulk_write_result, "nRemoved")), - "matchedCount", - BCON_INT32 (bson_lookup_int32 (bulk_write_result, "nMatched")), - "modifiedCount", - BCON_INT32 (bson_lookup_int32 (bulk_write_result, "nModified")), - "upsertedCount", - BCON_INT32 (bson_lookup_int32 (bulk_write_result, "nUpserted"))); + BCON_APPEND (res, + "insertedCount", + BCON_INT32 (bson_lookup_int32 (bulk_write_result, "nInserted")), + "deletedCount", + BCON_INT32 (bson_lookup_int32 (bulk_write_result, "nRemoved")), + "matchedCount", + BCON_INT32 (bson_lookup_int32 (bulk_write_result, "nMatched")), + "modifiedCount", + BCON_INT32 (bson_lookup_int32 (bulk_write_result, "nModified")), + "upsertedCount", + BCON_INT32 (bson_lookup_int32 (bulk_write_result, "nUpserted"))); if (bson_has_field (bulk_write_result, "upserted")) { - bson_t *const upserted_ids = - bson_lookup_bson (bulk_write_result, "upserted"); - bson_t *const rewritten_upserted_ids = - rewrite_upserted_ids (upserted_ids); + bson_t *const upserted_ids = bson_lookup_bson (bulk_write_result, "upserted"); + bson_t *const rewritten_upserted_ids = rewrite_upserted_ids (upserted_ids); BSON_APPEND_DOCUMENT (res, "upsertedIds", rewritten_upserted_ids); bson_destroy (upserted_ids); bson_destroy (rewritten_upserted_ids); @@ -162,9 +155,7 @@ rewrite_bulk_write_result (const bson_t *bulk_write_result) } void -result_from_bulk_write (result_t *result, - const bson_t *reply, - const bson_error_t *error) +result_from_bulk_write (result_t *result, const bson_t *reply, const bson_error_t *error) { bson_t *const write_result = rewrite_bulk_write_result (reply); bson_val_t *const val = bson_val_from_bson (write_result); @@ -176,18 +167,14 @@ result_from_bulk_write (result_t *result, } void -result_from_insert_one (result_t *result, - const bson_t *reply, - const bson_error_t *error) +result_from_insert_one (result_t *result, const bson_t *reply, const bson_error_t *error) { bson_t *write_result; bson_val_t *val; write_result = bson_new (); if (!bson_empty (reply)) { - BCON_APPEND (write_result, - "insertedCount", - BCON_INT32 (bson_lookup_int32 (reply, "insertedCount"))); + BCON_APPEND (write_result, "insertedCount", BCON_INT32 (bson_lookup_int32 (reply, "insertedCount"))); } val = bson_val_from_bson (write_result); @@ -197,9 +184,7 @@ result_from_insert_one (result_t *result, } void -result_from_insert_many (result_t *result, - const bson_t *reply, - const bson_error_t *error) +result_from_insert_many (result_t *result, const bson_t *reply, const bson_error_t *error) { bson_t *write_result; bson_val_t *val; @@ -229,9 +214,7 @@ result_from_insert_many (result_t *result, } void -result_from_update_or_replace (result_t *result, - const bson_t *reply, - const bson_error_t *error) +result_from_update_or_replace (result_t *result, const bson_t *reply, const bson_error_t *error) { bson_t *write_result; bson_val_t *val; @@ -248,8 +231,7 @@ result_from_update_or_replace (result_t *result, BCON_INT32 (bson_lookup_int32 (reply, "upsertedCount"))); if (bson_iter_init_find (&iter, reply, "upsertedId")) { - BSON_APPEND_VALUE ( - write_result, "upsertedId", bson_iter_value (&iter)); + BSON_APPEND_VALUE (write_result, "upsertedId", bson_iter_value (&iter)); } } @@ -260,18 +242,14 @@ result_from_update_or_replace (result_t *result, } void -result_from_delete (result_t *result, - const bson_t *reply, - const bson_error_t *error) +result_from_delete (result_t *result, const bson_t *reply, const bson_error_t *error) { bson_t *write_result; bson_val_t *val; write_result = bson_new (); if (!bson_empty (reply)) { - BCON_APPEND (write_result, - "deletedCount", - BCON_INT32 (bson_lookup_int32 (reply, "deletedCount"))); + BCON_APPEND (write_result, "deletedCount", BCON_INT32 (bson_lookup_int32 (reply, "deletedCount"))); } val = bson_val_from_bson (write_result); @@ -281,9 +259,7 @@ result_from_delete (result_t *result, } void -result_from_distinct (result_t *result, - const bson_t *reply, - const bson_error_t *error) +result_from_distinct (result_t *result, const bson_t *reply, const bson_error_t *error) { bson_val_t *val = NULL; bson_iter_t iter; @@ -312,8 +288,7 @@ result_from_cursor (result_t *result, mongoc_cursor_t *cursor) const char *key; char storage[16]; - bson_uint32_to_string ( - i, &key, storage, sizeof (storage) / sizeof (char)); + bson_uint32_to_string (i, &key, storage, sizeof (storage) / sizeof (char)); BSON_APPEND_DOCUMENT (documents, key, doc); i++; } @@ -328,10 +303,7 @@ result_from_cursor (result_t *result, mongoc_cursor_t *cursor) } void -result_from_val_and_reply (result_t *result, - const bson_val_t *val, - const bson_t *reply, - const bson_error_t *error) +result_from_val_and_reply (result_t *result, const bson_val_t *val, const bson_t *reply, const bson_error_t *error) { _result_init (result, val, reply, error); } @@ -344,11 +316,7 @@ result_from_ok (result_t *result) } bool -result_check (result_t *result, - entity_map_t *em, - bson_val_t *expect_result, - bson_t *expect_error, - bson_error_t *error) +result_check (result_t *result, entity_map_t *em, bson_val_t *expect_result, bson_t *expect_error, bson_error_t *error) { bool ret = false; bson_parser_t *parser = NULL; @@ -364,9 +332,7 @@ result_check (result_t *result, if (!expect_result && !expect_error) { if (!result->ok) { - test_set_error (error, - "expected success, but got error: %s", - result->error.message); + test_set_error (error, "expected success, but got error: %s", result->error.message); goto done; } ret = true; @@ -376,19 +342,13 @@ result_check (result_t *result, /* check result. */ if (expect_result) { if (!result->ok) { - test_set_error ( - error, "expected result, but got error: %s", result->error.message); + test_set_error (error, "expected result, but got error: %s", result->error.message); goto done; } - if (!entity_map_match (em, - expect_result, - result->value, - result->array_of_root_docs, - error)) { - test_diagnostics_error_info ( - "expectResult mismatch:\nExpected: %s\nActual: %s\n", - bson_val_to_json (expect_result), - bson_val_to_json (result->value)); + if (!entity_map_match (em, expect_result, result->value, result->array_of_root_docs, error)) { + test_diagnostics_error_info ("expectResult mismatch:\nExpected: %s\nActual: %s\n", + bson_val_to_json (expect_result), + bson_val_to_json (result->value)); goto done; } } @@ -400,10 +360,8 @@ result_check (result_t *result, bson_parser_utf8_optional (parser, "errorContains", &error_contains); bson_parser_int_optional (parser, "errorCode", &error_code); bson_parser_utf8_optional (parser, "errorCodeName", &error_code_name); - bson_parser_array_optional ( - parser, "errorLabelsContain", &error_labels_contain); - bson_parser_array_optional ( - parser, "errorLabelsOmit", &error_labels_omit); + bson_parser_array_optional (parser, "errorLabelsContain", &error_labels_contain); + bson_parser_array_optional (parser, "errorLabelsOmit", &error_labels_omit); bson_parser_any_optional (parser, "expectResult", &error_expect_result); bson_parser_any_optional (parser, "errorResponse", &error_response); if (!bson_parser_parse (parser, expect_error, error)) { @@ -413,9 +371,7 @@ result_check (result_t *result, MONGOC_DEBUG ("expected error"); if (result->ok) { - test_set_error (error, - "expected error, but no error: %s", - bson_val_to_json (result->value)); + test_set_error (error, "expected error, but no error: %s", bson_val_to_json (result->value)); goto done; } @@ -423,11 +379,9 @@ result_check (result_t *result, /* from errors.rst: "In Version 2, error codes originating on the * server always have error domain ``MONGOC_ERROR_SERVER`` or * ``MONGOC_ERROR_WRITE_CONCERN``" */ - if (result->error.domain == MONGOC_ERROR_SERVER || - result->error.domain == MONGOC_ERROR_WRITE_CONCERN_ERROR) { + if (result->error.domain == MONGOC_ERROR_SERVER || result->error.domain == MONGOC_ERROR_WRITE_CONCERN_ERROR) { test_set_error (error, - "expected client side error, but got: %" PRIu32 - ", %" PRIu32, + "expected client side error, but got: %" PRIu32 ", %" PRIu32, result->error.domain, result->error.code); goto done; @@ -436,21 +390,16 @@ result_check (result_t *result, if (error_contains) { if (strstr (result->error.message, error_contains) == NULL) { - test_set_error (error, - "expected error to contain \"%s\", but got: \"%s\"", - error_contains, - result->error.message); + test_set_error ( + error, "expected error to contain \"%s\", but got: \"%s\"", error_contains, result->error.message); goto done; } } if (error_code) { if ((*error_code) != (int64_t) result->error.code) { - test_set_error (error, - "expected error code %" PRIi64 - ", but got: %" PRIi64, - *error_code, - (int64_t) result->error.code); + test_set_error ( + error, "expected error code %" PRIi64 ", but got: %" PRIi64, *error_code, (int64_t) result->error.code); goto done; } } @@ -482,10 +431,7 @@ result_check (result_t *result, bson_iter_t iter; if (!result->reply) { - test_set_error ( - error, - "%s", - "expected error to contain labels, but got no error document"); + test_set_error (error, "%s", "expected error to contain labels, but got no error document"); goto done; } @@ -494,19 +440,15 @@ result_check (result_t *result, const char *label; if (!BSON_ITER_HOLDS_UTF8 (&iter)) { - test_set_error (error, - "expected UTF8 error label, got: %s", - bson_type_to_string (bson_iter_type (&iter))); + test_set_error ( + error, "expected UTF8 error label, got: %s", bson_type_to_string (bson_iter_type (&iter))); goto done; } label = bson_iter_utf8 (&iter, NULL); if (!mongoc_error_has_label (result->reply, label)) { test_set_error ( - error, - "expected error to contain label: %s, but got: %s", - label, - tmp_json (result->reply)); + error, "expected error to contain label: %s, but got: %s", label, tmp_json (result->reply)); goto done; } } @@ -516,10 +458,7 @@ result_check (result_t *result, bson_iter_t iter; if (!result->reply) { - test_set_error ( - error, - "%s", - "expected error to omit labels, but got no error document"); + test_set_error (error, "%s", "expected error to omit labels, but got no error document"); goto done; } @@ -528,18 +467,14 @@ result_check (result_t *result, const char *label; if (!BSON_ITER_HOLDS_UTF8 (&iter)) { - test_set_error (error, - "expected UTF8 error label, got: %s", - bson_type_to_string (bson_iter_type (&iter))); + test_set_error ( + error, "expected UTF8 error label, got: %s", bson_type_to_string (bson_iter_type (&iter))); goto done; } label = bson_iter_utf8 (&iter, NULL); if (mongoc_error_has_label (result->reply, label)) { - test_set_error (error, - "expected error to omit label: %s, but got: %s", - label, - tmp_json (result->reply)); + test_set_error (error, "expected error to omit label: %s, but got: %s", label, tmp_json (result->reply)); goto done; } } @@ -547,8 +482,7 @@ result_check (result_t *result, if (error_expect_result) { if (!result->value) { - test_set_error ( - error, "%s", "expected error with result, but result unset"); + test_set_error (error, "%s", "expected error with result, but result unset"); goto done; } @@ -556,22 +490,17 @@ result_check (result_t *result, * operations, so array_of_root_docs should always be false */ BSON_ASSERT (!result->array_of_root_docs); - if (!bson_match (error_expect_result, - result->value, - result->array_of_root_docs, - error)) { - test_diagnostics_error_info ( - "error.expectResult mismatch:\nExpected: %s\nActual: %s\n", - bson_val_to_json (error_expect_result), - bson_val_to_json (result->value)); + if (!bson_match (error_expect_result, result->value, result->array_of_root_docs, error)) { + test_diagnostics_error_info ("error.expectResult mismatch:\nExpected: %s\nActual: %s\n", + bson_val_to_json (error_expect_result), + bson_val_to_json (result->value)); goto done; } } if (error_response) { if (!result->reply) { - test_set_error ( - error, "%s", "expected error with a reply, but reply unset"); + test_set_error (error, "%s", "expected error with a reply, but reply unset"); goto done; } @@ -584,19 +513,17 @@ result_check (result_t *result, bson_iter_t child; if (!BSON_ITER_HOLDS_ARRAY (&iter)) { - test_set_error ( - error, - "expected errorReplies to be an array, but received %s", - bson_type_to_string (bson_iter_type (&iter))); + test_set_error (error, + "expected errorReplies to be an array, but received %s", + bson_type_to_string (bson_iter_type (&iter))); goto done; } bson_iter_recurse (&iter, &child); bson_iter_next (&child); if (!BSON_ITER_HOLDS_DOCUMENT (&child)) { - test_set_error ( - error, - "expected errorReplies.0 to be a document but received %s", - bson_type_to_string (bson_iter_type (&iter))); + test_set_error (error, + "expected errorReplies.0 to be a document but received %s", + bson_type_to_string (bson_iter_type (&iter))); goto done; } bson_iter_bson (&child, &doc_to_match); @@ -606,14 +533,10 @@ result_check (result_t *result, bson_val_t *val_to_match = bson_val_from_bson (&doc_to_match); - if (!bson_match (error_response, - val_to_match, - result->array_of_root_docs, - error)) { - test_diagnostics_error_info ( - "error.errorResponse mismatch:\nExpected: %s\nActual: %s\n", - bson_val_to_json (error_response), - bson_as_json (result->reply, NULL)); + if (!bson_match (error_response, val_to_match, result->array_of_root_docs, error)) { + test_diagnostics_error_info ("error.errorResponse mismatch:\nExpected: %s\nActual: %s\n", + bson_val_to_json (error_response), + bson_as_json (result->reply, NULL)); bson_val_destroy (val_to_match); bson_destroy (&doc_to_match); goto done; @@ -641,9 +564,8 @@ test_resultfrombulkwrite (void) result = result_new (); reply = tmp_bson ("{ 'nInserted': 0, 'nRemoved' : 1, 'nMatched' : 2, " "'nModified' : 3, 'nUpserted' : 4 }"); - expect = bson_val_from_json ( - "{ 'insertedCount': 0, 'deletedCount': 1, 'matchedCount': 2, " - "'modifiedCount': 3, 'upsertedCount': 4}"); + expect = bson_val_from_json ("{ 'insertedCount': 0, 'deletedCount': 1, 'matchedCount': 2, " + "'modifiedCount': 3, 'upsertedCount': 4}"); result_from_bulk_write (result, reply, &empty); MONGOC_DEBUG ("rewritten to: %s", bson_val_to_json (result->value)); if (!result_check (result, NULL, expect, NULL, &error)) { @@ -656,6 +578,5 @@ test_resultfrombulkwrite (void) void test_result_install (TestSuite *suite) { - TestSuite_Add ( - suite, "/unified/result/resultfrombulkwrite", test_resultfrombulkwrite); + TestSuite_Add (suite, "/unified/result/resultfrombulkwrite", test_resultfrombulkwrite); } diff --git a/src/libmongoc/tests/unified/result.h b/src/libmongoc/tests/unified/result.h index 0ecff3e91a..b0cf1b75f8 100644 --- a/src/libmongoc/tests/unified/result.h +++ b/src/libmongoc/tests/unified/result.h @@ -31,43 +31,28 @@ void result_destroy (result_t *result); void -result_from_bulk_write (result_t *result, - const bson_t *reply, - const bson_error_t *error); +result_from_bulk_write (result_t *result, const bson_t *reply, const bson_error_t *error); void -result_from_insert_one (result_t *result, - const bson_t *reply, - const bson_error_t *error); +result_from_insert_one (result_t *result, const bson_t *reply, const bson_error_t *error); void -result_from_insert_many (result_t *result, - const bson_t *reply, - const bson_error_t *error); +result_from_insert_many (result_t *result, const bson_t *reply, const bson_error_t *error); void -result_from_delete (result_t *result, - const bson_t *reply, - const bson_error_t *error); +result_from_delete (result_t *result, const bson_t *reply, const bson_error_t *error); void -result_from_distinct (result_t *result, - const bson_t *reply, - const bson_error_t *error); +result_from_distinct (result_t *result, const bson_t *reply, const bson_error_t *error); void -result_from_update_or_replace (result_t *result, - const bson_t *reply, - const bson_error_t *error); +result_from_update_or_replace (result_t *result, const bson_t *reply, const bson_error_t *error); void result_from_cursor (result_t *result, mongoc_cursor_t *cursor); void -result_from_val_and_reply (result_t *result, - const bson_val_t *value, - const bson_t *reply, - const bson_error_t *error); +result_from_val_and_reply (result_t *result, const bson_val_t *value, const bson_t *reply, const bson_error_t *error); void result_from_ok (result_t *result); @@ -82,10 +67,6 @@ bson_t * rewrite_bulk_write_result (const bson_t *bulk_write_result); bool -result_check (result_t *result, - entity_map_t *em, - bson_val_t *expect_result, - bson_t *expect_error, - bson_error_t *error); +result_check (result_t *result, entity_map_t *em, bson_val_t *expect_result, bson_t *expect_error, bson_error_t *error); #endif /* UNIFIED_OPERATION_RESULT_H */ diff --git a/src/libmongoc/tests/unified/runner.c b/src/libmongoc/tests/unified/runner.c index 3926fa0dd0..c43a6d4248 100644 --- a/src/libmongoc/tests/unified/runner.c +++ b/src/libmongoc/tests/unified/runner.c @@ -70,8 +70,7 @@ is_test_file_skipped (test_file_t *test_file) skipped_unified_test_t *skip; for (skip = SKIPPED_TESTS; skip->file_description != NULL; skip++) { - if (!strcmp (skip->file_description, test_file->description) && - skip->test_description == SKIP_ALL_TESTS) { + if (!strcmp (skip->file_description, test_file->description) && skip->test_description == SKIP_ALL_TESTS) { return true; } } @@ -125,10 +124,7 @@ failpoint_destroy (failpoint_t *fp) /* Set server_id to 0 if the failpoint was not against a pinned mongos. */ void -register_failpoint (test_t *test, - char *name, - char *client_id, - uint32_t server_id) +register_failpoint (test_t *test, char *name, char *client_id, uint32_t server_id) { failpoint_t *fp = NULL; @@ -155,22 +151,15 @@ cleanup_failpoints (test_t *test, bson_error_t *error) goto done; } - disable_cmd = - tmp_bson ("{'configureFailPoint': '%s', 'mode': 'off' }", iter->name); + disable_cmd = tmp_bson ("{'configureFailPoint': '%s', 'mode': 'off' }", iter->name); if (iter->server_id != 0) { - if (!mongoc_client_command_simple_with_server_id (client, - "admin", - disable_cmd, - rp, - iter->server_id, - NULL /* reply */, - error)) { + if (!mongoc_client_command_simple_with_server_id ( + client, "admin", disable_cmd, rp, iter->server_id, NULL /* reply */, error)) { bson_destroy (disable_cmd); goto done; } } else { - if (!mongoc_client_command_simple ( - client, "admin", disable_cmd, rp, NULL /* reply */, error)) { + if (!mongoc_client_command_simple (client, "admin", disable_cmd, rp, NULL /* reply */, error)) { bson_destroy (disable_cmd); goto done; } @@ -206,21 +195,18 @@ get_topology_type (mongoc_client_t *client); static bool is_topology_type_sharded (const char *topology_type) { - return 0 == strcmp ("sharded", topology_type) || - 0 == strcmp ("sharded-replicaset", topology_type); + return 0 == strcmp ("sharded", topology_type) || 0 == strcmp ("sharded-replicaset", topology_type); } static bool -is_topology_type_compatible (const char *test_topology_type, - const char *server_topology_type) +is_topology_type_compatible (const char *test_topology_type, const char *server_topology_type) { if (0 == strcmp (test_topology_type, server_topology_type)) { return true; } /* If a requirement specifies a "sharded" topology and server is of type * "sharded-replicaset", that is also compatible. */ - return 0 == strcmp (test_topology_type, "sharded") && - is_topology_type_sharded (server_topology_type); + return 0 == strcmp (test_topology_type, "sharded") && is_topology_type_sharded (server_topology_type); } /* This callback tracks the set of server IDs for all connected servers. @@ -236,8 +222,7 @@ on_topology_changed (const mongoc_apm_topology_changed_t *event) size_t sds_len; size_t i; - test_runner = - (test_runner_t *) mongoc_apm_topology_changed_get_context (event); + test_runner = (test_runner_t *) mongoc_apm_topology_changed_get_context (event); _mongoc_array_clear (&test_runner->server_ids); td = mongoc_apm_topology_changed_get_new_description (event); sds = mongoc_topology_description_get_servers (td, &sds_len); @@ -276,8 +261,7 @@ test_runner_get_all_server_ids (test_runner_t *test_runner, mongoc_array_t *out) * See also: Spec section "Terminating Open Transactions" */ static bool -test_runner_terminate_open_transactions (test_runner_t *test_runner, - bson_error_t *error) +test_runner_terminate_open_transactions (test_runner_t *test_runner, bson_error_t *error) { bson_t *kill_all_sessions_cmd = NULL; bool ret = false; @@ -303,22 +287,20 @@ test_runner_terminate_open_transactions (test_runner_t *test_runner, for (i = 0; i < server_ids.len; i++) { uint32_t server_id = _mongoc_array_index (&server_ids, uint32_t, i); - cmd_ret = mongoc_client_command_simple_with_server_id ( - test_runner->internal_client, - "admin", - kill_all_sessions_cmd, - NULL /* read prefs. */, - server_id, - NULL, - &cmd_error); + cmd_ret = mongoc_client_command_simple_with_server_id (test_runner->internal_client, + "admin", + kill_all_sessions_cmd, + NULL /* read prefs. */, + server_id, + NULL, + &cmd_error); /* Ignore error code 11601 as a workaround for SERVER-38335. */ if (!cmd_ret && cmd_error.code != 11601) { - test_set_error ( - error, - "Unexpected error running killAllSessions on server (%d): %s", - (int) server_id, - cmd_error.message); + test_set_error (error, + "Unexpected error running killAllSessions on server (%d): %s", + (int) server_id, + cmd_error.message); _mongoc_array_destroy (&server_ids); goto done; } @@ -326,19 +308,12 @@ test_runner_terminate_open_transactions (test_runner_t *test_runner, _mongoc_array_destroy (&server_ids); } else { /* Run on primary. */ - cmd_ret = mongoc_client_command_simple (test_runner->internal_client, - "admin", - kill_all_sessions_cmd, - NULL /* read prefs. */, - NULL, - &cmd_error); + cmd_ret = mongoc_client_command_simple ( + test_runner->internal_client, "admin", kill_all_sessions_cmd, NULL /* read prefs. */, NULL, &cmd_error); /* Ignore error code 11601 as a workaround for SERVER-38335. */ if (!cmd_ret && cmd_error.code != 11601) { - test_set_error ( - error, - "Unexpected error running killAllSessions on primary: %s", - cmd_error.message); + test_set_error (error, "Unexpected error running killAllSessions on primary: %s", cmd_error.message); goto done; } } @@ -363,8 +338,7 @@ test_runner_new (void) { mongoc_uri_t *const uri = test_framework_get_uri (); - test_runner->internal_client = - test_framework_client_new_from_uri (uri, NULL); + test_runner->internal_client = test_framework_client_new_from_uri (uri, NULL); /* In load balanced mode, the internal client must use the * SINGLE_LB_MONGOS_URI. */ @@ -382,18 +356,15 @@ test_runner_new (void) { mongoc_apm_callbacks_t *const callbacks = mongoc_apm_callbacks_new (); mongoc_apm_set_topology_changed_cb (callbacks, on_topology_changed); - mongoc_client_set_apm_callbacks ( - test_runner->internal_client, callbacks, test_runner); + mongoc_client_set_apm_callbacks (test_runner->internal_client, callbacks, test_runner); mongoc_apm_callbacks_destroy (callbacks); } test_framework_set_ssl_opts (test_runner->internal_client); - mongoc_client_set_error_api (test_runner->internal_client, - MONGOC_ERROR_API_VERSION_2); + mongoc_client_set_error_api (test_runner->internal_client, MONGOC_ERROR_API_VERSION_2); - test_runner->topology_type = - get_topology_type (test_runner->internal_client); + test_runner->topology_type = get_topology_type (test_runner->internal_client); server_semver (test_runner->internal_client, &test_runner->server_version); test_runner->is_serverless = test_framework_is_serverless (); @@ -406,15 +377,9 @@ test_runner_new (void) { bson_t reply; /* Cache server parameters to check runOnRequirements. */ - if (!mongoc_client_command_simple (test_runner->internal_client, - "admin", - tmp_bson ("{'getParameter': '*'}"), - NULL, - &reply, - &error)) { - test_error ("error getting server parameters: %s, full reply: %s", - error.message, - tmp_json (&reply)); + if (!mongoc_client_command_simple ( + test_runner->internal_client, "admin", tmp_bson ("{'getParameter': '*'}"), NULL, &reply, &error)) { + test_error ("error getting server parameters: %s, full reply: %s", error.message, tmp_json (&reply)); } test_runner->server_parameters = bson_copy (&reply); bson_destroy (&reply); @@ -445,10 +410,8 @@ test_file_new (test_runner_t *test_runner, bson_t *bson) parser = bson_parser_new (); bson_parser_utf8 (parser, "description", &test_file->description); bson_parser_utf8 (parser, "schemaVersion", &schema_version); - bson_parser_array_optional ( - parser, "runOnRequirements", &test_file->run_on_requirements); - bson_parser_array_optional ( - parser, "createEntities", &test_file->create_entities); + bson_parser_array_optional (parser, "runOnRequirements", &test_file->run_on_requirements); + bson_parser_array_optional (parser, "createEntities", &test_file->create_entities); bson_parser_array_optional (parser, "initialData", &test_file->initial_data); bson_parser_doc_optional (parser, "_yamlAnchors", &test_file->yaml_anchors); bson_parser_array (parser, "tests", &test_file->tests); @@ -482,8 +445,7 @@ test_new (test_file_t *test_file, bson_t *bson) test->test_file = test_file; parser = bson_parser_new (); bson_parser_utf8 (parser, "description", &test->description); - bson_parser_array_optional ( - parser, "runOnRequirements", &test->run_on_requirements); + bson_parser_array_optional (parser, "runOnRequirements", &test->run_on_requirements); bson_parser_utf8_optional (parser, "skipReason", &test->skip_reason); bson_parser_array (parser, "operations", &test->operations); bson_parser_array_optional (parser, "expectEvents", &test->expect_events); @@ -522,8 +484,7 @@ is_replset (bson_t *hello_reply) return true; } - if (bson_has_field (hello_reply, "isreplicaset") && - bson_lookup_bool (hello_reply, "isreplicaset") == true) { + if (bson_has_field (hello_reply, "isreplicaset") && bson_lookup_bool (hello_reply, "isreplicaset") == true) { return true; } @@ -560,17 +521,11 @@ get_topology_type (mongoc_client_t *client) return "load-balanced"; } - ret = mongoc_client_command_simple ( - client, "admin", tmp_bson ("{'hello': 1}"), NULL, &reply, &error); + ret = mongoc_client_command_simple (client, "admin", tmp_bson ("{'hello': 1}"), NULL, &reply, &error); if (!ret) { bson_destroy (&reply); ret = mongoc_client_command_simple ( - client, - "admin", - tmp_bson ("{'" HANDSHAKE_CMD_LEGACY_HELLO "': 1}"), - NULL, - &reply, - &error); + client, "admin", tmp_bson ("{'" HANDSHAKE_CMD_LEGACY_HELLO "': 1}"), NULL, &reply, &error); } ASSERT_OR_PRINT (ret, error); @@ -586,13 +541,10 @@ get_topology_type (mongoc_client_t *client) * collection. */ is_sharded_replset = true; config_shards = mongoc_client_get_collection (client, "config", "shards"); - cursor = mongoc_collection_find_with_opts (config_shards, - tmp_bson ("{}"), - NULL /* opts */, - NULL /* read prefs */); + cursor = + mongoc_collection_find_with_opts (config_shards, tmp_bson ("{}"), NULL /* opts */, NULL /* read prefs */); if (mongoc_cursor_error (cursor, &error)) { - test_error ("Attempting to query config.shards collection failed: %s", - error.message); + test_error ("Attempting to query config.shards collection failed: %s", error.message); } while (mongoc_cursor_next (cursor, &shard_doc)) { const char *host = bson_lookup_utf8 (shard_doc, "host"); @@ -619,15 +571,12 @@ get_topology_type (mongoc_client_t *client) static void check_schema_version (test_file_t *test_file) { - const char *supported_version_strs[] = { - "1.8", /* fully supported through this version */ - "1.12", /* partially supported (expectedError.errorResponse assertions) */ - "1.18" /* partially supported (additional properties in kmsProviders) */}; + const char *supported_version_strs[] = {"1.8", /* fully supported through this version */ + "1.12", /* partially supported (expectedError.errorResponse assertions) */ + "1.18" /* partially supported (additional properties in kmsProviders) */}; int i; - for (i = 0; i < sizeof (supported_version_strs) / - sizeof (supported_version_strs[0]); - i++) { + for (i = 0; i < sizeof (supported_version_strs) / sizeof (supported_version_strs[0]); i++) { semver_t supported_version; semver_parse (supported_version_strs[i], &supported_version); @@ -643,8 +592,7 @@ check_schema_version (test_file_t *test_file) } } - test_error ("Unsupported schema version: %s", - semver_to_string (&test_file->schema_version)); + test_error ("Unsupported schema version: %s", semver_to_string (&test_file->schema_version)); } static bool @@ -665,10 +613,9 @@ check_run_on_requirement (test_runner_t *test_runner, semver_parse (bson_iter_utf8 (&req_iter, NULL), &min_server_version); if (semver_cmp (server_version, &min_server_version) < 0) { - *fail_reason = bson_strdup_printf ( - "Server version(%s) is lower than minServerVersion(%s)", - semver_to_string (server_version), - semver_to_string (&min_server_version)); + *fail_reason = bson_strdup_printf ("Server version(%s) is lower than minServerVersion(%s)", + semver_to_string (server_version), + semver_to_string (&min_server_version)); return false; } continue; @@ -679,10 +626,9 @@ check_run_on_requirement (test_runner_t *test_runner, semver_parse (bson_iter_utf8 (&req_iter, NULL), &max_server_version); if (semver_cmp (server_version, &max_server_version) > 0) { - *fail_reason = bson_strdup_printf ( - "Server version(%s) is higher than maxServerVersion (%s)", - semver_to_string (server_version), - semver_to_string (&max_server_version)); + *fail_reason = bson_strdup_printf ("Server version(%s) is higher than maxServerVersion (%s)", + semver_to_string (server_version), + semver_to_string (&max_server_version)); return false; } continue; @@ -696,10 +642,8 @@ check_run_on_requirement (test_runner_t *test_runner, bson_iter_bson (&req_iter, &topologies); BSON_FOREACH (&topologies, topology_iter) { - const char *test_topology_type = - bson_iter_utf8 (&topology_iter, NULL); - if (is_topology_type_compatible (test_topology_type, - server_topology_type)) { + const char *test_topology_type = bson_iter_utf8 (&topology_iter, NULL); + if (is_topology_type_compatible (test_topology_type, server_topology_type)) { found = true; continue; } @@ -707,9 +651,7 @@ check_run_on_requirement (test_runner_t *test_runner, if (!found) { *fail_reason = bson_strdup_printf ( - "Topology (%s) was not found among listed topologies: %s", - server_topology_type, - tmp_json (&topologies)); + "Topology (%s) was not found among listed topologies: %s", server_topology_type, tmp_json (&topologies)); return false; } continue; @@ -729,8 +671,7 @@ check_run_on_requirement (test_runner_t *test_runner, bson_val_destroy (actual_val); bson_val_destroy (expected_val); if (!matched) { - *fail_reason = bson_strdup_printf ("serverParameters mismatch: %s", - error.message); + *fail_reason = bson_strdup_printf ("serverParameters mismatch: %s", error.message); return false; } continue; @@ -743,8 +684,7 @@ check_run_on_requirement (test_runner_t *test_runner, continue; } else if (0 == strcmp (serverless_mode, "require")) { if (!test_runner->is_serverless) { - *fail_reason = - bson_strdup_printf ("Not running in serverless mode"); + *fail_reason = bson_strdup_printf ("Not running in serverless mode"); return false; } @@ -770,9 +710,8 @@ check_run_on_requirement (test_runner_t *test_runner, continue; } - *fail_reason = bson_strdup_printf ( - "Server does not match auth requirement, test %s authentication.", - auth_requirement ? "requires" : "forbids"); + *fail_reason = bson_strdup_printf ("Server does not match auth requirement, test %s authentication.", + auth_requirement ? "requires" : "forbids"); return false; } @@ -784,11 +723,10 @@ check_run_on_requirement (test_runner_t *test_runner, semver_parse ("4.2.0", &min_server_version); if (semver_cmp (server_version, &min_server_version) < 0) { - *fail_reason = - bson_strdup_printf ("Server version %s is lower than " - "minServerVersion %s required by CSFLE", - semver_to_string (server_version), - semver_to_string (&min_server_version)); + *fail_reason = bson_strdup_printf ("Server version %s is lower than " + "minServerVersion %s required by CSFLE", + semver_to_string (server_version), + semver_to_string (&min_server_version)); return false; } @@ -796,9 +734,8 @@ check_run_on_requirement (test_runner_t *test_runner, continue; } - *fail_reason = - bson_strdup_printf ("CSFLE is not allowed but libmongoc was built " - "with MONGOC_ENABLE_CLIENT_SIDE_ENCRYPTION=ON"); + *fail_reason = bson_strdup_printf ("CSFLE is not allowed but libmongoc was built " + "with MONGOC_ENABLE_CLIENT_SIDE_ENCRYPTION=ON"); return false; #else @@ -809,9 +746,8 @@ check_run_on_requirement (test_runner_t *test_runner, continue; } - *fail_reason = bson_strdup_printf ( - "CSFLE is required but libmongoc was built " - "without MONGOC_ENABLE_CLIENT_SIDE_ENCRYPTION=ON"); + *fail_reason = bson_strdup_printf ("CSFLE is required but libmongoc was built " + "without MONGOC_ENABLE_CLIENT_SIDE_ENCRYPTION=ON"); return false; #endif /* !defined(MONGOC_CLIENT_SIDE_ENCRYPTION) */ @@ -823,9 +759,7 @@ check_run_on_requirement (test_runner_t *test_runner, } static bool -check_run_on_requirements (test_runner_t *test_runner, - bson_t *run_on_requirements, - const char **reason) +check_run_on_requirements (test_runner_t *test_runner, bson_t *run_on_requirements, const char **reason) { bson_string_t *fail_reasons = NULL; bool requirements_satisfied = false; @@ -848,17 +782,14 @@ check_run_on_requirements (test_runner_t *test_runner, break; } - bson_string_append_printf (fail_reasons, - "- Requirement %s failed because: %s\n", - bson_iter_key (&iter), - fail_reason); + bson_string_append_printf ( + fail_reasons, "- Requirement %s failed because: %s\n", bson_iter_key (&iter), fail_reason); bson_free (fail_reason); } *reason = NULL; if (!requirements_satisfied) { - (*reason) = - tmp_str ("runOnRequirements not satisfied:\n%s", fail_reasons->str); + (*reason) = tmp_str ("runOnRequirements not satisfied:\n%s", fail_reasons->str); } bson_string_free (fail_reasons, true); return requirements_satisfied; @@ -917,11 +848,9 @@ test_setup_initial_data (test_t *test, bson_error_t *error) create_opts = bson_new (); mongoc_write_concern_append (wc, create_opts); } - coll = mongoc_client_get_collection ( - test_runner->internal_client, database_name, collection_name); + coll = mongoc_client_get_collection (test_runner->internal_client, database_name, collection_name); if (!mongoc_collection_drop_with_opts (coll, drop_opts, error)) { - if (error->code != 26 && - (NULL == strstr (error->message, "ns not found"))) { + if (error->code != 26 && (NULL == strstr (error->message, "ns not found"))) { /* This is not a "ns not found" error. Fail the test. */ goto loopexit; } @@ -933,8 +862,7 @@ test_setup_initial_data (test_t *test, bson_error_t *error) if (bson_count_keys (documents) > 0) { bson_iter_t documents_iter; - bulk_insert = - mongoc_collection_create_bulk_operation_with_opts (coll, bulk_opts); + bulk_insert = mongoc_collection_create_bulk_operation_with_opts (coll, bulk_opts); BSON_FOREACH (documents, documents_iter) { @@ -950,10 +878,8 @@ test_setup_initial_data (test_t *test, bson_error_t *error) } else { mongoc_collection_t *new_coll = NULL; /* Test does not need data inserted, just create the collection. */ - db = mongoc_client_get_database (test_runner->internal_client, - database_name); - new_coll = mongoc_database_create_collection ( - db, collection_name, create_opts, error); + db = mongoc_client_get_database (test_runner->internal_client, database_name); + new_coll = mongoc_database_create_collection (db, collection_name, create_opts, error); if (!new_coll) { goto loopexit; } @@ -1023,8 +949,7 @@ test_run_operations (test_t *test, bson_error_t *error) bson_iter_bson (&iter, &op_bson); if (!operation_run (test, &op_bson, error)) { - test_diagnostics_error_info ("running operation: %s", - tmp_json (&op_bson)); + test_diagnostics_error_info ("running operation: %s", tmp_json (&op_bson)); goto done; } } @@ -1035,10 +960,7 @@ test_run_operations (test_t *test, bson_error_t *error) } static bool -test_check_event (test_t *test, - bson_t *expected, - event_t *actual, - bson_error_t *error) +test_check_event (test_t *test, bson_t *expected, event_t *actual, bson_error_t *error) { bool ret = false; bson_iter_t iter; @@ -1053,9 +975,7 @@ test_check_event (test_t *test, bool *expected_has_server_connection_id = NULL; if (bson_count_keys (expected) != 1) { - test_set_error (error, - "expected 1 key in expected event, but got: %s", - tmp_json (expected)); + test_set_error (error, "expected 1 key in expected event, but got: %s", tmp_json (expected)); goto done; } @@ -1063,17 +983,12 @@ test_check_event (test_t *test, bson_iter_next (&iter); expected_event_type = bson_iter_key (&iter); if (0 != bson_strcasecmp (expected_event_type, actual->type)) { - test_set_error (error, - "expected event type: %s, but got: %s", - expected_event_type, - actual->type); + test_set_error (error, "expected event type: %s, but got: %s", expected_event_type, actual->type); goto done; } if (!BSON_ITER_HOLDS_DOCUMENT (&iter)) { - test_set_error (error, - "unexpected non-document event assertion: %s", - tmp_json (expected)); + test_set_error (error, "unexpected non-document event assertion: %s", tmp_json (expected)); goto done; } bson_iter_bson (&iter, &expected_bson); @@ -1084,8 +999,7 @@ test_check_event (test_t *test, bson_parser_utf8_optional (bp, "databaseName", &expected_database_name); bson_parser_doc_optional (bp, "reply", &expected_reply); bson_parser_bool_optional (bp, "hasServiceId", &expected_has_service_id); - bson_parser_bool_optional ( - bp, "hasServerConnectionId", &expected_has_server_connection_id); + bson_parser_bool_optional (bp, "hasServerConnectionId", &expected_has_server_connection_id); if (!bson_parser_parse (bp, &expected_bson, error)) { goto done; } @@ -1102,8 +1016,7 @@ test_check_event (test_t *test, expected_val = bson_val_from_bson (expected_command); actual_val = bson_val_from_bson (actual->command); - if (!entity_map_match ( - test->entity_map, expected_val, actual_val, false, error)) { + if (!entity_map_match (test->entity_map, expected_val, actual_val, false, error)) { bson_val_destroy (expected_val); bson_val_destroy (actual_val); goto done; @@ -1112,29 +1025,20 @@ test_check_event (test_t *test, bson_val_destroy (actual_val); } - if (expected_command_name && - 0 != strcmp (expected_command_name, actual->command_name)) { - test_set_error (error, - "expected commandName: %s, but got: %s", - expected_command_name, - actual->command_name); + if (expected_command_name && 0 != strcmp (expected_command_name, actual->command_name)) { + test_set_error (error, "expected commandName: %s, but got: %s", expected_command_name, actual->command_name); goto done; } - if (expected_database_name && - 0 != strcmp (expected_database_name, actual->database_name)) { - test_set_error (error, - "expected databaseName: %s, but got: %s", - expected_database_name, - actual->database_name); + if (expected_database_name && 0 != strcmp (expected_database_name, actual->database_name)) { + test_set_error (error, "expected databaseName: %s, but got: %s", expected_database_name, actual->database_name); goto done; } if (expected_reply) { bson_val_t *expected_val = bson_val_from_bson (expected_reply); bson_val_t *actual_val = bson_val_from_bson (actual->reply); - if (!entity_map_match ( - test->entity_map, expected_val, actual_val, false, error)) { + if (!entity_map_match (test->entity_map, expected_val, actual_val, false, error)) { bson_val_destroy (expected_val); bson_val_destroy (actual_val); goto done; @@ -1148,8 +1052,7 @@ test_check_event (test_t *test, bool has_service_id = false; bson_oid_to_string (&actual->service_id, oid_str); - has_service_id = - 0 != bson_oid_compare (&actual->service_id, &kZeroServiceId); + has_service_id = 0 != bson_oid_compare (&actual->service_id, &kZeroServiceId); if (*expected_has_service_id && !has_service_id) { test_error ("expected serviceId, but got none"); @@ -1161,16 +1064,14 @@ test_check_event (test_t *test, } if (expected_has_server_connection_id) { - const bool has_server_connection_id = - actual->server_connection_id != MONGOC_NO_SERVER_CONNECTION_ID; + const bool has_server_connection_id = actual->server_connection_id != MONGOC_NO_SERVER_CONNECTION_ID; if (*expected_has_server_connection_id && !has_server_connection_id) { test_error ("expected server connectionId, but got none"); } if (!*expected_has_server_connection_id && has_server_connection_id) { - test_error ("expected no server connectionId, but got %" PRId64, - actual->server_connection_id); + test_error ("expected no server connectionId, but got %" PRId64, actual->server_connection_id); } } @@ -1181,9 +1082,7 @@ test_check_event (test_t *test, } static bool -test_check_expected_events_for_client (test_t *test, - bson_t *expected_events_for_client, - bson_error_t *error) +test_check_expected_events_for_client (test_t *test, bson_t *expected_events_for_client, bson_error_t *error) { bool ret = false; bson_parser_t *bp = NULL; @@ -1221,10 +1120,7 @@ test_check_expected_events_for_client (test_t *test, entity = entity_map_get (test->entity_map, client_id, error); if (0 != strcmp (entity->type, "client")) { - test_set_error (error, - "expected entity %s to be client, got: %s", - entity->id, - entity->type); + test_set_error (error, "expected entity %s to be client, got: %s", entity->id, entity->type); goto done; } @@ -1238,10 +1134,8 @@ test_check_expected_events_for_client (test_t *test, } bool too_few_events = actual_num_events < expected_num_events; if (too_few_events || too_many_events) { - test_set_error (error, - "expected: %" PRIu32 " events but got %" PRIu32, - expected_num_events, - actual_num_events); + test_set_error ( + error, "expected: %" PRIu32 " events but got %" PRIu32, expected_num_events, actual_num_events); goto done; } } @@ -1253,13 +1147,11 @@ test_check_expected_events_for_client (test_t *test, bson_iter_bson (&iter, &expected_event); if (!eiter) { - test_set_error ( - error, "could not find event: %s", tmp_json (&expected_event)); + test_set_error (error, "could not find event: %s", tmp_json (&expected_event)); goto done; } if (!test_check_event (test, &expected_event, eiter, error)) { - test_diagnostics_error_info ("checking for expected event: %s", - tmp_json (&expected_event)); + test_diagnostics_error_info ("checking for expected event: %s", tmp_json (&expected_event)); goto done; } eiter = eiter->next; @@ -1272,8 +1164,7 @@ test_check_expected_events_for_client (test_t *test, char *event_list_string = NULL; event_list_string = event_list_to_string (entity->events); - test_diagnostics_error_info ("all captured events:\n%s", - event_list_string); + test_diagnostics_error_info ("all captured events:\n%s", event_list_string); bson_free (event_list_string); } } @@ -1296,10 +1187,8 @@ test_check_expected_events (test_t *test, bson_error_t *error) { bson_t expected_events_for_client; bson_iter_bson (&iter, &expected_events_for_client); - if (!test_check_expected_events_for_client ( - test, &expected_events_for_client, error)) { - test_diagnostics_error_info ("checking expectations: %s", - tmp_json (&expected_events_for_client)); + if (!test_check_expected_events_for_client (test, &expected_events_for_client, error)) { + test_diagnostics_error_info ("checking expectations: %s", tmp_json (&expected_events_for_client)); goto done; } } @@ -1311,9 +1200,7 @@ test_check_expected_events (test_t *test, bson_error_t *error) } static bool -test_check_outcome_collection (test_t *test, - bson_t *collection_data, - bson_error_t *error) +test_check_outcome_collection (test_t *test, bson_t *collection_data, bson_error_t *error) { bool ret = false; bson_parser_t *bp = NULL; @@ -1339,16 +1226,12 @@ test_check_outcome_collection (test_t *test, goto done; } - coll = mongoc_client_get_collection ( - test->test_file->test_runner->internal_client, - database_name, - collection_name); + coll = mongoc_client_get_collection (test->test_file->test_runner->internal_client, database_name, collection_name); opts = BCON_NEW ("sort", "{", "_id", BCON_INT32 (1), "}"); rc = mongoc_read_concern_new (); mongoc_read_concern_set_level (rc, MONGOC_READ_CONCERN_LEVEL_LOCAL); rp = mongoc_read_prefs_new (MONGOC_READ_PRIMARY); - cursor = mongoc_collection_find_with_opts ( - coll, tmp_bson ("{}"), tmp_bson ("{'sort': {'_id': 1}}"), rp); + cursor = mongoc_collection_find_with_opts (coll, tmp_bson ("{}"), tmp_bson ("{'sort': {'_id': 1}}"), rp); /* Read the full cursor into a BSON array so error messages can include the * full list of documents. */ actual_data = bson_new (); @@ -1394,10 +1277,7 @@ test_check_outcome_collection (test_t *test, if (!bson_equal (actual_sorted, expected_sorted)) { - test_set_error (error, - "expected %s, but got %s", - tmp_json (expected_sorted), - tmp_json (actual_sorted)); + test_set_error (error, "expected %s, but got %s", tmp_json (expected_sorted), tmp_json (actual_sorted)); bson_destroy (actual_sorted); bson_destroy (expected_sorted); goto done; @@ -1493,16 +1373,11 @@ test_generate_atlas_results (test_t *test, bson_error_t *error) MONGOC_DEBUG ("generating events.json and results.json files..."); - size_t *const iterations = - entity_map_get_size_t (test->entity_map, "iterations", NULL); - size_t *const successes = - entity_map_get_size_t (test->entity_map, "successes", NULL); - mongoc_array_t *const errors = - entity_map_get_bson_array (test->entity_map, "errors", NULL); - mongoc_array_t *const failures = - entity_map_get_bson_array (test->entity_map, "failures", NULL); - mongoc_array_t *const events = - entity_map_get_bson_array (test->entity_map, "events", NULL); + size_t *const iterations = entity_map_get_size_t (test->entity_map, "iterations", NULL); + size_t *const successes = entity_map_get_size_t (test->entity_map, "successes", NULL); + mongoc_array_t *const errors = entity_map_get_bson_array (test->entity_map, "errors", NULL); + mongoc_array_t *const failures = entity_map_get_bson_array (test->entity_map, "failures", NULL); + mongoc_array_t *const events = entity_map_get_bson_array (test->entity_map, "events", NULL); bson_t events_doc = BSON_INITIALIZER; bson_t results_doc = BSON_INITIALIZER; @@ -1522,12 +1397,12 @@ test_generate_atlas_results (test_t *test, bson_error_t *error) const int perms = S_IRWXU; #endif - mongoc_stream_t *const events_file = mongoc_stream_file_new_for_path ( - "events.json", O_CREAT | O_WRONLY | O_TRUNC, perms); + mongoc_stream_t *const events_file = + mongoc_stream_file_new_for_path ("events.json", O_CREAT | O_WRONLY | O_TRUNC, perms); ASSERT_WITH_MSG (events_file, "could not open events.json"); - mongoc_stream_t *const results_file = mongoc_stream_file_new_for_path ( - "results.json", O_CREAT | O_WRONLY | O_TRUNC, perms); + mongoc_stream_t *const results_file = + mongoc_stream_file_new_for_path ("results.json", O_CREAT | O_WRONLY | O_TRUNC, perms); ASSERT_WITH_MSG (results_file, "could not open results.json"); size_t events_json_len = 0u; @@ -1535,16 +1410,12 @@ test_generate_atlas_results (test_t *test, bson_error_t *error) char *const events_json = bson_as_json (&events_doc, &events_json_len); char *const results_json = bson_as_json (&results_doc, &results_json_len); - ASSERT_WITH_MSG (events_json, - "failed to convert events BSON document to JSON"); - ASSERT_WITH_MSG (results_json, - "failed to convert results BSON document to JSON"); + ASSERT_WITH_MSG (events_json, "failed to convert events BSON document to JSON"); + ASSERT_WITH_MSG (results_json, "failed to convert results BSON document to JSON"); - ASSERT_WITH_MSG ( - mongoc_stream_write (events_file, events_json, events_json_len, 500) > 0, - "failed to write events to events.json"); - ASSERT_WITH_MSG (mongoc_stream_write ( - results_file, results_json, results_json_len, 500) > 0, + ASSERT_WITH_MSG (mongoc_stream_write (events_file, events_json, events_json_len, 500) > 0, + "failed to write events to events.json"); + ASSERT_WITH_MSG (mongoc_stream_write (results_file, results_json, results_json_len, 500) > 0, "failed to write results to results.json"); bson_free (events_json); @@ -1562,10 +1433,7 @@ test_generate_atlas_results (test_t *test, bson_error_t *error) } static bool -run_distinct_on_each_mongos (test_t *test, - char *db_name, - char *coll_name, - bson_error_t *error) +run_distinct_on_each_mongos (test_t *test, char *db_name, char *coll_name, bson_error_t *error) { bool ret = false; bson_t *cmd = NULL; @@ -1574,16 +1442,14 @@ run_distinct_on_each_mongos (test_t *test, cmd = BCON_NEW ("distinct", coll_name, "key", "x", "query", "{", "}"); for (size_t i = 0u; i < runner->server_ids.len; i++) { - const uint32_t server_id = - _mongoc_array_index (&runner->server_ids, uint32_t, i); - if (!mongoc_client_command_simple_with_server_id ( - test->test_file->test_runner->internal_client, - db_name, - cmd, - NULL /* read prefs */, - server_id, - NULL /* reply */, - error)) { + const uint32_t server_id = _mongoc_array_index (&runner->server_ids, uint32_t, i); + if (!mongoc_client_command_simple_with_server_id (test->test_file->test_runner->internal_client, + db_name, + cmd, + NULL /* read prefs */, + server_id, + NULL /* reply */, + error)) { goto done; } } @@ -1604,8 +1470,7 @@ test_run_distinct_workaround (test_t *test, bson_error_t *error) mongoc_collection_t *coll = NULL; if (0 != strcmp (test->test_file->test_runner->topology_type, "sharded") && - 0 != strcmp (test->test_file->test_runner->topology_type, - "sharded-replicaset")) { + 0 != strcmp (test->test_file->test_runner->topology_type, "sharded-replicaset")) { ret = true; goto done; } @@ -1626,9 +1491,7 @@ test_run_distinct_workaround (test_t *test, bson_error_t *error) bson_iter_t entity_iter; if (!BSON_ITER_HOLDS_DOCUMENT (&iter)) { - test_set_error (error, - "unexpected non-document createEntity: %s", - bson_iter_key (&iter)); + test_set_error (error, "unexpected non-document createEntity: %s", bson_iter_key (&iter)); goto done; } @@ -1639,9 +1502,7 @@ test_run_distinct_workaround (test_t *test, bson_error_t *error) } if (!BSON_ITER_HOLDS_DOCUMENT (&entity_iter)) { - test_set_error (error, - "unexpected non-document in iter: %s", - bson_iter_key (&entity_iter)); + test_set_error (error, "unexpected non-document in iter: %s", bson_iter_key (&entity_iter)); goto done; } @@ -1694,37 +1555,28 @@ test_run (test_t *test, bson_error_t *error) test_runner = test_file->test_runner; if (is_test_skipped (test)) { - MONGOC_DEBUG ( - "SKIPPING test '%s'. Reason: 'explicitly skipped in runner.c'", - test->description); + MONGOC_DEBUG ("SKIPPING test '%s'. Reason: 'explicitly skipped in runner.c'", test->description); ret = true; goto done; } subtest_selector = _mongoc_getenv ("MONGOC_JSON_SUBTEST"); - if (subtest_selector && - NULL == strstr (test->description, subtest_selector)) { - MONGOC_DEBUG ( - "SKIPPING test '%s'. Reason: 'skipped by MONGOC_JSON_SUBTEST'", - test->description); + if (subtest_selector && NULL == strstr (test->description, subtest_selector)) { + MONGOC_DEBUG ("SKIPPING test '%s'. Reason: 'skipped by MONGOC_JSON_SUBTEST'", test->description); ret = true; goto done; } if (test->skip_reason != NULL) { - MONGOC_DEBUG ("SKIPPING test '%s'. Reason: '%s'", - test->description, - test->skip_reason); + MONGOC_DEBUG ("SKIPPING test '%s'. Reason: '%s'", test->description, test->skip_reason); ret = true; goto done; } if (test->run_on_requirements) { const char *reason; - if (!check_run_on_requirements ( - test_runner, test->run_on_requirements, &reason)) { - MONGOC_DEBUG ( - "SKIPPING test '%s'. Reason: '%s'", test->description, reason); + if (!check_run_on_requirements (test_runner, test->run_on_requirements, &reason)) { + MONGOC_DEBUG ("SKIPPING test '%s'. Reason: '%s'", test->description, reason); ret = true; goto done; } @@ -1774,10 +1626,8 @@ test_run (test_t *test, bson_error_t *error) MONGOC_DEBUG ("error cleaning up failpoints: %s", nonfatal_error.message); } /* always terminate transactions, even on test failure. */ - if (!test_runner_terminate_open_transactions (test_runner, - &nonfatal_error)) { - MONGOC_DEBUG ("error terminating transactions: %s", - nonfatal_error.message); + if (!test_runner_terminate_open_transactions (test_runner, &nonfatal_error)) { + MONGOC_DEBUG ("error terminating transactions: %s", nonfatal_error.message); } bson_free (subtest_selector); return ret; @@ -1798,20 +1648,15 @@ run_one_test_file (bson_t *bson) test_diagnostics_test_info ("test file: %s", test_file->description); if (is_test_file_skipped (test_file)) { - MONGOC_DEBUG ( - "SKIPPING test file '%s'. Reason: 'explicitly skipped in runner.c'", - test_file->description); + MONGOC_DEBUG ("SKIPPING test file '%s'. Reason: 'explicitly skipped in runner.c'", test_file->description); goto done; } check_schema_version (test_file); if (test_file->run_on_requirements) { const char *reason; - if (!check_run_on_requirements ( - test_runner, test_file->run_on_requirements, &reason)) { - MONGOC_DEBUG ("SKIPPING test file (%s). Reason:\n%s", - test_file->description, - reason); + if (!check_run_on_requirements (test_runner, test_file->run_on_requirements, &reason)) { + MONGOC_DEBUG ("SKIPPING test file (%s). Reason:\n%s", test_file->description, reason); goto done; } } @@ -1845,12 +1690,8 @@ run_one_test_file (bson_t *bson) void run_unified_tests (TestSuite *suite, const char *base, const char *subdir) { - install_json_test_suite_with_check (suite, - base, - subdir, - &run_one_test_file, - TestSuite_CheckLive, - test_framework_skip_if_no_crypto); + install_json_test_suite_with_check ( + suite, base, subdir, &run_one_test_file, TestSuite_CheckLive, test_framework_skip_if_no_crypto); } void diff --git a/src/libmongoc/tests/unified/runner.h b/src/libmongoc/tests/unified/runner.h index 1d8f5857f7..51a68372a0 100644 --- a/src/libmongoc/tests/unified/runner.h +++ b/src/libmongoc/tests/unified/runner.h @@ -66,10 +66,7 @@ typedef struct { /* Set server_id to 0 if the failpoint was not against a pinned mongos. */ void -register_failpoint (test_t *test, - char *failpoint, - char *client_id, - uint32_t server_id); +register_failpoint (test_t *test, char *failpoint, char *client_id, uint32_t server_id); /* Run a directory of test files through the unified test runner. */ void diff --git a/src/libmongoc/tests/unified/test-diagnostics.h b/src/libmongoc/tests/unified/test-diagnostics.h index 1ffd9fa13b..992ef076d4 100644 --- a/src/libmongoc/tests/unified/test-diagnostics.h +++ b/src/libmongoc/tests/unified/test-diagnostics.h @@ -23,14 +23,12 @@ void _test_diagnostics_add (bool fail, const char *fmt, ...) BSON_GNUC_PRINTF (2, 3); #define test_diagnostics_test_info(fmt, ...) \ - _test_diagnostics_add ( \ - false, "[%s:%d %s()]\n" fmt, __FILE__, __LINE__, BSON_FUNC, __VA_ARGS__) + _test_diagnostics_add (false, "[%s:%d %s()]\n" fmt, __FILE__, __LINE__, BSON_FUNC, __VA_ARGS__) /* Append additional information to an error after it has occurred (similar to * backtrace). */ #define test_diagnostics_error_info(fmt, ...) \ - _test_diagnostics_add ( \ - true, "[%s:%d %s()]\n" fmt, __FILE__, __LINE__, BSON_FUNC, __VA_ARGS__) + _test_diagnostics_add (true, "[%s:%d %s()]\n" fmt, __FILE__, __LINE__, BSON_FUNC, __VA_ARGS__) void test_diagnostics_init (void); diff --git a/src/libmongoc/tests/unified/util.c b/src/libmongoc/tests/unified/util.c index 601b4a8f6a..f50119d7cf 100644 --- a/src/libmongoc/tests/unified/util.c +++ b/src/libmongoc/tests/unified/util.c @@ -57,26 +57,16 @@ typedef struct { /* List of aliases: https://www.mongodb.com/docs/manual/reference/bson-types/ */ bson_string_and_type_t bson_type_map[] = { - {"double", BSON_TYPE_DOUBLE}, - {"string", BSON_TYPE_UTF8}, - {"object", BSON_TYPE_DOCUMENT}, - {"array", BSON_TYPE_ARRAY}, - {"binData", BSON_TYPE_BINARY}, - {"undefined", BSON_TYPE_UNDEFINED}, - {"objectId", BSON_TYPE_OID}, - {"bool", BSON_TYPE_BOOL}, - {"date", BSON_TYPE_DATE_TIME}, - {"null", BSON_TYPE_NULL}, - {"regex", BSON_TYPE_REGEX}, - {"dbPointer", BSON_TYPE_DBPOINTER}, - {"javascript", BSON_TYPE_CODE}, - {"javascriptWithScope", BSON_TYPE_CODEWSCOPE}, - {"int", BSON_TYPE_INT32}, - {"timestamp", BSON_TYPE_TIMESTAMP}, - {"long", BSON_TYPE_INT64}, - {"decimal", BSON_TYPE_DECIMAL128}, - {"minKey", BSON_TYPE_MINKEY}, - {"maxKey", BSON_TYPE_MAXKEY}, + {"double", BSON_TYPE_DOUBLE}, {"string", BSON_TYPE_UTF8}, + {"object", BSON_TYPE_DOCUMENT}, {"array", BSON_TYPE_ARRAY}, + {"binData", BSON_TYPE_BINARY}, {"undefined", BSON_TYPE_UNDEFINED}, + {"objectId", BSON_TYPE_OID}, {"bool", BSON_TYPE_BOOL}, + {"date", BSON_TYPE_DATE_TIME}, {"null", BSON_TYPE_NULL}, + {"regex", BSON_TYPE_REGEX}, {"dbPointer", BSON_TYPE_DBPOINTER}, + {"javascript", BSON_TYPE_CODE}, {"javascriptWithScope", BSON_TYPE_CODEWSCOPE}, + {"int", BSON_TYPE_INT32}, {"timestamp", BSON_TYPE_TIMESTAMP}, + {"long", BSON_TYPE_INT64}, {"decimal", BSON_TYPE_DECIMAL128}, + {"minKey", BSON_TYPE_MINKEY}, {"maxKey", BSON_TYPE_MAXKEY}, {"eod", BSON_TYPE_EOD}, }; @@ -121,8 +111,7 @@ test_copy_and_sort (void) void test_bson_util_install (TestSuite *suite) { - TestSuite_Add ( - suite, "/unified/selftest/util/copy_and_sort", test_copy_and_sort); + TestSuite_Add (suite, "/unified/selftest/util/copy_and_sort", test_copy_and_sort); } /* TODO (CDRIVER-3525) add test support for CMAP events once the C driver