File: sql_audit.cc

package info (click to toggle)
mysql-8.0 8.0.45-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,273,048 kB
  • sloc: cpp: 4,685,434; ansic: 412,712; pascal: 108,396; java: 83,641; perl: 30,221; cs: 27,067; sql: 26,594; python: 21,816; sh: 17,285; yacc: 17,169; php: 11,522; xml: 7,388; javascript: 7,083; makefile: 1,793; lex: 1,075; awk: 670; asm: 520; objc: 183; ruby: 97; lisp: 86
file content (1463 lines) | stat: -rw-r--r-- 48,671 bytes parent folder | download
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
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
/* Copyright (c) 2007, 2025, Oracle and/or its affiliates.

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License, version 2.0,
   as published by the Free Software Foundation.

   This program is designed to work with certain software (including
   but not limited to OpenSSL) that is licensed under separate terms,
   as designated in a particular file or component or in included license
   documentation.  The authors of MySQL hereby grant you an additional
   permission to link the program and your derivative works with the
   separately licensed software that they have either included with
   the program or referenced in the documentation.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License, version 2.0, for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA */

#include "sql/sql_audit.h"

#include <sys/types.h>

#include "lex_string.h"
#include "m_ctype.h"
#include "my_compiler.h"
#include "my_dbug.h"
#include "my_inttypes.h"
#include "my_loglevel.h"
#include "my_macros.h"
#include "my_psi_config.h"
#include "my_sqlcommand.h"
#include "my_sys.h"
#include "mysql/components/services/bits/mysql_mutex_bits.h"
#include "mysql/components/services/bits/psi_bits.h"
#include "mysql/components/services/bits/psi_mutex_bits.h"
#include "mysql/components/services/log_builtins.h"
#include "mysql/components/services/log_shared.h"
#include "mysql/mysql_lex_string.h"
#include "mysql/plugin.h"
#include "mysql/psi/mysql_mutex.h"
#include "mysqld_error.h"
#include "prealloced_array.h"
#include "sql/auto_thd.h"  // Auto_THD
#include "sql/current_thd.h"
#include "sql/error_handler.h"  // Internal_error_handler
#include "sql/log.h"
#include "sql/mysqld.h"     // sql_statement_names
#include "sql/sql_class.h"  // THD
#include "sql/sql_error.h"
#include "sql/sql_lex.h"
#include "sql/sql_plugin.h"  // my_plugin_foreach
#include "sql/sql_plugin_ref.h"
#include "sql/sql_rewrite.h"  // mysql_rewrite_query
#include "sql/table.h"
#include "sql_string.h"
#include "thr_mutex.h"

/**
  @class Audit_error_handler

  Error handler that controls error reporting by plugin.
*/
class Audit_error_handler : public Internal_error_handler {
 private:
  /**
    @brief Blocked copy constructor (private).
  */
  Audit_error_handler(const Audit_error_handler &obj [[maybe_unused]])
      : m_thd(nullptr),
        m_warning_message(nullptr),
        m_error_reported(false),
        m_active(false) {}

 public:
  /**
    @brief Construction.

    @param thd            Current thread data.
    @param warning_message Warning message used when error has been
                               suppressed.
    @param active              Specifies whether the handler is active or not.
                               Optional parameter (default is true).
  */
  Audit_error_handler(THD *thd, const char *warning_message, bool active = true)
      : m_thd(thd),
        m_warning_message(warning_message),
        m_error_reported(false),
        m_active(active) {
    if (m_active) {
      /* Activate the error handler. */
      m_thd->push_internal_handler(this);
    }
  }

  /**
    @brief Destruction.
  */
  ~Audit_error_handler() override {
    if (m_active) {
      /* Deactivate this handler. */
      m_thd->pop_internal_handler();
    }
  }

  /**
    @brief Simplified custom handler.

    @returns True on error rejection, otherwise false.
  */
  virtual bool handle() = 0;

  /**
    @brief Error handler.

    @see Internal_error_handler::handle_condition

    @returns True on error rejection, otherwise false.
  */
  bool handle_condition(THD *, uint sql_errno, const char *sqlstate,
                        Sql_condition::enum_severity_level *,
                        const char *msg) override {
    if (m_active && handle()) {
      /* Error has been rejected. Write warning message. */
      print_warning(m_warning_message, sql_errno, sqlstate, msg);

      m_error_reported = true;

      return true;
    }

    return false;
  }

  /**
    @brief Warning print routine.

    Also prints the underlying error attributes if supplied.

    @param warn_msg  Warning message to be printed.
    @param sql_errno The error number of the underlying error
    @param sqlstate  The SQL state of the underlying error. NULL if none
    @param msg       The text of the underlying error. NULL if none
  */
  virtual void print_warning(const char *warn_msg, uint sql_errno,
                             const char *sqlstate, const char *msg) {
    LogErr(WARNING_LEVEL, ER_AUDIT_WARNING, warn_msg, sql_errno,
           sqlstate ? sqlstate : "<NO_STATE>", msg ? msg : "<NO_MESSAGE>");
  }

  /**
    @brief Convert the result value returned from the audit api.

    @param result Result value received from the plugin function.

    @returns Converted result value.
  */
  int get_result(int result) { return m_error_reported ? 0 : result; }

 private:
  /** Current thread data. */
  THD *m_thd;

  /** Warning message used when the error is rejected. */
  const char *m_warning_message;

  /** Error has been reported. */
  bool m_error_reported;

  /** Handler has been activated. */
  const bool m_active;
};

struct st_mysql_event_generic {
  mysql_event_class_t event_class;
  const void *event;
};

/**
  @struct st_mysql_subscribe_event

  Plugin event subscription structure. Used during acquisition of the plugins
  into user session.
*/
struct st_mysql_subscribe_event {
  /*
    Event class.
  */
  mysql_event_class_t event_class;
  /*
    Event subclass.
  */
  unsigned long event_subclass;
  /*
    The array that keeps sum (OR) mask of all plugins that subscribe
    to the event specified by the event_class and event_subclass.

    lookup_mask is acquired during build_lookup_mask call.
  */
  unsigned long lookup_mask[MYSQL_AUDIT_CLASS_MASK_SIZE];
  /*
    The array that keeps sum (OR) mask of all plugins that are acquired
    to the current session as a result of acquire_plugins call.

    subscribed_mask is acquired during acquisition of the plugins
    (acquire_plugins call).
  */
  unsigned long subscribed_mask[MYSQL_AUDIT_CLASS_MASK_SIZE];
  /*
    The array that keeps sum (OR) mask of all plugins that were not acquired
    to the current session as a result of acquire_plugins call.
  */
  unsigned long not_subscribed_mask[MYSQL_AUDIT_CLASS_MASK_SIZE];
};

unsigned long mysql_global_audit_mask[MYSQL_AUDIT_CLASS_MASK_SIZE];

static mysql_mutex_t LOCK_audit_mask;

static int event_class_dispatch(THD *thd, mysql_event_class_t event_class,
                                const void *event);

static int event_class_dispatch_error(THD *thd, mysql_event_class_t event_class,
                                      const char *event_name,
                                      const void *event);

/**
  Add mask specified by the rhs parameter to the mask parameter.

  @param mask Mask, to which rhs mask is to be added.
  @param rhs  Mask to be added to mask parameter.
*/
static inline void add_audit_mask(unsigned long *mask, unsigned long rhs) {
  *mask |= rhs;
}

/**
  Add entire audit mask specified by the src to dst.

  @param dst Destination mask array pointer.
  @param src Source mask array pointer.
*/
static inline void add_audit_mask(unsigned long *dst,
                                  const unsigned long *src) {
  int i;
  for (i = MYSQL_AUDIT_GENERAL_CLASS; i < MYSQL_AUDIT_CLASS_MASK_SIZE; i++)
    add_audit_mask(dst++, *src++);
}

/**
  Check, whether masks specified by lhs parameter and rhs parameters overlap.

  @param lhs First mask to check.
  @param rhs Second mask to check.

  @return false, when masks overlap, otherwise true.
*/
static inline bool check_audit_mask(const unsigned long lhs,
                                    const unsigned long rhs) {
  return !(lhs & rhs);
}

/**
  Check, whether mask arrays specified by the lhs parameter and rhs parameter
  overlap.

  @param lhs First mask array to check.
  @param rhs Second mask array to check.

  @return false, when mask array overlap, otherwise true.
*/
static inline bool check_audit_mask(const unsigned long *lhs,
                                    const unsigned long *rhs) {
  int i;
  for (i = MYSQL_AUDIT_GENERAL_CLASS; i < MYSQL_AUDIT_CLASS_MASK_SIZE; i++)
    if (!check_audit_mask(*lhs++, *rhs++)) return false;

  return true;
}

/**
  Fill query info extracted from the thread object and return
  the thread object charset info.

  @param[in]  thd     Thread data.
  @param[out] query   SQL query text.

  @return SQL query charset.
*/
inline const CHARSET_INFO *thd_get_audit_query(THD *thd,
                                               MYSQL_LEX_CSTRING *query) {
  /*
    If we haven't tried to rewrite the query to obfuscate passwords
    etc. yet, do so now.
  */
  if (thd->rewritten_query().length() == 0) mysql_rewrite_query(thd);

  /*
    If there was something to rewrite, use the rewritten query;
    otherwise, just use the original as submitted by the client.
  */
  if (thd->rewritten_query().length() > 0) {
    query->str = thd->rewritten_query().ptr();
    query->length = thd->rewritten_query().length();
    return thd->rewritten_query().charset();
  } else {
    query->str = thd->query().str;
    query->length = thd->query().length;
    DBUG_PRINT("print_query", ("%.*s\n", (int)query->length, query->str));
    return thd->charset();
  }
}

/**
  @class Ignore_event_error_handler

  Ignore all errors notified from within plugin.
*/
class Ignore_event_error_handler : public Audit_error_handler {
 public:
  /**
    @brief Construction.

    @param thd             Current thread data.
    @param event_name      Textual form of the audit event enum.
  */
  Ignore_event_error_handler(THD *thd, const char *event_name)
      : Audit_error_handler(thd, ""), m_event_name(event_name) {}

  /**
    @brief Ignore all errors.

    @retval True on error rejection, otherwise false.
  */
  bool handle() override { return true; }

  /**
    @brief Custom warning print routine.

    Also prints the underlying error attributes if supplied.

    @param warn_msg  Warning message to be printed.
    @param sql_errno The error number of the underlying error
    @param sqlstate  The SQL state of the underlying error. NULL if none
    @param msg       The text of the underlying error. NULL if none
  */
  void print_warning(const char *warn_msg [[maybe_unused]], uint sql_errno,
                     const char *sqlstate, const char *msg) override {
    LogErr(WARNING_LEVEL, ER_AUDIT_CANT_ABORT_EVENT, m_event_name, sql_errno,
           sqlstate ? sqlstate : "<NO_STATE>", msg ? msg : "<NO_MESSAGE>");
  }

 private:
  /**
  @brief Event name used in the warning message.
  */
  const char *m_event_name;
};

int mysql_audit_notify(THD *thd, mysql_event_general_subclass_t subclass,
                       const char *subclass_name, int error_code,
                       const char *msg, size_t msg_len) {
  mysql_event_general event;
  char user_buff[MAX_USER_HOST_SIZE];

  assert(thd);

  if (mysql_audit_acquire_plugins(thd, MYSQL_AUDIT_GENERAL_CLASS,
                                  static_cast<unsigned long>(subclass)))
    return 0;

  event.event_subclass = subclass;
  event.general_error_code = error_code;
  event.general_thread_id = thd->thread_id();

  Security_context *sctx = thd->security_context();

  event.general_user.str = user_buff;
  event.general_user.length = make_user_name(sctx, user_buff);
  event.general_ip = sctx->ip();
  event.general_host = sctx->host();
  event.general_external_user = sctx->external_user();
  event.general_rows = thd->get_stmt_da()->current_row_for_condition();

  if (msg != nullptr && thd->lex->sql_command == SQLCOM_END &&
      thd->get_command() != COM_QUERY) {
    event.general_sql_command = {STRING_WITH_LEN("")};
  } else {
    event.general_sql_command = sql_statement_names[thd->lex->sql_command];
  }

  event.general_charset = const_cast<CHARSET_INFO *>(
      thd_get_audit_query(thd, &event.general_query));

  event.general_time = thd->query_start_in_secs();

  DBUG_EXECUTE_IF("audit_log_negative_general_error_code",
                  event.general_error_code *= -1;);

  event.general_command.str = msg;
  event.general_command.length = msg_len;

  if (subclass == MYSQL_AUDIT_GENERAL_ERROR ||
      subclass == MYSQL_AUDIT_GENERAL_STATUS ||
      subclass == MYSQL_AUDIT_GENERAL_RESULT) {
    Ignore_event_error_handler handler(thd, subclass_name);

    return handler.get_result(
        event_class_dispatch(thd, MYSQL_AUDIT_GENERAL_CLASS, &event));
  }

  return event_class_dispatch_error(thd, MYSQL_AUDIT_GENERAL_CLASS,
                                    subclass_name, &event);
}

int mysql_audit_notify(THD *thd, mysql_event_connection_subclass_t subclass,
                       const char *subclass_name, int errcode) {
  mysql_event_connection event;

  /*
    Do not take into account m_auditing_activated flag. Always generate
    events of the MYSQL_AUDIT_CONNECTION_CLASS class.
  */
  if (mysql_audit_acquire_plugins(thd, MYSQL_AUDIT_CONNECTION_CLASS,
                                  static_cast<unsigned long>(subclass),
                                  false)) {
    return 0;
  }

  event.event_subclass = subclass;
  event.status = errcode;
  event.connection_id = thd->thread_id();
  event.user.str = thd->security_context()->user().str;
  event.user.length = thd->security_context()->user().length;
  event.priv_user.str = thd->security_context()->priv_user().str;
  event.priv_user.length = thd->security_context()->priv_user().length;
  event.external_user.str = thd->security_context()->external_user().str;
  event.external_user.length = thd->security_context()->external_user().length;
  event.proxy_user.str = thd->security_context()->proxy_user().str;
  event.proxy_user.length = thd->security_context()->proxy_user().length;
  event.host.str = thd->security_context()->host().str;
  event.host.length = thd->security_context()->host().length;
  event.ip.str = thd->security_context()->ip().str;
  event.ip.length = thd->security_context()->ip().length;
  event.database.str = thd->db().str;
  event.database.length = thd->db().length;
  event.connection_type = thd->get_vio_type();

  if (subclass == MYSQL_AUDIT_CONNECTION_DISCONNECT) {
    Ignore_event_error_handler handler(thd, subclass_name);

    return handler.get_result(event_class_dispatch_error(
        thd, MYSQL_AUDIT_CONNECTION_CLASS, subclass_name, &event));
  }

  return event_class_dispatch_error(thd, MYSQL_AUDIT_CONNECTION_CLASS,
                                    subclass_name, &event);
}

int mysql_audit_notify(THD *thd, mysql_event_connection_subclass_t subclass,
                       const char *subclass_name) {
  return mysql_audit_notify(
      thd, subclass, subclass_name,
      thd->get_stmt_da()->is_error() ? thd->get_stmt_da()->mysql_errno() : 0);
}

int mysql_audit_notify(THD *thd, mysql_event_parse_subclass_t subclass,
                       const char *subclass_name,
                       mysql_event_parse_rewrite_plugin_flag *flags,
                       LEX_CSTRING *rewritten_query) {
  mysql_event_parse event;

  if (mysql_audit_acquire_plugins(thd, MYSQL_AUDIT_PARSE_CLASS, subclass))
    return 0;

  event.event_subclass = subclass;
  event.flags = flags;
  event.query.str = thd->query().str;
  event.query.length = thd->query().length;
  event.rewritten_query = rewritten_query;

  return event_class_dispatch_error(thd, MYSQL_AUDIT_PARSE_CLASS, subclass_name,
                                    &event);
}

/**
  Check whether the table access event for a specified table will
  be generated.

  Events for Views, table catogories other than 'SYSTEM' or 'USER' and
  temporary tables are not generated.

  @param thd   Thread handler
  @param table Table that is to be check.

  @retval true - generate event, otherwise not.
*/
inline bool generate_table_access_event(THD *thd, Table_ref *table) {
  /* Discard views or derived tables. */
  if (table->is_view_or_derived()) return false;

  /* TRUNCATE query on Storage Engine supporting HTON_CAN_RECREATE flag. */
  if (!table->table) return true;

  /* Do not generate events, which come from PS preparation. */
  if (thd->lex->is_ps_or_view_context_analysis()) return false;

  /* Generate event for SYSTEM and USER tables, which are not temp tables. */
  if ((table->table->s->table_category == TABLE_CATEGORY_SYSTEM ||
       table->table->s->table_category == TABLE_CATEGORY_USER ||
       table->table->s->table_category == TABLE_CATEGORY_ACL_TABLE) &&
      table->table->s->tmp_table == NO_TMP_TABLE)
    return true;

  return false;
}

/**
  Function that allows to use AUDIT_EVENT macro for setting subclass
  and subclass name values.

  @param [out] out_subclass      Subclass value pointer to be set.
  @param [out] out_subclass_name Subclass name pointer to be set.
  @param subclass                Subclass that sets out_subclass value.
  @param subclass_name           Subclass name that sets out_subclass_name.
*/
inline static void set_table_access_subclass(
    mysql_event_table_access_subclass_t *out_subclass,
    const char **out_subclass_name,
    mysql_event_table_access_subclass_t subclass, const char *subclass_name) {
  *out_subclass = subclass;
  *out_subclass_name = subclass_name;
}

/**
  Generate table access event for a specified table. Table is being
  verified, whether the event for this table is to be generated.

  @see generate_event

  @param thd           Current thread data.
  @param subclass      Subclass value.
  @param subclass_name Subclass name.
  @param table         Table, for which table access event is to be generated.

  @return Abort execution on 'true', otherwise continue execution.
*/
static int mysql_audit_notify(THD *thd,
                              mysql_event_table_access_subclass_t subclass,
                              const char *subclass_name, Table_ref *table) {
  LEX_CSTRING str;
  mysql_event_table_access event;

  if (!generate_table_access_event(thd, table) ||
      mysql_audit_acquire_plugins(thd, MYSQL_AUDIT_TABLE_ACCESS_CLASS,
                                  static_cast<unsigned long>(subclass)))
    return 0;

  event.event_subclass = subclass;
  event.connection_id = thd->thread_id();
  event.sql_command_id = thd->lex->sql_command;

  event.query_charset = thd_get_audit_query(thd, &event.query);

  lex_cstring_set(&str, table->db);
  event.table_database.str = str.str;
  event.table_database.length = str.length;

  lex_cstring_set(&str, table->table_name);
  event.table_name.str = str.str;
  event.table_name.length = str.length;

  return event_class_dispatch_error(thd, MYSQL_AUDIT_TABLE_ACCESS_CLASS,
                                    subclass_name, &event);
}

int mysql_audit_table_access_notify(THD *thd, Table_ref *table) {
  mysql_event_table_access_subclass_t subclass;
  const char *subclass_name;
  int ret;

  /* Do not generate events for non query table access. */
  if (!thd->lex->query_tables) return 0;

  switch (thd->lex->sql_command) {
    case SQLCOM_REPLACE_SELECT:
    case SQLCOM_INSERT_SELECT: {
      /*
        INSERT/REPLACE SELECT generates Insert event for the first table in the
        list and Read for remaining tables.
      */
      set_table_access_subclass(&subclass, &subclass_name,
                                AUDIT_EVENT(MYSQL_AUDIT_TABLE_ACCESS_INSERT));

      if ((ret = mysql_audit_notify(thd, subclass, subclass_name, table)))
        return ret;

      /* Skip this table (event already generated). */
      table = table->next_global;

      set_table_access_subclass(&subclass, &subclass_name,
                                AUDIT_EVENT(MYSQL_AUDIT_TABLE_ACCESS_READ));
      break;
    }
    case SQLCOM_INSERT:
    case SQLCOM_REPLACE:
    case SQLCOM_LOAD:
      set_table_access_subclass(&subclass, &subclass_name,
                                AUDIT_EVENT(MYSQL_AUDIT_TABLE_ACCESS_INSERT));
      break;
    case SQLCOM_DELETE:
    case SQLCOM_DELETE_MULTI:
    case SQLCOM_TRUNCATE:
      set_table_access_subclass(&subclass, &subclass_name,
                                AUDIT_EVENT(MYSQL_AUDIT_TABLE_ACCESS_DELETE));
      break;
    case SQLCOM_UPDATE:
    case SQLCOM_UPDATE_MULTI:
      /* Update state is taken from the table instance in the
         mysql_audit_notify function. */
      set_table_access_subclass(&subclass, &subclass_name,
                                AUDIT_EVENT(MYSQL_AUDIT_TABLE_ACCESS_UPDATE));
      break;
    case SQLCOM_SELECT:
    case SQLCOM_HA_READ:
    case SQLCOM_ANALYZE:
      set_table_access_subclass(&subclass, &subclass_name,
                                AUDIT_EVENT(MYSQL_AUDIT_TABLE_ACCESS_READ));
      break;
    default:
      /* Do not generate event for not supported command. */
      return 0;
  }

  for (; table; table = table->next_global) {
    /*
      Do not generate audit logs for opening DD tables when processing I_S
      queries.
    */
    if (table->referencing_view && table->referencing_view->is_system_view)
      continue;

    /*
      Update-Multi query can have several updatable tables as well as readable
      tables. This is taken from table->updating field, which holds info,
      whether table is being updated or not. table->updating holds invalid
      info, when the updatable table is referenced by a view. View status is
      taken into account in that case.
    */
    if (subclass == MYSQL_AUDIT_TABLE_ACCESS_UPDATE &&
        !table->referencing_view && !table->updating)
      set_table_access_subclass(&subclass, &subclass_name,
                                AUDIT_EVENT(MYSQL_AUDIT_TABLE_ACCESS_READ));

    if ((ret = mysql_audit_notify(thd, subclass, subclass_name, table)))
      return ret;
  }

  return 0;
}

int mysql_audit_notify(THD *thd,
                       mysql_event_global_variable_subclass_t subclass,
                       const char *subclass_name, const char *name,
                       const char *value, const unsigned int value_length) {
  mysql_event_global_variable event;

  if (mysql_audit_acquire_plugins(thd, MYSQL_AUDIT_GLOBAL_VARIABLE_CLASS,
                                  static_cast<unsigned long>(subclass)))
    return 0;

  event.event_subclass = subclass;
  event.connection_id = thd->thread_id();
  event.sql_command_id = thd->lex->sql_command;

  LEX_CSTRING name_str;
  lex_cstring_set(&name_str, name);
  event.variable_name.str = name_str.str;
  event.variable_name.length = name_str.length;

  event.variable_value.str = value;
  event.variable_value.length = value_length;

  return event_class_dispatch_error(thd, MYSQL_AUDIT_GLOBAL_VARIABLE_CLASS,
                                    subclass_name, &event);
}

int mysql_audit_notify(mysql_event_server_startup_subclass_t subclass,
                       const char *subclass_name, const char **argv,
                       unsigned int argc) {
  mysql_event_server_startup event;
  Auto_THD thd;

  if (mysql_audit_acquire_plugins(thd.thd, MYSQL_AUDIT_SERVER_STARTUP_CLASS,
                                  static_cast<unsigned long>(subclass)))
    return 0;

  event.event_subclass = subclass;
  event.argv = argv;
  event.argc = argc;

  return event_class_dispatch_error(thd.thd, MYSQL_AUDIT_SERVER_STARTUP_CLASS,
                                    subclass_name, &event);
}

/**
  Call audit plugins of SERVER SHUTDOWN audit class.

  @param[in] thd       Client thread info or NULL.
  @param[in] subclass  Type of the server abort audit event.
  @param[in] reason    Reason code of the shutdown.
  @param[in] exit_code Abort exit code.

  @result Value returned is not taken into consideration by the server.
*/
int mysql_audit_notify(THD *thd,
                       mysql_event_server_shutdown_subclass_t subclass,
                       mysql_server_shutdown_reason_t reason, int exit_code) {
  mysql_event_server_shutdown event;

  if (mysql_audit_acquire_plugins(thd, MYSQL_AUDIT_SERVER_SHUTDOWN_CLASS,
                                  static_cast<unsigned long>(subclass)))
    return 0;

  event.event_subclass = subclass;
  event.exit_code = exit_code;
  event.reason = reason;

  return event_class_dispatch(thd, MYSQL_AUDIT_SERVER_SHUTDOWN_CLASS, &event);
}

int mysql_audit_notify(mysql_event_server_shutdown_subclass_t subclass,
                       mysql_server_shutdown_reason_t reason, int exit_code) {
  if (error_handler_hook == my_message_sql) {
    Auto_THD thd;

    return mysql_audit_notify(thd.thd, subclass, reason, exit_code);
  }

  return mysql_audit_notify(nullptr, subclass, reason, exit_code);
}

/*
Function commented out. No Audit API calls yet.

int mysql_audit_notify(THD *thd, mysql_event_authorization_subclass_t subclass,
                       const char* subclass_name,
                       const char *database, const char *table,
                       const char *object)
{
  mysql_event_authorization event;

  mysql_audit_acquire_plugins(thd, MYSQL_AUDIT_AUTHORIZATION_CLASS,
                              static_cast<unsigned long>(subclass));

  event.event_subclass= subclass;
  event.connection_id= thd->thread_id();
  event.sql_command_id= thd->lex->sql_command;

  event.query_charset = thd_get_audit_query(thd, &event.query);

  LEX_CSTRING obj_str;

  lex_cstring_set(&obj_str, database ? database : "");
  event.database.str= database;
  event.database.length= obj_str.length;

  lex_cstring_set(&obj_str, table ? table : "");
  event.table.str= table;
  event.table.length = obj_str.length;

  lex_cstring_set(&obj_str, object ? object : "");
  event.object.str= object;
  event.object.length= obj_str.length;

  return event_class_dispatch_error(thd, MYSQL_AUDIT_AUTHORIZATION_CLASS,
                                    subclass_name, &event);
}
*/

/**
  @class Ignore_command_start_error_handler

  Ignore error for specified commands.
*/
class Ignore_command_start_error_handler : public Audit_error_handler {
 public:
  /**
    @brief Construction.

    @param thd     Current thread data.
    @param command Current command that the handler will be active against.
    @param command_text SQL command.
  */
  Ignore_command_start_error_handler(THD *thd, enum_server_command command,
                                     const char *command_text)
      : Audit_error_handler(thd, "", ignore_command(command)),
        m_command(command),
        m_command_text(command_text) {}

  /**
    @brief Error for specified command handling routine.

    @retval True on error rejection, otherwise false.
  */
  bool handle() override { return ignore_command(m_command); }

  /**
    @brief Custom warning print routine.

    Also prints the underlying error attributes if supplied.

    @param warn_msg  Warning message to be printed.
    @param sql_errno The error number of the underlying error
    @param sqlstate  The SQL state of the underlying error. NULL if none
    @param msg       The text of the underlying error. NULL if none
  */
  void print_warning(const char *warn_msg [[maybe_unused]], uint sql_errno,
                     const char *sqlstate, const char *msg) override {
    LogErr(WARNING_LEVEL, ER_AUDIT_CANT_ABORT_COMMAND, m_command_text,
           sql_errno, sqlstate ? sqlstate : "<NO_STATE>",
           msg ? msg : "<NO_MESSAGE>");
  }

  /**
    @brief Check whether the command is to be ignored.

    @retval True whether the command is to be ignored. Otherwise false.
  */
  static bool ignore_command(enum_server_command command) {
    /* Ignore these commands. The plugin cannot abort on these commands. */
    if (command == COM_QUIT || command == COM_PING ||
        command == COM_SLEEP || /* Deprecated commands from here. */
        command == COM_CONNECT || command == COM_TIME ||
        command == COM_DELAYED_INSERT || command == COM_END) {
      return true;
    }

    return false;
  }

 private:
  /** Command that the handler is active against. */
  enum_server_command m_command;

  /** Command string. */
  const char *m_command_text;
};

int mysql_audit_notify(THD *thd, mysql_event_command_subclass_t subclass,
                       const char *subclass_name, enum_server_command command,
                       const char *command_text) {
  mysql_event_command event;

  if (mysql_audit_acquire_plugins(thd, MYSQL_AUDIT_COMMAND_CLASS,
                                  static_cast<unsigned long>(subclass)))
    return 0;

  event.event_subclass = subclass;
  event.status =
      thd->get_stmt_da()->is_error() ? thd->get_stmt_da()->mysql_errno() : 0;
  event.connection_id = thd && thd->thread_id();
  event.command_id = command;

  if (subclass == MYSQL_AUDIT_COMMAND_START) {
    Ignore_command_start_error_handler handler(thd, command, command_text);

    return handler.get_result(event_class_dispatch_error(
        thd, MYSQL_AUDIT_COMMAND_CLASS, subclass_name, &event));
  }

  /* MYSQL_AUDIT_COMMAND_END event handling. */
  Ignore_event_error_handler handler(thd, subclass_name);

  return handler.get_result(event_class_dispatch_error(
      thd, MYSQL_AUDIT_COMMAND_CLASS, subclass_name, &event));
}

int mysql_audit_notify(THD *thd, mysql_event_query_subclass_t subclass,
                       const char *subclass_name) {
  mysql_event_query event;

  if (mysql_audit_acquire_plugins(thd, MYSQL_AUDIT_QUERY_CLASS,
                                  static_cast<unsigned long>(subclass)))
    return 0;

  event.event_subclass = subclass;
  event.status =
      thd->get_stmt_da()->is_error() ? thd->get_stmt_da()->mysql_errno() : 0;
  event.connection_id = thd->thread_id();

  event.sql_command_id = thd->lex->sql_command;

  event.query_charset = thd_get_audit_query(thd, &event.query);

  return event_class_dispatch_error(thd, MYSQL_AUDIT_QUERY_CLASS, subclass_name,
                                    &event);
}

int mysql_audit_notify(THD *thd, mysql_event_stored_program_subclass_t subclass,
                       const char *subclass_name, const char *database,
                       const char *name, void *parameters) {
  mysql_event_stored_program event;

  if (mysql_audit_acquire_plugins(thd, MYSQL_AUDIT_STORED_PROGRAM_CLASS,
                                  static_cast<unsigned long>(subclass)))
    return 0;

  event.event_subclass = subclass;
  event.connection_id = thd->thread_id();
  event.sql_command_id = thd->lex->sql_command;

  event.query_charset = thd_get_audit_query(thd, &event.query);

  LEX_CSTRING obj_str;

  lex_cstring_set(&obj_str, database ? database : "");
  event.database.str = obj_str.str;
  event.database.length = obj_str.length;

  lex_cstring_set(&obj_str, name ? name : "");
  event.name.str = obj_str.str;
  event.name.length = obj_str.length;

  event.parameters = parameters;

  return event_class_dispatch_error(thd, MYSQL_AUDIT_STORED_PROGRAM_CLASS,
                                    subclass_name, &event);
}

int mysql_audit_notify(THD *thd, mysql_event_authentication_subclass_t subclass,
                       const char *subclass_name, int status, const char *user,
                       const char *host, const char *authentication_plugin,
                       bool is_role, const char *new_user,
                       const char *new_host) {
  mysql_event_authentication event;

  if (mysql_audit_acquire_plugins(thd, MYSQL_AUDIT_AUTHENTICATION_CLASS,
                                  static_cast<unsigned long>(subclass)))
    return 0;

  event.event_subclass = subclass;
  event.status = status;
  event.connection_id = thd->thread_id();
  event.sql_command_id = thd->lex->sql_command;

  event.query_charset = thd_get_audit_query(thd, &event.query);

  LEX_CSTRING obj_str;

  lex_cstring_set(&obj_str, user ? user : "");
  event.user.str = obj_str.str;
  event.user.length = obj_str.length;

  lex_cstring_set(&obj_str, host ? host : "");
  event.host.str = obj_str.str;
  event.host.length = obj_str.length;

  lex_cstring_set(&obj_str, authentication_plugin ? authentication_plugin : "");
  event.authentication_plugin.str = obj_str.str;
  event.authentication_plugin.length = obj_str.length;

  event.is_role = is_role;

  lex_cstring_set(&obj_str, new_user ? new_user : "");
  event.new_user.str = obj_str.str;
  event.new_user.length = obj_str.length;

  lex_cstring_set(&obj_str, new_host ? new_host : "");
  event.new_host.str = obj_str.str;
  event.new_host.length = obj_str.length;

  Ignore_event_error_handler handler(thd, subclass_name);

  return handler.get_result(event_class_dispatch_error(
      thd, MYSQL_AUDIT_AUTHENTICATION_CLASS, subclass_name, &event));
}

int mysql_audit_notify(THD *thd, mysql_event_message_subclass_t subclass,
                       const char *subclass_name, const char *component,
                       size_t component_length, const char *producer,
                       size_t producer_length, const char *message,
                       size_t message_length,
                       mysql_event_message_key_value_t *key_value_map,
                       size_t key_value_map_length) {
  if (mysql_audit_acquire_plugins(thd, MYSQL_AUDIT_MESSAGE_CLASS,
                                  static_cast<unsigned long>(subclass)))
    return 0;

  mysql_event_message event;

  event.event_subclass = subclass;
  event.component.str = component;
  event.component.length = component_length;
  event.producer.str = producer;
  event.producer.length = producer_length;
  event.message.str = message;
  event.message.length = message_length;
  event.key_value_map = key_value_map;
  event.key_value_map_length = key_value_map_length;

  return event_class_dispatch_error(thd, MYSQL_AUDIT_MESSAGE_CLASS,
                                    subclass_name, &event);
}

/**
  Acquire plugin masks subscribing to the specified event of the specified
  class, passed by arg parameter. lookup_mask of the st_mysql_subscribe_event
  structure is filled, when the plugin is interested in receiving the event.

  @param         plugin Plugin reference.
  @param[in,out] arg    Opaque st_mysql_subscribe_event pointer.

  @return false is always returned.
*/
static bool acquire_lookup_mask(THD *, plugin_ref plugin, void *arg) {
  st_mysql_subscribe_event *evt = static_cast<st_mysql_subscribe_event *>(arg);
  st_mysql_audit *audit = plugin_data<st_mysql_audit *>(plugin);

  /* Check if this plugin is interested in the event */
  if (!check_audit_mask(audit->class_mask[evt->event_class],
                        evt->event_subclass))
    add_audit_mask(evt->lookup_mask, audit->class_mask);

  return false;
}

/**
  Acquire and lock any additional audit plugins, whose subscription
  mask overlaps with the lookup_mask.

  @param         thd    Current session THD.
  @param         plugin Plugin reference.
  @param[in,out] arg    Opaque st_mysql_subscribe_event pointer.

  @return This function always returns false.
*/
static bool acquire_plugins(THD *thd, plugin_ref plugin, void *arg) {
  st_mysql_subscribe_event *evt = static_cast<st_mysql_subscribe_event *>(arg);
  st_mysql_audit *data = plugin_data<st_mysql_audit *>(plugin);

  /* Check if this plugin is interested in the event */
  if (check_audit_mask(data->class_mask, evt->lookup_mask)) {
    add_audit_mask(evt->not_subscribed_mask, data->class_mask);
    return false;
  }

  /* Prevent from adding the same plugin more than one time. */
  if (!thd->audit_class_plugins.exists(plugin)) {
    /* lock the plugin and add it to the list */
    plugin = my_plugin_lock(nullptr, &plugin);

    /* The plugin could not be acquired. */
    if (plugin == nullptr) {
      /* Add this plugin mask to non subscribed mask. */
      add_audit_mask(evt->not_subscribed_mask, data->class_mask);
      return false;
    }

    thd->audit_class_plugins.push_back(plugin);
  }

  /* Copy subscription mask from the plugin into the array. */
  add_audit_mask(evt->subscribed_mask, data->class_mask);

  return false;
}

/**
  Acquire audit plugins. Ensure that audit plugins interested in given event
  class are locked by current thread.

  @param thd            MySQL thread handle.
  @param event_class    Audit event class.
  @param event_subclass Audit event subclass.
  @param check_audited  Take into account m_auditing_activated flag
                        of the THD.

  @return Zero, when there is a plugins interested in the event specified
          by event_class and event_subclass. Otherwise non zero value is
          returned.
*/
int mysql_audit_acquire_plugins(THD *thd, mysql_event_class_t event_class,
                                unsigned long event_subclass,
                                bool check_audited) {
  DBUG_TRACE;

  if (check_audited && thd && thd->m_audited == false) return 1;

  unsigned long global_mask = mysql_global_audit_mask[event_class];

  if (thd && !check_audit_mask(global_mask, event_subclass) &&
      check_audit_mask(thd->audit_class_mask[event_class], event_subclass)) {
    /*
      There is a plugin registered for the subclass, but THD has not
      registered yet for this event. Refresh THD class mask.
    */
    st_mysql_subscribe_event evt = {event_class,
                                    event_subclass,
                                    {
                                        0,
                                    },
                                    {
                                        0,
                                    },
                                    {
                                        0,
                                    }};
    plugin_foreach_func *funcs[] = {acquire_lookup_mask, acquire_plugins,
                                    nullptr};
    /*
      Acquire lookup_mask, which contains mask of all plugins that subscribe
      event specified by the event_class and event_subclass
      (acquire_lookup_mask).
      Load plugins that overlap with the lookup_mask (acquire_plugins).
    */
    plugin_foreach(thd, funcs, MYSQL_AUDIT_PLUGIN, &evt);
    /*
      Iterate through event masks of the acquired plugin, excluding masks
      of the the plugin not acquired. It's more likely that these plugins will
      be acquired during the next audit plugin acquisition.
    */
    int i;
    for (i = MYSQL_AUDIT_GENERAL_CLASS; i < MYSQL_AUDIT_CLASS_MASK_SIZE; i++)
      add_audit_mask(&thd->audit_class_mask[i],
                     (evt.subscribed_mask[i] ^ evt.not_subscribed_mask[i]) &
                         evt.subscribed_mask[i]);

    global_mask = thd->audit_class_mask[event_class];
  }

  /* Check whether there is a plugin registered for this event. */
  return check_audit_mask(global_mask, event_subclass) ? 1 : 0;
}

/**
  Release any resources associated with the current thd.

  @param[in] thd Current thread

*/

void mysql_audit_release(THD *thd) {
  plugin_ref *plugins, *plugins_last;

  if (!thd || thd->audit_class_plugins.empty()) return;

  plugins = thd->audit_class_plugins.begin();
  plugins_last = thd->audit_class_plugins.end();
  for (; plugins != plugins_last; plugins++) {
    st_mysql_audit *data = plugin_data<st_mysql_audit *>(*plugins);

    /* Check to see if the plugin has a release method */
    if (!(data->release_thd)) continue;

    /* Tell the plugin to release its resources */
    data->release_thd(thd);
  }

  /* Move audit plugins array from THD to a tmp variable in order to avoid calls
     to them via THD after the plugin is unlocked (#bug34594035) */
  Plugin_array audit_class_plugins(std::move(thd->audit_class_plugins));

  /* Now we actually unlock the plugins */
  plugin_unlock_list(nullptr, audit_class_plugins.begin(),
                     audit_class_plugins.size());

  /* Reset the state of thread values */
  thd->audit_class_mask.clear();
  thd->audit_class_mask.resize(MYSQL_AUDIT_CLASS_MASK_SIZE);
}

void mysql_audit_enable_auditing(THD *thd) { thd->m_audited = true; }

/**
  Initialize thd variables used by Audit

  @param[in] thd Current thread

*/

void mysql_audit_init_thd(THD *thd) {
  thd->audit_class_mask.clear();
  thd->audit_class_mask.resize(MYSQL_AUDIT_CLASS_MASK_SIZE);
}

/**
  Free thd variables used by Audit

  @param thd Current thread
*/

void mysql_audit_free_thd(THD *thd) {
  mysql_audit_release(thd);
  assert(thd->audit_class_plugins.empty());
}

#ifdef HAVE_PSI_INTERFACE
static PSI_mutex_key key_LOCK_audit_mask;

static PSI_mutex_info all_audit_mutexes[] = {
    {&key_LOCK_audit_mask, "LOCK_audit_mask", PSI_FLAG_SINGLETON, 0,
     PSI_DOCUMENT_ME}};

static void init_audit_psi_keys(void) {
  const char *category = "sql";
  int count;

  count = static_cast<int>(array_elements(all_audit_mutexes));
  mysql_mutex_register(category, all_audit_mutexes, count);
}
#endif /* HAVE_PSI_INTERFACE */

/**
  Initialize Audit global variables
*/

void mysql_audit_initialize() {
#ifdef HAVE_PSI_INTERFACE
  init_audit_psi_keys();
#endif

  mysql_mutex_init(key_LOCK_audit_mask, &LOCK_audit_mask, MY_MUTEX_INIT_FAST);
  memset(mysql_global_audit_mask, 0, sizeof(mysql_global_audit_mask));
}

/**
  Finalize Audit global variables
*/

void mysql_audit_finalize() { mysql_mutex_destroy(&LOCK_audit_mask); }

/**
  Initialize an Audit plug-in

  @param[in] plugin Plugin structure pointer to be initialized.

  @retval false  OK
  @retval true   There was an error.
*/

int initialize_audit_plugin(st_plugin_int *plugin) {
  st_mysql_audit *data = (st_mysql_audit *)plugin->plugin->info;
  int i;
  unsigned long masks = 0;

  for (i = MYSQL_AUDIT_GENERAL_CLASS; i < MYSQL_AUDIT_CLASS_MASK_SIZE; i++) {
    masks |= data->class_mask[i];
  }

  if (data->class_mask[MYSQL_AUDIT_AUTHORIZATION_CLASS]) {
    LogErr(ERROR_LEVEL, ER_AUDIT_PLUGIN_DOES_NOT_SUPPORT_AUDIT_AUTH_EVENTS,
           plugin->name.str);
    return 1;
  }

  if (!data->event_notify || !masks) {
    LogErr(ERROR_LEVEL, ER_AUDIT_PLUGIN_HAS_INVALID_DATA, plugin->name.str);
    return 1;
  }

  if (plugin->plugin->init && plugin->plugin->init(plugin)) {
    LogErr(ERROR_LEVEL, ER_PLUGIN_INIT_FAILED, plugin->name.str);
    return 1;
  }

  /* Make the interface info more easily accessible */
  plugin->data = plugin->plugin->info;

  /* Add the bits the plugin is interested in to the global mask */
  mysql_mutex_lock(&LOCK_audit_mask);
  add_audit_mask(mysql_global_audit_mask, data->class_mask);
  mysql_mutex_unlock(&LOCK_audit_mask);

  return 0;
}

/**
  Performs a bitwise OR of the installed plugins event class masks

  @param[in] plugin Source of the audit mask.
  @param[in] arg    Destination, where the audit mask is copied.

  @retval false  always
*/
static bool calc_class_mask(THD *, plugin_ref plugin, void *arg) {
  st_mysql_audit *data = plugin_data<st_mysql_audit *>(plugin);
  if (data)
    add_audit_mask(reinterpret_cast<unsigned long *>(arg), data->class_mask);
  return false;
}

/**
  Finalize an Audit plug-in

  @param[in] plugin Plugin data pointer to be deinitialized.

  @retval false  OK
  @retval true   There was an error.
*/
int finalize_audit_plugin(st_plugin_int *plugin) {
  unsigned long event_class_mask[MYSQL_AUDIT_CLASS_MASK_SIZE];

  if (plugin->plugin->deinit && plugin->plugin->deinit(plugin)) {
    DBUG_PRINT("warning", ("Plugin '%s' deinit function returned error.",
                           plugin->name.str));
    DBUG_EXECUTE("finalize_audit_plugin", return 1;);
  }

  plugin->data = nullptr;
  memset(&event_class_mask, 0, sizeof(event_class_mask));

  /* Iterate through all the installed plugins to create new mask */

  /*
    LOCK_audit_mask/LOCK_plugin order is not fixed, but serialized with table
    lock on mysql.plugin.
  */
  mysql_mutex_lock(&LOCK_audit_mask);
  plugin_foreach(current_thd, calc_class_mask, MYSQL_AUDIT_PLUGIN,
                 &event_class_mask);

  /* Set the global audit mask */
  memmove(mysql_global_audit_mask, event_class_mask, sizeof(event_class_mask));
  mysql_mutex_unlock(&LOCK_audit_mask);

  return 0;
}

/**
  Dispatches an event by invoking the plugin's event_notify method.

  @param[in] thd    Session THD containing references to the audit plugins.
  @param[in] plugin Plugin used for dispatching the event.
  @param[in] arg    Opaque event data structure.

  @retval false  always
*/

static int plugins_dispatch(THD *thd, plugin_ref plugin, void *arg) {
  const struct st_mysql_event_generic *event_generic =
      (const struct st_mysql_event_generic *)arg;
  unsigned long subclass = static_cast<unsigned long>(
      *static_cast<const int *>(event_generic->event));
  st_mysql_audit *data = plugin_data<st_mysql_audit *>(plugin);

  /* Check to see if the plugin is interested in this event */
  if (check_audit_mask(data->class_mask[event_generic->event_class], subclass))
    return 0;

  /* Actually notify the plugin */
  return data->event_notify(thd, event_generic->event_class,
                            event_generic->event);
}

static bool plugins_dispatch_bool(THD *thd, plugin_ref plugin, void *arg) {
  return plugins_dispatch(thd, plugin, arg) ? true : false;
}

/**
  Distributes an audit event to plug-ins

  @param[in] thd          THD that generated the event.
  @param     event_class  Audit event class.
  @param[in] event        Opaque pointer to the event data.
*/

static int event_class_dispatch(THD *thd, mysql_event_class_t event_class,
                                const void *event) {
  int result = 0;
  struct st_mysql_event_generic event_generic;
  event_generic.event_class = event_class;
  event_generic.event = event;
  /*
    Check if we are doing a slow global dispatch. This event occurs when
    thd == NULL as it is not associated with any particular thread.
  */
  if (unlikely(!thd)) {
    return plugin_foreach(thd, plugins_dispatch_bool, MYSQL_AUDIT_PLUGIN,
                          &event_generic)
               ? 1
               : 0;
  } else {
    plugin_ref *plugins, *plugins_last;

    /* Use the cached set of audit plugins */
    plugins = thd->audit_class_plugins.begin();
    plugins_last = thd->audit_class_plugins.end();

    for (; plugins != plugins_last; plugins++)
      result |= plugins_dispatch(thd, *plugins, &event_generic);
  }

  return result;
}

static int event_class_dispatch_error(THD *thd, mysql_event_class_t event_class,
                                      const char *event_name,
                                      const void *event) {
  int result = 0;
  bool err = thd ? thd->get_stmt_da()->is_error() : true;

  if (err) /* Audit API cannot modify the already set DA's error state. */
    event_class_dispatch(thd, event_class, event);
  else {
    /* We are not is the error state, we can modify the existing one. */
    thd->get_stmt_da()->set_overwrite_status(true);

    result = event_class_dispatch(thd, event_class, event);

    if (result) {
      if (!thd->get_stmt_da()->is_error()) {
        my_error(ER_AUDIT_API_ABORT, MYF(0), event_name, result);
      }
    }

    thd->get_stmt_da()->set_overwrite_status(false);

    /* Because we rely on the error state, we have to notify our
    caller that the Audit API returned with error state. */
    if (thd->get_stmt_da()->is_error()) result = result != 0 ? result : 1;
  }

  return result;
}

/**  There's at least one active audit plugin tracking a specified class */
bool is_audit_plugin_class_active(THD *thd [[maybe_unused]],
                                  unsigned long event_class) {
  return mysql_global_audit_mask[event_class] != 0;
}

/**
  @brief Checks presence of active audit plugin

  @retval      TRUE             At least one audit plugin is present
  @retval      FALSE            No audit plugin is present
*/
bool is_global_audit_mask_set() {
  for (int i = MYSQL_AUDIT_GENERAL_CLASS; i < MYSQL_AUDIT_CLASS_MASK_SIZE;
       i++) {
    if (mysql_global_audit_mask[i] != 0) return true;
  }
  return false;
}

size_t make_user_name(Security_context *sctx, char *buf) {
  LEX_CSTRING sctx_user = sctx->user();
  LEX_CSTRING sctx_host = sctx->host();
  LEX_CSTRING sctx_ip = sctx->ip();
  LEX_CSTRING sctx_priv_user = sctx->priv_user();
  return static_cast<size_t>(
      strxnmov(buf, MAX_USER_HOST_SIZE,
               sctx_priv_user.str[0] ? sctx_priv_user.str : "", "[",
               sctx_user.length ? sctx_user.str : "", "] @ ",
               sctx_host.length ? sctx_host.str : "", " [",
               sctx_ip.length ? sctx_ip.str : "", "]", NullS) -
      buf);
}