libddwaf-src 2.1.0

Source distribution and build integration for DataDog/libddwaf
Documentation
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
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
// Unless explicitly stated otherwise all files in this repository are
// dual-licensed under the Apache-2.0 License or BSD-3-Clause License.
//
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2021 Datadog, Inc.

// This translation unit defines the transitional ABI entry points.
#define DDWAF_DISABLE_API_POISON

#include <algorithm>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <exception>
#include <limits>
#include <string_view>
#include <type_traits>
#include <utility>
#include <vector>

#include "builder/waf_builder.hpp"
#include "clock.hpp"
#include "configuration/common/raw_configuration.hpp"
#include "context.hpp"
#include "ddwaf.h"
#include "json_utils.hpp"
#include "log.hpp"
#include "memory_resource.hpp"
#include "object.hpp"
#include "object_type.hpp"
#include "pointer.hpp"
#include "re2.h"
#include "ruleset_info.hpp"
#include "user_resource.hpp"
#include "utils.hpp"
#include "version.hpp"
#include "waf.hpp"

using namespace ddwaf;

// Object type compatibility
static_assert(static_cast<uint8_t>(object_type::invalid) == DDWAF_OBJ_INVALID);
static_assert(static_cast<uint8_t>(object_type::null) == DDWAF_OBJ_NULL);
static_assert(static_cast<uint8_t>(object_type::boolean) == DDWAF_OBJ_BOOL);
static_assert(static_cast<uint8_t>(object_type::int64) == DDWAF_OBJ_SIGNED);
static_assert(static_cast<uint8_t>(object_type::uint64) == DDWAF_OBJ_UNSIGNED);
static_assert(static_cast<uint8_t>(object_type::float64) == DDWAF_OBJ_FLOAT);
static_assert(static_cast<uint8_t>(object_type::string) == DDWAF_OBJ_STRING);
static_assert(static_cast<uint8_t>(object_type::small_string) == DDWAF_OBJ_SMALL_STRING);
static_assert(static_cast<uint8_t>(object_type::literal_string) == DDWAF_OBJ_LITERAL_STRING);
static_assert(static_cast<uint8_t>(object_type::array) == DDWAF_OBJ_ARRAY);
static_assert(static_cast<uint8_t>(object_type::map) == DDWAF_OBJ_MAP);
static_assert(static_cast<uint8_t>(object_type::large_array) == DDWAF_OBJ_LARGE_ARRAY);
static_assert(static_cast<uint8_t>(object_type::large_map) == DDWAF_OBJ_LARGE_MAP);

// Object compatibility

// detail::object == ddwaf_object
static_assert(sizeof(detail::object) == sizeof(ddwaf_object));
static_assert(offsetof(detail::object, type) == offsetof(ddwaf_object, type));
static_assert(offsetof(detail::object, via) == offsetof(ddwaf_object, via));

// detail::object_kv == _ddwaf_object_kv
static_assert(sizeof(detail::object_kv) == sizeof(struct _ddwaf_object_kv));
static_assert(offsetof(detail::object_kv, key) == offsetof(_ddwaf_object_kv, key));
static_assert(offsetof(detail::object_kv, val) == offsetof(_ddwaf_object_kv, val));

// detail::object_scalar<bool> == _ddwaf_object_bool
static_assert(sizeof(detail::object_scalar<bool>) == sizeof(_ddwaf_object_bool));
static_assert(offsetof(detail::object_scalar<bool>, type) == offsetof(_ddwaf_object_bool, type));
static_assert(offsetof(detail::object_scalar<bool>, val) == offsetof(_ddwaf_object_bool, val));

// detail::object_scalar<int64_t> == _ddwaf_object_signed
static_assert(sizeof(detail::object_scalar<int64_t>) == sizeof(_ddwaf_object_signed));
static_assert(
    offsetof(detail::object_scalar<int64_t>, type) == offsetof(_ddwaf_object_signed, type));
static_assert(offsetof(detail::object_scalar<int64_t>, val) == offsetof(_ddwaf_object_signed, val));

// detail::object_scalar<uint64_t> == _ddwaf_object_unsigned
static_assert(sizeof(detail::object_scalar<uint64_t>) == sizeof(_ddwaf_object_unsigned));
static_assert(
    offsetof(detail::object_scalar<uint64_t>, type) == offsetof(_ddwaf_object_unsigned, type));
static_assert(
    offsetof(detail::object_scalar<uint64_t>, val) == offsetof(_ddwaf_object_unsigned, val));

// detail::object_scalar<double> == _ddwaf_object_float
static_assert(sizeof(detail::object_scalar<double>) == sizeof(_ddwaf_object_float));
static_assert(offsetof(detail::object_scalar<double>, type) == offsetof(_ddwaf_object_float, type));
static_assert(offsetof(detail::object_scalar<double>, val) == offsetof(_ddwaf_object_float, val));

// detail::object_string == _ddwaf_object_string
static_assert(sizeof(detail::object_string) == sizeof(_ddwaf_object_string));
static_assert(offsetof(detail::object_string, type) == offsetof(_ddwaf_object_string, type));
static_assert(offsetof(detail::object_string, size) == offsetof(_ddwaf_object_string, size));
static_assert(offsetof(detail::object_string, ptr) == offsetof(_ddwaf_object_string, ptr));

// detail::object_small_string == _ddwaf_object_small_string
static_assert(sizeof(detail::object_small_string) == sizeof(_ddwaf_object_small_string));
static_assert(
    offsetof(detail::object_small_string, type) == offsetof(_ddwaf_object_small_string, type));
static_assert(
    offsetof(detail::object_small_string, size) == offsetof(_ddwaf_object_small_string, size));
static_assert(
    offsetof(detail::object_small_string, data) == offsetof(_ddwaf_object_small_string, data));

// detail::object_array == _ddwaf_object_array
static_assert(sizeof(detail::object_array) == sizeof(_ddwaf_object_array));
static_assert(offsetof(detail::object_array, type) == offsetof(_ddwaf_object_array, type));
static_assert(offsetof(detail::object_array, size) == offsetof(_ddwaf_object_array, size));
static_assert(offsetof(detail::object_array, capacity) == offsetof(_ddwaf_object_array, capacity));
static_assert(offsetof(detail::object_array, ptr) == offsetof(_ddwaf_object_array, ptr));

// detail::object_map == _ddwaf_object_map
static_assert(sizeof(detail::object_map) == sizeof(_ddwaf_object_map));
static_assert(offsetof(detail::object_map, type) == offsetof(_ddwaf_object_map, type));
static_assert(offsetof(detail::object_map, size) == offsetof(_ddwaf_object_map, size));
static_assert(offsetof(detail::object_map, capacity) == offsetof(_ddwaf_object_map, capacity));
static_assert(offsetof(detail::object_map, ptr) == offsetof(_ddwaf_object_map, ptr));

// detail::object_large_array == _ddwaf_object_large_array
static_assert(sizeof(detail::object_large_array) == sizeof(_ddwaf_object_large_array));
static_assert(
    offsetof(detail::object_large_array, ptr) == offsetof(_ddwaf_object_large_array, ptr));
static_assert(std::is_same_v<decltype(detail::object_large_array::ptr), detail::object *>);
static_assert(std::is_same_v<decltype(_ddwaf_object_large_array::ptr), ddwaf_object *>);
#if defined(__GNUC__) && !defined(__clang__)
constexpr _ddwaf_object_large_array ddwaf_object_large_array_type_byte_probe{._type = 0xFF};
static_assert(__builtin_memcmp(&ddwaf_object_large_array_type_byte_probe, "\xFF", 1) == 0);
#endif

// detail::object_large_map == _ddwaf_object_large_map
static_assert(sizeof(detail::object_large_map) == sizeof(_ddwaf_object_large_map));
static_assert(offsetof(detail::object_large_map, ptr) == offsetof(_ddwaf_object_large_map, ptr));
static_assert(std::is_same_v<decltype(detail::object_large_map::ptr), detail::object_kv *>);
static_assert(std::is_same_v<decltype(_ddwaf_object_large_map::ptr), ddwaf_object_kv *>);
#if defined(__GNUC__) && !defined(__clang__)
constexpr _ddwaf_object_large_map ddwaf_object_large_map_type_byte_probe{._type = 0xFF};
static_assert(__builtin_memcmp(&ddwaf_object_large_map_type_byte_probe, "\xFF", 1) == 0);
#endif

// Allocator callback compatibility
static_assert(std::is_same_v<ddwaf_alloc_fn_type, memory::user_resource::alloc_fn_type>);
static_assert(std::is_same_v<ddwaf_free_fn_type, memory::user_resource::free_fn_type>);
static_assert(std::is_same_v<ddwaf_udata_free_fn_type, memory::user_resource::udata_free_fn_type>);

// Log compatibility
static_assert(DDWAF_LOG_TRACE == static_cast<uint8_t>(log_level::trace));
static_assert(DDWAF_LOG_DEBUG == static_cast<uint8_t>(log_level::debug));
static_assert(DDWAF_LOG_INFO == static_cast<uint8_t>(log_level::info));
static_assert(DDWAF_LOG_WARN == static_cast<uint8_t>(log_level::warn));
static_assert(DDWAF_LOG_ERROR == static_cast<uint8_t>(log_level::error));
static_assert(DDWAF_LOG_OFF == static_cast<uint8_t>(log_level::off));
static_assert(sizeof(DDWAF_LOG_LEVEL) == sizeof(log_level));
static_assert(alignof(DDWAF_LOG_LEVEL) == alignof(log_level));

namespace {

// NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
detail::object *to_ptr(ddwaf_object *ptr) { return reinterpret_cast<detail::object *>(ptr); }
const detail::object *to_ptr(const ddwaf_object *ptr)
{
    // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
    return reinterpret_cast<const detail::object *>(ptr);
}

detail::object &to_ref(ddwaf_object *ptr) { return *to_ptr(ptr); }
const detail::object &to_ref(const ddwaf_object *ptr) { return *to_ptr(ptr); }

// UNSAFE: caller is responsible for ensuring that the allocator macthes the
// object's memory; to the extent that the borrow is from a larger owned object,
// the allocator must match that of the owned object. The reason for this is the
// contents of the borrowed object may be replaced through the assignment
// operator, and this new value may be destroyed using the allocator of the
// owning object.
borrowed_object to_borrowed(ddwaf_object *ptr, nonnull_ptr<memory::memory_resource> alloc)
{
    // safety: caller is responsible for ensuring allocator matches object's memory
    // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
    return borrowed_object{reinterpret_cast<detail::object *>(ptr), alloc};
}

memory::memory_resource *to_alloc_ptr(ddwaf_allocator alloc)
{
    // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
    return reinterpret_cast<memory::memory_resource *>(alloc);
}

} // namespace

// explicit instantiation declaration to suppress warning
extern "C" {
ddwaf::waf *ddwaf_init(const ddwaf_object *ruleset, ddwaf_object *diagnostics)
{
    try {
        if (ruleset != nullptr) {
            waf_builder builder;

            ddwaf::raw_configuration input{to_ref(ruleset)};
            ddwaf::ruleset_info ri;
            const ddwaf::defer on_exit([&]() {
                if (diagnostics != nullptr) {
                    // avoid to_borrowed(diagnostics, ...) = ... as that would destroy
                    // the current value in diagnostics, which could be uninitialized
                    *to_ptr(diagnostics) = ri.to_object().move();
                }
            });
            builder.add_or_update("default", input, ri);
            return new ddwaf::waf{builder.build()};
        }
    } catch (const std::exception &e) {
        DDWAF_ERROR("{}", e.what());
    } catch (...) {
        DDWAF_ERROR("unknown exception");
    }

    return nullptr;
}

void ddwaf_destroy(ddwaf::waf *handle)
{
    try {
        delete handle;
    } catch (const std::exception &e) {
        DDWAF_ERROR("{}", e.what());
    } catch (...) {
        DDWAF_ERROR("unknown exception");
    }
}

const char *const *ddwaf_known_addresses(ddwaf::waf *handle, uint32_t *size)
{
    if (handle == nullptr) {
        *size = 0;
        return nullptr;
    }

    const auto &addresses = handle->get_root_addresses();
    if (addresses.empty() || addresses.size() > std::numeric_limits<uint32_t>::max()) {
        *size = 0;
        return nullptr;
    }

    *size = (uint32_t)addresses.size();
    return addresses.data();
}

const char *const *ddwaf_known_actions(ddwaf::waf *handle, uint32_t *size)
{
    if (handle == nullptr) {
        *size = 0;
        return nullptr;
    }

    const auto &action_types = handle->get_available_action_types();
    if (action_types.empty() || action_types.size() > std::numeric_limits<uint32_t>::max()) {
        *size = 0;
        return nullptr;
    }

    *size = (uint32_t)action_types.size();
    return action_types.data();
}

ddwaf_context ddwaf_context_init(ddwaf::waf *handle, ddwaf_allocator output_alloc)
{
    try {
        if (handle != nullptr && output_alloc != nullptr) {
            return new context(handle->create_context(to_alloc_ptr(output_alloc)));
        }
    } catch (const std::exception &e) {
        DDWAF_ERROR("{}", e.what());
    } catch (...) {
        DDWAF_ERROR("unknown exception");
    }
    return nullptr;
}

DDWAF_RET_CODE ddwaf_context_eval(ddwaf_context context, ddwaf_object *data,
    // NOLINTNEXTLINE(bugprone-easily-swappable-parameters)
    ddwaf_allocator alloc, ddwaf_object *result, uint64_t timeout)
{
    if (context == nullptr || data == nullptr) {
        DDWAF_WARN("Illegal WAF call: context or data was null");
        return DDWAF_ERR_INVALID_ARGUMENT;
    }

    try {
        if (alloc != nullptr) {
            // safety: caller is responsible to ensure that the passed allocator
            // can deallocate memory allocated for `data`. An array carries
            // multiple input batches, anything else is a single (map) batch.
            owned_object input{to_ref(data), to_alloc_ptr(alloc)};
            if (!context->insert_batch(std::move(input))) {
                return DDWAF_ERR_INVALID_OBJECT;
            }
        } else {
            const object_view input{to_ref(data)};
            if (!input.is_map() || !context->insert_batch(input.as<map_view>())) {
                return DDWAF_ERR_INVALID_OBJECT;
            }
        }

        // The timers will actually count nanoseconds, std::chrono doesn't
        // deal well with durations being beyond range.
        constexpr uint64_t max_timeout_us = std::chrono::nanoseconds::max().count() / 1000;
        timeout = std::min(timeout, max_timeout_us);

        timer deadline{std::chrono::microseconds(timeout)};
        auto [code, res] = context->eval(deadline);
        if (result != nullptr) {
            // avoid to_borrowed(result, res.alloc()) = std::move(res);
            // as that would destroy the current value in result, which could be
            // garbage (result could be uninitialized memory)
            *to_ptr(result) = res.move();
        }
        return code ? DDWAF_MATCH : DDWAF_OK;
    } catch (const std::exception &e) {
        DDWAF_ERROR("{}", e.what());
    } catch (...) {
        DDWAF_ERROR("unknown exception");
    }

    return DDWAF_ERR_INTERNAL;
}

DDWAF_RET_CODE ddwaf_context_multieval(ddwaf_context context, ddwaf_object *data,
    // NOLINTNEXTLINE(bugprone-easily-swappable-parameters)
    ddwaf_allocator alloc, ddwaf_object *result, uint64_t timeout)
{
    if (context == nullptr || data == nullptr) {
        DDWAF_WARN("Illegal WAF call: context or data was null");
        return DDWAF_ERR_INVALID_ARGUMENT;
    }

    try {
        if (alloc != nullptr) {
            if (!context->insert_batches(owned_object{to_ref(data), to_alloc_ptr(alloc)})) {
                return DDWAF_ERR_INVALID_OBJECT;
            }
        } else {
            const object_view input{to_ref(data)};
            if (!input.is_array() || !context->insert_batches(input.as<array_view>())) {
                return DDWAF_ERR_INVALID_OBJECT;
            }
        }

        constexpr uint64_t max_timeout_us = std::chrono::nanoseconds::max().count() / 1000;
        timeout = std::min(timeout, max_timeout_us);

        timer deadline{std::chrono::microseconds(timeout)};
        auto [code, res] = context->eval(deadline);
        if (result != nullptr) {
            *to_ptr(result) = res.move();
        }
        return code ? DDWAF_MATCH : DDWAF_OK;
    } catch (const std::exception &e) {
        DDWAF_ERROR("{}", e.what());
    } catch (...) {
        DDWAF_ERROR("unknown exception");
    }

    return DDWAF_ERR_INTERNAL;
}

void ddwaf_context_destroy(ddwaf_context context)
{
    try {
        delete context;
    } catch (const std::exception &e) {
        DDWAF_ERROR("{}", e.what());
    } catch (...) {
        DDWAF_ERROR("unknown exception");
    }
}

ddwaf_subcontext ddwaf_subcontext_init(ddwaf_context context)
{
    try {
        if (context != nullptr) {
            return new subcontext(context->create_subcontext());
        }
    } catch (const std::exception &e) {
        DDWAF_ERROR("{}", e.what());
    } catch (...) {
        DDWAF_ERROR("unknown exception");
    }
    return nullptr;
}

DDWAF_RET_CODE ddwaf_subcontext_eval(ddwaf_subcontext subcontext, ddwaf_object *data,
    // NOLINTNEXTLINE(bugprone-easily-swappable-parameters)
    ddwaf_allocator alloc, ddwaf_object *result, uint64_t timeout)
{
    if (subcontext == nullptr || data == nullptr) {
        DDWAF_WARN("Illegal WAF call: subcontext or data was null");
        return DDWAF_ERR_INVALID_ARGUMENT;
    }

    try {
        if (alloc != nullptr) {
            // safety: caller is responsible to ensure that the passed allocator
            // can deallocate memory allocated for `data`. An array carries
            // multiple input batches, anything else is a single (map) batch.
            owned_object input{to_ref(data), to_alloc_ptr(alloc)};
            if (!subcontext->insert_batch(std::move(input))) {
                return DDWAF_ERR_INVALID_OBJECT;
            }
        } else {
            const object_view input{to_ref(data)};
            if (!input.is_map() || !subcontext->insert_batch(input.as<map_view>())) {
                return DDWAF_ERR_INVALID_OBJECT;
            }
        }
        // The timers will actually count nanoseconds, std::chrono doesn't
        // deal well with durations being beyond range.
        constexpr uint64_t max_timeout_us = std::chrono::nanoseconds::max().count() / 1000;
        timeout = std::min(timeout, max_timeout_us);

        timer deadline{std::chrono::microseconds(timeout)};
        auto [code, res] = subcontext->eval(deadline);
        if (result != nullptr) {
            *to_ptr(result) = res.move();
        }
        return code ? DDWAF_MATCH : DDWAF_OK;
    } catch (const std::exception &e) {
        DDWAF_ERROR("{}", e.what());
    } catch (...) {
        DDWAF_ERROR("unknown exception");
    }

    return DDWAF_ERR_INTERNAL;
}

DDWAF_RET_CODE ddwaf_subcontext_multieval(ddwaf_subcontext subcontext, ddwaf_object *data,
    // NOLINTNEXTLINE(bugprone-easily-swappable-parameters)
    ddwaf_allocator alloc, ddwaf_object *result, uint64_t timeout)
{
    if (subcontext == nullptr || data == nullptr) {
        DDWAF_WARN("Illegal WAF call: subcontext or data was null");
        return DDWAF_ERR_INVALID_ARGUMENT;
    }

    try {
        if (alloc != nullptr) {
            if (!subcontext->insert_batches(owned_object{to_ref(data), to_alloc_ptr(alloc)})) {
                return DDWAF_ERR_INVALID_OBJECT;
            }
        } else {
            const object_view input{to_ref(data)};
            if (!input.is_array() || !subcontext->insert_batches(input.as<array_view>())) {
                return DDWAF_ERR_INVALID_OBJECT;
            }
        }

        constexpr uint64_t max_timeout_us = std::chrono::nanoseconds::max().count() / 1000;
        timeout = std::min(timeout, max_timeout_us);

        timer deadline{std::chrono::microseconds(timeout)};
        auto [code, res] = subcontext->eval(deadline);
        if (result != nullptr) {
            *to_ptr(result) = res.move();
        }
        return code ? DDWAF_MATCH : DDWAF_OK;
    } catch (const std::exception &e) {
        DDWAF_ERROR("{}", e.what());
    } catch (...) {
        DDWAF_ERROR("unknown exception");
    }

    return DDWAF_ERR_INTERNAL;
}

void ddwaf_subcontext_destroy(ddwaf_subcontext subcontext)
{
    try {
        delete subcontext;
    } catch (const std::exception &e) {
        DDWAF_ERROR("{}", e.what());
    } catch (...) {
        DDWAF_ERROR("unknown exception");
    }
}

const char *ddwaf_get_version() { return ddwaf::current_version.cstring(); }

bool ddwaf_set_log_cb(ddwaf_log_cb cb, DDWAF_LOG_LEVEL min_level)
{
    auto level = static_cast<log_level>(min_level);
    // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
    ddwaf::logger::init(reinterpret_cast<logger::log_cb_type>(cb), level);
    DDWAF_INFO("Sending log messages to binding, min level {}", log_level_to_str(level));
    return true;
}

ddwaf_builder ddwaf_builder_init()
{
    try {
        return new waf_builder();
    } catch (const std::exception &e) {
        DDWAF_ERROR("{}", e.what());
    } catch (...) {
        DDWAF_ERROR("unknown exception");
    }

    return nullptr;
}

bool ddwaf_builder_add_or_update_config(ddwaf::waf_builder *builder, const char *path,
    uint32_t path_len, const ddwaf_object *config, ddwaf_object *diagnostics)
{
    if (builder == nullptr || path == nullptr || path_len == 0 || config == nullptr) {
        return false;
    }

    try {
        auto input = static_cast<ddwaf::raw_configuration>(to_ref(config));

        ddwaf::ruleset_info ri;
        const ddwaf::defer on_exit([&]() {
            if (diagnostics != nullptr) {
                // avoid to_borrowed(diagnostics, ...) = ... as that would destroy
                // the current value in diagnostics, which could be uninitialized
                *to_ptr(diagnostics) = ri.to_object().move();
            }
        });
        return builder->add_or_update({path, path_len}, input, ri);
    } catch (const std::exception &e) {
        DDWAF_ERROR("{}", e.what());
    } catch (...) {
        DDWAF_ERROR("unknown exception");
    }

    return false;
}

bool ddwaf_builder_remove_config(ddwaf::waf_builder *builder, const char *path, uint32_t path_len)
{
    if (builder == nullptr || path == nullptr || path_len == 0) {
        return false;
    }

    try {
        return builder->remove({path, path_len});
    } catch (const std::exception &e) {
        DDWAF_ERROR("{}", e.what());
    } catch (...) {
        DDWAF_ERROR("unknown exception");
    }

    return false;
}

ddwaf_handle ddwaf_builder_build_instance(ddwaf::waf_builder *builder)
{
    if (builder == nullptr) {
        return nullptr;
    }

    try {
        return new ddwaf::waf{builder->build()};
    } catch (const std::exception &e) {
        DDWAF_ERROR("{}", e.what());
    } catch (...) {
        DDWAF_ERROR("unknown exception");
    }

    return nullptr;
}

uint32_t ddwaf_builder_get_config_paths(
    ddwaf_builder builder, ddwaf_object *paths, const char *filter, uint32_t filter_len)
{
    if (builder == nullptr) {
        return 0;
    }

    try {
        std::vector<std::string_view> config_paths;
        if (filter != nullptr) {
            re2::RE2::Options options;
            options.set_log_errors(false);
            options.set_case_sensitive(true);

            re2::RE2 regex_filter{{filter, static_cast<std::size_t>(filter_len)}, options};
            config_paths = builder->get_filtered_config_paths(regex_filter);
        } else {
            config_paths = builder->get_config_paths();
        }

        if (paths != nullptr) {
            auto *default_allocator = memory::get_default_resource();
            auto object = owned_object::make_array(config_paths.size(), default_allocator);
            for (const auto &value : config_paths) { object.emplace_back(value); }
            // avoid to_borrowed(paths, ...) = ... as that would destroy
            // the current value in paths, which could be uninitialized
            *to_ptr(paths) = object.move();
        }
        return config_paths.size();
    } catch (const std::exception &e) {
        DDWAF_ERROR("{}", e.what());
    } catch (...) {
        DDWAF_ERROR("unknown exception");
    }

    return 0;
}

void ddwaf_builder_destroy(ddwaf_builder builder)
{
    try {
        delete builder;
    } catch (const std::exception &e) {
        DDWAF_ERROR("{}", e.what());
    } catch (...) {
        DDWAF_ERROR("unknown exception");
    }
}

ddwaf_allocator ddwaf_get_default_allocator() { return memory::get_default_resource(); }

ddwaf_allocator ddwaf_synchronized_pool_allocator_init()
{
    try {
        return new memory::synchronized_pool_resource();
    } catch (const std::exception &e) {
        DDWAF_ERROR("{}", e.what());
    } catch (...) {
        DDWAF_ERROR("unknown exception");
    }
    return nullptr;
}

ddwaf_allocator ddwaf_unsynchronized_pool_allocator_init()
{
    try {
        return new memory::unsynchronized_pool_resource();
    } catch (const std::exception &e) {
        DDWAF_ERROR("{}", e.what());
    } catch (...) {
        DDWAF_ERROR("unknown exception");
    }
    return nullptr;
}

ddwaf_allocator ddwaf_monotonic_allocator_init()
{
    try {
        return new memory::monotonic_buffer_resource();
    } catch (const std::exception &e) {
        DDWAF_ERROR("{}", e.what());
    } catch (...) {
        DDWAF_ERROR("unknown exception");
    }
    return nullptr;
}

ddwaf_allocator ddwaf_user_allocator_init(ddwaf_alloc_fn_type alloc_fn, ddwaf_free_fn_type free_fn,
    void *udata, ddwaf_udata_free_fn_type udata_free_fn)
{
    try {
        return new memory::user_resource(alloc_fn, free_fn, udata, udata_free_fn);
    } catch (const std::exception &e) {
        DDWAF_ERROR("{}", e.what());
    } catch (...) {
        DDWAF_ERROR("unknown exception");
    }
    return nullptr;
}

void *ddwaf_allocator_alloc(ddwaf_allocator alloc, size_t bytes, size_t alignment)
{
    if (alloc == nullptr) {
        return nullptr;
    }

    try {
        return to_alloc_ptr(alloc)->allocate(bytes, alignment);
    } catch (const std::exception &e) {
        DDWAF_ERROR("{}", e.what());
    } catch (...) {
        DDWAF_ERROR("unknown exception");
    }
    return nullptr;
}

void ddwaf_allocator_free(ddwaf_allocator alloc, void *p, size_t bytes, size_t alignment)
{
    if (alloc != nullptr) {
        to_alloc_ptr(alloc)->deallocate(p, bytes, alignment);
    }
}

void ddwaf_allocator_destroy(ddwaf_allocator alloc)
{
    if (alloc == memory::get_default_resource()) {
        return;
    }

    try {
        delete to_alloc_ptr(alloc);
    } catch (const std::exception &e) {
        DDWAF_ERROR("{}", e.what());
    } catch (...) {
        DDWAF_ERROR("unknown exception");
    }
}

ddwaf_object *ddwaf_object_set_invalid(ddwaf_object *object)
{
    if (object == nullptr) {
        return nullptr;
    }

    to_ref(object) = detail::object{
        .type = object_type::invalid,
    };

    return object;
}

ddwaf_object *ddwaf_object_set_null(ddwaf_object *object)
{
    if (object == nullptr) {
        return nullptr;
    }

    to_ref(object) = detail::object{
        .type = object_type::null,
    };

    return object;
}

ddwaf_object *ddwaf_object_null(ddwaf_object *object) { return ddwaf_object_set_null(object); }

ddwaf_object *ddwaf_object_set_string(
    ddwaf_object *object, const char *string, uint32_t length, ddwaf_allocator alloc)
{
    if (object == nullptr || (string == nullptr && length != 0) || alloc == nullptr) {
        return nullptr;
    }
    owned_object new_str = owned_object::make_string(string, length, to_alloc_ptr(alloc));
    to_ref(object) = new_str.move();
    return object;
}

ddwaf_object *ddwaf_object_set_string_nocopy(
    ddwaf_object *object, const char *string, uint32_t length)
{
    if (object == nullptr || string == nullptr) {
        return nullptr;
    }
    // safety: the allocator is irrelevant: unsafe_make_string_copy doesn't
    // allocate from it and we forget it afterwards (we just care about the
    // detail::object part of the owned_object)
    to_ref(object) =
        owned_object::make_string_nocopy(string, length, memory::get_default_null_resource())
            .move();
    return object;
}

ddwaf_object *ddwaf_object_set_string_literal(
    ddwaf_object *object, const char *string, uint32_t length)
{
    if (object == nullptr || string == nullptr) {
        return nullptr;
    }
    to_ref(object) = owned_object::make_string_literal(string, length).ref();
    return object;
}

ddwaf_object *ddwaf_object_set_unsigned(ddwaf_object *object, uint64_t value)
{
    if (object == nullptr) {
        return nullptr;
    }

    to_ref(object) = detail::object{
        .via = {.u64 = {.type = object_type::uint64, .val = value}},
    };
    return object;
}

ddwaf_object *ddwaf_object_unsigned(ddwaf_object *object, uint64_t value)
{
    return ddwaf_object_set_unsigned(object, value);
}

ddwaf_object *ddwaf_object_set_signed(ddwaf_object *object, int64_t value)
{
    if (object == nullptr) {
        return nullptr;
    }

    to_ref(object) = detail::object{
        .via = {.i64 = {.type = object_type::int64, .val = value}},
    };
    return object;
}

ddwaf_object *ddwaf_object_signed(ddwaf_object *object, int64_t value)
{
    return ddwaf_object_set_signed(object, value);
}

ddwaf_object *ddwaf_object_set_bool(ddwaf_object *object, bool value)
{
    if (object == nullptr) {
        return nullptr;
    }
    to_ref(object) = detail::object{
        .via = {.b8 = {.type = object_type::boolean, .val = value}},
    };
    return object;
}

ddwaf_object *ddwaf_object_bool(ddwaf_object *object, bool value)
{
    return ddwaf_object_set_bool(object, value);
}

ddwaf_object *ddwaf_object_set_float(ddwaf_object *object, double value)
{
    if (object == nullptr) {
        return nullptr;
    }
    to_ref(object) = detail::object{
        .via = {.f64 = {.type = object_type::float64, .val = value}},
    };
    return object;
}

ddwaf_object *ddwaf_object_float(ddwaf_object *object, double value)
{
    return ddwaf_object_set_float(object, value);
}

#undef ddwaf_object_set_array
#undef ddwaf_object_set_map

ddwaf_object *ddwaf_object_set_array(ddwaf_object *object, uint16_t capacity, ddwaf_allocator alloc)
{
    return ddwaf_object_set_array_large(object, capacity, alloc);
}

ddwaf_object *ddwaf_object_set_array_large(
    ddwaf_object *object, size_t capacity, ddwaf_allocator alloc)
{
    if (object == nullptr || alloc == nullptr) {
        return nullptr;
    }

    try {
        // object may be uninitialized
        auto new_array = owned_object::make_array(capacity, to_alloc_ptr(alloc));
        to_ref(object) = new_array.move();
        return object;
    } catch (...) {} // NOLINT(bugprone-empty-catch)
    return nullptr;
}

ddwaf_object *ddwaf_object_set_map(ddwaf_object *object, uint16_t capacity, ddwaf_allocator alloc)
{
    return ddwaf_object_set_map_large(object, capacity, alloc);
}

ddwaf_object *ddwaf_object_set_map_large(
    ddwaf_object *object, size_t capacity, ddwaf_allocator alloc)
{
    if (object == nullptr || alloc == nullptr) {
        return nullptr;
    }

    try {
        // object may be uninitialized
        auto new_map = owned_object::make_map(capacity, to_alloc_ptr(alloc));
        to_ref(object) = new_map.move();
        return object;
    } catch (...) {} // NOLINT(bugprone-empty-catch)
    return nullptr;
}

bool ddwaf_object_from_json(
    ddwaf_object *output, const char *json_str, uint32_t length, ddwaf_allocator alloc)
{
    if (output == nullptr || json_str == nullptr || length == 0) {
        return false;
    }

    auto *alloc_ptr = to_alloc_ptr(alloc);
    try {
        // avoid to_borrowed(output, ...) = ... as that would destroy
        // the current value in output, which could be uninitialized
        *to_ptr(output) = json_to_object({json_str, length}, alloc_ptr).move();
        return to_borrowed(output, alloc_ptr).is_valid();
    } catch (...) {} // NOLINT(bugprone-empty-catch)

    return false;
}

ddwaf_object *ddwaf_object_insert(ddwaf_object *array, ddwaf_allocator alloc)
{
    if (array == nullptr || !ddwaf::is_array(static_cast<object_type>(array->type)) ||
        alloc == nullptr) {
        return nullptr;
    }

    try {
        auto *alloc_ptr = to_alloc_ptr(alloc);
        borrowed_object container = to_borrowed(array, alloc_ptr);
        owned_object new_element = owned_object{};
        borrowed_object inserted = container.emplace_back(std::move(new_element));

        // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
        return reinterpret_cast<ddwaf_object *>(inserted.ptr());
    } catch (...) {} // NOLINT(bugprone-empty-catch)
    return nullptr;
}
ddwaf_object *ddwaf_object_insert_key(
    ddwaf_object *map, const char *key, uint32_t length, ddwaf_allocator alloc)
{
    if (map == nullptr || !ddwaf::is_map(static_cast<object_type>(map->type)) || alloc == nullptr) {
        return nullptr;
    }

    try {
        auto *alloc_ptr = to_alloc_ptr(alloc);
        borrowed_object container = to_borrowed(map, alloc_ptr);
        owned_object new_value = owned_object{};
        borrowed_object inserted =
            container.emplace(std::string_view{key, length}, std::move(new_value));

        // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
        return reinterpret_cast<ddwaf_object *>(inserted.ptr());
    } catch (...) {} // NOLINT(bugprone-empty-catch)
    return nullptr;
}

ddwaf_object *ddwaf_object_insert_key_nocopy(
    ddwaf_object *map, const char *key, uint32_t length, ddwaf_allocator alloc)
{
    if (map == nullptr || !ddwaf::is_map(static_cast<object_type>(map->type)) || alloc == nullptr) {
        return nullptr;
    }

    try {
        auto *alloc_ptr = to_alloc_ptr(alloc);
        auto key_obj = owned_object::make_string_nocopy(key, length, alloc_ptr);
        auto value_obj = owned_object{};

        // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
        return reinterpret_cast<ddwaf_object *>(
            to_borrowed(map, alloc_ptr)
                // safety: it's part of the contract of this function that the
                // key can be deallocated with alloc
                .emplace(std::move(key_obj), std::move(value_obj))
                .ptr());
    } catch (...) {} // NOLINT(bugprone-empty-catch)
    return nullptr;
}

ddwaf_object *ddwaf_object_insert_literal_key(
    ddwaf_object *map, const char *key, uint32_t length, ddwaf_allocator alloc)
{
    if (map == nullptr || !ddwaf::is_map(static_cast<object_type>(map->type)) || alloc == nullptr) {
        return nullptr;
    }

    try {
        auto *alloc_ptr = to_alloc_ptr(alloc);
        auto key_obj = owned_object::make_string_literal(key, length);
        auto value_obj = owned_object{};

        // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
        return reinterpret_cast<ddwaf_object *>(
            to_borrowed(map, alloc_ptr).emplace(std::move(key_obj), std::move(value_obj)).ptr());
    } catch (...) {} // NOLINT(bugprone-empty-catch)
    return nullptr;
}

void ddwaf_object_destroy(ddwaf_object *object, ddwaf_allocator alloc)
{
    if (object == nullptr || alloc == nullptr) {
        return;
    }

    detail::object_destroy(to_ref(object), to_alloc_ptr(alloc));

    ddwaf_object_set_invalid(object);
}

DDWAF_OBJ_TYPE ddwaf_object_get_type(const ddwaf_object *object)
{
    const object_view view{to_ptr(object)};
    if (!view.has_value()) {
        return DDWAF_OBJ_INVALID;
    }

    return static_cast<DDWAF_OBJ_TYPE>(view.type());
}

size_t ddwaf_object_get_size(const ddwaf_object *object)
{
    const object_view view{to_ptr(object)};
    if (!view.has_value() || !view.is_container()) {
        return 0;
    }

    return view.size();
}

size_t ddwaf_object_get_length(const ddwaf_object *object)
{
    const object_view view{to_ptr(object)};
    if (!view.has_value() || !view.is_string()) {
        return 0;
    }

    return view.size();
}

const char *ddwaf_object_get_string(const ddwaf_object *object, size_t *length)
{
    const object_view view{to_ptr(object)};
    if (!view.has_value() || !view.is_string()) {
        return nullptr;
    }

    if (length != nullptr) {
        *length = view.size();
    }

    return view.data();
}

uint64_t ddwaf_object_get_unsigned(const ddwaf_object *object)
{
    const object_view view{to_ptr(object)};
    if (!view.has_value() || !view.is<uint64_t>()) {
        return 0;
    }
    return view.as<uint64_t>();
}

int64_t ddwaf_object_get_signed(const ddwaf_object *object)
{
    const object_view view{to_ptr(object)};
    if (!view.has_value() || !view.is<int64_t>()) {
        return 0;
    }
    return view.as<int64_t>();
}

double ddwaf_object_get_float(const ddwaf_object *object)
{
    const object_view view{to_ptr(object)};
    if (!view.has_value() || !view.is<double>()) {
        return 0;
    }
    return view.as<double>();
}

bool ddwaf_object_get_bool(const ddwaf_object *object)
{
    const object_view view{to_ptr(object)};
    if (!view.has_value() || !view.is<bool>()) {
        return false;
    }
    return view.as<bool>();
}

const ddwaf_object *ddwaf_object_at_key(const ddwaf_object *object, size_t index)
{
    const object_view view{to_ptr(object)};
    if (!view.has_value() || !view.is_map() || index >= view.size()) {
        return nullptr;
    }

    // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
    return reinterpret_cast<const ddwaf_object *>(view.at_key(index).ptr());
}

const ddwaf_object *ddwaf_object_at_value(const ddwaf_object *object, size_t index)
{
    const object_view view{to_ptr(object)};
    if (!view.has_value() || !view.is_container() || index >= view.size()) {
        return nullptr;
    }

    // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
    return reinterpret_cast<const ddwaf_object *>(view.at_value(index).ptr());
}

const ddwaf_object *ddwaf_object_find(const ddwaf_object *object, const char *key, size_t length)
{
    const object_view view{to_ptr(object)};
    if (!view.has_value() || !view.is_map() || view.empty() || key == nullptr || length == 0) {
        return nullptr;
    }

    // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
    return reinterpret_cast<const ddwaf_object *>(view.find(std::string_view{key, length}).ptr());
}

ddwaf_object *ddwaf_object_clone(
    const ddwaf_object *source, ddwaf_object *destination, ddwaf_allocator alloc)
{
    const object_view view{to_ptr(source)};
    if (!view.has_value() || destination == nullptr || alloc == nullptr) {
        return nullptr;
    }

    try {
        auto *alloc_ptr = to_alloc_ptr(alloc);
        // destination may be uninitialized; don't use borrowed_object
        auto output = view.clone(alloc_ptr);
        to_ref(destination) = output.move();
        return destination;
    } catch (...) {} // NOLINT(bugprone-empty-catch)
    return nullptr;
}

bool ddwaf_object_is_invalid(const ddwaf_object *object)
{
    const object_view view{to_ptr(object)};
    return view.has_value() && view.is_invalid();
}

bool ddwaf_object_is_null(const ddwaf_object *object)
{
    const object_view view{to_ptr(object)};
    return view.has_value() && view.type() == object_type::null;
}

bool ddwaf_object_is_bool(const ddwaf_object *object)
{
    const object_view view{to_ptr(object)};
    return view.has_value() && view.type() == object_type::boolean;
}

bool ddwaf_object_is_signed(const ddwaf_object *object)
{
    const object_view view{to_ptr(object)};
    return view.has_value() && view.type() == object_type::int64;
}

bool ddwaf_object_is_unsigned(const ddwaf_object *object)
{
    const object_view view{to_ptr(object)};
    return view.has_value() && view.type() == object_type::uint64;
}

bool ddwaf_object_is_float(const ddwaf_object *object)
{
    const object_view view{to_ptr(object)};
    return view.has_value() && view.type() == object_type::float64;
}

bool ddwaf_object_is_string(const ddwaf_object *object)
{
    const object_view view{to_ptr(object)};
    return view.has_value() && view.is_string();
}

bool ddwaf_object_is_array(const ddwaf_object *object)
{
    const object_view view{to_ptr(object)};
    return view.has_value() && view.is_array();
}

bool ddwaf_object_is_map(const ddwaf_object *object)
{
    const object_view view{to_ptr(object)};
    return view.has_value() && view.is_map();
}
}